当前位置:   article > 正文

MuJoCo 入门教程(五)Python 绑定_mujoco tutorial

mujoco tutorial

系列文章目录

 


前言

        本笔记本提供了使用本地 Python 绑定的 MuJoCo 物理入门教程。

版权声明
        DeepMind Technologies Limited 2022 年版权所有。

        根据 Apache License 2.0 版(以下简称 "许可协议")授权;除非遵守许可协议,否则不得使用本文件。您可从 http://www.apache.org/licenses/LICENSE-2.0 获取许可证副本。

        除非适用法律要求或书面同意,否则根据许可协议分发的软件均按 "原样 "分发,不附带任何明示或暗示的保证或条件。请参阅许可协议,了解有关许可协议下的权限和限制的具体语言。

        本教程所有代码编辑器为 Jupyter Notebook 


 

一、All imports

  1. !pip install mujoco
  2. # Set up GPU rendering.
  3. from google.colab import files
  4. import distutils.util
  5. import os
  6. import subprocess
  7. if subprocess.run('nvidia-smi').returncode:
  8. raise RuntimeError(
  9. 'Cannot communicate with GPU. '
  10. 'Make sure you are using a GPU Colab runtime. '
  11. 'Go to the Runtime menu and select Choose runtime type.')
  12. # Add an ICD config so that glvnd can pick up the Nvidia EGL driver.
  13. # This is usually installed as part of an Nvidia driver package, but the Colab
  14. # kernel doesn't install its driver via APT, and as a result the ICD is missing.
  15. # (https://github.com/NVIDIA/libglvnd/blob/master/src/EGL/icd_enumeration.md)
  16. NVIDIA_ICD_CONFIG_PATH = '/usr/share/glvnd/egl_vendor.d/10_nvidia.json'
  17. if not os.path.exists(NVIDIA_ICD_CONFIG_PATH):
  18. with open(NVIDIA_ICD_CONFIG_PATH, 'w') as f:
  19. f.write("""{
  20. "file_format_version" : "1.0.0",
  21. "ICD" : {
  22. "library_path" : "libEGL_nvidia.so.0"
  23. }
  24. }
  25. """)
  26. # Configure MuJoCo to use the EGL rendering backend (requires GPU)
  27. print('Setting environment variable to use GPU rendering:')
  28. %env MUJOCO_GL=egl
  29. # Check if installation was succesful.
  30. try:
  31. print('Checking that the installation succeeded:')
  32. import mujoco
  33. mujoco.MjModel.from_xml_string('<mujoco/>')
  34. except Exception as e:
  35. raise e from RuntimeError(
  36. 'Something went wrong during installation. Check the shell output above '
  37. 'for more information.\n'
  38. 'If using a hosted Colab runtime, make sure you enable GPU acceleration '
  39. 'by going to the Runtime menu and selecting "Choose runtime type".')
  40. print('Installation successful.')
  41. # Other imports and helper functions
  42. import time
  43. import itertools
  44. import numpy as np
  45. # Graphics and plotting.
  46. print('Installing mediapy:')
  47. !command -v ffmpeg >/dev/null || (apt update && apt install -y ffmpeg)
  48. !pip install -q mediapy
  49. import mediapy as media
  50. import matplotlib.pyplot as plt
  51. # More legible printing from numpy.
  52. np.set_printoptions(precision=3, suppress=True, linewidth=100)
  53. from IPython.display import clear_output
  54. clear_output()

 二、MuJoCo 基础知识

        我们首先定义并加载一个简单的模型:

  1. import mujoco
  2. xml = """
  3. <mujoco>
  4. <worldbody>
  5. <geom name="red_box" type="box" size=".2 .2 .2" rgba="1 0 0 1"/>
  6. <geom name="green_sphere" pos=".2 .2 .2" size=".1" rgba="0 1 0 1"/>
  7. </worldbody>
  8. </mujoco>
  9. """
  10. model = mujoco.MjModel.from_xml_string(xml)

        xml 字符串是用 MuJoCo 的 MJCF 编写的,这是一种基于 XML 的建模语言。

  • 唯一需要的元素是 <mujoco>。最小的有效 MJCF 模型是 <mujoco/>,它是一个完全空的模型。
  • 所有物理元素都位于 <worldbody> 中,而 <worldbody> 始终是顶层主体,并构成笛卡尔坐标中的全局原点。
  • 我们在世界中定义了两个几何体,分别命名为 red_box 和 green_sphere。
  • 问题 red_box 没有位置,green_sphere 没有类型,这是为什么?
    • 答:MJCF 属性有默认值: MJCF 属性有默认值。默认位置为 0 0 0,默认几何类型为球体。MJCF 语言在文档的 XML 参考章节中有描述。

        from_xml_string() 方法调用模型编译器,创建二进制 mjModel 实例。

 2.1 mjModel

        MuJoCo 的 mjModel 包含模型描述,即所有不随时间变化的量。mjModel 的完整描述可在头文件 mjmodel.h 的末尾找到。请注意,头文件包含简短、有用的内联注释,描述了每个字段。

        在 mjModel 中可以找到的量的例子有 ngeom(场景中的 geoms 数量)和 geom_rgba(它们各自的颜色):

model.ngeom
model.geom_rgba

2.1.1 命名访问

        MuJoCo Python 绑定提供了使用名称的便捷访问器。在没有名称字符串的情况下调用 model.geom() 访问器会产生一个方便的错误,告诉我们有效的名称是什么。

  1. try:
  2. model.geom()
  3. except KeyError as e:
  4. print(e)

         在不指定属性的情况下调用已命名的访问器,会告诉我们所有有效的属性是什么:

model.geom('green_sphere')

         让我们读取 green_sphere 的 rgba 值:

model.geom('green_sphere').rgba

         该功能是 MuJoCo 的 mj_name2id 函数的快捷方式:

  1. id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_GEOM, 'green_sphere')
  2. model.geom_rgba[id, :]

         同样,只读 id 和 name 属性可用于将 id 转换为 name,然后再转换回来:

  1. print('id of "green_sphere": ', model.geom('green_sphere').id)
  2. print('name of geom 1: ', model.geom(1).name)
  3. print('name of body 0: ', model.body(0).name)

        请注意,第 0 个机构始终是世界。它不能重命名。

        id 和 name 属性在 Python 解析中很有用:        

[model.geom(i).name for i in range(model.ngeom)]

2.2 mjData

        mjData 包含状态和与之相关的量。状态由时间、广义位置和广义速度组成。它们分别是 data.time、data.qpos 和 data.qvel。要创建一个新的 mjData,我们只需要我们的 mjModel

data = mujoco.MjData(model)

         mjData 还包含状态的函数,例如物体在世界坐标系中的笛卡尔位置。我们两个几何体的(x、y、z)位置在 data.geom_xpos 中:

print(data.geom_xpos)

        等等,为什么我们的两个几何体都在原点?我们不是偏移了绿球吗?答案是 mjData 中的派生量需要显式传播(见下文)。在我们的例子中,所需的最小函数是 mj_kinematics,它可以计算所有对象(不包括摄像机和灯光)的全局笛卡尔姿态。

  1. mujoco.mj_kinematics(model, data)
  2. print('raw access:\n', data.geom_xpos)
  3. # MjData also supports named access:
  4. print('\nnamed access:\n', data.geom('green_sphere').xpos)

2.3 基本渲染、仿真和动画

        为了进行渲染,我们需要实例化一个渲染器对象并调用其渲染方法。

        我们还将重新加载模型,使 colab 的各个部分相互独立。

  1. import mediapy as media
  2. xml = """
  3. <mujoco>
  4. <worldbody>
  5. <geom name="red_box" type="box" size=".2 .2 .2" rgba="1 0 0 1"/>
  6. <geom name="green_sphere" pos=".2 .2 .2" size=".1" rgba="0 1 0 1"/>
  7. </worldbody>
  8. </mujoco>
  9. """
  10. # Make model and data
  11. model = mujoco.MjModel.from_xml_string(xml)
  12. data = mujoco.MjData(model)
  13. # Make renderer, render and show the pixels
  14. renderer = mujoco.Renderer(model)
  15. media.show_image(renderer.render())

         嗯?为什么是黑色像素?

        答案是 原因同上,我们首先需要传播 mjData 中的值。这一次,我们将调用 mj_forward,它调用了计算加速度之前的整个流水线,即计算 eq?%5Cdot%7Bx%7D%3Df%28x%29,其中 eq?x 是状态。这个函数所做的比我们实际需要的要多,但除非我们想节省计算时间,否则调用 mj_forward 是个不错的做法,因为这样我们就知道没有遗漏任何东西。

        我们还需要更新 mjvScene,这是一个由呈现器持有的描述视觉场景的对象。我们稍后会看到,场景可以包括不属于物理模型的视觉对象。

  1. mujoco.mj_forward(model, data)
  2. renderer.update_scene(data)
  3. media.show_image(renderer.render())

 虽然成功了,但图像有点暗。让我们添加一束光,然后重新渲染。

  1. xml = """
  2. <mujoco>
  3. <worldbody>
  4. <light name="top" pos="0 0 1"/>
  5. <geom name="red_box" type="box" size=".2 .2 .2" rgba="1 0 0 1"/>
  6. <geom name="green_sphere" pos=".2 .2 .2" size=".1" rgba="0 1 0 1"/>
  7. </worldbody>
  8. </mujoco>
  9. """
  10. model = mujoco.MjModel.from_xml_string(xml)
  11. data = mujoco.MjData(model)
  12. renderer = mujoco.Renderer(model)
  13. mujoco.mj_forward(model, data)
  14. renderer.update_scene(data)
  15. media.show_image(renderer.render())

         好多了!

        请注意,mjModel 实例中的所有值都是可写的。虽然一般不建议这样做,而是修改 XML 中的值,因为这样很容易创建一个无效的模型,但有些值是可以安全写入的,例如颜色:

  1. # Run this cell multiple times for different colors
  2. model.geom('red_box').rgba[:3] = np.random.rand(3)
  3. renderer.update_scene(data)
  4. media.show_image(renderer.render())

2.4 仿真

现在我们来仿真并制作一段视频。我们将使用 MuJoCo 的主要高级函数 mj_step,它将状态步进为 eq?x_%7Bt&plus;h%7D%3Df%28x_t%29.

请注意,在下面的代码块中,每次调用 mj_step 之后,我们都不会进行渲染。这是因为默认的时间步长是 2ms,而我们想要的是 60fps 的视频,而不是 500fps。

  1. duration = 3.8 # (seconds)
  2. framerate = 60 # (Hz)
  3. # Simulate and display video.
  4. frames = []
  5. mujoco.mj_resetData(model, data) # Reset state and time.
  6. while data.time < duration:
  7. mujoco.mj_step(model, data)
  8. if len(frames) < data.time * framerate:
  9. renderer.update_scene(data)
  10. pixels = renderer.render()
  11. frames.append(pixels)
  12. media.show_video(frames, fps=framerate)

        嗯,视频在播放,但什么都没动,这是为什么?

        这是因为这个模型没有自由度(DoF)。可以移动的物体(具有惯性)称为体。我们通过为体添加关节来增加自由度,指定体如何相对于其父体移动。让我们创建一个包含几何体的新体,添加一个铰链关节并重新渲染,同时使用可视化选项对象 MjvOption 可视化关节轴。

  1. xml = """
  2. <mujoco>
  3. <worldbody>
  4. <light name="top" pos="0 0 1"/>
  5. <body name="box_and_sphere" euler="0 0 -30">
  6. <joint name="swing" type="hinge" axis="1 -1 0" pos="-.2 -.2 -.2"/>
  7. <geom name="red_box" type="box" size=".2 .2 .2" rgba="1 0 0 1"/>
  8. <geom name="green_sphere" pos=".2 .2 .2" size=".1" rgba="0 1 0 1"/>
  9. </body>
  10. </worldbody>
  11. </mujoco>
  12. """
  13. model = mujoco.MjModel.from_xml_string(xml)
  14. data = mujoco.MjData(model)
  15. renderer = mujoco.Renderer(model)
  16. # enable joint visualization option:
  17. scene_option = mujoco.MjvOption()
  18. scene_option.flags[mujoco.mjtVisFlag.mjVIS_JOINT] = True
  19. duration = 3.8 # (seconds)
  20. framerate = 60 # (Hz)
  21. frames = []
  22. mujoco.mj_resetData(model, data)
  23. while data.time < duration:
  24. mujoco.mj_step(model, data)
  25. if len(frames) < data.time * framerate:
  26. renderer.update_scene(data, scene_option=scene_option)
  27. pixels = renderer.render()
  28. frames.append(pixels)
  29. # Simulate and display video.
  30. media.show_video(frames, fps=framerate)

 请注意,我们使用指令 euler="0 0 -30 "将 box_and_sphere 主体绕 Z 轴(垂直轴)旋转了 30°。这样做是为了强调运动学树中元素的姿势始终是相对于其父体而言的,因此我们的两个几何体也通过这种变换进行了旋转。

物理选项位于 mjModel.opt 中,例如时间步长:

model.opt.timestep

让我们翻转重力,重新渲染:

  1. print('default gravity', model.opt.gravity)
  2. model.opt.gravity = (0, 0, 10)
  3. print('flipped gravity', model.opt.gravity)
  4. frames = []
  5. mujoco.mj_resetData(model, data)
  6. while data.time < duration:
  7. mujoco.mj_step(model, data)
  8. if len(frames) < data.time * framerate:
  9. renderer.update_scene(data, scene_option=scene_option)
  10. pixels = renderer.render()
  11. frames.append(pixels)
  12. media.show_video(frames, fps=60)

我们也可以使用 XML 中的顶级 <option> 元素来实现这一功能:

  1. <mujoco>
  2. <option gravity="0 0 10"/>
  3. ...
  4. </mujoco>

2.5 了解自由度

        在现实世界中,所有刚性物体都有 6 个自由度:3 个平移和 3 个旋转。现实世界中的关节就像约束一样,消除了由关节连接的物体的相对自由度。一些物理仿真软件使用这种被称为 "笛卡尔 "或 "减法 "表示法,但其效率很低。MuJoCo 使用的是一种称为 "拉格朗日"、"广义 "或 "加法 "的表示法,根据这种表示法,除非使用关节明确添加,否则物体没有自由度。

        我们的模型只有一个铰链关节,只有一个自由度,整个状态由该关节的角度和角速度定义。这就是系统的广义位置和速度。

  1. print('Total number of DoFs in the model:', model.nv)
  2. print('Generalized positions:', data.qpos)
  3. print('Generalized velocities:', data.qvel)

        MuJoCo 使用广义坐标的原因是,在渲染或读取对象的全局姿态之前,需要调用一个函数(例如 mj_forward)--笛卡尔位置是从广义位置导出的,需要明确计算。

三、举例说明: 使用自反 "尖顶 "仿真自由体

        自由体是指具有 6 个 DoFs(即 3 个平移和 3 个旋转)的自由关节的物体。我们可以给我们的 "盒子与球体 "一个自由关节,然后看着它坠落,但让我们看看更有趣的东西。小陀螺 "是一种会自己翻转的旋转玩具(视频,维基百科)。我们对其进行如下建模:

  1. tippe_top = """
  2. <mujoco model="tippe top">
  3. <option integrator="RK4"/>
  4. <asset>
  5. <texture name="grid" type="2d" builtin="checker" rgb1=".1 .2 .3"
  6. rgb2=".2 .3 .4" width="300" height="300"/>
  7. <material name="grid" texture="grid" texrepeat="8 8" reflectance=".2"/>
  8. </asset>
  9. <worldbody>
  10. <geom size=".2 .2 .01" type="plane" material="grid"/>
  11. <light pos="0 0 .6"/>
  12. <camera name="closeup" pos="0 -.1 .07" xyaxes="1 0 0 0 1 2"/>
  13. <body name="top" pos="0 0 .02">
  14. <freejoint/>
  15. <geom name="ball" type="sphere" size=".02" />
  16. <geom name="stem" type="cylinder" pos="0 0 .02" size="0.004 .008"/>
  17. <geom name="ballast" type="box" size=".023 .023 0.005" pos="0 0 -.015"
  18. contype="0" conaffinity="0" group="3"/>
  19. </body>
  20. </worldbody>
  21. <keyframe>
  22. <key name="spinning" qpos="0 0 0.02 1 0 0 0" qvel="0 0 0 0 1 200" />
  23. </keyframe>
  24. </mujoco>
  25. """
  26. model = mujoco.MjModel.from_xml_string(tippe_top)
  27. renderer = mujoco.Renderer(model)
  28. data = mujoco.MjData(model)
  29. mujoco.mj_forward(model, data)
  30. renderer.update_scene(data, camera="closeup")
  31. media.show_image(renderer.render())

        请注意该模型定义的几个新特征:

  1. 使用 <freejoint/> 子句添加了一个 6-DoF 自由度关节。
  2. 我们使用 <option/> 子句将积分器设置为 4 阶 Runge Kutta。与默认的欧拉积分器相比,Runge-Kutta 具有更高的收敛速度,在许多情况下可以提高给定时间步长下的精度。
  3. 我们在 <asset/> 子句中定义了地板的网格材料,并在 "floor "geom 中对其进行引用。
  4. 我们使用一个名为 "ballast "的不可见、不碰撞的盒状几何体来降低顶部的质量中心。低质量中心是发生翻转行为的必要条件(与直觉相反)。
  5. 我们将初始旋转状态保存为一个关键帧。它绕 Z 轴的旋转速度很高,但与世界的方向并不完全一致,这就引入了翻转所需的对称性破坏。
  6. 我们在模型中定义了一个 <camera>(摄像机),然后使用 update_scene() 的摄像机参数对其进行渲染。让我们检查一下状态:
  1. print('positions', data.qpos)
  2. print('velocities', data.qvel)

        速度很容易解释,6 个零,每个自由度一个。那么长度 7 的位置呢?我们可以看到身体最初的 2 厘米高度;随后的 4 个数字是三维方向,由单位四元数定义。三维方向用 4 个数字表示,而角速度用 3 个数字表示。更多信息,请参阅维基百科上关于四元数和空间旋转的文章。

        让我们来制作一段视频:

  1. duration = 7 # (seconds)
  2. framerate = 60 # (Hz)
  3. # Simulate and display video.
  4. frames = []
  5. mujoco.mj_resetDataKeyframe(model, data, 0) # Reset the state to keyframe 0
  6. while data.time < duration:
  7. mujoco.mj_step(model, data)
  8. if len(frames) < data.time * framerate:
  9. renderer.update_scene(data, "closeup")
  10. pixels = renderer.render()
  11. frames.append(pixels)
  12. media.show_video(frames, fps=framerate)

3.1 测量 mjData 中的值

        如上所述,mjData 结构包含仿真产生的动态变量和中间结果,预计在每个时间步上都会发生变化。下面我们仿真 2000 个时间步,并绘制出茎顶和茎高的角速度与时间的函数关系图。

  1. timevals = []
  2. angular_velocity = []
  3. stem_height = []
  4. # Simulate and save data
  5. mujoco.mj_resetDataKeyframe(model, data, 0)
  6. while data.time < duration:
  7. mujoco.mj_step(model, data)
  8. timevals.append(data.time)
  9. angular_velocity.append(data.qvel[3:6].copy())
  10. stem_height.append(data.geom_xpos[2,2]);
  11. dpi = 120
  12. width = 600
  13. height = 800
  14. figsize = (width / dpi, height / dpi)
  15. _, ax = plt.subplots(2, 1, figsize=figsize, dpi=dpi, sharex=True)
  16. ax[0].plot(timevals, angular_velocity)
  17. ax[0].set_title('angular velocity')
  18. ax[0].set_ylabel('radians / second')
  19. ax[1].plot(timevals, stem_height)
  20. ax[1].set_xlabel('time (seconds)')
  21. ax[1].set_ylabel('meters')
  22. _ = ax[1].set_title('stem height')

3.2 举例说明: 混沌摆

        下面是一个混沌摆的模型,与旧金山探索馆的这个模型类似。

  1. chaotic_pendulum = """
  2. <mujoco>
  3. <option timestep=".001">
  4. <flag energy="enable" contact="disable"/>
  5. </option>
  6. <default>
  7. <joint type="hinge" axis="0 -1 0"/>
  8. <geom type="capsule" size=".02"/>
  9. </default>
  10. <worldbody>
  11. <light pos="0 -.4 1"/>
  12. <camera name="fixed" pos="0 -1 0" xyaxes="1 0 0 0 0 1"/>
  13. <body name="0" pos="0 0 .2">
  14. <joint name="root"/>
  15. <geom fromto="-.2 0 0 .2 0 0" rgba="1 1 0 1"/>
  16. <geom fromto="0 0 0 0 0 -.25" rgba="1 1 0 1"/>
  17. <body name="1" pos="-.2 0 0">
  18. <joint/>
  19. <geom fromto="0 0 0 0 0 -.2" rgba="1 0 0 1"/>
  20. </body>
  21. <body name="2" pos=".2 0 0">
  22. <joint/>
  23. <geom fromto="0 0 0 0 0 -.2" rgba="0 1 0 1"/>
  24. </body>
  25. <body name="3" pos="0 0 -.25">
  26. <joint/>
  27. <geom fromto="0 0 0 0 0 -.2" rgba="0 0 1 1"/>
  28. </body>
  29. </body>
  30. </worldbody>
  31. </mujoco>
  32. """
  33. model = mujoco.MjModel.from_xml_string(chaotic_pendulum)
  34. renderer = mujoco.Renderer(model, 480, 640)
  35. data = mujoco.MjData(model)
  36. mujoco.mj_forward(model, data)
  37. renderer.update_scene(data, camera="fixed")
  38. media.show_image(renderer.render())

3.2.1  计时

        让我们来观看一段视频,看看它是如何工作的:

  1. # setup
  2. n_seconds = 6
  3. framerate = 30 # Hz
  4. n_frames = int(n_seconds * framerate)
  5. frames = []
  6. renderer = mujoco.Renderer(model, 240, 320)
  7. # set initial state
  8. mujoco.mj_resetData(model, data)
  9. data.joint('root').qvel = 10
  10. # simulate and record frames
  11. frame = 0
  12. sim_time = 0
  13. render_time = 0
  14. n_steps = 0
  15. for i in range(n_frames):
  16. while data.time * framerate < i:
  17. tic = time.time()
  18. mujoco.mj_step(model, data)
  19. sim_time += time.time() - tic
  20. n_steps += 1
  21. tic = time.time()
  22. renderer.update_scene(data, "fixed")
  23. frame = renderer.render()
  24. render_time += time.time() - tic
  25. frames.append(frame)
  26. # print timing and play video
  27. step_time = 1e6*sim_time/n_steps
  28. step_fps = n_steps/sim_time
  29. print(f'simulation: {step_time:5.3g} μs/step ({step_fps:5.0f}Hz)')
  30. frame_time = 1e6*render_time/n_frames
  31. frame_fps = n_frames/render_time
  32. print(f'rendering: {frame_time:5.3g} μs/frame ({frame_fps:5.0f}Hz)')
  33. print('\n')
  34. # show video
  35. media.show_video(frames, fps=framerate)

        请注意,渲染比仿真物理要慢得多。

3.2.2 混沌

        这是一个混沌系统(初始条件中的微小扰动会迅速累积):

  1. PERTURBATION = 1e-7
  2. SIM_DURATION = 10 # seconds
  3. NUM_REPEATS = 8
  4. # preallocate
  5. n_steps = int(SIM_DURATION / model.opt.timestep)
  6. sim_time = np.zeros(n_steps)
  7. angle = np.zeros(n_steps)
  8. energy = np.zeros(n_steps)
  9. # prepare plotting axes
  10. _, ax = plt.subplots(2, 1, figsize=(8, 6), sharex=True)
  11. # simulate NUM_REPEATS times with slightly different initial conditions
  12. for _ in range(NUM_REPEATS):
  13. # initialize
  14. mujoco.mj_resetData(model, data)
  15. data.qvel[0] = 10 # root joint velocity
  16. # perturb initial velocities
  17. data.qvel[:] += PERTURBATION * np.random.randn(model.nv)
  18. # simulate
  19. for i in range(n_steps):
  20. mujoco.mj_step(model, data)
  21. sim_time[i] = data.time
  22. angle[i] = data.joint('root').qpos
  23. energy[i] = data.energy[0] + data.energy[1]
  24. # plot
  25. ax[0].plot(sim_time, angle)
  26. ax[1].plot(sim_time, energy)
  27. # finalize plot
  28. ax[0].set_title('root angle')
  29. ax[0].set_ylabel('radian')
  30. ax[1].set_title('total energy')
  31. ax[1].set_ylabel('Joule')
  32. ax[1].set_xlabel('second')
  33. plt.tight_layout()

3.2.3 时间表和准确性

        问题 为什么能量会发生变化?没有摩擦或阻尼,这个系统应该节省能量。

        答:因为时间离散化: 因为时间离散化。

        如果我们减小时间步长,就能获得更高的精度和更好的能量守恒:

  1. SIM_DURATION = 10 # (seconds)
  2. TIMESTEPS = np.power(10, np.linspace(-2, -4, 5))
  3. # prepare plotting axes
  4. _, ax = plt.subplots(1, 1)
  5. for dt in TIMESTEPS:
  6. # set timestep, print
  7. model.opt.timestep = dt
  8. # allocate
  9. n_steps = int(SIM_DURATION / model.opt.timestep)
  10. sim_time = np.zeros(n_steps)
  11. energy = np.zeros(n_steps)
  12. # initialize
  13. mujoco.mj_resetData(model, data)
  14. data.qvel[0] = 9 # root joint velocity
  15. # simulate
  16. print('{} steps at dt = {:2.2g}ms'.format(n_steps, 1000*dt))
  17. for i in range(n_steps):
  18. mujoco.mj_step(model, data)
  19. sim_time[i] = data.time
  20. energy[i] = data.energy[0] + data.energy[1]
  21. # plot
  22. ax.plot(sim_time, energy, label='timestep = {:2.2g}ms'.format(1000*dt))
  23. # finalize plot
  24. ax.set_title('energy')
  25. ax.set_ylabel('Joule')
  26. ax.set_xlabel('second')
  27. ax.legend(frameon=True);
  28. plt.tight_layout()

3.2.4 时间步长和发散

        当我们增加时间步长时,仿真会迅速发散:

  1. SIM_DURATION = 10 # (seconds)
  2. TIMESTEPS = np.power(10, np.linspace(-2, -1.5, 7))
  3. # get plotting axes
  4. ax = plt.gca()
  5. for dt in TIMESTEPS:
  6. # set timestep
  7. model.opt.timestep = dt
  8. # allocate
  9. n_steps = int(SIM_DURATION / model.opt.timestep)
  10. sim_time = np.zeros(n_steps)
  11. energy = np.zeros(n_steps) * np.nan
  12. speed = np.zeros(n_steps) * np.nan
  13. # initialize
  14. mujoco.mj_resetData(model, data)
  15. data.qvel[0] = 11 # set root joint velocity
  16. # simulate
  17. print('simulating {} steps at dt = {:2.2g}ms'.format(n_steps, 1000*dt))
  18. for i in range(n_steps):
  19. mujoco.mj_step(model, data)
  20. if data.warning.number.any():
  21. warning_index = np.nonzero(data.warning.number)[0][0]
  22. warning = mujoco.mjtWarning(warning_index).name
  23. print(f'stopped due to divergence ({warning}) at timestep {i}.\n')
  24. break
  25. sim_time[i] = data.time
  26. energy[i] = sum(abs(data.qvel))
  27. speed[i] = np.linalg.norm(data.qvel)
  28. # plot
  29. ax.plot(sim_time, energy, label='timestep = {:2.2g}ms'.format(1000*dt))
  30. ax.set_yscale('log')
  31. # finalize plot
  32. ax.set_ybound(1, 1e3)
  33. ax.set_title('energy')
  34. ax.set_ylabel('Joule')
  35. ax.set_xlabel('second')
  36. ax.legend(frameon=True, loc='lower right');
  37. plt.tight_layout()

3.2.5 接触

        让我们回到 "方框和球体 "的示例,让它自由连接:

  1. free_body_MJCF = """
  2. <mujoco>
  3. <asset>
  4. <texture name="grid" type="2d" builtin="checker" rgb1=".1 .2 .3"
  5. rgb2=".2 .3 .4" width="300" height="300" mark="edge" markrgb=".2 .3 .4"/>
  6. <material name="grid" texture="grid" texrepeat="2 2" texuniform="true"
  7. reflectance=".2"/>
  8. </asset>
  9. <worldbody>
  10. <light pos="0 0 1" mode="trackcom"/>
  11. <geom name="ground" type="plane" pos="0 0 -.5" size="2 2 .1" material="grid" solimp=".99 .99 .01" solref=".001 1"/>
  12. <body name="box_and_sphere" pos="0 0 0">
  13. <freejoint/>
  14. <geom name="red_box" type="box" size=".1 .1 .1" rgba="1 0 0 1" solimp=".99 .99 .01" solref=".001 1"/>
  15. <geom name="green_sphere" size=".06" pos=".1 .1 .1" rgba="0 1 0 1"/>
  16. <camera name="fixed" pos="0 -.6 .3" xyaxes="1 0 0 0 1 2"/>
  17. <camera name="track" pos="0 -.6 .3" xyaxes="1 0 0 0 1 2" mode="track"/>
  18. </body>
  19. </worldbody>
  20. </mujoco>
  21. """
  22. model = mujoco.MjModel.from_xml_string(free_body_MJCF)
  23. renderer = mujoco.Renderer(model, 400, 600)
  24. data = mujoco.MjData(model)
  25. mujoco.mj_forward(model, data)
  26. renderer.update_scene(data, "fixed")
  27. media.show_image(renderer.render())

        让这个体在地板上慢速滚动,同时想象接触点和力量:

  1. n_frames = 200
  2. height = 240
  3. width = 320
  4. frames = []
  5. renderer = mujoco.Renderer(model, height, width)
  6. # visualize contact frames and forces, make body transparent
  7. options = mujoco.MjvOption()
  8. mujoco.mjv_defaultOption(options)
  9. options.flags[mujoco.mjtVisFlag.mjVIS_CONTACTPOINT] = True
  10. options.flags[mujoco.mjtVisFlag.mjVIS_CONTACTFORCE] = True
  11. options.flags[mujoco.mjtVisFlag.mjVIS_TRANSPARENT] = True
  12. # tweak scales of contact visualization elements
  13. model.vis.scale.contactwidth = 0.1
  14. model.vis.scale.contactheight = 0.03
  15. model.vis.scale.forcewidth = 0.05
  16. model.vis.map.force = 0.3
  17. # random initial rotational velocity:
  18. mujoco.mj_resetData(model, data)
  19. data.qvel[3:6] = 5*np.random.randn(3)
  20. # simulate and render
  21. for i in range(n_frames):
  22. while data.time < i/120.0: #1/4x real time
  23. mujoco.mj_step(model, data)
  24. renderer.update_scene(data, "track", options)
  25. frame = renderer.render()
  26. frames.append(frame)
  27. # show video
  28. media.show_video(frames, fps=30)

3.2.6 接触力分析

        让我们重新运行上述仿真(使用不同的随机初始条件),并绘制一些与接触力相关的值

  1. n_steps = 499
  2. # allocate
  3. sim_time = np.zeros(n_steps)
  4. ncon = np.zeros(n_steps)
  5. force = np.zeros((n_steps,3))
  6. velocity = np.zeros((n_steps, model.nv))
  7. penetration = np.zeros(n_steps)
  8. acceleration = np.zeros((n_steps, model.nv))
  9. forcetorque = np.zeros(6)
  10. # random initial rotational velocity:
  11. mujoco.mj_resetData(model, data)
  12. data.qvel[3:6] = 2*np.random.randn(3)
  13. # simulate and save data
  14. for i in range(n_steps):
  15. mujoco.mj_step(model, data)
  16. sim_time[i] = data.time
  17. ncon[i] = data.ncon
  18. velocity[i] = data.qvel[:]
  19. acceleration[i] = data.qacc[:]
  20. # iterate over active contacts, save force and distance
  21. for j,c in enumerate(data.contact):
  22. mujoco.mj_contactForce(model, data, j, forcetorque)
  23. force[i] += forcetorque[0:3]
  24. penetration[i] = min(penetration[i], c.dist)
  25. # we could also do
  26. # force[i] += data.qfrc_constraint[0:3]
  27. # do you see why?
  28. # plot
  29. _, ax = plt.subplots(3, 2, sharex=True, figsize=(10, 10))
  30. lines = ax[0,0].plot(sim_time, force)
  31. ax[0,0].set_title('contact force')
  32. ax[0,0].set_ylabel('Newton')
  33. ax[0,0].legend(iter(lines), ('normal z', 'friction x', 'friction y'));
  34. ax[1,0].plot(sim_time, acceleration)
  35. ax[1,0].set_title('acceleration')
  36. ax[1,0].set_ylabel('(meter,radian)/s/s')
  37. ax[2,0].plot(sim_time, velocity)
  38. ax[2,0].set_title('velocity')
  39. ax[2,0].set_ylabel('(meter,radian)/s')
  40. ax[2,0].set_xlabel('second')
  41. ax[0,1].plot(sim_time, ncon)
  42. ax[0,1].set_title('number of contacts')
  43. ax[0,1].set_yticks(range(6))
  44. ax[1,1].plot(sim_time, force[:,0])
  45. ax[1,1].set_yscale('log')
  46. ax[1,1].set_title('normal (z) force - log scale')
  47. ax[1,1].set_ylabel('Newton')
  48. z_gravity = -model.opt.gravity[2]
  49. mg = model.body("box_and_sphere").mass[0] * z_gravity
  50. mg_line = ax[1,1].plot(sim_time, np.ones(n_steps)*mg, label='m*g', linewidth=1)
  51. ax[1,1].legend()
  52. ax[2,1].plot(sim_time, 1000*penetration)
  53. ax[2,1].set_title('penetration depth')
  54. ax[2,1].set_ylabel('millimeter')
  55. ax[2,1].set_xlabel('second')
  56. plt.tight_layout()

3.2.7 摩擦力

        让我们看看改变摩擦力值的效果

  1. MJCF = """
  2. <mujoco>
  3. <asset>
  4. <texture name="grid" type="2d" builtin="checker" rgb1=".1 .2 .3"
  5. rgb2=".2 .3 .4" width="300" height="300" mark="none"/>
  6. <material name="grid" texture="grid" texrepeat="6 6"
  7. texuniform="true" reflectance=".2"/>
  8. <material name="wall" rgba='.5 .5 .5 1'/>
  9. </asset>
  10. <default>
  11. <geom type="box" size=".05 .05 .05" />
  12. <joint type="free"/>
  13. </default>
  14. <worldbody>
  15. <light name="light" pos="-.2 0 1"/>
  16. <geom name="ground" type="plane" size=".5 .5 10" material="grid"
  17. zaxis="-.3 0 1" friction=".1"/>
  18. <camera name="y" pos="-.1 -.6 .3" xyaxes="1 0 0 0 1 2"/>
  19. <body pos="0 0 .1">
  20. <joint/>
  21. <geom/>
  22. </body>
  23. <body pos="0 .2 .1">
  24. <joint/>
  25. <geom friction=".33"/>
  26. </body>
  27. </worldbody>
  28. </mujoco>
  29. """
  30. n_frames = 60
  31. height = 300
  32. width = 300
  33. frames = []
  34. # load
  35. model = mujoco.MjModel.from_xml_string(MJCF)
  36. data = mujoco.MjData(model)
  37. renderer = mujoco.Renderer(model, height, width)
  38. # simulate and render
  39. mujoco.mj_resetData(model, data)
  40. for i in range(n_frames):
  41. while data.time < i/30.0:
  42. mujoco.mj_step(model, data)
  43. renderer.update_scene(data, "y")
  44. frame = renderer.render()
  45. frames.append(frame)
  46. media.show_video(frames, fps=30)

四、肌腱、致动器和传感器

  1. MJCF = """
  2. """
  3. model = mujoco.MjModel.from_xml_string(MJCF)
  4. renderer = mujoco.Renderer(model, 480, 480)
  5. data = mujoco.MjData(model)
  6. mujoco.mj_forward(model, data)
  7. renderer.update_scene(data, "fixed")
  8. media.show_image(renderer.render())

驱动蝙蝠和被动 "皮纳塔":

  1. n_frames = 180
  2. height = 240
  3. width = 320
  4. frames = []
  5. fps = 60.0
  6. times = []
  7. sensordata = []
  8. renderer = mujoco.Renderer(model, height, width)
  9. # constant actuator signal
  10. mujoco.mj_resetData(model, data)
  11. data.ctrl = 20
  12. # simulate and render
  13. for i in range(n_frames):
  14. while data.time < i/fps:
  15. mujoco.mj_step(model, data)
  16. times.append(data.time)
  17. sensordata.append(data.sensor('accelerometer').data.copy())
  18. renderer.update_scene(data, "fixed")
  19. frame = renderer.render()
  20. frames.append(frame)
  21. media.show_video(frames, fps=fps)

让我们绘制加速度传感器测得的数值:

  1. ax = plt.gca()
  2. ax.plot(np.asarray(times), np.asarray(sensordata), label='timestep = {:2.2g}ms'.format(1000*dt))
  3. # finalize plot
  4. ax.set_title('Accelerometer values')
  5. ax.set_ylabel('meter/second^2')
  6. ax.set_xlabel('second')
  7. ax.legend(frameon=True, loc='lower right');
  8. plt.tight_layout()

请注意,从加速度计的测量结果中可以清楚地看到身体被球棒击中的瞬间。

五、高级渲染

        与关节可视化一样,其他渲染选项也作为参数显示在渲染方法中。

让我们回到第一个模型:

  1. xml = """
  2. """
  3. model = mujoco.MjModel.from_xml_string(xml)
  4. renderer = mujoco.Renderer(model)
  5. data = mujoco.MjData(model)
  6. mujoco.mj_forward(model, data)
  7. renderer.update_scene(data)
  8. media.show_image(renderer.render())
  1. #@title Enable transparency and frame visualization {vertical-output: true}
  2. scene_option.frame = mujoco.mjtFrame.mjFRAME_GEOM
  3. scene_option.flags[mujoco.mjtVisFlag.mjVIS_TRANSPARENT] = True
  4. renderer.update_scene(data, scene_option=scene_option)
  5. frame = renderer.render()
  6. media.show_image(frame)
  1. #@title Depth rendering {vertical-output: true}
  2. # update renderer to render depth
  3. renderer.enable_depth_rendering()
  4. # reset the scene
  5. renderer.update_scene(data)
  6. # depth is a float array, in meters.
  7. depth = renderer.render()
  8. # Shift nearest values to the origin.
  9. depth -= depth.min()
  10. # Scale by 2 mean distances of near rays.
  11. depth /= 2*depth[depth <= 1].mean()
  12. # Scale to [0, 255]
  13. pixels = 255*np.clip(depth, 0, 1)
  14. media.show_image(pixels.astype(np.uint8))
  15. renderer.disable_depth_rendering()
  1. #@title Segmentation rendering {vertical-output: true}
  2. # update renderer to render segmentation
  3. renderer.enable_segmentation_rendering()
  4. # reset the scene
  5. renderer.update_scene(data)
  6. seg = renderer.render()
  7. # Display the contents of the first channel, which contains object
  8. # IDs. The second channel, seg[:, :, 1], contains object types.
  9. geom_ids = seg[:, :, 0]
  10. # Infinity is mapped to -1
  11. geom_ids = geom_ids.astype(np.float64) + 1
  12. # Scale to [0, 1]
  13. geom_ids = geom_ids / geom_ids.max()
  14. pixels = 255*geom_ids
  15. media.show_image(pixels.astype(np.uint8))
  16. renderer.disable_segmentation_rendering()

5.1 摄像机矩阵
有关摄像机矩阵的描述,请参阅维基百科上的 "摄像机矩阵 "一文。

  1. def compute_camera_matrix(renderer, data):
  2. """Returns the 3x4 camera matrix."""
  3. # If the camera is a 'free' camera, we get its position and orientation
  4. # from the scene data structure. It is a stereo camera, so we average over
  5. # the left and right channels. Note: we call `self.update()` in order to
  6. # ensure that the contents of `scene.camera` are correct.
  7. renderer.update_scene(data)
  8. pos = np.mean([camera.pos for camera in renderer.scene.camera], axis=0)
  9. z = -np.mean([camera.forward for camera in renderer.scene.camera], axis=0)
  10. y = np.mean([camera.up for camera in renderer.scene.camera], axis=0)
  11. rot = np.vstack((np.cross(y, z), y, z))
  12. fov = model.vis.global_.fovy
  13. # Translation matrix (4x4).
  14. translation = np.eye(4)
  15. translation[0:3, 3] = -pos
  16. # Rotation matrix (4x4).
  17. rotation = np.eye(4)
  18. rotation[0:3, 0:3] = rot
  19. # Focal transformation matrix (3x4).
  20. focal_scaling = (1./np.tan(np.deg2rad(fov)/2)) * renderer.height / 2.0
  21. focal = np.diag([-focal_scaling, focal_scaling, 1.0, 0])[0:3, :]
  22. # Image matrix (3x3).
  23. image = np.eye(3)
  24. image[0, 2] = (renderer.width - 1) / 2.0
  25. image[1, 2] = (renderer.height - 1) / 2.0
  26. return image @ focal @ rotation @ translation
  1. #@title Project from world to camera coordinates {vertical-output: true}
  2. # reset the scene
  3. renderer.update_scene(data)
  4. # Get the world coordinates of the box corners
  5. box_pos = data.geom_xpos[model.geom('red_box').id]
  6. box_mat = data.geom_xmat[model.geom('red_box').id].reshape(3, 3)
  7. box_size = model.geom_size[model.geom('red_box').id]
  8. offsets = np.array([-1, 1]) * box_size[:, None]
  9. xyz_local = np.stack(list(itertools.product(*offsets))).T
  10. xyz_global = box_pos[:, None] + box_mat @ xyz_local
  11. # Camera matrices multiply homogenous [x, y, z, 1] vectors.
  12. corners_homogeneous = np.ones((4, xyz_global.shape[1]), dtype=float)
  13. corners_homogeneous[:3, :] = xyz_global
  14. # Get the camera matrix.
  15. m = compute_camera_matrix(renderer, data)
  16. # Project world coordinates into pixel space. See:
  17. # https://en.wikipedia.org/wiki/3D_projection#Mathematical_formula
  18. xs, ys, s = m @ corners_homogeneous
  19. # x and y are in the pixel coordinate system.
  20. x = xs / s
  21. y = ys / s
  22. # Render the camera view and overlay the projected corner coordinates.
  23. pixels = renderer.render()
  24. fig, ax = plt.subplots(1, 1)
  25. ax.imshow(pixels)
  26. ax.plot(x, y, '+', c='w')
  27. ax.set_axis_off()

5.2 修改场景
让我们在 mjvScene 中添加一些任意几何体。

  1. def get_geom_speed(model, data, geom_name):
  2. """Returns the speed of a geom."""
  3. geom_vel = np.zeros(6)
  4. geom_type = mujoco.mjtObj.mjOBJ_GEOM
  5. geom_id = data.geom(geom_name).id
  6. mujoco.mj_objectVelocity(model, data, geom_type, geom_id, geom_vel, 0)
  7. return np.linalg.norm(geom_vel)
  8. def add_visual_capsule(scene, point1, point2, radius, rgba):
  9. """Adds one capsule to an mjvScene."""
  10. if scene.ngeom >= scene.maxgeom:
  11. return
  12. scene.ngeom += 1 # increment ngeom
  13. # initialise a new capsule, add it to the scene using mjv_makeConnector
  14. mujoco.mjv_initGeom(scene.geoms[scene.ngeom-1],
  15. mujoco.mjtGeom.mjGEOM_CAPSULE, np.zeros(3),
  16. np.zeros(3), np.zeros(9), rgba.astype(np.float32))
  17. mujoco.mjv_makeConnector(scene.geoms[scene.ngeom-1],
  18. mujoco.mjtGeom.mjGEOM_CAPSULE, radius,
  19. point1[0], point1[1], point1[2],
  20. point2[0], point2[1], point2[2])
  21. # traces of time, position and speed
  22. times = []
  23. positions = []
  24. speeds = []
  25. offset = model.jnt_axis[0]/16 # offset along the joint axis
  26. def modify_scene(scn):
  27. """Draw position trace, speed modifies width and colors."""
  28. if len(positions) > 1:
  29. for i in range(len(positions)-1):
  30. rgba=np.array((np.clip(speeds[i]/10, 0, 1),
  31. np.clip(1-speeds[i]/10, 0, 1),
  32. .5, 1.))
  33. radius=.003*(1+speeds[i])
  34. point1 = positions[i] + offset*times[i]
  35. point2 = positions[i+1] + offset*times[i+1]
  36. add_visual_capsule(scn, point1, point2, radius, rgba)
  37. duration = 6 # (seconds)
  38. framerate = 30 # (Hz)
  39. # Simulate and display video.
  40. frames = []
  41. # Reset state and time.
  42. mujoco.mj_resetData(model, data)
  43. mujoco.mj_forward(model, data)
  44. while data.time < duration:
  45. # append data to the traces
  46. positions.append(data.geom_xpos[data.geom("green_sphere").id].copy())
  47. times.append(data.time)
  48. speeds.append(get_geom_speed(model, data, "green_sphere"))
  49. mujoco.mj_step(model, data)
  50. if len(frames) < data.time * framerate:
  51. renderer.update_scene(data)
  52. modify_scene(renderer.scene)
  53. pixels = renderer.render()
  54. frames.append(pixels)
  55. media.show_video(frames, fps=framerate)

5.3 摄像机控制
摄像机可以动态控制,以实现电影效果。运行下面的三个单元格,就能看到静态摄像机和移动摄像机渲染效果的不同。

摄像机控制代码在两个轨迹之间平滑转换,一个轨迹围绕一个固定点运行,另一个轨迹跟踪一个移动物体。代码中的参数值是通过快速迭代低分辨率视频获得的。

  1. #@title Load the "dominos" model
  2. dominos_xml = """
  3. """
  4. model = mujoco.MjModel.from_xml_string(dominos_xml)
  5. data = mujoco.MjData(model)
  6. renderer = mujoco.Renderer(model, height=1024, width=1440)
  1. #@title Render from fixed camera
  2. duration = 2.5 # (seconds)
  3. framerate = 60 # (Hz)
  4. # Simulate and display video.
  5. frames = []
  6. mujoco.mj_resetData(model, data) # Reset state and time.
  7. while data.time < duration:
  8. mujoco.mj_step(model, data)
  9. if len(frames) < data.time * framerate:
  10. renderer.update_scene(data, camera='top')
  11. pixels = renderer.render()
  12. frames.append(pixels)
  13. media.show_video(frames, fps=framerate)
  1. #@title Render from moving camera
  2. duration = 3 # (seconds)
  3. # find time when box is thrown (speed > 2cm/s)
  4. throw_time = 0.0
  5. mujoco.mj_resetData(model, data)
  6. while data.time < duration and not throw_time:
  7. mujoco.mj_step(model, data)
  8. box_speed = np.linalg.norm(data.joint('box').qvel[:3])
  9. if box_speed > 0.02:
  10. throw_time = data.time
  11. assert throw_time > 0
  12. def mix(time, t0=0.0, width=1.0):
  13. """Sigmoidal mixing function."""
  14. t = (time - t0) / width
  15. s = 1 / (1 + np.exp(-t))
  16. return 1 - s, s
  17. def unit_cos(t):
  18. """Unit cosine sigmoid from (0,0) to (1,1)."""
  19. return 0.5 - np.cos(np.pi*np.clip(t, 0, 1))/2
  20. def orbit_motion(t):
  21. """Return orbit trajectory."""
  22. distance = 0.9
  23. azimuth = 140 + 100 * unit_cos(t)
  24. elevation = -30
  25. lookat = data.geom('floor').xpos.copy()
  26. return distance, azimuth, elevation, lookat
  27. def track_motion():
  28. """Return box-track trajectory."""
  29. distance = 0.08
  30. azimuth = 280
  31. elevation = -10
  32. lookat = data.geom('box').xpos.copy()
  33. return distance, azimuth, elevation, lookat
  34. def cam_motion():
  35. """Return sigmoidally-mixed {orbit, box-track} trajectory."""
  36. d0, a0, e0, l0 = orbit_motion(data.time / throw_time)
  37. d1, a1, e1, l1 = track_motion()
  38. mix_time = 0.3
  39. w0, w1 = mix(data.time, throw_time, mix_time)
  40. return w0*d0+w1*d1, w0*a0+w1*a1, w0*e0+w1*e1, w0*l0+w1*l1
  41. # Make a camera.
  42. cam = mujoco.MjvCamera()
  43. mujoco.mjv_defaultCamera(cam)
  44. # Simulate and display video.
  45. framerate = 60 # (Hz)
  46. slowdown = 4 # 4x slow-down
  47. mujoco.mj_resetData(model, data)
  48. frames = []
  49. while data.time < duration:
  50. mujoco.mj_step(model, data)
  51. if len(frames) < data.time * framerate * slowdown:
  52. cam.distance, cam.azimuth, cam.elevation, cam.lookat = cam_motion()
  53. renderer.update_scene(data, cam)
  54. pixels = renderer.render()
  55. frames.append(pixels)
  56. media.show_video(frames, fps=framerate)

 

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号