From ebcdccf4f88462ba55c9fdb4ea01891a7fce68c2 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sun, 15 Nov 2026 13:29:30 -0800 Subject: [PATCH 01/63] feat(fr3): record 1 kHz control loop states in a lock-free ring buffer Opt-in via FrankaConfig.record_control_states. The control threads (osc, joint and zero torque controller) copy every robot state into a preallocated single producer single consumer ring buffer (no allocation, no locks, no Python in the loop). Franka.drain_control_states() returns everything since the last call as one contiguous numpy array per signal (N or N x D) plus num_samples and dropped. The buffer is also exposed as hw.ControlStateBuffer for tests and mocks. --- .../rcs_fr3/src/hw/ControlStateBuffer.h | 207 ++++++++++++++++++ extensions/rcs_fr3/src/hw/Franka.cpp | 12 + extensions/rcs_fr3/src/hw/Franka.h | 17 ++ extensions/rcs_fr3/src/pybind/rcs.cpp | 117 ++++++++++ .../rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi | 30 +++ .../tests/test_control_state_buffer.py | 58 +++++ 6 files changed, 441 insertions(+) create mode 100644 extensions/rcs_fr3/src/hw/ControlStateBuffer.h create mode 100644 extensions/rcs_fr3/tests/test_control_state_buffer.py diff --git a/extensions/rcs_fr3/src/hw/ControlStateBuffer.h b/extensions/rcs_fr3/src/hw/ControlStateBuffer.h new file mode 100644 index 00000000..6bc5f69a --- /dev/null +++ b/extensions/rcs_fr3/src/hw/ControlStateBuffer.h @@ -0,0 +1,207 @@ +#ifndef RCS_FRANKA_CONTROL_STATE_BUFFER_H +#define RCS_FRANKA_CONTROL_STATE_BUFFER_H + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rcs { +namespace hw { + +/** + * @brief One sample of the robot state as seen by the 1 kHz control loop. + * + * Plain old data so that it can be copied into a preallocated ring buffer + * without any allocation inside the real-time loop. + */ +struct ControlStateSample { + // host wall clock in seconds since epoch (same clock as Python's + // time.time()), taken when the sample was recorded + double timestamp = 0.0; + // robot clock in seconds (franka::RobotState::time) + double robot_time = 0.0; + std::array q{}; + std::array dq{}; + std::array tau_J{}; + std::array tau_J_d{}; + std::array dtau_J{}; + std::array tau_ext_hat_filtered{}; + std::array O_F_ext_hat_K{}; + std::array K_F_ext_hat_K{}; + // column major 4x4 end effector pose in base frame + std::array O_T_EE{}; + double control_command_success_rate = 0.0; + // franka::RobotMode as integer + int32_t robot_mode = 0; + // bit i is set if error i of franka::Errors is active + uint64_t current_errors = 0; + uint64_t last_motion_errors = 0; +}; + +// number of error flags in franka::Errors +constexpr size_t kNumFrankaErrors = 41; +static_assert(kNumFrankaErrors <= 64, "errors must fit into a uint64 mask"); + +/** + * @brief Packs the error flags of franka::Errors into a bit mask. + * + * franka::Errors only exposes its flags as references into a private + * std::array, bound in declaration order. The first reference + * therefore points to the start of that array. + */ +inline uint64_t ErrorsToMask(const franka::Errors& errors) noexcept { + const bool* flags = &errors.joint_position_limits_violation; + uint64_t mask = 0; + for (size_t i = 0; i < kNumFrankaErrors; ++i) { + if (flags[i]) { + mask |= (uint64_t{1} << i); + } + } + return mask; +} + +/** + * @brief Names of the error flags, index i corresponds to bit i of the masks. + */ +inline std::vector ErrorNames() { + std::vector names; + names.reserve(kNumFrankaErrors); + for (size_t i = 0; i < kNumFrankaErrors; ++i) { + std::array flags{}; + flags[i] = true; + // format is ["name"] + std::string name; + for (char c : static_cast(franka::Errors(flags))) { + if (c != '[' && c != ']' && c != '"') { + name.push_back(c); + } + } + names.push_back(name); + } + return names; +} + +inline void FillSample(const franka::RobotState& state, + ControlStateSample& sample) noexcept { + sample.timestamp = std::chrono::duration( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + sample.robot_time = state.time.toSec(); + sample.q = state.q; + sample.dq = state.dq; + sample.tau_J = state.tau_J; + sample.tau_J_d = state.tau_J_d; + sample.dtau_J = state.dtau_J; + sample.tau_ext_hat_filtered = state.tau_ext_hat_filtered; + sample.O_F_ext_hat_K = state.O_F_ext_hat_K; + sample.K_F_ext_hat_K = state.K_F_ext_hat_K; + sample.O_T_EE = state.O_T_EE; + sample.control_command_success_rate = state.control_command_success_rate; + sample.robot_mode = static_cast(state.robot_mode); + sample.current_errors = ErrorsToMask(state.current_errors); + sample.last_motion_errors = ErrorsToMask(state.last_motion_errors); +} + +/** + * @brief Single producer single consumer lock-free ring buffer of + * ControlStateSample. + * + * The producer is the 1 kHz control thread (push), the consumer is the + * Python env step (drain). All memory is allocated in the constructor, push + * neither allocates nor locks. If the consumer does not drain in time the + * newest samples are dropped and counted. + */ +class ControlStateBuffer { + public: + // 8192 samples are > 8 s at 1 kHz, much longer than one env step + static constexpr size_t kDefaultCapacity = 8192; + + explicit ControlStateBuffer(size_t capacity = kDefaultCapacity) + : m_capacity(RoundUpPow2(capacity)), + m_mask(m_capacity - 1), + m_samples(std::make_unique(m_capacity)) {} + + ControlStateBuffer(const ControlStateBuffer&) = delete; + ControlStateBuffer& operator=(const ControlStateBuffer&) = delete; + + size_t capacity() const noexcept { return m_capacity; } + + /// producer side, real-time safe + bool push(const franka::RobotState& state) noexcept { + const size_t head = m_head.load(std::memory_order_relaxed); + const size_t tail = m_tail.load(std::memory_order_acquire); + if (head - tail >= m_capacity) { + m_dropped.fetch_add(1, std::memory_order_relaxed); + return false; + } + FillSample(state, m_samples[head & m_mask]); + m_head.store(head + 1, std::memory_order_release); + return true; + } + + /// consumer side: number of samples ready to be drained + size_t size() const noexcept { + return m_head.load(std::memory_order_acquire) - + m_tail.load(std::memory_order_relaxed); + } + + /** + * @brief consumer side: calls fn(index, sample) for every available sample + * in order and frees them. Returns the number of drained samples. + */ + template + size_t drain(Fn&& fn, size_t max_samples) { + const size_t tail = m_tail.load(std::memory_order_relaxed); + const size_t head = m_head.load(std::memory_order_acquire); + size_t n = head - tail; + if (n > max_samples) { + n = max_samples; + } + for (size_t i = 0; i < n; ++i) { + fn(i, m_samples[(tail + i) & m_mask]); + } + m_tail.store(tail + n, std::memory_order_release); + return n; + } + + /// consumer side: discard all available samples + void clear() noexcept { + m_tail.store(m_head.load(std::memory_order_acquire), + std::memory_order_release); + } + + /// number of samples dropped since the last call, resets the counter + uint64_t take_dropped() noexcept { + return m_dropped.exchange(0, std::memory_order_relaxed); + } + + private: + static size_t RoundUpPow2(size_t v) { + size_t p = 1; + while (p < v) { + p <<= 1; + } + return p; + } + + const size_t m_capacity; + const size_t m_mask; + std::unique_ptr m_samples; + // separate cache lines for producer and consumer indices + alignas(64) std::atomic m_head{0}; + alignas(64) std::atomic m_tail{0}; + alignas(64) std::atomic m_dropped{0}; +}; + +} // namespace hw +} // namespace rcs + +#endif // RCS_FRANKA_CONTROL_STATE_BUFFER_H diff --git a/extensions/rcs_fr3/src/hw/Franka.cpp b/extensions/rcs_fr3/src/hw/Franka.cpp index ca34468d..944fc9cd 100644 --- a/extensions/rcs_fr3/src/hw/Franka.cpp +++ b/extensions/rcs_fr3/src/hw/Franka.cpp @@ -35,6 +35,7 @@ Franka::Franka(const FrankaConfig& cfg, m_ik(ik), robot(cfg.ip, cfg.ignore_realtime ? franka::RealtimeConfig::kIgnore : franka::RealtimeConfig::kEnforce) { + this->m_record_control_states.store(cfg.record_control_states); // set collision behavior and impedance this->set_default_robot_behavior(); this->set_guiding_mode(true, true, true, true, true, true, true); @@ -56,6 +57,7 @@ Franka::~Franka() { bool Franka::set_config(const FrankaConfig& cfg) { this->m_cfg = cfg; this->m_cfg.speed_factor = std::min(std::max(cfg.speed_factor, 0.0), 1.0); + this->m_record_control_states.store(cfg.record_control_states); if (this->m_cfg.load_parameters.has_value()) { auto load_value = &(this->m_cfg.load_parameters.value()); @@ -269,6 +271,13 @@ void Franka::controller_set_joint_position(const common::Vector7d& desired_q) { } } +void Franka::record_control_state( + const franka::RobotState& robot_state) noexcept { + if (this->m_record_control_states.load(std::memory_order_relaxed)) { + this->m_control_states.push(robot_state); + } +} + void Franka::check_for_background_errors() { std::exception_ptr ex = this->background_exception.load_and_clear(); if (ex) { @@ -474,6 +483,7 @@ void Franka::osc() { int traj_rate = 500; this->curr_state.store(robot_state); + this->record_control_state(robot_state); this->interpolator_mutex.lock(); this->controller_time += period.toSec(); @@ -665,6 +675,7 @@ void Franka::joint_controller() { common::Vector7d desired_q; this->curr_state.store(robot_state); + this->record_control_state(robot_state); this->interpolator_mutex.lock(); this->controller_time += period.toSec(); @@ -747,6 +758,7 @@ void Franka::zero_torque_controller() { this->robot.control([&](const franka::RobotState& robot_state, franka::Duration period) -> franka::Torques { this->curr_state.store(robot_state); + this->record_control_state(robot_state); this->interpolator_mutex.lock(); this->controller_time += period.toSec(); diff --git a/extensions/rcs_fr3/src/hw/Franka.h b/extensions/rcs_fr3/src/hw/Franka.h index 7d875f9a..a0eb86a8 100644 --- a/extensions/rcs_fr3/src/hw/Franka.h +++ b/extensions/rcs_fr3/src/hw/Franka.h @@ -12,6 +12,7 @@ #include #include +#include "ControlStateBuffer.h" #include "rcs/Kinematics.h" #include "rcs/LinearPoseTrajInterpolator.h" #include "rcs/Pose.h" @@ -76,6 +77,11 @@ struct FrankaConfig : common::RobotConfig { double approach_cartesian_speed = 0.1; double approach_rotation_speed = 0.5; bool ignore_realtime = false; + // When true, every state seen by the 1 kHz control loop is copied into a + // preallocated lock-free ring buffer that can be drained once per env step + // with Franka::drain_control_states. Only active while a controller thread + // runs (async_control). + bool record_control_states = false; size_t dof = 7; Eigen::Matrix joint_limits = (Eigen::Matrix(2, 7) << @@ -123,6 +129,10 @@ class Franka : public common::Robot { std::mutex interpolator_mutex; std::atomic running_controller{Controller::none}; common::ThreadSafeValue background_exception; + // filled by the control thread, drained by the env step + ControlStateBuffer m_control_states; + std::atomic m_record_control_states{false}; + void record_control_state(const franka::RobotState& robot_state) noexcept; void osc(); void joint_controller(); void zero_torque_controller(); @@ -183,6 +193,13 @@ class Franka : public common::Robot { void reset() override; void close() override {}; + + /** + * @brief Buffer of the states seen by the control loop, see + * FrankaConfig::record_control_states. Must only be drained from one + * thread. + */ + ControlStateBuffer& control_state_buffer() { return m_control_states; } }; } // namespace hw } // namespace rcs diff --git a/extensions/rcs_fr3/src/pybind/rcs.cpp b/extensions/rcs_fr3/src/pybind/rcs.cpp index fc3ddc18..2593b655 100644 --- a/extensions/rcs_fr3/src/pybind/rcs.cpp +++ b/extensions/rcs_fr3/src/pybind/rcs.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -22,6 +23,96 @@ namespace py = pybind11; +namespace { +template +void CopyRow(const std::array& src, double* dst, size_t row) { + std::copy(src.begin(), src.end(), dst + row * D); +} + +/** + * Drains all samples of the buffer into one contiguous numpy array per signal + * (shape N or N x D) plus the sample count and number of dropped samples. + */ +py::dict DrainControlStates(rcs::hw::ControlStateBuffer& buffer) { + const auto n = static_cast(buffer.size()); + auto vec = [n]() { return py::array_t(n); }; + auto mat = [n](py::ssize_t d) { + return py::array_t(std::vector{n, d}); + }; + auto timestamp = vec(); + auto robot_time = vec(); + auto q = mat(7); + auto dq = mat(7); + auto tau_J = mat(7); + auto tau_J_d = mat(7); + auto dtau_J = mat(7); + auto tau_ext = mat(7); + auto O_F_ext = mat(6); + auto K_F_ext = mat(6); + auto O_T_EE = mat(16); + auto success_rate = vec(); + auto robot_mode = py::array_t(n); + auto current_errors = py::array_t(n); + auto last_motion_errors = py::array_t(n); + + double* p_timestamp = timestamp.mutable_data(); + double* p_robot_time = robot_time.mutable_data(); + double* p_q = q.mutable_data(); + double* p_dq = dq.mutable_data(); + double* p_tau_J = tau_J.mutable_data(); + double* p_tau_J_d = tau_J_d.mutable_data(); + double* p_dtau_J = dtau_J.mutable_data(); + double* p_tau_ext = tau_ext.mutable_data(); + double* p_O_F_ext = O_F_ext.mutable_data(); + double* p_K_F_ext = K_F_ext.mutable_data(); + double* p_O_T_EE = O_T_EE.mutable_data(); + double* p_success_rate = success_rate.mutable_data(); + int32_t* p_robot_mode = robot_mode.mutable_data(); + uint64_t* p_current_errors = current_errors.mutable_data(); + uint64_t* p_last_motion_errors = last_motion_errors.mutable_data(); + + const size_t drained = buffer.drain( + [&](size_t i, const rcs::hw::ControlStateSample& s) { + p_timestamp[i] = s.timestamp; + p_robot_time[i] = s.robot_time; + CopyRow(s.q, p_q, i); + CopyRow(s.dq, p_dq, i); + CopyRow(s.tau_J, p_tau_J, i); + CopyRow(s.tau_J_d, p_tau_J_d, i); + CopyRow(s.dtau_J, p_dtau_J, i); + CopyRow(s.tau_ext_hat_filtered, p_tau_ext, i); + CopyRow(s.O_F_ext_hat_K, p_O_F_ext, i); + CopyRow(s.K_F_ext_hat_K, p_K_F_ext, i); + CopyRow(s.O_T_EE, p_O_T_EE, i); + p_success_rate[i] = s.control_command_success_rate; + p_robot_mode[i] = s.robot_mode; + p_current_errors[i] = s.current_errors; + p_last_motion_errors[i] = s.last_motion_errors; + }, + static_cast(n)); + + py::dict out; + out["num_samples"] = drained; + out["dropped"] = buffer.take_dropped(); + out["timestamp"] = timestamp; + out["robot_time"] = robot_time; + out["q"] = q; + out["dq"] = dq; + out["tau_J"] = tau_J; + out["tau_J_d"] = tau_J_d; + out["dtau_J"] = dtau_J; + out["tau_ext_hat_filtered"] = tau_ext; + out["O_F_ext_hat_K"] = O_F_ext; + out["K_F_ext_hat_K"] = K_F_ext; + out["O_T_EE"] = O_T_EE; + out["control_command_success_rate"] = success_rate; + out["robot_mode"] = robot_mode; + out["current_errors"] = current_errors; + out["last_motion_errors"] = last_motion_errors; + return out; +} +} // namespace + PYBIND11_MODULE(_core, m) { m.doc() = R"pbdoc( Franka Python Bindings @@ -107,6 +198,21 @@ PYBIND11_MODULE(_core, m) { // .def_readonly("time", &franka::RobotState::time) .def_readonly("robot_mode", &franka::RobotState::robot_mode); + py::class_( + hw, "ControlStateBuffer", + "Lock-free ring buffer of the states seen by the 1 kHz control loop.") + .def(py::init(), + py::arg("capacity") = rcs::hw::ControlStateBuffer::kDefaultCapacity) + .def("capacity", &rcs::hw::ControlStateBuffer::capacity) + .def("size", &rcs::hw::ControlStateBuffer::size) + .def("push", &rcs::hw::ControlStateBuffer::push, py::arg("state"), + "Adds a state as the control loop would do (for tests and mocks).") + .def("drain", &DrainControlStates) + .def("clear", &rcs::hw::ControlStateBuffer::clear); + hw.def("control_state_error_names", &rcs::hw::ErrorNames, + "Names of the franka error flags, index i is bit i of the " + "current_errors and last_motion_errors masks."); + py::object robot_state = (py::object)py::module_::import("rcs").attr("common").attr("RobotState"); py::class_(hw, "FrankaState", robot_state) @@ -158,6 +264,8 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("approach_rotation_speed", &rcs::hw::FrankaConfig::approach_rotation_speed) .def_readwrite("ignore_realtime", &rcs::hw::FrankaConfig::ignore_realtime) + .def_readwrite("record_control_states", + &rcs::hw::FrankaConfig::record_control_states) .def_readwrite("ip", &rcs::hw::FrankaConfig::ip); rcs::hw::FR3Config default_fr3_config; @@ -337,6 +445,15 @@ PYBIND11_MODULE(_core, m) { &rcs::hw::Franka::controller_set_joint_position, py::arg("desired_q")) .def("stop_control_thread", &rcs::hw::Franka::stop_control_thread) + .def( + "drain_control_states", + [](rcs::hw::Franka& self) { + return DrainControlStates(self.control_state_buffer()); + }, + "Returns and removes all states recorded by the control loop since " + "the last call, see FrankaConfig.record_control_states.") + .def("clear_control_states", + [](rcs::hw::Franka& self) { self.control_state_buffer().clear(); }) .def("automatic_error_recovery", &rcs::hw::Franka::automatic_error_recovery) .def("double_tap_robot_to_continue", diff --git a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi index 5b9ab3eb..1e7fb31c 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi +++ b/extensions/rcs_fr3/src/rcs_fr3/_core/hw/__init__.pyi @@ -13,6 +13,7 @@ import rcs._core.common from . import exceptions __all__: list[str] = [ + "ControlStateBuffer", "FHConfig", "FHState", "FR3Config", @@ -25,6 +26,7 @@ __all__: list[str] = [ "PandaConfig", "RobotMode", "RobotState", + "control_state_error_names", "exceptions", "franka_ik", "kAutomaticErrorRecovery", @@ -37,6 +39,22 @@ __all__: list[str] = [ "rcs_ik", ] +class ControlStateBuffer: + """ + Lock-free ring buffer of the states seen by the 1 kHz control loop. + """ + + def __init__(self, capacity: int = 8192) -> None: ... + def capacity(self) -> int: ... + def clear(self) -> None: ... + def drain(self) -> dict: ... + def push(self, state: RobotState) -> bool: + """ + Adds a state as the control loop would do (for tests and mocks). + """ + + def size(self) -> int: ... + class FHConfig(rcs._core.common.GripperConfig): async_control: bool epsilon_inner: float @@ -76,10 +94,16 @@ class FHState(rcs._core.common.GripperState): class Franka(rcs._core.common.Robot): def __init__(self, cfg: FrankaConfig, ik: rcs._core.common.Kinematics | None = None) -> None: ... def automatic_error_recovery(self) -> None: ... + def clear_control_states(self) -> None: ... def controller_set_joint_position( self, desired_q: numpy.ndarray[tuple[typing.Literal[7]], numpy.dtype[numpy.float64]] ) -> None: ... def double_tap_robot_to_continue(self) -> None: ... + def drain_control_states(self) -> dict: + """ + Returns and removes all states recorded by the control loop since the last call, see FrankaConfig.record_control_states. + """ + def get_cartesian_flange_position(self) -> rcs._core.common.Pose: ... def get_config(self) -> FrankaConfig: ... def get_state(self) -> FrankaState: ... @@ -119,6 +143,7 @@ class FrankaConfig(rcs._core.common.RobotConfig): kp_r: float load_parameters: FrankaLoad | None policy_rate: int + record_control_states: bool speed_factor: float tcp_offset: rcs._core.common.Pose tcp_offset_explicit: bool @@ -351,6 +376,11 @@ class FrankaState(rcs._core.common.RobotState): @property def robot_state(self) -> RobotState: ... +def control_state_error_names() -> list[str]: + """ + Names of the franka error flags, index i is bit i of the current_errors and last_motion_errors masks. + """ + franka_ik: IKSolver # value = kAutomaticErrorRecovery: RobotMode # value = kGuiding: RobotMode # value = diff --git a/extensions/rcs_fr3/tests/test_control_state_buffer.py b/extensions/rcs_fr3/tests/test_control_state_buffer.py new file mode 100644 index 00000000..2634a834 --- /dev/null +++ b/extensions/rcs_fr3/tests/test_control_state_buffer.py @@ -0,0 +1,58 @@ +"""Tests of the control state ring buffer, they do not need a robot.""" + +import numpy as np +import pytest + +hw = pytest.importorskip("rcs_fr3._core").hw + + +def test_drain_shapes_and_order(): + buffer = hw.ControlStateBuffer(100) + assert buffer.capacity() == 128 + state = hw.RobotState() + for _ in range(66): + assert buffer.push(state) + assert buffer.size() == 66 + states = buffer.drain() + assert states["num_samples"] == 66 + assert states["dropped"] == 0 + assert states["timestamp"].shape == (66,) + assert states["q"].shape == (66, 7) + assert states["tau_J"].shape == (66, 7) + assert states["dtau_J"].shape == (66, 7) + assert states["tau_ext_hat_filtered"].shape == (66, 7) + assert states["O_F_ext_hat_K"].shape == (66, 6) + assert states["O_T_EE"].shape == (66, 16) + assert states["robot_mode"].dtype == np.int32 + assert states["current_errors"].dtype == np.uint64 + # timestamps are taken at push time and must be monotonic + assert np.all(np.diff(states["timestamp"]) >= 0) + assert buffer.size() == 0 + assert buffer.drain()["num_samples"] == 0 + + +def test_overflow_drops_newest_and_counts(): + buffer = hw.ControlStateBuffer(8) + state = hw.RobotState() + pushed = [buffer.push(state) for _ in range(10)] + assert pushed == [True] * 8 + [False] * 2 + states = buffer.drain() + assert states["num_samples"] == 8 + assert states["dropped"] == 2 + # counter is reset after it was reported + assert buffer.drain()["dropped"] == 0 + + +def test_error_names(): + names = hw.control_state_error_names() + assert len(names) == 41 + assert names[0] == "joint_position_limits_violation" + assert "joint_reflex" in names + assert "cartesian_reflex" in names + + +def test_config_flag_is_opt_in(): + cfg = hw.FR3Config(ip="localhost") + assert cfg.record_control_states is False + cfg.record_control_states = True + assert cfg.record_control_states is True From 9b1cb7cecde6048f00e47b3768e8cf0e9d62e753 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sun, 15 Nov 2026 13:30:16 -0800 Subject: [PATCH 02/63] feat(fr3): forward control loop states through the env info FR3HW drains the control state buffer once per step and adds it to info["control_states"] (one array per signal with N samples since the last step), so the 1 kHz states travel synchronously with the step and end up in the same recording. States recorded during reset are dropped. Nothing changes unless record_control_states is enabled. --- extensions/rcs_fr3/src/rcs_fr3/envs.py | 23 ++++- extensions/rcs_fr3/tests/test_fr3hw_mock.py | 99 +++++++++++++++++++++ 2 files changed, 120 insertions(+), 2 deletions(-) create mode 100644 extensions/rcs_fr3/tests/test_fr3hw_mock.py diff --git a/extensions/rcs_fr3/src/rcs_fr3/envs.py b/extensions/rcs_fr3/src/rcs_fr3/envs.py index 3bd10c58..2a7640ef 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/envs.py +++ b/extensions/rcs_fr3/src/rcs_fr3/envs.py @@ -9,22 +9,38 @@ class FR3HW(gym.Wrapper): + """Hardware specific additions for the FR3. + + - adds the libfranka robot state to the observation (``obs["robot_state"]``) + - if ``record_control_states`` is enabled in the robot config, all states seen by the 1 kHz + control loop since the last step are added to ``info["control_states"]`` as one array per + signal (shape N or N x D) together with ``num_samples`` and ``dropped`` + """ + + CONTROL_STATES_KEY = "control_states" + def __init__(self, env): super().__init__(env) assert self.env.get_wrapper_attr("PLATFORM") == RobotPlatform.HARDWARE, "Base environment must be hardware." assert isinstance(self.get_wrapper_attr("robot"), hw.Franka), "Robot must be a hw.Franka instance." self.hw_robot = cast(hw.Franka, self.get_wrapper_attr("robot")) self._robot_state_keys: list[str] | None = None + self._record_control_states = bool(self.hw_robot.get_config().record_control_states) + + def _add_control_states(self, info: dict[str, Any]) -> dict[str, Any]: + if self._record_control_states: + info[self.CONTROL_STATES_KEY] = self.hw_robot.drain_control_states() + return info def step(self, action: Any) -> tuple[dict[str, Any], SupportsFloat, bool, bool, dict]: try: obs, reward, terminated, truncated, info = super().step(action) obs = self.get_obs(obs) - return obs, reward, terminated, truncated, info + return obs, reward, terminated, truncated, self._add_control_states(info) except hw.exceptions.FrankaControlException as e: _logger.error("FrankaControlException: %s", e) self.hw_robot.automatic_error_recovery() - return self.get_obs(), 0, False, True, {} + return self.get_obs(), 0, False, True, self._add_control_states({}) def get_obs(self, obs: dict | None = None) -> dict[str, Any]: if obs is None: @@ -45,6 +61,9 @@ def reset( self, *, seed: int | None = None, options: dict[str, Any] | None = None ) -> tuple[dict[str, Any], dict[str, Any]]: obs, info = super().reset(seed=seed, options=options) + # the config might have changed, states recorded before and during the reset do not belong to the next episode + self._record_control_states = bool(self.hw_robot.get_config().record_control_states) + self.hw_robot.clear_control_states() return self.get_obs(obs), info def close(self): diff --git a/extensions/rcs_fr3/tests/test_fr3hw_mock.py b/extensions/rcs_fr3/tests/test_fr3hw_mock.py new file mode 100644 index 00000000..8c897675 --- /dev/null +++ b/extensions/rcs_fr3/tests/test_fr3hw_mock.py @@ -0,0 +1,99 @@ +"""Tests of the FR3HW wrapper against a mocked robot, no hardware is contacted.""" + +from types import SimpleNamespace +from typing import Any + +import gymnasium as gym +import numpy as np +import pytest +from rcs._core.common import RobotPlatform + +core = pytest.importorskip("rcs_fr3._core") +envs = pytest.importorskip("rcs_fr3.envs") +hw = core.hw + + +class FakeFranka: + """Stands in for hw.Franka: the control loop is simulated by pushing into a real ControlStateBuffer.""" + + def __init__(self, record: bool = True): + self.cfg = SimpleNamespace(record_control_states=record, robot_type=SimpleNamespace(id="FR3")) + self.buffer = hw.ControlStateBuffer() + self.fail_next_step = False + self.recovered = 0 + + def get_config(self): + return self.cfg + + def get_state(self): + return SimpleNamespace(robot_state=hw.RobotState()) + + def drain_control_states(self): + return self.buffer.drain() + + def clear_control_states(self): + self.buffer.clear() + + def automatic_error_recovery(self): + self.recovered += 1 + + def stop_control_thread(self): + pass + + def control_loop(self, n: int): + state = hw.RobotState() + for _ in range(n): + self.buffer.push(state) + + +class FakeHardwareEnv(gym.Env): + PLATFORM = RobotPlatform.HARDWARE + + def __init__(self, robot: FakeFranka): + self.robot = robot + + def get_robot_obs(self) -> dict[str, Any]: + return {"joints": np.zeros(7)} + + def step(self, action): + if self.robot.fail_next_step: + self.robot.fail_next_step = False + msg = "libfranka: Move command aborted: motion aborted by reflex! ['cartesian_reflex']" + raise hw.exceptions.FrankaControlException(msg) + # 15 Hz env step with a 1 kHz control loop + self.robot.control_loop(66) + return self.get_robot_obs(), 0.0, False, False, {"platform": "hardware"} + + def reset(self, *, seed=None, options=None): + # samples during the reset (e.g. homing) must not leak into the next episode + self.robot.control_loop(10) + return self.get_robot_obs(), {} + + +@pytest.fixture() +def _patched_hw(monkeypatch): + fake_hw = SimpleNamespace( + Franka=FakeFranka, FrankaState=SimpleNamespace, RobotState=hw.RobotState, exceptions=hw.exceptions + ) + monkeypatch.setattr(envs, "hw", fake_hw) + + +@pytest.mark.usefixtures("_patched_hw") +def test_control_states_in_info(): + robot = FakeFranka(record=True) + env = envs.FR3HW(FakeHardwareEnv(robot)) + env.reset() + _, _, _, _, info = env.step({}) + states = info["control_states"] + assert states["num_samples"] == 66 + assert states["q"].shape == (66, 7) + assert states["tau_ext_hat_filtered"].shape == (66, 7) + + +@pytest.mark.usefixtures("_patched_hw") +def test_control_states_opt_in(): + robot = FakeFranka(record=False) + env = envs.FR3HW(FakeHardwareEnv(robot)) + env.reset() + _, _, _, _, info = env.step({}) + assert "control_states" not in info From 757ec87aa26fd8570d10fb8ad096d2575068c45a Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sun, 15 Nov 2026 13:30:34 -0800 Subject: [PATCH 03/63] fix(fr3): end the episode visibly on robot errors A FrankaControlException (e.g. a reflex) used to be recovered inside the step and returned with an empty info, so the error vanished from the recording. Now the step returns truncated=True, keeps the robot info and the control states up to the error and reports the message in info["robot_error"] (empty string otherwise, so the column has a stable type). The automatic error recovery happens on the next reset. --- extensions/rcs_fr3/src/rcs_fr3/envs.py | 23 ++++++++++++++++++--- extensions/rcs_fr3/tests/test_fr3hw_mock.py | 22 ++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/extensions/rcs_fr3/src/rcs_fr3/envs.py b/extensions/rcs_fr3/src/rcs_fr3/envs.py index 2a7640ef..7eaef151 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/envs.py +++ b/extensions/rcs_fr3/src/rcs_fr3/envs.py @@ -15,9 +15,13 @@ class FR3HW(gym.Wrapper): - if ``record_control_states`` is enabled in the robot config, all states seen by the 1 kHz control loop since the last step are added to ``info["control_states"]`` as one array per signal (shape N or N x D) together with ``num_samples`` and ``dropped`` + - a robot error (e.g. a reflex) ends the episode visibly: the step returns ``truncated=True`` + and the error message in ``info["robot_error"]`` (empty string if there is no error). + The robot is not recovered silently in the step, the recovery happens on the next reset. """ CONTROL_STATES_KEY = "control_states" + ROBOT_ERROR_KEY = "robot_error" def __init__(self, env): super().__init__(env) @@ -26,6 +30,7 @@ def __init__(self, env): self.hw_robot = cast(hw.Franka, self.get_wrapper_attr("robot")) self._robot_state_keys: list[str] | None = None self._record_control_states = bool(self.hw_robot.get_config().record_control_states) + self._last_obs: dict[str, Any] | None = None def _add_control_states(self, info: dict[str, Any]) -> dict[str, Any]: if self._record_control_states: @@ -36,17 +41,28 @@ def step(self, action: Any) -> tuple[dict[str, Any], SupportsFloat, bool, bool, try: obs, reward, terminated, truncated, info = super().step(action) obs = self.get_obs(obs) + info[self.ROBOT_ERROR_KEY] = "" return obs, reward, terminated, truncated, self._add_control_states(info) except hw.exceptions.FrankaControlException as e: - _logger.error("FrankaControlException: %s", e) - self.hw_robot.automatic_error_recovery() - return self.get_obs(), 0, False, True, self._add_control_states({}) + _logger.error("FrankaControlException, truncating the episode: %s", e) + try: + obs = self.get_obs() + except Exception: + _logger.exception("could not read the robot state after the control exception") + obs = self._last_obs if self._last_obs is not None else {} + info = { + "platform": "hardware", + "robot_type": self.hw_robot.get_config().robot_type.id, + self.ROBOT_ERROR_KEY: str(e), + } + return obs, 0, False, True, self._add_control_states(info) def get_obs(self, obs: dict | None = None) -> dict[str, Any]: if obs is None: obs = dict(self.get_wrapper_attr("get_robot_obs")()) robot_state = cast(hw.FrankaState, self.hw_robot.get_state()) obs["robot_state"] = self._rs2dict(robot_state.robot_state) + self._last_obs = obs return obs def _rs2dict(self, state: hw.RobotState): @@ -64,6 +80,7 @@ def reset( # the config might have changed, states recorded before and during the reset do not belong to the next episode self._record_control_states = bool(self.hw_robot.get_config().record_control_states) self.hw_robot.clear_control_states() + info[self.ROBOT_ERROR_KEY] = "" return self.get_obs(obs), info def close(self): diff --git a/extensions/rcs_fr3/tests/test_fr3hw_mock.py b/extensions/rcs_fr3/tests/test_fr3hw_mock.py index 8c897675..68d6984b 100644 --- a/extensions/rcs_fr3/tests/test_fr3hw_mock.py +++ b/extensions/rcs_fr3/tests/test_fr3hw_mock.py @@ -97,3 +97,25 @@ def test_control_states_opt_in(): env.reset() _, _, _, _, info = env.step({}) assert "control_states" not in info + + +@pytest.mark.usefixtures("_patched_hw") +def test_robot_error_truncates_visibly(): + robot = FakeFranka(record=True) + env = envs.FR3HW(FakeHardwareEnv(robot)) + env.reset() + _, _, _, truncated, info = env.step({}) + assert not truncated + assert info["robot_error"] == "" + + robot.fail_next_step = True + robot.control_loop(5) # states recorded until the reflex + obs, _, terminated, truncated, info = env.step({}) + assert truncated + assert not terminated + assert "reflex" in info["robot_error"] + # the states that lead to the reflex are not lost + assert info["control_states"]["num_samples"] == 5 + # no silent recovery inside the step, this happens on reset + assert robot.recovered == 0 + assert "joints" in obs From fbd5e16bdc0e5d992f1e9d726b496d3b0fd3d380 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sun, 15 Nov 2026 13:30:53 -0800 Subject: [PATCH 04/63] fix(operator): reset the teleop episode when the env ends it TeleopLoop ignored terminated/truncated, so after a robot error the loop kept stepping a robot in error state. It now logs the reason and resets the env and the operator, the episode ends as unsuccessful. --- python/rcs/operator/interface.py | 11 +++++- python/tests/test_teleop_loop.py | 59 ++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 python/tests/test_teleop_loop.py diff --git a/python/rcs/operator/interface.py b/python/rcs/operator/interface.py index 3e7b6f05..5a327445 100644 --- a/python/rcs/operator/interface.py +++ b/python/rcs/operator/interface.py @@ -194,8 +194,17 @@ def environment_step_loop(self): # 2. Step the Environment actions = self.operator.consume_action() actions = self._translate_keys(actions) - self._last_obs, _, _, _, _ = self.env.step(actions) + self._last_obs, _, terminated, truncated, info = self.env.step(actions) self.operator.set_camera(self._last_obs) + if terminated or truncated: + # e.g. a robot error (reflex): end the episode as unsuccessful instead of continuing silently + logger.warning( + "Episode ended by the env (terminated=%s, truncated=%s): %s", terminated, truncated, info + ) + self._last_obs, _ = self.env.reset() + self.operator.set_camera(self._last_obs) + self.operator.reset_operator_state() + self._synced = self.operator.control_mode[1] != RelativeTo.NONE def sync_robot_to_operator(self, duration: float = 3.0): print(f"Command: Syncing robot to operator (duration: {duration}s)...") diff --git a/python/tests/test_teleop_loop.py b/python/tests/test_teleop_loop.py new file mode 100644 index 00000000..e09040fa --- /dev/null +++ b/python/tests/test_teleop_loop.py @@ -0,0 +1,59 @@ +from typing import Any + +import numpy as np +from rcs.envs.base import ControlMode, RelativeTo +from rcs.operator.interface import BaseOperator, TeleopCommands, TeleopLoop + + +class _Operator(BaseOperator): + control_mode = (ControlMode.CARTESIAN_TQuat, RelativeTo.LAST_STEP) + controller_names = ["right"] # noqa: RUF012 + + def __init__(self): + super().__init__(config=None) # type: ignore[arg-type] + self.resets = 0 + + def consume_commands(self) -> TeleopCommands: + return TeleopCommands() + + def consume_action(self) -> dict[str, Any]: + return {"right": {"tquat": np.array([0, 0, 0, 0, 0, 0, 1.0]), "gripper": np.array([1.0])}} + + def reset_operator_state(self): + self.resets += 1 + + +class _Env: + """Truncates the second step like a reflex on the hardware would do.""" + + def __init__(self): + self.steps = 0 + self.resets = 0 + self.loop: TeleopLoop | None = None + + def get_wrapper_attr(self, name: str): + assert name == "envs" + return {"right": None} + + def reset(self): + self.resets += 1 + return {"right": {"joints": np.zeros(7)}}, {} + + def step(self, _action): + self.steps += 1 + if self.steps >= 3: + assert self.loop is not None + self.loop._exit_requested = True + truncated = self.steps == 2 + return {"right": {"joints": np.zeros(7)}}, 0.0, False, truncated, {"robot_error": "reflex" if truncated else ""} + + +def test_teleop_loop_resets_on_truncation(): + env = _Env() + operator = _Operator() + loop = TeleopLoop(env, operator) # type: ignore[arg-type] + env.loop = loop + loop.environment_step_loop() + # initial reset and one reset because of the truncated step + assert env.resets == 2 + assert operator.resets == 1 From 7cb331ae8a0954bd91d21e0d2b252489aac8ee85 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sun, 15 Nov 2026 13:31:37 -0800 Subject: [PATCH 05/63] feat(envs): record multi-dimensional info arrays and episode end flags The StorageWrapper now stores numpy arrays with ndim > 1 inside the info dict flattened with a "_shape" column (same convention as for the observation) instead of failing on them, without touching the info that is returned to the caller. This makes the per step control loop states (N x D) end up in the parquet data. terminated and truncated are stored in their own columns so episodes that were cut short (e.g. by a reflex) are visible in the data. --- python/rcs/envs/storage_wrapper.py | 24 ++++++++++- python/tests/test_storage_wrapper.py | 59 ++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 python/tests/test_storage_wrapper.py diff --git a/python/rcs/envs/storage_wrapper.py b/python/rcs/envs/storage_wrapper.py index 3fe9090d..db40c827 100644 --- a/python/rcs/envs/storage_wrapper.py +++ b/python/rcs/envs/storage_wrapper.py @@ -53,6 +53,12 @@ def __init__( in-place, and their original shapes are stored alongside as ``"_shape"``. Nested dicts are traversed recursively. - Lists/tuples of arrays are not supported. + - The info dict is stored as well. Numpy arrays with ndim > 1 inside it (e.g. the + ``N x D`` control loop states of one step in ``info["control_states"]``) are stored + flattened with their shape in ``"_shape"``, the info dict returned to the + caller is not modified. + - ``terminated`` and ``truncated`` of every step are stored in their own columns, e.g. an + episode that was ended by a robot error has ``truncated=True`` in its last row. - ``close()`` must be called to flush the final batch and run consolidation. Parameters @@ -221,6 +227,20 @@ def _flatten_arrays(self, d: dict[str, Any]): updates[f"{k}_shape"] = v.shape d.update(updates) + @classmethod + def _flattened(cls, d: dict[str, Any]) -> dict[str, Any]: + """Like _flatten_arrays but returns a new dict and leaves the input untouched.""" + out: dict[str, Any] = {} + for k, v in d.items(): + if isinstance(v, dict): + out[k] = cls._flattened(v) + elif isinstance(v, np.ndarray) and len(v.shape) > 1: + out[k] = v.reshape(-1) + out[f"{k}_shape"] = v.shape + else: + out[k] = v + return out + def _encode_images(self, obs: dict[str, Any]): # images _ = [ @@ -284,8 +304,10 @@ def step(self, action): frame = { "obs": obs, - "info": info, + "info": self._flattened(info), "reward": reward, + "terminated": bool(terminated), + "truncated": bool(truncated), "step": self.step_cnt, "uuid": self.uuid.hex, "date": datetime.date.today().isoformat(), diff --git a/python/tests/test_storage_wrapper.py b/python/tests/test_storage_wrapper.py new file mode 100644 index 00000000..49df9a2f --- /dev/null +++ b/python/tests/test_storage_wrapper.py @@ -0,0 +1,59 @@ +from typing import Any + +import gymnasium as gym +import numpy as np +import pyarrow.dataset as ds +from rcs.envs.storage_wrapper import StorageWrapper + + +class _Env(gym.Env): + """Returns control loop states like FR3HW does and truncates the last step.""" + + def __init__(self, n_steps: int): + self.n_steps = n_steps + self.t = 0 + + def reset(self, *, seed=None, options=None): + self.t = 0 + return {"joints": np.zeros(7)}, {} + + def step(self, action): + self.t += 1 + n = 60 + self.t # the number of control samples varies from step to step + info: dict[str, Any] = { + "robot_error": "reflex" if self.t == self.n_steps else "", + "control_states": { + "num_samples": n, + "timestamp": np.arange(n, dtype=np.float64), + "q": np.full((n, 7), float(self.t)), + "O_T_EE": np.zeros((n, 16)), + }, + } + return {"joints": np.full(7, float(self.t))}, 0.0, False, self.t == self.n_steps, info + + +def test_storage_wrapper_stores_control_states_and_truncation(tmp_path): + n_steps = 5 + env = StorageWrapper(_Env(n_steps), str(tmp_path), "test", batch_size=2, always_record=True) + env.reset() + for _ in range(n_steps): + _, _, _, truncated, info = env.step({"joints": np.zeros(7)}) + # the caller still gets the unflattened arrays + assert info["control_states"]["q"].ndim == 2 + assert truncated + env.close() + + table = ds.dataset(str(tmp_path), format="parquet").to_table().sort_by("step") + rows = table.to_pylist() + assert len(rows) == n_steps + assert [r["truncated"] for r in rows] == [False] * (n_steps - 1) + [True] + assert all(r["terminated"] is False for r in rows) + assert rows[-1]["info"]["robot_error"] == "reflex" + for i, row in enumerate(rows): + states = row["info"]["control_states"] + n = 60 + i + 1 + assert states["num_samples"] == n + q = np.asarray(states["q"]).reshape(states["q_shape"]) + assert q.shape == (n, 7) + assert np.all(q == i + 1) + assert np.asarray(states["O_T_EE"]).reshape(states["O_T_EE_shape"]).shape == (n, 16) From fd8ca816df15964604455aa412e8fabab3607de5 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sun, 15 Nov 2026 13:33:58 -0800 Subject: [PATCH 06/63] feat(sim): mirror the control state recording at physics rate WrapperConfig.record_control_states adds SimControlStateWrapper to every simulated robot. It samples the robot after each physics step (SimEnv steps one physics step at a time when sub step callbacks are registered, which is identical to sim.step(n)) and puts the samples of the env step into info["control_states"] with the same keys and shapes as on the FR3, so recordings, tests and the viewer work in sim. Without async_control one sample per step is recorded. --- python/rcs/envs/base.py | 11 +- python/rcs/envs/scenes.py | 12 ++- python/rcs/envs/sim.py | 132 +++++++++++++++++++++++- python/tests/test_sim_control_states.py | 79 ++++++++++++++ 4 files changed, 230 insertions(+), 4 deletions(-) create mode 100644 python/tests/test_sim_control_states.py diff --git a/python/rcs/envs/base.py b/python/rcs/envs/base.py index 0d1b6261..9fafafa3 100644 --- a/python/rcs/envs/base.py +++ b/python/rcs/envs/base.py @@ -270,7 +270,16 @@ def step_sim(self): self.sim.set_state(self._replay_state[0], self._replay_state[1]) self._replay_state = None elif cfg.async_control: - self.sim.step(round(1 / cfg.frequency / self.sim.model.opt.timestep)) + n_substeps = round(1 / cfg.frequency / self.sim.model.opt.timestep) + substep_callbacks = getattr(self.sim, "substep_callbacks", None) + if substep_callbacks: + # identical to sim.step(n_substeps) but lets e.g. SimControlStateWrapper sample every physics step + for _ in range(n_substeps): + self.sim.step(1) + for callback in substep_callbacks: + callback() + else: + self.sim.step(n_substeps) if cfg.realtime: self.frame_rate.frame_rate = cfg.frequency self.frame_rate() diff --git a/python/rcs/envs/scenes.py b/python/rcs/envs/scenes.py index 28170de3..8f7fc1f1 100644 --- a/python/rcs/envs/scenes.py +++ b/python/rcs/envs/scenes.py @@ -22,7 +22,7 @@ RobotWrapper, SimEnv, ) -from rcs.envs.sim import GripperWrapperSim, RobotSimWrapper +from rcs.envs.sim import GripperWrapperSim, RobotSimWrapper, SimControlStateWrapper from rcs.sim.composer import ModelComposer from rcs.sim.sim import Sim from rcs.sim.visual_randomization import VisualRandomizer, VisualRandomizerConfig @@ -53,6 +53,11 @@ class WrapperConfig: binary_gripper: bool = True home_on_reset: bool = True include_depth: bool = False + record_control_states: bool = False + """Adds all robot states seen by the low level controller since the last step to + ``info["control_states"]`` (one array per signal, shape N or N x D). On hardware this is the 1 kHz + control loop (if the robot supports it), in simulation every physics step (only with ``async_control``, + otherwise one sample per step).""" #### SIM SPECIFIC #### @@ -464,7 +469,10 @@ def add_robot_env( # rcs wrapper composition robot = rcs.sim.SimRobot(sim=simulation, ik=ik, cfg=prefixed_cfg.robot_cfgs[robot_name]) env = RobotWrapper(env, robot, prefixed_cfg.control_mode, home_on_reset=prefixed_cfg.wrapper_cfg.home_on_reset) - return RobotSimWrapper(env) + env = RobotSimWrapper(env) + if prefixed_cfg.wrapper_cfg.record_control_states: + env = SimControlStateWrapper(env) + return env def add_gripper_mujoco( self, cfg: SimEnvCreatorConfig, composer: ModelComposer, robot_name: str, gripper_xml: str, attachment_site: str diff --git a/python/rcs/envs/sim.py b/python/rcs/envs/sim.py index 77354065..da9c60d1 100644 --- a/python/rcs/envs/sim.py +++ b/python/rcs/envs/sim.py @@ -1,7 +1,10 @@ import logging -from typing import Any, cast +import time +from typing import Any, SupportsFloat, cast import gymnasium as gym +import mujoco as mj +import numpy as np from rcs._core.common import RobotPlatform from rcs.envs.space_utils import ActObsInfoWrapper @@ -40,6 +43,133 @@ def reset( return super().reset(seed=seed, options=options) +class SimControlStateWrapper(gym.Wrapper): + """Simulation counterpart of the control loop state recording of the hardware (see ``FR3HW``). + + Samples the robot state after every physics step and adds all samples since the last env step to + ``info["control_states"]`` with the same keys and shapes as on the hardware, so that recordings, tests + and the data viewer work the same in simulation. Only ``async_control`` steps the physics in fixed + sub steps, with ``step_until_convergence`` one sample per env step is recorded. + + Notes on the simulated signals: ``tau_J`` is the actuator torque in joint space, ``tau_J_d`` the + actuator force, ``dtau_J`` the finite difference of ``tau_J``, ``tau_ext_hat_filtered`` the constraint + (contact and limit) torques, ``O_F_ext_hat_K`` the wrench at the attachment site that explains these + torques (least squares through the jacobian) in the robot base frame, ``K_F_ext_hat_K`` the same + wrench in the attachment site frame and ``O_T_EE`` the column major pose of the attachment site in + the robot base frame. ``robot_mode``, ``current_errors`` and ``last_motion_errors`` are always zero. + """ + + CONTROL_STATES_KEY = "control_states" + + def __init__(self, env): + super().__init__(env) + assert self.env.get_wrapper_attr("PLATFORM") == RobotPlatform.SIMULATION, "Base environment must be simulation." + self.sim = cast(sim.Sim, self.get_wrapper_attr("sim")) + cfg = cast(sim.SimRobotConfig, self.get_wrapper_attr("robot").get_config()) + m = self.sim.model + joint_ids = [mj.mj_name2id(m, mj.mjtObj.mjOBJ_JOINT, name) for name in cfg.joints] + actuator_ids = [mj.mj_name2id(m, mj.mjtObj.mjOBJ_ACTUATOR, name) for name in cfg.actuators] + assert all(i >= 0 for i in joint_ids), f"joints {cfg.joints} not found in the model" + self._qpos_adr = m.jnt_qposadr[joint_ids] + self._dof_adr = m.jnt_dofadr[joint_ids] + self._actuator_ids = np.array([i for i in actuator_ids if i >= 0], dtype=int) + self._site_id = mj.mj_name2id(m, mj.mjtObj.mjOBJ_SITE, cfg.attachment_site) + self._base_id = mj.mj_name2id(m, mj.mjtObj.mjOBJ_BODY, cfg.base) + self._jacp = np.zeros((3, m.nv)) + self._jacr = np.zeros((3, m.nv)) + self._samples: list[dict[str, Any]] = [] + self._prev_tau: np.ndarray | None = None + if not hasattr(self.sim, "substep_callbacks"): + self.sim.substep_callbacks = [] # type: ignore[attr-defined] + self.sim.substep_callbacks.append(self._sample) # type: ignore[attr-defined] + + def _base_pose(self) -> tuple[np.ndarray, np.ndarray]: + d = self.sim.data + if self._base_id < 0: + return np.zeros(3), np.eye(3) + return d.xpos[self._base_id], d.xmat[self._base_id].reshape(3, 3) + + def _sample(self): + m, d = self.sim.model, self.sim.data + tau = d.qfrc_actuator[self._dof_adr].copy() + dt = m.opt.timestep + dtau = np.zeros_like(tau) if self._prev_tau is None else (tau - self._prev_tau) / dt + self._prev_tau = tau + tau_ext = d.qfrc_constraint[self._dof_adr] + d.qfrc_applied[self._dof_adr] + + base_pos, base_rot = self._base_pose() + o_t_ee = np.eye(4) + o_f_ext = np.zeros(6) + k_f_ext = np.zeros(6) + if self._site_id >= 0: + site_rot_o = base_rot.T @ d.site_xmat[self._site_id].reshape(3, 3) + o_t_ee[:3, :3] = site_rot_o + o_t_ee[:3, 3] = base_rot.T @ (d.site_xpos[self._site_id] - base_pos) + mj.mj_jacSite(m, d, self._jacp, self._jacr, self._site_id) + jac = np.vstack([self._jacp[:, self._dof_adr], self._jacr[:, self._dof_adr]]) + # tau_ext = J^T F (world frame) -> least squares wrench, then into the base frame + f_world = np.linalg.lstsq(jac.T, tau_ext, rcond=None)[0] + o_f_ext = np.concatenate([base_rot.T @ f_world[:3], base_rot.T @ f_world[3:]]) + k_f_ext = np.concatenate([site_rot_o.T @ o_f_ext[:3], site_rot_o.T @ o_f_ext[3:]]) + + self._samples.append( + { + "timestamp": time.time(), + "robot_time": d.time, + "q": d.qpos[self._qpos_adr].copy(), + "dq": d.qvel[self._dof_adr].copy(), + "tau_J": tau, + "tau_J_d": d.actuator_force[self._actuator_ids].copy(), + "dtau_J": dtau, + "tau_ext_hat_filtered": tau_ext, + "O_F_ext_hat_K": o_f_ext, + "K_F_ext_hat_K": k_f_ext, + "O_T_EE": o_t_ee.flatten(order="F"), + } + ) + + def drain_control_states(self) -> dict[str, Any]: + n = len(self._samples) + out: dict[str, Any] = {"num_samples": n, "dropped": 0} + widths = {"q": 0, "dq": 0, "tau_J": 0, "tau_J_d": 0, "dtau_J": 0, "tau_ext_hat_filtered": 0} + for key in ("timestamp", "robot_time"): + out[key] = np.array([s[key] for s in self._samples], dtype=np.float64) + for key, width in [*widths.items(), ("O_F_ext_hat_K", 6), ("K_F_ext_hat_K", 6), ("O_T_EE", 16)]: + dim = width or len(self._dof_adr) + out[key] = ( + np.stack([s[key] for s in self._samples]).astype(np.float64) if n else np.zeros((0, dim), np.float64) + ) + out["control_command_success_rate"] = np.ones(n, dtype=np.float64) + out["robot_mode"] = np.zeros(n, dtype=np.int32) + out["current_errors"] = np.zeros(n, dtype=np.uint64) + out["last_motion_errors"] = np.zeros(n, dtype=np.uint64) + self._samples = [] + return out + + def step(self, action: Any) -> tuple[dict[str, Any], SupportsFloat, bool, bool, dict[str, Any]]: + self._samples = [] + obs, reward, terminated, truncated, info = super().step(action) + if not self._samples: + # no fixed sub steps (step_until_convergence), record the state after the step + self._sample() + info[self.CONTROL_STATES_KEY] = self.drain_control_states() + return obs, reward, terminated, truncated, info + + def reset( + self, *, seed: int | None = None, options: dict[str, Any] | None = None + ) -> tuple[dict[str, Any], dict[str, Any]]: + obs, info = super().reset(seed=seed, options=options) + self._samples = [] + self._prev_tau = None + return obs, info + + def close(self): + callbacks = getattr(self.sim, "substep_callbacks", []) + if self._sample in callbacks: + callbacks.remove(self._sample) + super().close() + + class GripperWrapperSim(ActObsInfoWrapper): def __init__(self, env): super().__init__(env) diff --git a/python/tests/test_sim_control_states.py b/python/tests/test_sim_control_states.py new file mode 100644 index 00000000..1fc1fdb5 --- /dev/null +++ b/python/tests/test_sim_control_states.py @@ -0,0 +1,79 @@ +import numpy as np +import pytest +from rcs._core.sim import SimConfig +from rcs.envs.configs import EmptyWorldFR3, EmptyWorldFR3Duo +from rcs.envs.scenes import SimEnvCreatorConfig + +FREQUENCY = 15 + + +def _cfg(creator, record: bool, async_control: bool = True) -> SimEnvCreatorConfig: + cfg = creator.config() + cfg.sim_cfg = SimConfig(async_control=async_control, realtime=False, frequency=FREQUENCY, max_convergence_steps=500) + cfg.headless = True + cfg.camera_cfgs = None + cfg.camera_adds = None + cfg.wrapper_cfg.record_control_states = record + return cfg + + +def _zero_action(env): + return { + name: {"tquat": np.array([0, 0, 0, 0, 0, 0, 1.0]), "gripper": np.array([1.0])} + for name in env.get_wrapper_attr("envs") + } + + +@pytest.mark.parametrize("creator_cls", [EmptyWorldFR3, EmptyWorldFR3Duo]) +def test_sim_control_states_match_hardware_layout(creator_cls): + creator = creator_cls() + env = creator.create_env(_cfg(creator, record=True)) + try: + env.reset() + sim = env.get_wrapper_attr("sim") + expected = round(1 / FREQUENCY / sim.model.opt.timestep) + for _ in range(3): + _, _, _, _, info = env.step(_zero_action(env)) + for robot_name in env.get_wrapper_attr("envs"): + states = info[robot_name]["control_states"] + n = states["num_samples"] + assert n == expected + assert states["timestamp"].shape == (n,) + assert states["q"].shape == (n, 7) + assert states["dq"].shape == (n, 7) + assert states["tau_J"].shape == (n, 7) + assert states["dtau_J"].shape == (n, 7) + assert states["tau_ext_hat_filtered"].shape == (n, 7) + assert states["O_F_ext_hat_K"].shape == (n, 6) + assert states["O_T_EE"].shape == (n, 16) + assert states["robot_mode"].shape == (n,) + # robot time advances by one physics step per sample + assert np.allclose(np.diff(states["robot_time"]), sim.model.opt.timestep) + # the last sample is the state the observation was taken in + o_t_ee = states["O_T_EE"][-1].reshape(4, 4, order="F") + assert np.allclose(o_t_ee[3], [0, 0, 0, 1]) + finally: + env.close() + + +def test_sim_control_states_are_opt_in(): + creator = EmptyWorldFR3() + env = creator.create_env(_cfg(creator, record=False)) + try: + env.reset() + _, _, _, _, info = env.step(_zero_action(env)) + assert "control_states" not in info[next(iter(env.get_wrapper_attr("envs")))] + assert not getattr(env.get_wrapper_attr("sim"), "substep_callbacks", []) + finally: + env.close() + + +def test_sim_control_states_sync_mode_records_one_sample(): + creator = EmptyWorldFR3() + env = creator.create_env(_cfg(creator, record=True, async_control=False)) + try: + env.reset() + _, _, _, _, info = env.step(_zero_action(env)) + assert info[next(iter(env.get_wrapper_attr("envs")))]["control_states"]["num_samples"] == 1 + finally: + env.close() From cba1bcf957603d8fc07f94c0c63aeb826b61f9b8 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sun, 15 Nov 2026 13:34:02 -0800 Subject: [PATCH 07/63] feat(fr3): enable control state recording from the wrapper config WrapperConfig.record_control_states now switches on the 1 kHz state recording of the FR3 as well, so the same flag works in sim and on hardware. --- extensions/rcs_fr3/src/rcs_fr3/creators.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/extensions/rcs_fr3/src/rcs_fr3/creators.py b/extensions/rcs_fr3/src/rcs_fr3/creators.py index 57a1f7b0..762b6743 100644 --- a/extensions/rcs_fr3/src/rcs_fr3/creators.py +++ b/extensions/rcs_fr3/src/rcs_fr3/creators.py @@ -190,6 +190,8 @@ def create_env(self, cfg: FR3HardwareEnvCreatorConfig) -> gym.Env: urdf=cfg.robot_cfg.kinematic_model_path.endswith(".urdf"), joint_limits=cfg.robot_cfg.joint_limits, ) + if cfg.wrapper_cfg.record_control_states: + cfg.robot_cfg.record_control_states = True robot = hw.Franka(cfg.robot_cfg, ik) env: gym.Env = HardwareEnv(frequency=cfg.frequency) From 5a5600b2e25599380de235dd534749d5771a1754 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sun, 15 Nov 2026 13:44:54 -0800 Subject: [PATCH 08/63] feat(webui): add extension with reproducible env config snapshots New pure Python extension rcs_webui. snapshot.py serializes the complete env creator config (dataclasses with pybind11 robot, gripper, camera and sim configs, poses, enums, arrays) into tagged JSON that can be loaded back into a config, supports dotted path overrides and logs the git commit, branch, untracked files and diff of every repository in use. --- extensions/rcs_webui/Makefile | 18 ++ extensions/rcs_webui/pyproject.toml | 35 +++ .../rcs_webui/src/rcs_webui/__init__.py | 3 + .../rcs_webui/src/rcs_webui/snapshot.py | 265 ++++++++++++++++++ extensions/rcs_webui/tests/test_snapshot.py | 86 ++++++ 5 files changed, 407 insertions(+) create mode 100644 extensions/rcs_webui/Makefile create mode 100644 extensions/rcs_webui/pyproject.toml create mode 100644 extensions/rcs_webui/src/rcs_webui/__init__.py create mode 100644 extensions/rcs_webui/src/rcs_webui/snapshot.py create mode 100644 extensions/rcs_webui/tests/test_snapshot.py diff --git a/extensions/rcs_webui/Makefile b/extensions/rcs_webui/Makefile new file mode 100644 index 00000000..4c746c8c --- /dev/null +++ b/extensions/rcs_webui/Makefile @@ -0,0 +1,18 @@ +PYSRC = src/rcs_webui +TESTSRC = tests + +pycheckformat: + isort --check-only ${PYSRC} ${TESTSRC} + black --check ${PYSRC} ${TESTSRC} + +pyformat: + isort ${PYSRC} ${TESTSRC} + black ${PYSRC} ${TESTSRC} + +ruff: + ruff check ${PYSRC} ${TESTSRC} + +pytest: + python -m pytest ${TESTSRC} + +.PHONY: pycheckformat pyformat ruff pytest diff --git a/extensions/rcs_webui/pyproject.toml b/extensions/rcs_webui/pyproject.toml new file mode 100644 index 00000000..83174194 --- /dev/null +++ b/extensions/rcs_webui/pyproject.toml @@ -0,0 +1,35 @@ +[build-system] +requires = ["setuptools>=61"] +build-backend = "setuptools.build_meta" + +[project] +name = "rcs_webui" +version = "0.7.4" +description = "RCS web interface for data collection and evaluation" +readme = "README.md" +license = "AGPL-3.0-or-later" +# only uses what rcs-core already depends on (standard library http server, pyarrow, simplejpeg, typer) +dependencies = ["rcs-core>=0.7.4"] +maintainers = [{ name = "Tobias Juelg", email = "tobias.juelg@utn.de" }] +authors = [{ name = "Tobias Juelg", email = "tobias.juelg@utn.de" }] +requires-python = ">=3.11" + +[project.optional-dependencies] +# client of the policy server used in eval mode +eval = ["vlagents"] + +[project.scripts] +rcs-webui = "rcs_webui.cli:main" + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.setuptools.package-data] +rcs_webui = ["static/*"] + +[tool.black] +line-length = 120 +target-version = ["py310"] + +[tool.isort] +profile = "black" diff --git a/extensions/rcs_webui/src/rcs_webui/__init__.py b/extensions/rcs_webui/src/rcs_webui/__init__.py new file mode 100644 index 00000000..0e950781 --- /dev/null +++ b/extensions/rcs_webui/src/rcs_webui/__init__.py @@ -0,0 +1,3 @@ +"""Web interface for data collection and evaluation with RCS.""" + +__version__ = "0.7.4" diff --git a/extensions/rcs_webui/src/rcs_webui/snapshot.py b/extensions/rcs_webui/src/rcs_webui/snapshot.py new file mode 100644 index 00000000..875dd169 --- /dev/null +++ b/extensions/rcs_webui/src/rcs_webui/snapshot.py @@ -0,0 +1,265 @@ +"""Reproducibility snapshot of an env start: the complete env config as JSON, git commit and git diff. + +The env creator configs are dataclasses that contain pybind11 objects (robot, gripper, camera and sim configs, +poses, enums). They are serialized into plain JSON with type tags so that a new env can be created from the +stored file again, see :func:`config_to_json` and :func:`config_from_json`. +""" + +import dataclasses +import datetime +import enum +import importlib +import json +import logging +import re +import subprocess +import typing +from pathlib import Path +from typing import Any + +import numpy as np + +from rcs import common + +logger = logging.getLogger(__name__) + +CONFIG_FILE = "env_config.json" +SESSION_FILE = "session.json" +GIT_FILE = "git.json" +DIFF_SUFFIX = ".diff" +DATA_DIR = "data" + +# fields that only exist at runtime and must not be stored +_SKIP_FIELDS = {"_original_cfg"} + + +def _qualname(obj_type: type) -> str: + return f"{obj_type.__module__}:{obj_type.__qualname__}" + + +def _import(qualname: str) -> Any: + module_name, _, attr_path = qualname.partition(":") + obj: Any = importlib.import_module(module_name) + for attr in attr_path.split("."): + obj = getattr(obj, attr) + return obj + + +def _is_pybind_enum(value: Any) -> bool: + return hasattr(type(value), "__members__") and hasattr(value, "name") and hasattr(value, "value") + + +def _readwrite_properties(obj_type: type) -> list[str]: + names = [] + for name in dir(obj_type): + attr = getattr(obj_type, name, None) + if isinstance(attr, property) and attr.fset is not None and not name.startswith("_"): + names.append(name) + return names + + +def to_jsonable(value: Any) -> Any: + """Converts a config (dataclasses, pybind11 configs, poses, enums, numpy arrays) into JSON compatible data.""" + if value is None or isinstance(value, bool | int | float | str): + return value + if isinstance(value, enum.Enum): + return {"__enum__": _qualname(type(value)), "name": value.name} + if isinstance(value, np.generic): + return value.item() + if isinstance(value, np.ndarray): + return {"__ndarray__": value.tolist(), "dtype": str(value.dtype)} + if isinstance(value, common.Pose): + return {"__pose__": value.pose_matrix().tolist()} + if isinstance(value, type): + return {"__type__": _qualname(value)} + if dataclasses.is_dataclass(value): + return { + "__dataclass__": _qualname(type(value)), + "fields": { + f.name: to_jsonable(getattr(value, f.name)) + for f in dataclasses.fields(value) + if f.name not in _SKIP_FIELDS + }, + } + if isinstance(value, dict): + if all(isinstance(k, str) for k in value): + return {k: to_jsonable(v) for k, v in value.items()} + return {"__items__": [[to_jsonable(k), to_jsonable(v)] for k, v in value.items()]} + if isinstance(value, tuple): + return {"__tuple__": [to_jsonable(v) for v in value]} + if isinstance(value, list): + return [to_jsonable(v) for v in value] + if _is_pybind_enum(value): + return {"__enum__": _qualname(type(value)), "name": value.name} + obj_type = type(value) + props = _readwrite_properties(obj_type) + if props: + return { + "__object__": _qualname(obj_type), + "fields": {name: to_jsonable(getattr(value, name)) for name in props}, + } + if hasattr(value, "id") and isinstance(value.id, str): + # e.g. RobotType / GripperType which are constructed from their id + return {"__object__": _qualname(obj_type), "init": [value.id]} + msg = f"cannot serialize config value of type {obj_type}" + raise TypeError(msg) + + +def _init_kwargs(cls: type, fields: dict[str, Any]) -> dict[str, Any]: + """Keyword arguments of a pybind11 constructor that are present in the stored fields.""" + doc = getattr(getattr(cls, "__init__", None), "__doc__", None) or "" + names = set(re.findall(r"(\w+):", doc)) + return {k: v for k, v in fields.items() if k in names} + + +def from_jsonable(value: Any) -> Any: + """Inverse of :func:`to_jsonable`.""" + if isinstance(value, list): + return [from_jsonable(v) for v in value] + if not isinstance(value, dict): + return value + if "__enum__" in value: + enum_type = _import(value["__enum__"]) + return enum_type[value["name"]] if isinstance(enum_type, enum.EnumMeta) else getattr(enum_type, value["name"]) + if "__ndarray__" in value: + return np.array(value["__ndarray__"], dtype=value["dtype"]) + if "__pose__" in value: + return common.Pose(pose_matrix=np.array(value["__pose__"])) + if "__type__" in value: + return _import(value["__type__"]) + if "__tuple__" in value: + return tuple(from_jsonable(v) for v in value["__tuple__"]) + if "__items__" in value: + return {from_jsonable(k): from_jsonable(v) for k, v in value["__items__"]} + if "__dataclass__" in value: + cls = _import(value["__dataclass__"]) + fields = {k: from_jsonable(v) for k, v in value["fields"].items()} + known = {f.name for f in dataclasses.fields(cls) if f.init} + return cls(**{k: v for k, v in fields.items() if k in known}) + if "__object__" in value: + cls = _import(value["__object__"]) + if "init" in value: + return cls(*value["init"]) + fields = {k: from_jsonable(v) for k, v in value["fields"].items()} + try: + obj = cls() + except TypeError: + obj = cls(**_init_kwargs(cls, fields)) + for name, field_value in fields.items(): + try: + setattr(obj, name, field_value) + except (AttributeError, TypeError) as e: + logger.warning("could not restore %s.%s: %s", cls.__name__, name, e) + return obj + return {k: from_jsonable(v) for k, v in value.items()} + + +def config_to_json(cfg: Any) -> str: + return json.dumps(to_jsonable(cfg), indent=2) + + +def config_from_json(text: str) -> Any: + return from_jsonable(json.loads(text)) + + +def apply_overrides(cfg_json: Any, overrides: dict[str, Any]) -> Any: + """Sets values in a serialized config, keys are dotted paths, e.g. ``{"sim_cfg.frequency": 15}``. + + Path elements walk through dict keys and the ``fields`` of dataclasses and pybind11 objects. Values are + given in the serialized form (plain JSON for numbers, strings, lists, booleans). + """ + for path, new_value in overrides.items(): + node = cfg_json + parts = path.split(".") + for part in parts[:-1]: + node = _child(node, part, path) + last = parts[-1] + container = node["fields"] if isinstance(node, dict) and "fields" in node else node + if not isinstance(container, dict) or (last not in container and "fields" in node): + msg = f"unknown config key {path!r}" + raise KeyError(msg) + old = container.get(last) + value = new_value + if isinstance(old, dict) and "__ndarray__" in old and isinstance(new_value, list): + value = {"__ndarray__": new_value, "dtype": old["dtype"]} + elif isinstance(old, dict) and "__enum__" in old and isinstance(new_value, str): + value = {"__enum__": old["__enum__"], "name": new_value} + container[last] = value + return cfg_json + + +def _child(node: Any, part: str, path: str) -> Any: + if isinstance(node, dict) and "fields" in node: + node = node["fields"] + if isinstance(node, dict) and part in node: + return node[part] + msg = f"unknown config key {path!r} (at {part!r})" + raise KeyError(msg) + + +def _git(args: list[str], cwd: Path) -> str | None: + try: + out = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, check=True, timeout=30) + except (OSError, subprocess.SubprocessError): + return None + return out.stdout + + +def git_state(path: Path) -> dict[str, Any] | None: + """Commit, branch and diff (incl. untracked file names) of the git repository that contains path.""" + path = path if path.is_dir() else path.parent + root = _git(["rev-parse", "--show-toplevel"], path) + if root is None: + return None + root_path = Path(root.strip()) + return { + "root": str(root_path), + "commit": (_git(["rev-parse", "HEAD"], root_path) or "").strip(), + "branch": (_git(["rev-parse", "--abbrev-ref", "HEAD"], root_path) or "").strip(), + "remote": (_git(["remote", "get-url", "origin"], root_path) or "").strip(), + "untracked": (_git(["ls-files", "--others", "--exclude-standard"], root_path) or "").splitlines(), + "diff": _git(["diff", "HEAD"], root_path) or "", + } + + +def code_locations() -> dict[str, Path]: + """Source locations whose git state is logged: RCS itself, its extensions and the current working directory.""" + import rcs + + locations = {"rcs": Path(rcs.__file__).resolve()} + for name in ("rcs_fr3", "rcs_webui", "rcs_robotiq2f85", "rcs_realsense", "rcs_zed"): + try: + module = importlib.import_module(name) + except Exception: + continue + if getattr(module, "__file__", None): + locations[name] = Path(typing.cast(str, module.__file__)).resolve() + locations["cwd"] = Path.cwd() + return locations + + +def write_snapshot(session_dir: Path, cfg: Any, meta: dict[str, Any]) -> None: + """Writes env_config.json, session.json, git.json and one .diff per git repository.""" + session_dir.mkdir(parents=True, exist_ok=True) + (session_dir / CONFIG_FILE).write_text(config_to_json(cfg)) + repos: dict[str, dict[str, Any]] = {} + for name, location in code_locations().items(): + state = git_state(location) + if state is None or any(r["root"] == state["root"] for r in repos.values()): + continue + diff = state.pop("diff") + diff_name = f"{name}{DIFF_SUFFIX}" + (session_dir / diff_name).write_text(diff) + state["diff_file"] = diff_name + state["dirty"] = bool(diff.strip()) or bool(state["untracked"]) + repos[name] = state + (session_dir / GIT_FILE).write_text(json.dumps(repos, indent=2)) + meta = {"created": datetime.datetime.now().isoformat(timespec="seconds"), **meta} + (session_dir / SESSION_FILE).write_text(json.dumps(meta, indent=2, default=str)) + + +def load_session_config(session_dir: Path) -> tuple[Any, dict[str, Any]]: + """Loads the env config and the session meta data of a previous recording.""" + cfg = config_from_json((session_dir / CONFIG_FILE).read_text()) + meta = json.loads((session_dir / SESSION_FILE).read_text()) if (session_dir / SESSION_FILE).exists() else {} + return cfg, meta diff --git a/extensions/rcs_webui/tests/test_snapshot.py b/extensions/rcs_webui/tests/test_snapshot.py new file mode 100644 index 00000000..21249d82 --- /dev/null +++ b/extensions/rcs_webui/tests/test_snapshot.py @@ -0,0 +1,86 @@ +import json +import subprocess + +import numpy as np +import pytest +from rcs.envs.base import ControlMode +from rcs.envs.configs import EmptyWorldDroid, EmptyWorldFR3, EmptyWorldFR3Duo +from rcs_webui import snapshot + + +def _assert_close(a, b, path="cfg"): + """Compares two serialized configs, poses may differ by float noise.""" + if isinstance(a, dict): + assert isinstance(b, dict), path + assert a.keys() == b.keys(), path + for k in a: + _assert_close(a[k], b[k], f"{path}.{k}") + elif isinstance(a, list): + assert len(a) == len(b), path + for i, (x, y) in enumerate(zip(a, b, strict=True)): + _assert_close(x, y, f"{path}[{i}]") + elif isinstance(a, float): + assert a == pytest.approx(b, abs=1e-9), path + else: + assert a == b, path + + +@pytest.mark.parametrize("creator", [EmptyWorldFR3(), EmptyWorldFR3Duo(), EmptyWorldDroid()]) +def test_config_round_trip(creator): + cfg = creator.config() + text = snapshot.config_to_json(cfg) + restored = snapshot.config_from_json(text) + _assert_close(json.loads(text), json.loads(snapshot.config_to_json(restored))) + assert type(restored) is type(cfg) + assert restored.control_mode == cfg.control_mode + name = next(iter(cfg.robot_cfgs)) + assert np.allclose(restored.robot_cfgs[name].q_home, cfg.robot_cfgs[name].q_home) + assert restored.robot_cfgs[name].tcp_offset.is_close(cfg.robot_cfgs[name].tcp_offset) + + +def test_fr3_hardware_config_round_trip(): + configs = pytest.importorskip("rcs_fr3.configs") + cfg = configs.DefaultFR3HardwareEnv().config() + cfg.robot_cfg.record_control_states = True + restored = snapshot.config_from_json(snapshot.config_to_json(cfg)) + assert restored.robot_cfg.ip == cfg.robot_cfg.ip + assert restored.robot_cfg.record_control_states is True + assert restored.gripper_cfg.force == cfg.gripper_cfg.force + assert restored.camera_cfgs["realsense"].camera_cfgs["side"].identifier == "243522070385" + + +def test_overrides(): + cfg_json = snapshot.to_jsonable(EmptyWorldFR3().config()) + snapshot.apply_overrides( + cfg_json, + { + "sim_cfg.frequency": 20, + "control_mode": "JOINTS", + "robot_cfgs.right.q_home": [0.0] * 7, + "camera_cfgs.wrist.resolution_width": 64, + }, + ) + cfg = snapshot.from_jsonable(cfg_json) + assert cfg.sim_cfg.frequency == 20 + assert cfg.control_mode == ControlMode.JOINTS + assert np.allclose(cfg.robot_cfgs["right"].q_home, 0) + assert cfg.camera_cfgs["wrist"].resolution_width == 64 + with pytest.raises(KeyError): + snapshot.apply_overrides(cfg_json, {"sim_cfg.does_not_exist": 1}) + + +def test_git_state_logs_commit_and_diff(tmp_path): + repo = tmp_path / "repo" + repo.mkdir() + git = ["git", "-C", str(repo), "-c", "user.name=t", "-c", "user.email=t@t"] + subprocess.run([*git, "init", "-q"], check=True) + (repo / "a.txt").write_text("a\n") + subprocess.run([*git, "add", "a.txt"], check=True) + subprocess.run([*git, "commit", "-q", "-m", "init"], check=True) + (repo / "a.txt").write_text("b\n") + (repo / "new.txt").write_text("new\n") + state = snapshot.git_state(repo) + assert state is not None + assert len(state["commit"]) == 40 + assert "+b" in state["diff"] + assert state["untracked"] == ["new.txt"] From 8e3bc3d89287ec962b26558b0d8d660cb37937af Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sun, 15 Nov 2026 13:44:54 -0800 Subject: [PATCH 09/63] feat(webui): session runner for Quest labelled recording The runner thread owns the env, the Quest operator and the StorageWrapper. A starts an episode (recording), B ends it successful, Y unsuccessful, a truncating env (robot error) ends it as unsuccessful. Every env (re)start writes a new folder with env_config.json, session.json, git.json and the diffs next to the parquet data. Default configs are adapted for recording (control state forwarding, async control at the step rate, Quest action space), configs from a file or a previous recording are used as stored. --- extensions/rcs_webui/src/rcs_webui/envs.py | 107 +++++ extensions/rcs_webui/src/rcs_webui/hw_envs.py | 39 ++ extensions/rcs_webui/src/rcs_webui/session.py | 386 ++++++++++++++++++ 3 files changed, 532 insertions(+) create mode 100644 extensions/rcs_webui/src/rcs_webui/envs.py create mode 100644 extensions/rcs_webui/src/rcs_webui/hw_envs.py create mode 100644 extensions/rcs_webui/src/rcs_webui/session.py diff --git a/extensions/rcs_webui/src/rcs_webui/envs.py b/extensions/rcs_webui/src/rcs_webui/envs.py new file mode 100644 index 00000000..6d49d2f6 --- /dev/null +++ b/extensions/rcs_webui/src/rcs_webui/envs.py @@ -0,0 +1,107 @@ +"""Which env creators the interface can start and how their default configs are adapted for recording.""" + +import dataclasses +import importlib +import logging +from typing import Any + +import gymnasium as gym +import rcs.envs.configs # noqa: F401 registers the rcs/* sim envs +from rcs.envs.base import ControlMode, RelativeTo +from rcs.envs.scenes import RCSEnvCreator, SimEnvCreatorConfig + +logger = logging.getLogger(__name__) + +# hardware creators of the FR3 extension, only available if rcs_fr3 is installed +HARDWARE_CREATORS = { + "fr3": "rcs_webui.hw_envs:SingleFR3Env", + "fr3_duo": "rcs_fr3.configs:FrankaDuoEnv", + "fr3_dual": "rcs_fr3.configs:DefaultFR3DualMultiHardwareEnv", + "droid": "rcs_fr3.configs:DROIDEnv", +} + + +def available_envs() -> list[str]: + """Names that can be passed to :func:`load_creator`: registered rcs gym ids and the hardware creators.""" + names = [name for name in gym.registry if name.startswith("rcs/")] + try: + importlib.import_module("rcs_fr3") + names += list(HARDWARE_CREATORS) + except ImportError: + pass + return sorted(names) + + +def load_creator(name: str) -> RCSEnvCreator: + """Returns an env creator by gym id (``rcs/fr3``), hardware short name (``fr3_duo``) or import path + (``my_package.my_module:MyCreator``).""" + if name in HARDWARE_CREATORS: + name = HARDWARE_CREATORS[name] + if ":" in name: + module_name, _, attr = name.partition(":") + creator = getattr(importlib.import_module(module_name), attr) + return creator() if isinstance(creator, type) else creator + entry_point = gym.spec(name).entry_point + if isinstance(entry_point, str): + module_name, _, attr = entry_point.partition(":") + entry_point = getattr(importlib.import_module(module_name), attr) + if not isinstance(entry_point, RCSEnvCreator): + msg = f"{name} is not registered with an RCSEnvCreator entry point" + raise TypeError(msg) + return entry_point + + +def creator_name(creator: RCSEnvCreator) -> str: + return f"{type(creator).__module__}:{type(creator).__qualname__}" + + +def is_sim_config(cfg: Any) -> bool: + return isinstance(cfg, SimEnvCreatorConfig) + + +def _robot_cfgs(cfg: Any) -> list[Any]: + if hasattr(cfg, "robot_cfgs"): + return list(cfg.robot_cfgs.values()) + if hasattr(cfg, "robot_cfg"): + return [cfg.robot_cfg] + return [] + + +def prepare_config( + cfg: Any, + *, + frequency: float, + control_mode: tuple[ControlMode, RelativeTo] | None, + headless: bool, +) -> Any: + """Adapts a default creator config for recording with the interface. + + Applied only to default configs (a config loaded from a previous recording is used as stored): + + - the forwarding of the controller rate robot states is switched on (``wrapper_cfg.record_control_states``) + - the env runs at ``frequency`` (sim: async control in realtime, hardware: rate limited steps and the + controller interpolation window), asynchronous control so that the controller thread runs + - the action space matches the operator (e.g. Quest: tquat relative to the configured origin) + """ + if hasattr(cfg, "wrapper_cfg"): + cfg.wrapper_cfg.record_control_states = True + if control_mode is not None: + cfg.control_mode = control_mode[0] + cfg.relative_to = control_mode[1] + if cfg.max_relative_movement is None and control_mode[1] != RelativeTo.NONE: + import numpy as np + + cfg.max_relative_movement = 0.5 if control_mode[0] == ControlMode.JOINTS else (0.5, np.deg2rad(90)) + if is_sim_config(cfg): + cfg.sim_cfg.async_control = True + cfg.sim_cfg.realtime = True + cfg.sim_cfg.frequency = frequency + cfg.headless = headless + else: + if dataclasses.is_dataclass(cfg) and hasattr(cfg, "frequency"): + cfg.frequency = frequency + for robot_cfg in _robot_cfgs(cfg): + for attr, value in (("async_control", True), ("policy_rate", int(round(frequency)))): + if hasattr(robot_cfg, attr): + setattr(robot_cfg, attr, value) + return cfg diff --git a/extensions/rcs_webui/src/rcs_webui/hw_envs.py b/extensions/rcs_webui/src/rcs_webui/hw_envs.py new file mode 100644 index 00000000..8dfad1ad --- /dev/null +++ b/extensions/rcs_webui/src/rcs_webui/hw_envs.py @@ -0,0 +1,39 @@ +"""Hardware env creators for the interface, needs the rcs_fr3 extension. + +The interface always talks to a multi robot env (actions and observations keyed by robot name, like the +Quest operator produces them), so a single FR3 is wrapped as a multi robot env with one robot ``right``. +""" + +import numpy as np +from rcs.envs.base import ControlMode, RelativeTo +from rcs_fr3.configs import DefaultFR3HardwareEnv +from rcs_fr3.creators import ( + FR3MultiHardwareEnvCreatorConfig, + RCSFR3MultiConfigEnvCreator, +) + +from rcs import common + + +class SingleFR3Env(RCSFR3MultiConfigEnvCreator): + """One FR3 with Franka Hand, robot name ``right`` (the right Quest controller). No cameras by default, + add them with a config file (see ``rcs-webui dump-config``).""" + + ip = "192.168.101.1" + + def config(self) -> FR3MultiHardwareEnvCreatorConfig: + base = DefaultFR3HardwareEnv() + base.ip = self.ip + cfg = base.config() + cfg.robot_cfg.async_control = True + if cfg.gripper_cfg is not None and hasattr(cfg.gripper_cfg, "async_control"): + cfg.gripper_cfg.async_control = True + return FR3MultiHardwareEnvCreatorConfig( + control_mode=ControlMode.CARTESIAN_TQuat, + robot_cfgs={"right": cfg.robot_cfg}, + gripper_cfgs={"right": cfg.gripper_cfg}, + camera_cfgs=None, + max_relative_movement=(0.5, np.deg2rad(90)), + relative_to=RelativeTo.CONFIGURED_ORIGIN, + robot_to_shared_base_frame={"right": common.Pose()}, + ) diff --git a/extensions/rcs_webui/src/rcs_webui/session.py b/extensions/rcs_webui/src/rcs_webui/session.py new file mode 100644 index 00000000..75be46fb --- /dev/null +++ b/extensions/rcs_webui/src/rcs_webui/session.py @@ -0,0 +1,386 @@ +"""The session runner owns the gym env, the operator (Meta Quest) and the recording. + +Everything that touches the env runs in one thread (the runner thread): env creation, stepping, resets and +closing. MuJoCo greenlets and hardware controllers are bound to the thread that created them, and the +recording stays strictly synchronous with the steps. The web server only puts commands into a queue and +reads a status snapshot. + +Episode protocol (the same for data collection, human intervention and eval): + +- ``A`` starts an episode: the recording of the StorageWrapper is started (and in eval the policy). +- ``B`` ends it as successful: the episode is marked successful, flushed and the env is reset. +- ``Y`` ends it as unsuccessful: the episode is flushed and the env is reset. +- if the env truncates or terminates (e.g. a reflex on the robot), the episode ends as unsuccessful, the + error is visible in the status and in the recorded data (``truncated`` and ``info.robot_error``). +""" + +import copy +import dataclasses +import datetime +import logging +import queue +import re +import threading +import time +import traceback +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import gymnasium as gym +import numpy as np +from rcs.envs.base import ControlMode, RelativeTo +from rcs.envs.storage_wrapper import StorageWrapper +from rcs.operator.interface import BaseOperator, TeleopCommands +from rcs.utils import SimpleFrameRate +from rcs_webui import envs, snapshot + +logger = logging.getLogger(__name__) + +QUEST_CONTROL_MODE = (ControlMode.CARTESIAN_TQuat, RelativeTo.CONFIGURED_ORIGIN) + + +@dataclass(kw_only=True) +class EnvSpec: + """What to start: a creator with its default config, a config file or the config of a previous recording, + each optionally with overrides (dotted paths into the serialized config, see snapshot.apply_overrides).""" + + env: str | None = None + config_file: Path | None = None + from_recording: Path | None = None + overrides: dict[str, Any] = field(default_factory=dict) + + +@dataclass(kw_only=True) +class SessionSettings: + data_root: Path + mode: str = "collect" + """collect (teleop) or eval (policy with optional human intervention)""" + instruction: str = "" + frequency: float = 15.0 + headless: bool = True + operator: str = "quest" + """quest or none (episodes are then controlled with the buttons of the web interface)""" + quest_addr: str = "10.42.0.1" + quest_switched_left_right: bool = False + batch_size: int = 32 + + +def _session_dir_name(env_name: str, mode: str) -> str: + stamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + short = re.sub(r"[^A-Za-z0-9_-]+", "-", env_name.rsplit(":", 1)[-1].rsplit("/", 1)[-1]).strip("-") + return f"{stamp}_{short}_{mode}" + + +class SessionRunner(threading.Thread): + """Runs the env loop in its own thread, see the module docstring.""" + + def __init__(self, settings: SessionSettings, env_spec: EnvSpec, operator: BaseOperator | None = None): + super().__init__(daemon=True, name="rcs-webui-session") + self.settings = settings + self.env_spec = env_spec + self._operator = operator + self._commands: queue.Queue[tuple[str, Any]] = queue.Queue() + self._lock = threading.Lock() + self._exit = threading.Event() + self.env: gym.Env | None = None + self.storage: StorageWrapper | None = None + self.session_dir: Path | None = None + self._cfg: Any = None + self._robot_names: list[str] = [] + self._control_mode: tuple[ControlMode, RelativeTo] | None = None + self._last_obs: dict[str, Any] = {} + self._episode_active = False + self._status: dict[str, Any] = { + "state": "starting", + "mode": settings.mode, + "env": None, + "session_dir": None, + "episode_active": False, + "episode_steps": 0, + "episodes": {"successful": 0, "unsuccessful": 0, "truncated": 0}, + "last_event": None, + "error": None, + "step_hz": 0.0, + "instruction": settings.instruction, + } + + # ---------------------------------------------------------------- public, thread safe + def status(self) -> dict[str, Any]: + with self._lock: + return copy.deepcopy(self._status) + + def submit(self, command: str, payload: Any = None): + """Commands: button (A, B or Y), restart (EnvSpec or None for the same spec), instruction (str), stop.""" + self._commands.put((command, payload)) + + def stop(self, timeout: float | None = 30.0): + self.submit("stop") + self._exit.set() + self.join(timeout) + + def latest_frame(self, camera: str) -> np.ndarray | None: + frames = self._last_obs.get("frames") if isinstance(self._last_obs, dict) else None + if not frames or camera not in frames: + return None + return frames[camera].get("rgb", {}).get("data") + + def cameras(self) -> list[str]: + frames = self._last_obs.get("frames") if isinstance(self._last_obs, dict) else None + return list(frames) if frames else [] + + # ---------------------------------------------------------------- internals + def _set_status(self, **kwargs): + with self._lock: + self._status.update(kwargs) + + def _event(self, message: str, level: int = logging.INFO): + logger.log(level, message) + self._set_status(last_event=f"{datetime.datetime.now().strftime('%H:%M:%S')} {message}") + + def _resolve_config(self, spec: EnvSpec) -> tuple[Any, str, dict[str, Any]]: + """Returns the config, the creator name and how it was obtained.""" + source: dict[str, Any] = {"overrides": spec.overrides} + if spec.from_recording is not None: + cfg, meta = snapshot.load_session_config(Path(spec.from_recording)) + name = meta.get("creator") + if name is None: + msg = f"{spec.from_recording} has no creator in its session.json" + raise ValueError(msg) + source["from_recording"] = str(spec.from_recording) + elif spec.config_file is not None: + cfg = snapshot.config_from_json(Path(spec.config_file).read_text()) + if spec.env is None: + msg = "a config file needs the env (creator) it belongs to" + raise ValueError(msg) + name = envs.creator_name(envs.load_creator(spec.env)) + source["config_file"] = str(spec.config_file) + else: + if spec.env is None: + msg = "no env given" + raise ValueError(msg) + creator = envs.load_creator(spec.env) + name = envs.creator_name(creator) + cfg = envs.prepare_config( + creator.config(), + frequency=self.settings.frequency, + control_mode=QUEST_CONTROL_MODE if self.settings.mode == "collect" else None, + headless=self.settings.headless, + ) + source["default_config_of"] = spec.env + if spec.overrides: + cfg = snapshot.from_jsonable(snapshot.apply_overrides(snapshot.to_jsonable(cfg), spec.overrides)) + return cfg, name, source + + def _close_env(self): + if self.storage is not None: + # flushes a running episode (unsuccessful) and waits for the writer + try: + self.storage.close() + except Exception: + logger.exception("closing the env failed") + self.env = None + self.storage = None + self._episode_active = False + + def _start_env(self, spec: EnvSpec): + self._close_env() + self._set_status(state="starting", error=None, episode_active=False, episode_steps=0) + cfg, name, source = self._resolve_config(spec) + creator = envs.load_creator(name) + session_dir = Path(self.settings.data_root) / _session_dir_name(spec.env or name, self.settings.mode) + snapshot.write_snapshot( + session_dir, + cfg, + { + "creator": name, + "mode": self.settings.mode, + "instruction": self.settings.instruction, + "frequency": self.settings.frequency, + "operator": self.settings.operator, + "source": source, + "data_dir": snapshot.DATA_DIR, + }, + ) + env = creator.create_env(cfg) + self.storage = StorageWrapper( + env, + str(session_dir / snapshot.DATA_DIR), + self.settings.instruction, + batch_size=self.settings.batch_size, + always_record=False, + ) + self.env = self.storage + self.session_dir = session_dir + self._cfg = cfg + self._control_mode = (cfg.control_mode, cfg.relative_to) if hasattr(cfg, "relative_to") else None + self.env_spec = spec + robot_envs = self.env.get_wrapper_attr("envs") + self._robot_names = list(robot_envs) if isinstance(robot_envs, dict) else [] + if self._operator is not None: + sim = self.env.get_wrapper_attr("sim") if envs.is_sim_config(cfg) else None + self._operator.sim = sim + self._reset_env() + self._set_status(state="ready", env=name, session_dir=str(session_dir)) + self._event(f"env {name} started, recording into {session_dir}") + + def _reset_env(self): + assert self.env is not None + self._last_obs, _ = self.env.reset() + if self._operator is not None: + self._operator.set_camera(self._last_obs) + self._operator.reset_operator_state() + self._episode_active = False + self._set_status(episode_active=False, episode_steps=0) + + def _hold_action(self) -> dict[str, Any]: + """Action that keeps every robot where it is.""" + actions: dict[str, Any] = {} + mode, relative_to = self._control_mode or QUEST_CONTROL_MODE + for robot in self._robot_names: + obs = self._last_obs.get(robot, {}) + act: dict[str, Any] = {} + if relative_to != RelativeTo.NONE: + if mode == ControlMode.JOINTS: + act["joints"] = np.zeros_like(obs.get("joints", np.zeros(7))) + elif mode == ControlMode.CARTESIAN_TRPY: + act["xyzrpy"] = np.zeros(6) + else: + act["tquat"] = np.array([0, 0, 0, 0, 0, 0, 1.0]) + elif mode == ControlMode.JOINTS: + act["joints"] = np.asarray(obs["joints"]).copy() + elif mode == ControlMode.CARTESIAN_TRPY: + act["xyzrpy"] = np.asarray(obs["xyzrpy"]).copy() + else: + act["tquat"] = np.asarray(obs["tquat"]).copy() + if "gripper" in obs: + act["gripper"] = np.asarray(obs["gripper"], dtype=np.float32).reshape(-1) + actions[robot] = act + return actions + + def _operator_action(self) -> dict[str, Any]: + actions = self._hold_action() + if self._operator is None: + return actions + for robot, act in self._operator.consume_action().items(): + if robot in actions: + actions[robot] = act + return actions + + def _end_episode(self, success: bool, reason: str): + assert self.storage is not None + if self._episode_active: + if success: + self.storage.success() + with self._lock: + key = "successful" if success else ("truncated" if reason == "truncated" else "unsuccessful") + self._status["episodes"][key] += 1 + self._event(f"episode ended: {reason}") + self._reset_env() + + def _start_episode(self): + assert self.storage is not None + if self._episode_active: + return + self.storage.set_instruction(self.settings.instruction) + self.storage.start_record() + self._episode_active = True + self._set_status(episode_active=True, episode_steps=0) + self._event("episode started") + + def _handle_buttons(self, cmds: TeleopCommands) -> bool: + """Returns True if the env was reset.""" + if cmds.record: + self._start_episode() + if cmds.success: + self._end_episode(True, "successful (B)") + return True + if cmds.failure: + self._end_episode(False, "unsuccessful (Y)") + return True + return False + + def _process_commands(self) -> TeleopCommands: + web = TeleopCommands() + while True: + try: + command, payload = self._commands.get_nowait() + except queue.Empty: + break + if command == "stop": + self._exit.set() + elif command == "button": + web.record |= payload == "A" + web.success |= payload == "B" + web.failure |= payload == "Y" + elif command == "restart": + try: + self._start_env(payload or self.env_spec) + except Exception as e: + self._fail(e) + elif command == "instruction": + self.settings.instruction = str(payload) + self._set_status(instruction=self.settings.instruction) + return web + + def _fail(self, e: BaseException): + logger.exception("session error") + self._set_status(state="error", error="".join(traceback.format_exception_only(type(e), e)).strip()) + self._close_env() + + def _tick(self, web: TeleopCommands): + assert self.env is not None + cmds = self._operator.consume_commands() if self._operator is not None else TeleopCommands() + cmds.record |= web.record + cmds.success |= web.success + cmds.failure |= web.failure + if self._handle_buttons(cmds): + return + for controller, reset in cmds.reset_origin_to_current.items(): + robot_envs = self.env.get_wrapper_attr("envs") + if reset and controller in robot_envs: + robot_envs[controller].get_wrapper_attr("set_origin_to_current")() + self._last_obs, _, terminated, truncated, info = self.env.step(self._operator_action()) + if self._operator is not None: + self._operator.set_camera(self._last_obs) + if self._episode_active: + with self._lock: + self._status["episode_steps"] += 1 + if terminated or truncated: + errors = {k: v.get("robot_error") for k, v in info.items() if isinstance(v, dict) and v.get("robot_error")} + self._set_status( + error=f"episode ended by the env: {errors or ('terminated' if terminated else 'truncated')}" + ) + self._end_episode(False, "truncated") + + def run(self): + try: + self._start_env(self.env_spec) + except Exception as e: + self._fail(e) + rate = SimpleFrameRate(None, "webui") + last = time.perf_counter() + while not self._exit.is_set(): + web = self._process_commands() + if self._exit.is_set(): + break + if self.env is None: + time.sleep(0.05) + continue + try: + self._tick(web) + except Exception as e: + self._fail(e) + continue + now = time.perf_counter() + self._set_status( + step_hz=round(1.0 / max(now - last, 1e-6), 1), state="recording" if self._episode_active else "ready" + ) + last = now + rate() + self._close_env() + self._set_status(state="stopped") + + +def with_overrides(spec: EnvSpec, **changes: Any) -> EnvSpec: + return dataclasses.replace(spec, **changes) From 261661bf091072142e36ab8f5c9a4f3316933c27 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sun, 15 Nov 2026 13:44:54 -0800 Subject: [PATCH 10/63] feat(webui): http server, session page and rcs-webui CLI Standard library HTTP server with a JSON API (status, A/B/Y buttons, instruction, env restart from the same, a default or a recorded config with overrides, live camera images) and a static page without external dependencies. rcs-webui collect starts env, operator and server; rcs-webui envs and rcs-webui dump-config help to write config files. --- .../rcs_webui/src/rcs_webui/__main__.py | 4 + extensions/rcs_webui/src/rcs_webui/cli.py | 166 ++++++++++++++ extensions/rcs_webui/src/rcs_webui/server.py | 216 ++++++++++++++++++ .../rcs_webui/src/rcs_webui/static/app.js | 132 +++++++++++ .../rcs_webui/src/rcs_webui/static/index.html | 73 ++++++ .../rcs_webui/src/rcs_webui/static/style.css | 77 +++++++ 6 files changed, 668 insertions(+) create mode 100644 extensions/rcs_webui/src/rcs_webui/__main__.py create mode 100644 extensions/rcs_webui/src/rcs_webui/cli.py create mode 100644 extensions/rcs_webui/src/rcs_webui/server.py create mode 100644 extensions/rcs_webui/src/rcs_webui/static/app.js create mode 100644 extensions/rcs_webui/src/rcs_webui/static/index.html create mode 100644 extensions/rcs_webui/src/rcs_webui/static/style.css diff --git a/extensions/rcs_webui/src/rcs_webui/__main__.py b/extensions/rcs_webui/src/rcs_webui/__main__.py new file mode 100644 index 00000000..9e649e2f --- /dev/null +++ b/extensions/rcs_webui/src/rcs_webui/__main__.py @@ -0,0 +1,4 @@ +from rcs_webui.cli import main + +if __name__ == "__main__": + main() diff --git a/extensions/rcs_webui/src/rcs_webui/cli.py b/extensions/rcs_webui/src/rcs_webui/cli.py new file mode 100644 index 00000000..e06193cc --- /dev/null +++ b/extensions/rcs_webui/src/rcs_webui/cli.py @@ -0,0 +1,166 @@ +"""Command line entry point: ``rcs-webui collect ...``, ``rcs-webui envs``, ``rcs-webui dump-config ...``.""" + +import json +import logging +import signal +import threading +from pathlib import Path +from typing import Annotated, Any, Optional + +import typer +from rcs_webui import envs, snapshot +from rcs_webui.server import App, make_server, serve_in_thread +from rcs_webui.session import ( + QUEST_CONTROL_MODE, + EnvSpec, + SessionRunner, + SessionSettings, +) + +logger = logging.getLogger("rcs_webui") + +app = typer.Typer(help="RCS web interface for data collection and evaluation.", no_args_is_help=True) + + +def parse_overrides(items: list[str] | None) -> dict[str, Any]: + """``key.path=value`` pairs, the value is parsed as JSON and taken as string if that fails.""" + overrides: dict[str, Any] = {} + for item in items or []: + key, sep, value = item.partition("=") + if not sep or not key: + msg = f"--set expects key.path=value, got {item!r}" + raise typer.BadParameter(msg) + try: + overrides[key] = json.loads(value) + except json.JSONDecodeError: + overrides[key] = value + return overrides + + +def _make_operator(settings: SessionSettings, is_sim: bool): + if settings.operator == "none": + return None + if settings.operator != "quest": + msg = f"unknown operator {settings.operator!r}, use quest or none" + raise typer.BadParameter(msg) + from rcs.operator.quest import QuestConfig, QuestOperator + + config = QuestConfig( + mq3_addr=settings.quest_addr, + simulation=is_sim, + switched_left_right=settings.quest_switched_left_right, + display_cameras=False, + read_frequency=90, + ) + operator = QuestOperator(config) + operator.start() + return operator + + +def run_interface(settings: SessionSettings, spec: EnvSpec, host: str, port: int): + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s") + settings.data_root.mkdir(parents=True, exist_ok=True) + is_sim = spec.env is not None and spec.env.startswith("rcs/") + if spec.from_recording is not None: + _, meta = snapshot.load_session_config(spec.from_recording) + is_sim = str(meta.get("creator", "")).startswith("rcs.envs.") + operator = _make_operator(settings, is_sim) + runner = SessionRunner(settings, spec, operator) + server = make_server(App(runner, settings.data_root), host, port) + stop = threading.Event() + signal.signal(signal.SIGINT, lambda *_: stop.set()) + signal.signal(signal.SIGTERM, lambda *_: stop.set()) + runner.start() + serve_in_thread(server) + logger.info("interface on http://%s:%d , data in %s", host, port, settings.data_root) + stop.wait() + logger.info("shutting down, flushing the recording") + server.shutdown() + runner.stop() + if operator is not None: + operator.close() + + +EnvOpt = Annotated[ + Optional[str], typer.Option("--env", "-e", help="env to start, see `rcs-webui envs` (e.g. rcs/fr3 or fr3)") +] +ConfigOpt = Annotated[ + Optional[Path], typer.Option("--config", help="env config JSON (e.g. from `rcs-webui dump-config`), needs --env") +] +FromRecOpt = Annotated[ + Optional[Path], typer.Option("--from-recording", help="session folder whose env_config.json is used") +] +SetOpt = Annotated[ + Optional[list[str]], typer.Option("--set", help="override a config value: key.path=json_value, repeatable") +] +DataRootOpt = Annotated[Path, typer.Option("--data-root", help="every env start creates a new folder in here")] + + +@app.command() +def collect( + env: EnvOpt = None, + config: ConfigOpt = None, + from_recording: FromRecOpt = None, + set_: SetOpt = None, + data_root: DataRootOpt = Path("rcs_data"), + instruction: Annotated[str, typer.Option(help="language instruction stored with every step")] = "", + frequency: Annotated[float, typer.Option(help="env step rate in Hz (default configs only)")] = 15.0, + operator: Annotated[str, typer.Option(help="quest or none (web buttons only)")] = "quest", + quest_addr: Annotated[str, typer.Option(help="IP of this PC in the network of the Quest")] = "10.42.0.1", + quest_switch_left_right: bool = False, + gui: Annotated[bool, typer.Option(help="open the MuJoCo viewer (sim only)")] = False, + host: Annotated[str, typer.Option(help="address of the web server")] = "0.0.0.0", + port: Annotated[int, typer.Option(help="port of the web server")] = 8080, +): + """Teleoperated data collection: Quest A starts an episode, B ends it successful, Y unsuccessful.""" + if sum(x is not None for x in (config, from_recording)) > 1: + msg = "use either --config or --from-recording" + raise typer.BadParameter(msg) + if env is None and from_recording is None: + msg = "--env or --from-recording is required" + raise typer.BadParameter(msg) + settings = SessionSettings( + data_root=data_root, + mode="collect", + instruction=instruction, + frequency=frequency, + headless=not gui, + operator=operator, + quest_addr=quest_addr, + quest_switched_left_right=quest_switch_left_right, + ) + spec = EnvSpec(env=env, config_file=config, from_recording=from_recording, overrides=parse_overrides(set_)) + run_interface(settings, spec, host, port) + + +@app.command("envs") +def list_envs(): + """Lists the envs that can be started.""" + for name in envs.available_envs(): + typer.echo(name) + + +@app.command("dump-config") +def dump_config( + env: Annotated[str, typer.Argument(help="env name, see `rcs-webui envs`")], + set_: SetOpt = None, + frequency: float = 15.0, + mode: Annotated[str, typer.Option(help="collect or eval, adapts the action space")] = "collect", +): + """Prints the config the interface would start the env with, edit it and pass it with --config.""" + cfg = envs.prepare_config( + envs.load_creator(env).config(), + frequency=frequency, + control_mode=QUEST_CONTROL_MODE if mode == "collect" else None, + headless=True, + ) + cfg_json = snapshot.apply_overrides(snapshot.to_jsonable(cfg), parse_overrides(set_)) + typer.echo(json.dumps(cfg_json, indent=2)) + + +def main(): + app() + + +if __name__ == "__main__": + main() diff --git a/extensions/rcs_webui/src/rcs_webui/server.py b/extensions/rcs_webui/src/rcs_webui/server.py new file mode 100644 index 00000000..0139700b --- /dev/null +++ b/extensions/rcs_webui/src/rcs_webui/server.py @@ -0,0 +1,216 @@ +"""HTTP server of the interface: a JSON API plus a single static page, standard library only.""" + +import json +import logging +import mimetypes +import re +import threading +from collections.abc import Callable +from http import HTTPStatus +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from importlib import resources +from pathlib import Path +from typing import Any +from urllib.parse import parse_qs, unquote, urlparse + +import numpy as np +import simplejpeg +from rcs_webui import envs, snapshot +from rcs_webui.session import EnvSpec, SessionRunner + +logger = logging.getLogger(__name__) + +Route = Callable[["Handler", re.Match, dict[str, Any]], Any] + + +class ApiError(Exception): + def __init__(self, status: HTTPStatus, message: str): + super().__init__(message) + self.status = status + + +class App: + """Routes of the interface. ``runner`` is None if the interface only shows recorded data.""" + + def __init__(self, runner: SessionRunner | None, data_root: Path): + self.runner = runner + self.data_root = Path(data_root) + self.get_routes: list[tuple[re.Pattern, Route]] = [] + self.post_routes: list[tuple[re.Pattern, Route]] = [] + self._register() + + def get(self, pattern: str): + def deco(fn: Route) -> Route: + self.get_routes.append((re.compile(f"^{pattern}$"), fn)) + return fn + + return deco + + def post(self, pattern: str): + def deco(fn: Route) -> Route: + self.post_routes.append((re.compile(f"^{pattern}$"), fn)) + return fn + + return deco + + def _need_runner(self) -> SessionRunner: + if self.runner is None: + raise ApiError(HTTPStatus.CONFLICT, "no env session is running (viewer only mode)") + return self.runner + + def _register(self): + @self.get("/api/status") + def status(_h, _m, _q): + if self.runner is None: + return {"state": "viewer", "data_root": str(self.data_root)} + return {**self.runner.status(), "data_root": str(self.data_root), "cameras": self.runner.cameras()} + + @self.get("/api/envs") + def list_envs(_h, _m, _q): + return {"envs": envs.available_envs()} + + @self.get("/api/sessions") + def sessions(_h, _m, _q): + out = [] + if self.data_root.exists(): + for d in sorted(self.data_root.iterdir(), reverse=True): + if (d / snapshot.CONFIG_FILE).exists(): + meta = ( + json.loads((d / snapshot.SESSION_FILE).read_text()) + if (d / snapshot.SESSION_FILE).exists() + else {} + ) + out.append({"name": d.name, **meta}) + return {"sessions": out} + + @self.get(r"/api/live/(?P[^/]+)\.jpg") + def live_frame(h, m, _q): + frame = self._need_runner().latest_frame(unquote(m["camera"])) + if frame is None: + raise ApiError(HTTPStatus.NOT_FOUND, "no frame") + h.send_bytes(simplejpeg.encode_jpeg(np.ascontiguousarray(frame), quality=70), "image/jpeg") + + @self.post("/api/button") + def button(_h, _m, body): + name = str(body.get("button", "")).upper() + if name not in ("A", "B", "Y"): + raise ApiError(HTTPStatus.BAD_REQUEST, "button must be A, B or Y") + self._need_runner().submit("button", name) + return {"ok": True} + + @self.post("/api/instruction") + def instruction(_h, _m, body): + self._need_runner().submit("instruction", body.get("instruction", "")) + return {"ok": True} + + @self.post("/api/restart") + def restart(_h, _m, body): + runner = self._need_runner() + overrides = body.get("overrides") or {} + if not isinstance(overrides, dict): + raise ApiError(HTTPStatus.BAD_REQUEST, "overrides must be an object of dotted paths to values") + from_recording = body.get("from_recording") + if from_recording: + path = (self.data_root / from_recording).resolve() + if self.data_root.resolve() not in path.parents: + raise ApiError(HTTPStatus.BAD_REQUEST, "from_recording must be a session in the data root") + spec = EnvSpec(from_recording=path, overrides=overrides) + elif body.get("env"): + spec = EnvSpec(env=body["env"], overrides=overrides) + else: + spec = EnvSpec( + env=runner.env_spec.env, + config_file=runner.env_spec.config_file, + from_recording=runner.env_spec.from_recording, + overrides={**runner.env_spec.overrides, **overrides}, + ) + runner.submit("restart", spec) + return {"ok": True} + + +class Handler(BaseHTTPRequestHandler): + app: App + server_version = "rcs-webui" + + def log_message(self, format: str, *args: Any): + logger.debug("%s %s", self.address_string(), format % args) + + def send_bytes(self, data: bytes, content_type: str, status: HTTPStatus = HTTPStatus.OK): + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(data) + + def send_json(self, value: Any, status: HTTPStatus = HTTPStatus.OK): + self.send_bytes(json.dumps(value, default=_json_default).encode(), "application/json", status) + + def _dispatch(self, routes: list[tuple[re.Pattern, Route]], body: dict[str, Any]): + path = urlparse(self.path).path + for pattern, fn in routes: + match = pattern.match(path) + if match: + try: + result = fn(self, match, body) + except ApiError as e: + self.send_json({"error": str(e)}, e.status) + return + except Exception as e: + logger.exception("request %s failed", path) + self.send_json({"error": f"{type(e).__name__}: {e}"}, HTTPStatus.INTERNAL_SERVER_ERROR) + return + if result is not None: + self.send_json(result) + return + if self.command == "GET" and self._static(path): + return + self.send_json({"error": "not found"}, HTTPStatus.NOT_FOUND) + + def _static(self, path: str) -> bool: + name = "index.html" if path in ("", "/") else path.lstrip("/") + if "/" in name or name.startswith("."): + return False + static = resources.files("rcs_webui") / "static" / name + if not static.is_file(): + return False + content_type = mimetypes.guess_type(name)[0] or "application/octet-stream" + self.send_bytes(static.read_bytes(), content_type) + return True + + def do_GET(self): + query = {k: v[-1] for k, v in parse_qs(urlparse(self.path).query).items()} + self._dispatch(self.app.get_routes, query) + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length) if length else b"{}" + try: + body = json.loads(raw or b"{}") + except json.JSONDecodeError: + self.send_json({"error": "body must be JSON"}, HTTPStatus.BAD_REQUEST) + return + self._dispatch(self.app.post_routes, body if isinstance(body, dict) else {}) + + +def _json_default(value: Any) -> Any: + if isinstance(value, np.ndarray): + return value.tolist() + if isinstance(value, np.generic): + return value.item() + if isinstance(value, Path): + return str(value) + return str(value) + + +def make_server(app: App, host: str, port: int) -> ThreadingHTTPServer: + handler = type("BoundHandler", (Handler,), {"app": app}) + server = ThreadingHTTPServer((host, port), handler) + server.daemon_threads = True + return server + + +def serve_in_thread(server: ThreadingHTTPServer) -> threading.Thread: + thread = threading.Thread(target=server.serve_forever, daemon=True, name="rcs-webui-http") + thread.start() + return thread diff --git a/extensions/rcs_webui/src/rcs_webui/static/app.js b/extensions/rcs_webui/src/rcs_webui/static/app.js new file mode 100644 index 00000000..7b6f94a4 --- /dev/null +++ b/extensions/rcs_webui/src/rcs_webui/static/app.js @@ -0,0 +1,132 @@ +"use strict"; + +const $ = (sel) => document.querySelector(sel); + +async function api(path, body) { + const opts = body === undefined ? {} : { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }; + const res = await fetch(path, opts); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || res.statusText); + return data; +} + +function esc(s) { + return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); +} + +// ------------------------------------------------------------------ tabs +function showTab(name) { + document.querySelectorAll(".tabpane").forEach((p) => (p.hidden = p.id !== `tab-${name}`)); + document.querySelectorAll(".tab").forEach((a) => a.classList.toggle("active", a.dataset.tab === name)); + window.dispatchEvent(new CustomEvent("tab", { detail: name })); +} +window.addEventListener("hashchange", () => showTab(location.hash.slice(1) || "session")); + +// ------------------------------------------------------------------ session +let knownCameras = ""; +let instructionTouched = false; + +function renderStatus(s) { + const state = $("#state"); + state.textContent = s.state === "recording" ? `recording (${s.episode_steps} steps)` : s.state; + state.className = `badge ${s.state}`; + if (s.state === "viewer") { + document.querySelector('[data-tab="session"]').hidden = true; + if (!location.hash) showTab("data"); + return; + } + const rows = [ + ["mode", s.mode], + ["env", s.env], + ["policy", s.policy ? `${s.policy.host}:${s.policy.port} (${s.policy.connected ? "connected" : "not connected"})` : null], + ["data folder", s.session_dir], + ["step rate", `${s.step_hz} Hz`], + ["episodes", `${s.episodes.successful} successful, ${s.episodes.unsuccessful} unsuccessful, ${s.episodes.truncated} ended by the robot`], + ["last event", s.last_event], + ].filter(([, v]) => v !== null && v !== undefined); + $("#status").innerHTML = rows.map(([k, v]) => `
${esc(k)}
${esc(v)}
`).join(""); + $("#error").textContent = s.error || ""; + if (!instructionTouched) $("#instruction").value = s.instruction || ""; + const cams = (s.cameras || []).join(","); + if (cams !== knownCameras) { + knownCameras = cams; + $("#cameras").innerHTML = (s.cameras || []) + .map((c) => `
${esc(c)}
${esc(c)}
`) + .join("") || '

no cameras in the observation

'; + } +} + +async function pollStatus() { + try { + renderStatus(await api("/api/status")); + } catch (e) { + $("#state").textContent = "offline"; + $("#state").className = "badge error"; + } + setTimeout(pollStatus, 500); +} + +function refreshCameras() { + if (!$("#tab-session").hidden) { + document.querySelectorAll("#cameras img").forEach((img) => { + img.src = `/api/live/${encodeURIComponent(img.dataset.cam)}.jpg?t=${Date.now()}`; + }); + } + setTimeout(refreshCameras, 200); +} + +document.querySelectorAll("[data-button]").forEach((b) => + b.addEventListener("click", () => api("/api/button", { button: b.dataset.button }).catch(alert)) +); + +$("#instruction").addEventListener("input", () => (instructionTouched = true)); +$("#instruction-form").addEventListener("submit", async (e) => { + e.preventDefault(); + await api("/api/instruction", { instruction: $("#instruction").value }).catch(alert); + instructionTouched = false; +}); + +async function fillRestartOptions() { + const src = $("#restart-source").value; + $("#env-label").hidden = src !== "env"; + $("#rec-label").hidden = src !== "recording"; + if (src === "env" && !$("#env-select").options.length) { + const { envs } = await api("/api/envs"); + $("#env-select").innerHTML = envs.map((e) => ``).join(""); + } + if (src === "recording") { + const { sessions } = await api("/api/sessions"); + $("#rec-select").innerHTML = sessions + .map((s) => ``) + .join(""); + } +} +$("#restart-source").addEventListener("change", fillRestartOptions); + +$("#restart-form").addEventListener("submit", async (e) => { + e.preventDefault(); + let overrides = {}; + const text = $("#overrides").value.trim(); + if (text) { + try { + overrides = JSON.parse(text); + } catch (err) { + alert(`overrides are not valid JSON: ${err}`); + return; + } + } + const body = { overrides }; + const src = $("#restart-source").value; + if (src === "env") body.env = $("#env-select").value; + if (src === "recording") body.from_recording = $("#rec-select").value; + if (!confirm("Restart the env? A running episode is stored as unsuccessful.")) return; + await api("/api/restart", body).catch(alert); +}); + +showTab(location.hash.slice(1) || "session"); +pollStatus(); +refreshCameras(); diff --git a/extensions/rcs_webui/src/rcs_webui/static/index.html b/extensions/rcs_webui/src/rcs_webui/static/index.html new file mode 100644 index 00000000..cdae6040 --- /dev/null +++ b/extensions/rcs_webui/src/rcs_webui/static/index.html @@ -0,0 +1,73 @@ + + + + + +RCS Web Interface + + + +
+

RCS

+ + ... +
+ +
+
+
+
+

Episode

+

Main control is the Meta Quest: A start, B successful, Y unsuccessful. The buttons below do the same.

+
+ + + +
+
+

+
+ +
+

Instruction

+
+ + +
+

Restart env

+

Every restart creates a new data folder with the complete env config, git commit and diff.

+
+ + + + + +
+
+
+ +
+

Cameras

+
+
+
+ + +
+ + + + diff --git a/extensions/rcs_webui/src/rcs_webui/static/style.css b/extensions/rcs_webui/src/rcs_webui/static/style.css new file mode 100644 index 00000000..f04cad21 --- /dev/null +++ b/extensions/rcs_webui/src/rcs_webui/static/style.css @@ -0,0 +1,77 @@ +:root { + --bg: #f6f7f9; + --card: #ffffff; + --text: #1d2330; + --muted: #677085; + --border: #dde1e8; + --accent: #2f6fde; + --ok: #1f8f4e; + --fail: #c23b3b; + --warn: #b7791f; +} +@media (prefers-color-scheme: dark) { + :root { + --bg: #14171c; + --card: #1d2128; + --text: #e6e9ef; + --muted: #9aa3b5; + --border: #2d333d; + --accent: #5b8ff0; + --ok: #3fb373; + --fail: #e06060; + --warn: #d9a441; + } +} +* { box-sizing: border-box; } +body { margin: 0; font: 15px/1.45 system-ui, sans-serif; background: var(--bg); color: var(--text); } +header { display: flex; align-items: center; gap: 24px; padding: 10px 16px; border-bottom: 1px solid var(--border); background: var(--card); position: sticky; top: 0; z-index: 2; } +header h1 { font-size: 18px; margin: 0; } +nav { display: flex; gap: 12px; flex: 1; } +nav a { color: var(--muted); text-decoration: none; padding: 4px 8px; border-radius: 6px; } +nav a.active { color: var(--text); background: var(--bg); } +main { padding: 16px; max-width: 1400px; margin: 0 auto; } +.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 16px; } +.card { background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 14px 16px; margin-bottom: 16px; } +.card h2 { font-size: 15px; margin: 4px 0 10px; } +.muted { color: var(--muted); font-size: 13px; } +.error { color: var(--fail); white-space: pre-wrap; } +.badge { padding: 3px 10px; border-radius: 999px; background: var(--bg); border: 1px solid var(--border); font-size: 13px; } +.badge.recording { background: var(--fail); color: #fff; border-color: var(--fail); } +.badge.ready { background: var(--ok); color: #fff; border-color: var(--ok); } +.badge.error { background: var(--warn); color: #fff; } +.buttons { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 10px; } +.btn { border: 1px solid var(--border); background: var(--bg); color: var(--text); border-radius: 8px; padding: 7px 14px; cursor: pointer; font: inherit; } +.btn:hover { border-color: var(--accent); } +.btn.start { border-color: var(--accent); } +.btn.ok { border-color: var(--ok); } +.btn.fail { border-color: var(--fail); } +.btn.small { padding: 3px 8px; font-size: 13px; } +dl { display: grid; grid-template-columns: max-content 1fr; gap: 2px 12px; margin: 0; font-size: 13px; } +dt { color: var(--muted); } +dd { margin: 0; overflow-wrap: anywhere; } +form { display: flex; flex-direction: column; gap: 8px; margin-bottom: 12px; } +form#instruction-form { flex-direction: row; } +input, select, textarea { width: 100%; font: inherit; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 6px 8px; } +label { display: flex; flex-direction: column; gap: 4px; font-size: 13px; color: var(--muted); } +.cameras { display: flex; flex-wrap: wrap; gap: 12px; } +.cameras figure { margin: 0; } +.cameras img { max-width: 100%; width: 420px; border-radius: 6px; background: #000; display: block; } +.cameras figcaption { font-size: 12px; color: var(--muted); } +table { border-collapse: collapse; width: 100%; font-size: 13px; } +th, td { text-align: left; padding: 5px 8px; border-bottom: 1px solid var(--border); } +tr.selected { background: var(--bg); } +tr.clickable { cursor: pointer; } +.pill { padding: 1px 8px; border-radius: 999px; font-size: 12px; } +.pill.ok { background: var(--ok); color: #fff; } +.pill.fail { background: var(--fail); color: #fff; } +.pill.warn { background: var(--warn); color: #fff; } +.plots { display: grid; grid-template-columns: repeat(auto-fit, minmax(420px, 1fr)); gap: 12px; } +.plot { border: 1px solid var(--border); border-radius: 8px; padding: 6px; } +.plot h3 { font-size: 13px; margin: 2px 4px 4px; font-weight: 600; } +.plot svg { width: 100%; height: 200px; display: block; } +.plot .legend { font-size: 11px; color: var(--muted); display: flex; flex-wrap: wrap; gap: 6px; padding: 0 4px; } +.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } +@media (max-width: 600px) { + header { gap: 10px; } + .plots { grid-template-columns: 1fr; } +} From 2236d30d25c1457e292a027f428056110dc860a5 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sun, 15 Nov 2026 13:44:54 -0800 Subject: [PATCH 11/63] test(webui): end to end recording in simulation Starts the interface on rcs/fr3 with the web buttons, records a successful and an unsuccessful episode, checks the snapshot files, the parquet rows (labels, steps, timestamps, control states, frames) and restarting from a previous recording with overrides. --- extensions/rcs_webui/tests/test_session.py | 125 +++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 extensions/rcs_webui/tests/test_session.py diff --git a/extensions/rcs_webui/tests/test_session.py b/extensions/rcs_webui/tests/test_session.py new file mode 100644 index 00000000..2dcf2327 --- /dev/null +++ b/extensions/rcs_webui/tests/test_session.py @@ -0,0 +1,125 @@ +"""End to end tests of the interface against the simulation (no Quest: the web buttons are used).""" + +import json +import time +import urllib.request +from pathlib import Path + +import numpy as np +import pyarrow.dataset as ds +import pytest +from rcs_webui import snapshot +from rcs_webui.server import App, make_server, serve_in_thread +from rcs_webui.session import EnvSpec, SessionRunner, SessionSettings + +SMALL_CAMERAS = { + f"camera_cfgs.{cam}.{key}": value + for cam in ("bird_eye", "wrist") + for key, value in (("resolution_width", 64), ("resolution_height", 48)) +} + + +def wait_for(predicate, timeout: float = 60.0, interval: float = 0.05): + end = time.time() + timeout + while time.time() < end: + if predicate(): + return + time.sleep(interval) + msg = "condition not reached in time" + raise TimeoutError(msg) + + +@pytest.fixture() +def interface(tmp_path): + settings = SessionSettings(data_root=tmp_path, mode="collect", instruction="pick", frequency=30.0, operator="none") + runner = SessionRunner(settings, EnvSpec(env="rcs/fr3", overrides=SMALL_CAMERAS)) + server = make_server(App(runner, tmp_path), "127.0.0.1", 0) + serve_in_thread(server) + runner.start() + wait_for(lambda: runner.status()["state"] in ("ready", "error")) + assert runner.status()["error"] is None + yield runner, f"http://127.0.0.1:{server.server_address[1]}", tmp_path + server.shutdown() + runner.stop() + + +def call(base: str, path: str, body: dict | None = None): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request(base + path, data=data, headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as res: + raw = res.read() + return json.loads(raw) if res.headers.get_content_type() == "application/json" else raw + + +def record_episode(runner: SessionRunner, base: str, button: str, steps: int = 10): + call(base, "/api/button", {"button": "A"}) + wait_for(lambda: runner.status()["episode_steps"] >= steps) + call(base, "/api/button", {"button": button}) + wait_for(lambda: not runner.status()["episode_active"]) + + +def read_session(session_dir: Path): + # wait until the writer thread has flushed (it runs in the background) + return ds.dataset(str(session_dir / snapshot.DATA_DIR), format="parquet").to_table() + + +def test_collect_records_episodes_with_snapshot(interface): + runner, base, data_root = interface + status = call(base, "/api/status") + session_dir = Path(status["session_dir"]) + assert session_dir.parent == data_root + for name in (snapshot.CONFIG_FILE, snapshot.SESSION_FILE, snapshot.GIT_FILE): + assert (session_dir / name).exists() + meta = json.loads((session_dir / snapshot.SESSION_FILE).read_text()) + assert meta["creator"] == "rcs.envs.configs:EmptyWorldFR3" + git = json.loads((session_dir / snapshot.GIT_FILE).read_text()) + assert git["rcs"]["commit"] + assert (session_dir / git["rcs"]["diff_file"]).exists() + + # live camera image + assert call(base, "/api/live/wrist.jpg")[:2] == b"\xff\xd8" + + record_episode(runner, base, "B") + record_episode(runner, base, "Y") + # restart flushes and creates a new folder + call(base, "/api/restart", {}) + wait_for(lambda: runner.status()["session_dir"] != str(session_dir) and runner.status()["state"] == "ready") + new_dir = Path(runner.status()["session_dir"]) + assert new_dir != session_dir + + table = read_session(session_dir) + rows = table.to_pylist() + episodes: dict[str, list[dict]] = {} + for row in rows: + episodes.setdefault(row["uuid"], []).append(row) + assert len(episodes) == 2 + labels = [] + for ep_rows in episodes.values(): + ep_rows.sort(key=lambda r: r["step"]) + assert [r["step"] for r in ep_rows] == list(range(len(ep_rows))) + assert len(ep_rows) >= 10 + labels.append(ep_rows[-1]["success"]) + assert all(r["instruction"] == "pick" for r in ep_rows) + ts = [r["timestamp"] for r in ep_rows] + assert np.all(np.diff(ts) > 0) + states = ep_rows[-1]["info"]["right"]["control_states"] + n = states["num_samples"] + # 30 Hz env with a 2 ms physics step + assert n == round(1 / 30 / 0.002) + assert np.asarray(states["q"]).reshape(states["q_shape"]).shape == (n, 7) + assert "wrist" in ep_rows[-1]["obs"]["frames"] + assert sorted(labels) == [False, True] + + +def test_restart_from_recording_uses_stored_config(interface): + runner, base, _ = interface + first = Path(runner.status()["session_dir"]) + call(base, "/api/restart", {"from_recording": first.name, "overrides": {"sim_cfg.frequency": 20}}) + wait_for(lambda: runner.status()["session_dir"] != str(first) and runner.status()["state"] == "ready") + second = Path(runner.status()["session_dir"]) + cfg, meta = snapshot.load_session_config(second) + assert cfg.sim_cfg.frequency == 20 + assert meta["source"]["from_recording"] == str(first) + # everything else is taken over + cfg_first, _ = snapshot.load_session_config(first) + assert cfg.camera_cfgs["wrist"].resolution_width == cfg_first.camera_cfgs["wrist"].resolution_width == 64 From fdfa9a4fc1799c9bef532a54a7ffd3c4fdb0fc75 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Sun, 15 Nov 2026 13:44:54 -0800 Subject: [PATCH 12/63] docs(webui): setup from scratch and docs page --- docs/extensions/index.md | 1 + docs/extensions/rcs_webui.md | 5 ++ extensions/rcs_webui/README.md | 131 +++++++++++++++++++++++++++++++++ 3 files changed, 137 insertions(+) create mode 100644 docs/extensions/rcs_webui.md create mode 100644 extensions/rcs_webui/README.md diff --git a/docs/extensions/index.md b/docs/extensions/index.md index 74935733..4765048b 100644 --- a/docs/extensions/index.md +++ b/docs/extensions/index.md @@ -17,4 +17,5 @@ rcs_usb_cam rcs_tacto rcs_robotiq2f85 rcs_zed +rcs_webui ``` diff --git a/docs/extensions/rcs_webui.md b/docs/extensions/rcs_webui.md new file mode 100644 index 00000000..db96809e --- /dev/null +++ b/docs/extensions/rcs_webui.md @@ -0,0 +1,5 @@ +# RCS Web Interface + +```{include} ../../extensions/rcs_webui/README.md +:start-line: 1 +``` diff --git a/extensions/rcs_webui/README.md b/extensions/rcs_webui/README.md new file mode 100644 index 00000000..b7d8cab9 --- /dev/null +++ b/extensions/rcs_webui/README.md @@ -0,0 +1,131 @@ +# RCS Web Interface + +A web interface for data collection and evaluation with RCS. It starts and owns the gym env, reads the +Meta Quest and records every step of every episode into the RCS parquet format with the `StorageWrapper`. + +- **Labelling on the Quest**: `A` starts an episode, `B` ends it as successful, `Y` as unsuccessful. + The same buttons are in the web page. +- **Everything in one place**: observations, camera frames, actions, the info dict and all robot states of + the low level controller since the last step (1 kHz on the FR3, every physics step in sim) are stored in + the same parquet rows. A robot error (e.g. a reflex) ends the episode with `truncated=True` and the error + message in `info..robot_error`. +- **Reproducible**: every env (re)start creates a new data folder with the complete env config, the git + commit and the git diff. A new env can be started from that stored config. + +Status of this PR (draft): data collection with the Quest is implemented and tested in simulation. +Data viewer, relabel / delete, eval mode with the policy server switch follow in the same PR. + +## Setup from scratch + +Steps marked *untested on hardware* were only checked in simulation or with mocked hardware. + +### 1. Repositories and versions + +| what | where | version | +|------|-------|---------| +| RCS incl. this extension and `rcs_fr3` | `https://github.com/RobotControlStack/robot-control-stack` | branch `feat/webui-extension` (based on v0.7.4) | +| Quest app (IRIS) | `https://github.com/RobotControlStack/IRIS-Meta-Quest3/releases/tag/rcsv0.7.x` | `rcsv0.7.x` APK | +| SimPublisher (Python client of the Quest app) | `https://github.com/RobotControlStack/SimPublisher` | default branch | + +Linux (Debian / Ubuntu LTS), Python 3.11, a real time kernel for the FR3 (see the libfranka docs). + +### 2. Install RCS, the FR3 extension and this extension + +```shell +git clone -b feat/webui-extension https://github.com/RobotControlStack/robot-control-stack.git +cd robot-control-stack +sudo apt install $(cat debian_deps.txt) $(cat extensions/rcs_fr3/debian_deps.txt) +python3.11 -m venv .venv && source .venv/bin/activate +pip install 'pip>=25.1' +pip install --group build_deps +pip install -ve . --no-build-isolation # RCS core (C++ build, a few minutes) +pip install -ve extensions/rcs_fr3 --no-build-isolation # FR3 (fetches and builds libfranka) +pip install -ve extensions/rcs_webui # this extension, provides the rcs-webui command +``` + +Limit the parallel C++ build jobs on machines with little memory with `export CMAKE_BUILD_PARALLEL_LEVEL=8`. + +Optional, depending on the setup: + +```shell +pip install -ve extensions/rcs_robotiq2f85 # Robotiq 2F-85 gripper +pip install -ve extensions/rcs_realsense # RealSense cameras +pip install -ve extensions/rcs_zed # ZED cameras (needs the ZED SDK) +``` + +### 3. Meta Quest (operator) + +Install the Quest app and SimPublisher as described in +[`examples/teleop/README.md`](../../examples/teleop/README.md) ("Teleoperation with Meta Quest 3"): +put PC and Quest into the same network, install the IRIS APK, `pip install` SimPublisher from source, +name the Quest `RCSNode` and align the coordinate frame with `examples/teleop/quest_align_frame.py`. +The IP of the PC in that network is passed with `--quest-addr` (default `10.42.0.1`). + +### 4. Try it in simulation + +```shell +rcs-webui envs # envs that can be started +rcs-webui collect --env rcs/fr3 --data-root ~/rcs_data --instruction "pick up the cube" +# without a Quest, control episodes with the web buttons only: +rcs-webui collect --env rcs/fr3 --operator none --data-root ~/rcs_data +``` + +Open `http://:8080` in a browser. Add `--gui` for the MuJoCo viewer. + +### 5. Start on the robot PC (*untested on hardware*) + +1. Unlock the FR3 joints and activate FCI in Desk. +2. Get the default config of your setup, edit it (robot IP, gripper, cameras with their serial numbers) and + start from it: + + ```shell + rcs-webui dump-config fr3 > fr3.json # single FR3 with Franka Hand, robot name "right" + # or: fr3_duo (two FR3 with Robotiq), droid, fr3_dual + rcs-webui collect --env fr3 --config fr3.json --data-root ~/rcs_data --quest-addr 10.42.0.1 \ + --instruction "pick up the red cube and place it in the bowl" + ``` + + Small changes can also be given directly: `--set robot_cfgs.right.ip=192.168.101.1` + (dotted path into the JSON config, the value is parsed as JSON and taken as string otherwise). +3. Open `http://:8080`. Hold the index trigger of the right controller to move the robot, the + hand trigger closes the gripper. Press `A` to start recording, `B` (successful) or `Y` (unsuccessful) + to end the episode, the env is reset (the robot moves home) after each episode. + +Default configs are adapted for recording: `wrapper_cfg.record_control_states=True`, async control at +`--frequency` (default 15 Hz, also the controller interpolation window `policy_rate`), and the action space +of the Quest (`tquat` relative to the configured origin). A config file or a previous recording is used +exactly as stored. + +### 6. Where the data lands + +```text +/ + 2026-11-15_13-42-36_fr3_collect/ one folder per env (re)start: _