Repository: sail-sg/envpool (language: python)

Issue:
[Feature Request] Mujoco integration
https://github.com/openai/gym/tree/master/gym/envs/mujoco

Env List:

- [x] Ant-v4 (#74)
- [x] HalfCheetah-v4 (#75)
- [x] Hopper-v4 (#76)
- [x] Humanoid-v4 (#77)
- [x] HumanoidStandup-v4 (#78)
- [x] InvertedDoublePendulum-v4 (@Benjamin-eecs, #83)
- [x] InvertedPendulum-v4 (#79)
- [x] Pusher-v4 (#82)
- [x] Reacher-v4 (#81)
- [x] Swimmer-v4 (#80)
- [x] Walker2d-v4 (@Benjamin-eecs, #86)
- [x] add other options to align with gym (#93)

Road Map:

- [x] Get comfortable with current codebase, go through https://envpool.readthedocs.io/en/latest/pages/env.html and add a toy environment by yourself locally;
- [x] Download Mujoco and run on your local machine [1] [5], try with different env settings and see the actual behavior;
- [x] Go through their code [1] [2] (I think it's better to go through both openai and deepmind versions, but only use deepmind's solution as reference), understand their ctype APIs and what we can use to bind with EnvPool APIs [3];
- [x] Integrate only one game and let it work;
- [x] Add some unit tests (good to submit the first PR here);
- [x] Integrate other environments (submit another PR) and related tests.

Resources:
1. https://github.com/openai/mujoco-py 
2. https://github.com/deepmind/dm_control/tree/master/dm_control/mujoco 
3. https://github.com/deepmind/mujoco/blob/main/doc/programming.rst
4. It is quite similar with Atari games which we have already integrated: https://github.com/mgbellemare/Arcade-Learning-Environment
5. First install gym and mujoco, then run with
```python
import gym
env = gym.make("Ant-v3")
env.reset()
for _ in range(10):
  env.step(env.action_space.sample())
  env.render()
```
6. https://github.com/ikostrikov/gym_dmc/blob/master/compare.py a checker


Discussion / hints:

Fix patch:
diff --git a/docs/api/mujoco.rst b/docs/api/mujoco.rst
index ab195d58..345113f9 100644
--- a/docs/api/mujoco.rst
+++ b/docs/api/mujoco.rst
@@ -78,6 +78,21 @@ Humanoid-v3/v4, HumanoidStandup-v2/v4
 - Action space: ``(17)``, with range ``[-0.4, 0.4]``.
 
 
+InvertedDoublePendulum-v2/v4
+----------------------------
+
+`gym InvertedDoublePendulum-v2 source code
+<https://github.com/openai/gym/blob/master/gym/envs/mujoco/inverted_double_pendulum.py>`_
+
+`gym InvertedDoublePendulum-v4 source code
+<https://github.com/openai/gym/blob/master/gym/envs/mujoco/inverted_double_pendulum_v4.py>`_
+
+- Observation space: ``(11)``, first 1 element for ``qpos[0]``, next 2
+  elements for ``sin(qpos[1:])``, next 2 elements for ``cos(qpos[1:])``,
+  next 3 elements for ``qvel``, next 3 elements for ``qfrc_constraint``;
+- Action space: ``(1)``, with range ``[-1, 1]``.
+
+
 InvertedPendulum-v2/v4
 ----------------------
 
diff --git a/envpool/mujoco/BUILD b/envpool/mujoco/BUILD
index 31d68112..ee9ee03b 100644
--- a/envpool/mujoco/BUILD
+++ b/envpool/mujoco/BUILD
@@ -73,6 +73,15 @@ cc_library(
     ],
 )
 
+cc_library(
+    name = "inverted_double_pendulum",
+    hdrs = ["inverted_double_pendulum.h"],
+    deps = [
+        ":mujoco_env",
+        "//envpool/core:async_envpool",
+    ],
+)
+
 cc_library(
     name = "inverted_pendulum",
     hdrs = ["inverted_pendulum.h"],
@@ -118,6 +127,7 @@ pybind_extension(
         ":hopper",
         ":humanoid",
         ":humanoid_standup",
+        ":inverted_double_pendulum",
         ":inverted_pendulum",
         ":pusher",
         ":reacher",
diff --git a/envpool/mujoco/__init__.py b/envpool/mujoco/__init__.py
index a3efbb1e..1b2bc550 100644
--- a/envpool/mujoco/__init__.py
+++ b/envpool/mujoco/__init__.py
@@ -26,6 +26,8 @@
   _HumanoidEnvSpec,
   _HumanoidStandupEnvPool,
   _HumanoidStandupEnvSpec,
+  _InvertedDoublePendulumEnvPool,
+  _InvertedDoublePendulumEnvSpec,
   _InvertedPendulumEnvPool,
   _InvertedPendulumEnvSpec,
   _PusherEnvPool,
@@ -56,6 +58,12 @@
   HumanoidStandupGymEnvPool,
 ) = py_env(_HumanoidStandupEnvSpec, _HumanoidStandupEnvPool)
 
+(
+  InvertedDoublePendulumEnvSpec,
+  InvertedDoublePendulumDMEnvPool,
+  InvertedDoublePendulumGymEnvPool,
+) = py_env(_InvertedDoublePendulumEnvSpec, _InvertedDoublePendulumEnvPool)
+
 (
   InvertedPendulumEnvSpec,
   InvertedPendulumDMEnvPool,
@@ -90,6 +98,9 @@
   "HumanoidStandupEnvSpec",
   "HumanoidStandupDMEnvPool",
   "HumanoidStandupGymEnvPool",
+  "InvertedDoublePendulumEnvSpec",
+  "InvertedDoublePendulumDMEnvPool",
+  "InvertedDoublePendulumGymEnvPool"
   "InvertedPendulumEnvSpec",
   "InvertedPendulumDMEnvPool",
   "InvertedPendulumGymEnvPool",
diff --git a/envpool/mujoco/inverted_double_pendulum.h b/envpool/mujoco/inverted_double_pendulum.h
new file mode 100644
index 00000000..c57c2195
--- /dev/null
+++ b/envpool/mujoco/inverted_double_pendulum.h
@@ -0,0 +1,160 @@
+/*
+ * Copyright 2022 Garena Online Private Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ENVPOOL_MUJOCO_INVERTED_DOUBLE_PENDULUM_H_
+#define ENVPOOL_MUJOCO_INVERTED_DOUBLE_PENDULUM_H_
+
+#include <algorithm>
+#include <limits>
+#include <memory>
+#include <string>
+
+#include "envpool/core/async_envpool.h"
+#include "envpool/core/env.h"
+#include "envpool/mujoco/mujoco_env.h"
+
+namespace mujoco {
+
+class InvertedDoublePendulumEnvFns {
+ public:
+  static decltype(auto) DefaultConfig() {
+    return MakeDict("max_episode_steps"_.bind(1000),
+                    "reward_threshold"_.bind(9100.0), "frame_skip"_.bind(5),
+                    "post_constraint"_.bind(true), "healthy_reward"_.bind(10.0),
+                    "healthy_z_max"_.bind(1.0), "observation_min"_.bind(-10.0),
+                    "observation_max"_.bind(10.0),
+                    "reset_noise_scale"_.bind(0.1));
+  }
+  template <typename Config>
+  static decltype(auto) StateSpec(const Config& conf) {
+    mjtNum inf = std::numeric_limits<mjtNum>::infinity();
+    return MakeDict("obs"_.bind(Spec<mjtNum>({11}, {-inf, inf})),
+                    // TODO(jiayi): remove these two lines for speed
+                    "info:qpos0"_.bind(Spec<mjtNum>({3})),
+                    "info:qvel0"_.bind(Spec<mjtNum>({3})));
+  }
+  template <typename Config>
+  static decltype(auto) ActionSpec(const Config& conf) {
+    return MakeDict("action"_.bind(Spec<mjtNum>({-1, 1}, {-1.0f, 1.0f})));
+  }
+};
+
+typedef class EnvSpec<InvertedDoublePendulumEnvFns>
+    InvertedDoublePendulumEnvSpec;
+
+class InvertedDoublePendulumEnv : public Env<InvertedDoublePendulumEnvSpec>,
+                                  public MujocoEnv {
+ protected:
+  int max_episode_steps_, elapsed_step_;
+  mjtNum healthy_reward_, healthy_z_max_;
+  mjtNum observation_min_, observation_max_;
+  std::unique_ptr<mjtNum> qpos0_, qvel0_;  // for align check
+  std::uniform_real_distribution<> dist_qpos_;
+  std::normal_distribution<> dist_qvel_;
+  bool done_;
+
+ public:
+  InvertedDoublePendulumEnv(const Spec& spec, int env_id)
+      : Env<InvertedDoublePendulumEnvSpec>(spec, env_id),
+        MujocoEnv(spec.config["base_path"_] +
+                      "/mujoco/assets/inverted_double_pendulum.xml",
+                  spec.config["frame_skip"_], spec.config["post_constraint"_]),
+        max_episode_steps_(spec.config["max_episode_steps"_]),
+        elapsed_step_(max_episode_steps_ + 1),
+        healthy_reward_(spec.config["healthy_reward"_]),
+        healthy_z_max_(spec.config["healthy_z_max"_]),
+        observation_min_(spec.config["observation_min"_]),
+        observation_max_(spec.config["observation_max"_]),
+        qpos0_(new mjtNum[model_->nq]),
+        qvel0_(new mjtNum[model_->nv]),
+        dist_qpos_(-spec.config["reset_noise_scale"_],
+                   spec.config["reset_noise_scale"_]),
+        dist_qvel_(0, spec.config["reset_noise_scale"_]),
+        done_(true) {}
+
+  void MujocoResetModel() {
+    for (int i = 0; i < model_->nq; ++i) {
+      data_->qpos[i] = qpos0_.get()[i] = init_qpos_[i] + dist_qpos_(gen_);
+    }
+    for (int i = 0; i < model_->nv; ++i) {
+      data_->qvel[i] = qvel0_.get()[i] = init_qvel_[i] + dist_qvel_(gen_);
+    }
+  }
+
+  bool IsDone() override { return done_; }
+
+  void Reset() override {
+    done_ = false;
+    elapsed_step_ = 0;
+    MujocoReset();
+    WriteObs(0.0f);
+  }
+
+  void Step(const Action& action) override {
+    // step
+    MujocoStep(static_cast<mjtNum*>(action["action"_].data()));
+
+    // dist_penalty
+    mjtNum x = data_->site_xpos[0];
+    mjtNum y = data_->site_xpos[2];
+    mjtNum dist_penalty = 0.01 * x * x + (y - 2) * (y - 2);
+    // vel_penalty
+    mjtNum v1 = data_->qvel[1];
+    mjtNum v2 = data_->qvel[2];
+    mjtNum vel_penalty = 1e-3 * v1 * v1 + 5e-3 * v2 * v2;
+    // reward and done
+    float reward = healthy_reward_ - dist_penalty - vel_penalty;
+    ++elapsed_step_;
+    done_ = !IsHealthy() || (elapsed_step_ >= max_episode_steps_);
+    WriteObs(reward);
+  }
+
+ private:
+  bool IsHealthy() { return data_->site_xpos[2] > healthy_z_max_; }
+
+  void WriteObs(float reward) {
+    State state = Allocate();
+    state["reward"_] = reward;
+    // obs
+    mjtNum* obs = static_cast<mjtNum*>(state["obs"_].data());
+    *(obs++) = data_->qpos[0];
+    *(obs++) = std::sin(data_->qpos[1]);
+    *(obs++) = std::sin(data_->qpos[2]);
+    *(obs++) = std::cos(data_->qpos[1]);
+    *(obs++) = std::cos(data_->qpos[2]);
+    for (int i = 0; i < model_->nv; ++i) {
+      mjtNum x = data_->qvel[i];
+      x = std::min(observation_max_, x);
+      x = std::max(observation_min_, x);
+      *(obs++) = x;
+    }
+    for (int i = 0; i < model_->nv; ++i) {
+      mjtNum x = data_->qfrc_constraint[i];
+      x = std::min(observation_max_, x);
+      x = std::max(observation_min_, x);
+      *(obs++) = x;
+    }
+    // info
+    state["info:qpos0"_].Assign(qpos0_.get(), model_->nq);
+    state["info:qvel0"_].Assign(qvel0_.get(), model_->nv);
+  }
+};
+
+typedef AsyncEnvPool<InvertedDoublePendulumEnv> InvertedDoublePendulumEnvPool;
+
+}  // namespace mujoco
+
+#endif  // ENVPOOL_MUJOCO_INVERTED_DOUBLE_PENDULUM_H_
diff --git a/envpool/mujoco/mujoco_envpool.cc b/envpool/mujoco/mujoco_envpool.cc
index e73700f8..e2c68ef0 100644
--- a/envpool/mujoco/mujoco_envpool.cc
+++ b/envpool/mujoco/mujoco_envpool.cc
@@ -18,6 +18,7 @@
 #include "envpool/mujoco/hopper.h"
 #include "envpool/mujoco/humanoid.h"
 #include "envpool/mujoco/humanoid_standup.h"
+#include "envpool/mujoco/inverted_double_pendulum.h"
 #include "envpool/mujoco/inverted_pendulum.h"
 #include "envpool/mujoco/pusher.h"
 #include "envpool/mujoco/reacher.h"
@@ -38,6 +39,11 @@ typedef PyEnvPool<mujoco::HumanoidEnvPool> HumanoidEnvPool;
 typedef PyEnvSpec<mujoco::HumanoidStandupEnvSpec> HumanoidStandupEnvSpec;
 typedef PyEnvPool<mujoco::HumanoidStandupEnvPool> HumanoidStandupEnvPool;
 
+typedef PyEnvSpec<mujoco::InvertedDoublePendulumEnvSpec>
+    InvertedDoublePendulumEnvSpec;
+typedef PyEnvPool<mujoco::InvertedDoublePendulumEnvPool>
+    InvertedDoublePendulumEnvPool;
+
 typedef PyEnvSpec<mujoco::InvertedPendulumEnvSpec> InvertedPendulumEnvSpec;
 typedef PyEnvPool<mujoco::InvertedPendulumEnvPool> InvertedPendulumEnvPool;
 
@@ -56,6 +62,7 @@ PYBIND11_MODULE(mujoco_envpool, m) {
   REGISTER(m, HopperEnvSpec, HopperEnvPool)
   REGISTER(m, HumanoidEnvSpec, HumanoidEnvPool)
   REGISTER(m, HumanoidStandupEnvSpec, HumanoidStandupEnvPool)
+  REGISTER(m, InvertedDoublePendulumEnvSpec, InvertedDoublePendulumEnvPool)
   REGISTER(m, InvertedPendulumEnvSpec, InvertedPendulumEnvPool)
   REGISTER(m, PusherEnvSpec, PusherEnvPool)
   REGISTER(m, ReacherEnvSpec, ReacherEnvPool)
diff --git a/envpool/mujoco/registration.py b/envpool/mujoco/registration.py
index 5ae29172..1b7a22a1 100644
--- a/envpool/mujoco/registration.py
+++ b/envpool/mujoco/registration.py
@@ -30,6 +30,8 @@
   ("Humanoid", "v4", True),
   ("HumanoidStandup", "v2", False),
   ("HumanoidStandup", "v4", True),
+  ("InvertedDoublePendulum", "v2", False),
+  ("InvertedDoublePendulum", "v4", True),
   ("InvertedPendulum", "v2", False),
   ("InvertedPendulum", "v4", True),
   ("Pusher", "v2", False),


Test patch:
diff --git a/envpool/make_test.py b/envpool/make_test.py
index 9d77e0a5..d2f65975 100644
--- a/envpool/make_test.py
+++ b/envpool/make_test.py
@@ -102,6 +102,8 @@ def test_make_mujoco(self) -> None:
         "Humanoid-v4",
         "HumanoidStandup-v2",
         "HumanoidStandup-v4",
+        "InvertedDoublePendulum-v2",
+        "InvertedDoublePendulum-v4",
         "InvertedPendulum-v2",
         "InvertedPendulum-v4",
         "Pusher-v2",
diff --git a/envpool/mujoco/mujoco_test.py b/envpool/mujoco/mujoco_test.py
index f33f5b39..35e08707 100644
--- a/envpool/mujoco/mujoco_test.py
+++ b/envpool/mujoco/mujoco_test.py
@@ -32,6 +32,8 @@
   HumanoidGymEnvPool,
   HumanoidStandupEnvSpec,
   HumanoidStandupGymEnvPool,
+  InvertedDoublePendulumEnvSpec,
+  InvertedDoublePendulumGymEnvPool,
   InvertedPendulumEnvSpec,
   InvertedPendulumGymEnvPool,
   PusherEnvSpec,
@@ -162,6 +164,19 @@ def test_humanoid_standup(self) -> None:
       HumanoidStandupEnvSpec, HumanoidStandupGymEnvPool
     )
 
+  def test_inverted_double_pendulum(self) -> None:
+    env0 = mjc_mwe.InvertedDoublePendulumEnv()
+    env1 = InvertedDoublePendulumGymEnvPool(
+      InvertedDoublePendulumEnvSpec(
+        InvertedDoublePendulumEnvSpec.gen_config()
+      )
+    )
+    self.run_space_check(env0, env1)
+    self.run_align_check(env0, env1)
+    self.run_deterministic_check(
+      InvertedDoublePendulumEnvSpec, InvertedDoublePendulumGymEnvPool
+    )
+
   def test_inverted_pendulum(self) -> None:
     env0 = mjc_mwe.InvertedPendulumEnv()
     env1 = InvertedPendulumGymEnvPool(