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 cbe3d7db..d9e8bcea 100644
--- a/docs/api/mujoco.rst
+++ b/docs/api/mujoco.rst
@@ -61,3 +61,14 @@ Humanoid-v4, HumanoidStandup-v4
   rot; 3D tran]), next 23 elements for ``qfrc_actuator`` (actuator force),
   next 84 elements for ``cfrc_ext`` (com-based external force on body);
 - Action space: ``(17)``, with range ``[-0.4, 0.4]``.
+
+
+InvertedPendulum-v4
+-------------------
+
+`gym InvertedPendulum-v4 source code
+<https://github.com/openai/gym/blob/master/gym/envs/mujoco/inverted_pendulum_v4.py>`_
+
+- Observation space: ``(4)``, first 2 elements for ``qpos``, next 2 elements
+  for ``qvel``;
+- Action space: ``(1)``, with range ``[-3, 3]``.
diff --git a/envpool/mujoco/BUILD b/envpool/mujoco/BUILD
index 67396ce8..755e9efd 100644
--- a/envpool/mujoco/BUILD
+++ b/envpool/mujoco/BUILD
@@ -73,6 +73,15 @@ cc_library(
     ],
 )
 
+cc_library(
+    name = "inverted_pendulum",
+    hdrs = ["inverted_pendulum.h"],
+    deps = [
+        ":mujoco_env",
+        "//envpool/core:async_envpool",
+    ],
+)
+
 pybind_extension(
     name = "mujoco_envpool",
     srcs = ["mujoco_envpool.cc"],
@@ -82,6 +91,7 @@ pybind_extension(
         ":hopper",
         ":humanoid",
         ":humanoid_standup",
+        ":inverted_pendulum",
         "//envpool/core:py_envpool",
     ],
 )
diff --git a/envpool/mujoco/__init__.py b/envpool/mujoco/__init__.py
index 46723799..f7aa8a7c 100644
--- a/envpool/mujoco/__init__.py
+++ b/envpool/mujoco/__init__.py
@@ -26,6 +26,8 @@
   _HumanoidEnvSpec,
   _HumanoidStandupEnvPool,
   _HumanoidStandupEnvSpec,
+  _InvertedPendulumEnvPool,
+  _InvertedPendulumEnvSpec,
 )
 
 AntEnvSpec, AntDMEnvPool, AntGymEnvPool = py_env(_AntEnvSpec, _AntEnvPool)
@@ -45,6 +47,9 @@
 HumanoidStandupEnvSpec, HumanoidStandupDMEnvPool, HumanoidStandupGymEnvPool \
   = py_env(_HumanoidStandupEnvSpec, _HumanoidStandupEnvPool)
 
+InvertedPendulumEnvSpec, InvertedPendulumDMEnvPool, InvertedPendulumGymEnvPool\
+  = py_env(_InvertedPendulumEnvSpec, _InvertedPendulumEnvPool)
+
 __all__ = [
   "AntEnvSpec",
   "AntDMEnvPool",
@@ -61,4 +66,7 @@
   "HumanoidStandupEnvSpec",
   "HumanoidStandupDMEnvPool",
   "HumanoidStandupGymEnvPool",
+  "InvertedPendulumEnvSpec",
+  "InvertedPendulumDMEnvPool",
+  "InvertedPendulumGymEnvPool",
 ]
diff --git a/envpool/mujoco/ant.h b/envpool/mujoco/ant.h
index a7f84ef9..b371ccba 100644
--- a/envpool/mujoco/ant.h
+++ b/envpool/mujoco/ant.h
@@ -152,25 +152,24 @@ class AntEnv : public Env<AntEnvSpec>, public MujocoEnv {
 
  private:
   bool IsHealthy() {
-    if (healthy_z_min_ <= data_->qpos[2] && data_->qpos[2] <= healthy_z_max_) {
-      for (int i = 0; i < model_->nq; ++i) {
-        if (!std::isfinite(data_->qpos[i])) {
-          return false;
-        }
+    if (data_->qpos[2] < healthy_z_min_ || data_->qpos[2] > healthy_z_max_) {
+      return false;
+    }
+    for (int i = 0; i < model_->nq; ++i) {
+      if (!std::isfinite(data_->qpos[i])) {
+        return false;
       }
-      for (int i = 0; i < model_->nv; ++i) {
-        if (!std::isfinite(data_->qvel[i])) {
-          return false;
-        }
+    }
+    for (int i = 0; i < model_->nv; ++i) {
+      if (!std::isfinite(data_->qvel[i])) {
+        return false;
       }
-      return true;
     }
-    return false;
+    return true;
   }
 
   void WriteObs(float reward, mjtNum xv, mjtNum yv, mjtNum ctrl_cost,
-                mjtNum contact_cost, mjtNum x_after,
-                mjtNum y_after) {  // NOLINT
+                mjtNum contact_cost, mjtNum x_after, mjtNum y_after) {
     State state = Allocate();
     state["reward"_] = reward;
     // obs
diff --git a/envpool/mujoco/half_cheetah.h b/envpool/mujoco/half_cheetah.h
index bb5e54eb..e530b9f7 100644
--- a/envpool/mujoco/half_cheetah.h
+++ b/envpool/mujoco/half_cheetah.h
@@ -122,8 +122,7 @@ class HalfCheetahEnv : public Env<HalfCheetahEnvSpec>, public MujocoEnv {
   }
 
  private:
-  void WriteObs(float reward, mjtNum xv, mjtNum ctrl_cost,
-                mjtNum x_after) {  // NOLINT
+  void WriteObs(float reward, mjtNum xv, mjtNum ctrl_cost, mjtNum x_after) {
     State state = Allocate();
     state["reward"_] = reward;
     // obs
diff --git a/envpool/mujoco/hopper.h b/envpool/mujoco/hopper.h
index e0a83783..30b47a41 100644
--- a/envpool/mujoco/hopper.h
+++ b/envpool/mujoco/hopper.h
@@ -156,7 +156,7 @@ class HopperEnv : public Env<HopperEnvSpec>, public MujocoEnv {
     return true;
   }
 
-  void WriteObs(float reward, mjtNum xv, mjtNum x_after) {  // NOLINT
+  void WriteObs(float reward, mjtNum xv, mjtNum x_after) {
     State state = Allocate();
     state["reward"_] = reward;
     // obs
diff --git a/envpool/mujoco/humanoid.h b/envpool/mujoco/humanoid.h
index 7b58fd5d..249e4496 100644
--- a/envpool/mujoco/humanoid.h
+++ b/envpool/mujoco/humanoid.h
@@ -168,8 +168,7 @@ class HumanoidEnv : public Env<HumanoidEnvSpec>, public MujocoEnv {
   }
 
   void WriteObs(float reward, mjtNum xv, mjtNum yv, mjtNum ctrl_cost,
-                mjtNum contact_cost, mjtNum x_after,
-                mjtNum y_after) {  // NOLINT
+                mjtNum contact_cost, mjtNum x_after, mjtNum y_after) {
     State state = Allocate();
     state["reward"_] = reward;
     // obs
diff --git a/envpool/mujoco/inverted_pendulum.h b/envpool/mujoco/inverted_pendulum.h
new file mode 100644
index 00000000..aba0896b
--- /dev/null
+++ b/envpool/mujoco/inverted_pendulum.h
@@ -0,0 +1,149 @@
+/*
+ * 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_PENDULUM_H_
+#define ENVPOOL_MUJOCO_INVERTED_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 InvertedPendulumEnvFns {
+ public:
+  static decltype(auto) DefaultConfig() {
+    return MakeDict("max_episode_steps"_.bind(1000),
+                    "reward_threshold"_.bind(950.0), "frame_skip"_.bind(2),
+                    "post_constraint"_.bind(true), "healthy_reward"_.bind(1.0),
+                    "healthy_z_min"_.bind(-0.2), "healthy_z_max"_.bind(0.2),
+                    "reset_noise_scale"_.bind(0.01));
+  }
+  template <typename Config>
+  static decltype(auto) StateSpec(const Config& conf) {
+    mjtNum inf = std::numeric_limits<mjtNum>::infinity();
+    return MakeDict("obs"_.bind(Spec<mjtNum>({4}, {-inf, inf})),
+                    // TODO(jiayi): remove these two lines for speed
+                    "info:qpos0"_.bind(Spec<mjtNum>({2})),
+                    "info:qvel0"_.bind(Spec<mjtNum>({2})));
+  }
+  template <typename Config>
+  static decltype(auto) ActionSpec(const Config& conf) {
+    return MakeDict("action"_.bind(Spec<mjtNum>({-1, 1}, {-3.0f, 3.0f})));
+  }
+};
+
+typedef class EnvSpec<InvertedPendulumEnvFns> InvertedPendulumEnvSpec;
+
+class InvertedPendulumEnv : public Env<InvertedPendulumEnvSpec>,
+                            public MujocoEnv {
+ protected:
+  int max_episode_steps_, elapsed_step_;
+  mjtNum healthy_reward_, healthy_z_min_, healthy_z_max_;
+  std::unique_ptr<mjtNum> qpos0_, qvel0_;  // for align check
+  std::uniform_real_distribution<> dist_;
+  bool done_;
+
+ public:
+  InvertedPendulumEnv(const Spec& spec, int env_id)
+      : Env<InvertedPendulumEnvSpec>(spec, env_id),
+        MujocoEnv(
+            spec.config["base_path"_] + "/mujoco/assets/inverted_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_min_(spec.config["healthy_z_min"_]),
+        healthy_z_max_(spec.config["healthy_z_max"_]),
+        qpos0_(new mjtNum[model_->nq]),
+        qvel0_(new mjtNum[model_->nv]),
+        dist_(-spec.config["reset_noise_scale"_],
+              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_(gen_);
+    }
+    for (int i = 0; i < model_->nv; ++i) {
+      data_->qvel[i] = qvel0_.get()[i] = init_qvel_[i] + dist_(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()));
+
+    // reward and done
+    ++elapsed_step_;
+    done_ = !IsHealthy() || (elapsed_step_ >= max_episode_steps_);
+    WriteObs(1.0f);
+  }
+
+ private:
+  bool IsHealthy() {
+    if (data_->qpos[1] < healthy_z_min_ || data_->qpos[1] > healthy_z_max_) {
+      return false;
+    }
+    for (int i = 0; i < model_->nq; ++i) {
+      if (!std::isfinite(data_->qpos[i])) {
+        return false;
+      }
+    }
+    for (int i = 0; i < model_->nv; ++i) {
+      if (!std::isfinite(data_->qvel[i])) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  void WriteObs(float reward) {
+    State state = Allocate();
+    state["reward"_] = reward;
+    // obs
+    mjtNum* obs = static_cast<mjtNum*>(state["obs"_].data());
+    for (int i = 0; i < model_->nq; ++i) {
+      *(obs++) = data_->qpos[i];
+    }
+    for (int i = 0; i < model_->nv; ++i) {
+      *(obs++) = data_->qvel[i];
+    }
+    // info
+    state["info:qpos0"_].Assign(qpos0_.get(), model_->nq);
+    state["info:qvel0"_].Assign(qvel0_.get(), model_->nv);
+  }
+};
+
+typedef AsyncEnvPool<InvertedPendulumEnv> InvertedPendulumEnvPool;
+
+}  // namespace mujoco
+
+#endif  // ENVPOOL_MUJOCO_INVERTED_PENDULUM_H_
diff --git a/envpool/mujoco/mujoco_envpool.cc b/envpool/mujoco/mujoco_envpool.cc
index 1ae1deae..68736161 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_pendulum.h"
 
 typedef PyEnvSpec<mujoco::AntEnvSpec> AntEnvSpec;
 typedef PyEnvPool<mujoco::AntEnvPool> AntEnvPool;
@@ -34,10 +35,14 @@ typedef PyEnvPool<mujoco::HumanoidEnvPool> HumanoidEnvPool;
 typedef PyEnvSpec<mujoco::HumanoidStandupEnvSpec> HumanoidStandupEnvSpec;
 typedef PyEnvPool<mujoco::HumanoidStandupEnvPool> HumanoidStandupEnvPool;
 
+typedef PyEnvSpec<mujoco::InvertedPendulumEnvSpec> InvertedPendulumEnvSpec;
+typedef PyEnvPool<mujoco::InvertedPendulumEnvPool> InvertedPendulumEnvPool;
+
 PYBIND11_MODULE(mujoco_envpool, m) {
   REGISTER(m, AntEnvSpec, AntEnvPool)
   REGISTER(m, HalfCheetahEnvSpec, HalfCheetahEnvPool)
   REGISTER(m, HopperEnvSpec, HopperEnvPool)
   REGISTER(m, HumanoidEnvSpec, HumanoidEnvPool)
   REGISTER(m, HumanoidStandupEnvSpec, HumanoidStandupEnvPool)
+  REGISTER(m, InvertedPendulumEnvSpec, InvertedPendulumEnvPool)
 }
diff --git a/envpool/mujoco/registration.py b/envpool/mujoco/registration.py
index 84ab4825..8c654210 100644
--- a/envpool/mujoco/registration.py
+++ b/envpool/mujoco/registration.py
@@ -71,3 +71,14 @@
   max_episode_steps=1000,
   base_path=base_path,
 )
+
+register(
+  task_id="InvertedPendulum-v4",
+  import_path="envpool.mujoco",
+  spec_cls="InvertedPendulumEnvSpec",
+  dm_cls="InvertedPendulumDMEnvPool",
+  gym_cls="InvertedPendulumGymEnvPool",
+  max_episode_steps=1000,
+  reward_threshold=950.0,
+  base_path=base_path,
+)


Test patch:
diff --git a/envpool/make_test.py b/envpool/make_test.py
index fd184f63..ad591db6 100644
--- a/envpool/make_test.py
+++ b/envpool/make_test.py
@@ -97,6 +97,7 @@ def test_make_mujoco(self) -> None:
         "Hopper-v4",
         "Humanoid-v4",
         "HumanoidStandup-v4",
+        "InvertedPendulum-v4",
       ]
     )
 
diff --git a/envpool/mujoco/mujoco_test.py b/envpool/mujoco/mujoco_test.py
index f16d20b2..8c788221 100644
--- a/envpool/mujoco/mujoco_test.py
+++ b/envpool/mujoco/mujoco_test.py
@@ -32,6 +32,8 @@
   HumanoidGymEnvPool,
   HumanoidStandupEnvSpec,
   HumanoidStandupGymEnvPool,
+  InvertedPendulumEnvSpec,
+  InvertedPendulumGymEnvPool,
 )
 
 
@@ -152,6 +154,17 @@ def test_humanoid_standup(self) -> None:
       HumanoidStandupEnvSpec, HumanoidStandupGymEnvPool
     )
 
+  def test_inverted_pendulum(self) -> None:
+    env0 = mjc_mwe.InvertedPendulumEnv()
+    env1 = InvertedPendulumGymEnvPool(
+      InvertedPendulumEnvSpec(InvertedPendulumEnvSpec.gen_config())
+    )
+    self.run_space_check(env0, env1)
+    self.run_align_check(env0, env1)
+    self.run_deterministic_check(
+      InvertedPendulumEnvSpec, InvertedPendulumGymEnvPool
+    )
+
 
 if __name__ == "__main__":
   absltest.main()