コンテンツにスキップ

03 · ロボットの調整

⏱ 25 分 · レベル:初級 → 中級 · スクリプト:isaac/03_tune_robot.py、isaac/03_before_after.py

目標: インポートした Lime がシミュレーションで正しく動くようにします。アームは姿勢を保ち、車輪は速度指令に従い、キャスターは滑り、グリッパーは開閉するようにします。そのうえで、見た目を実機に近づけます。調整内容は専用の USD ファイルに入れるので、再インポートしても失われません。

調整前と調整後。両方に同じテストを行います:2 秒待ち、両輪を 5 rad/s で 3 秒間回し、グリッパーを開きます。左:チュートリアル 02 でインポートしたままのロボット(車輪がそもそも回るように、車輪のドライブだけは与えています)。アームは倒れ、ロボットは約 0.25 m 進んで約 18° 向きが変わり、グリッパーは閉じたままです。右:調整後。アームは折りたたんだ「home」姿勢を保ち、ロボットは 0.87 m まっすぐ進み(理想は 0.90 m)、グリッパーが開きます。

考え方

ジョイントドライブ

動かせるジョイントにはそれぞれドライブがあります。ドライブはばね・ダンパーで、PhysX がこれを陰的に(implicit)解くため、硬くしても安定しています。

\[ \tau = k_p\,(q_{target} - q) + k_d\,(\dot q_{target} - \dot q), \qquad |\tau| \le \tau_{max} \]
用途 剛性 \(k_p\) 減衰 \(k_d\) 目標値
位置制御(アーム、グリッパー) > 0 > 0 位置
速度制御(車輪) 0 > 0 速度

\(\tau_{max}\) は Max Force(最大力)です。インポーターはこれを URDF の effort の制限値(車輪 3 N·m、アーム 1 N·m)から取りましたが、剛性(stiffness)と減衰(damping)は 0 のままにしました。チュートリアル 02 ですべてがぐにゃぐにゃだったのはこのためです。

単位:USD は角度のゲインを度あたりで保存します

Property パネルと .usda ファイルでは、回転ジョイントの剛性は N·m/deg、減衰は N·m·s/deg です。Isaac Sim の Python API (Articulation.set_dof_gains) はラジアンを使います。200 N·m/rad = 3.49 N·m/deg です。スクリプトは gain * π / 180 で変換しています。

摩擦と結合モード

2 つのコライダーが接触すると、PhysX はそれぞれの摩擦係数を結合します。デフォルトは average(平均)です。キャスターは滑らせたいので、摩擦を 0 にします。床(自前の物理マテリアルを持たないグラウンドプレーン)は PhysX のデフォルトのマテリアルを使い、その摩擦は > 0 です。この 2 つの平均は 0 になりません。キャスターのパッドは後部の重いバッテリーを支えているので、その摩擦がロボットにブレーキをかけます。キャスターのマテリアルの結合モード(combine mode)を min にすると、0.0 のほうが採用されます。

最終的な調整済みアセットで測定した結果です(両輪を 5 rad/s で 3 秒間、理想の距離は 0.90 m)。

キャスターのマテリアル 床 走行距離 車輪の速度
摩擦 0、結合 average デフォルトのマテリアル 0.67 m 1.2 / 2.4 rad/s(しかも曲がる)
摩擦 0、結合 average 摩擦を 0 に設定 0.87 m 5.0 rad/s
摩擦 0、結合 min デフォルトのマテリアル 0.87 m 5.0 rad/s

2 行目で原因が確かめられます。キャスターと床の接触から摩擦をなくすと、問題は解消します。3 行目は、床に手を加えずに解消しています。

ページ上部の動画で左にいるロボットは、さらに短い約 0.25 m しか進みません。そのキャスターのパッドには物理マテリアルがまったくないので、摩擦は 0 ではなく PhysX のデフォルトのままです。このロボットにキャスターのマテリアル(摩擦 0、結合 min)だけを与えると、アームは倒れたまま、タイヤは円柱のままでも、同じテストで 0.86 m 進みます。

車輪のコライダー:円柱か球か

URDF では、各タイヤは半径 0.06 m、幅 24 mm の円柱です。円柱は、接地面(トレッド)を横切る線で床に接します。ロボットが旋回するとき、この線の内側の端と外側の端では必要な速度が異なるため、タイヤが床を擦って旋回に抵抗します。同じ半径の球なら、床と 1 つの点で接します。これは差動二輪の式(チュートリアル 06)が前提とする理想的な車輪です。

測定方法:0.2 m/s と 0.5 rad/s を指令し、ロボットの実際のヨー角速度を読み取ります。

タイヤのコライダー 車輪の速度(指令 2.11 / 4.56 rad/s) ヨー角速度(指令 0.5 rad/s)
円柱 (URDF) 2.40 / 4.16 rad/s 0.44 rad/s
球 2.06 / 4.56 rad/s 0.50 rad/s

そこで調整済みアセットでは、円柱の衝突判定をオフにし、各車輪リンクに見えない球のコライダー(sphere_collider、purpose は guide)を追加しています。目に見えるタイヤのメッシュは変わりません。

見た目:実機の色

URDF はロボット全体を灰色に塗っています。実機の Lime は黒とライムグリーンです。黒いワッフルプレートと Dynamixel サーボ、ライムグリーンの 3D プリント製ブラケット、ライムグリーンのハブが付いた半透明の黄緑色のタイヤ、金属のスペーサー、そしてライムグリーンのマウントに載った LiDAR です。以下の色は、実機の写真から測ったものです。

実機の TurtleBot3 Lime(左、写真:Momoi Open Source)と調整済みのシミュレーション上の Lime(右)

リンクごとにメッシュ 1 つでは粗すぎます。例えば link2.stl には、サーボ、ブラケット、ネジ 4 本が入っています。しかしメッシュの中では、これらは別々のソリッド(solid)になっています。ソリッドとは、ほかの部分と頂点を共有しない三角形のまとまりです。スクリプトはすべてのメッシュをソリッドに分割し、それぞれの大きさで色を決めます。28 × 42 × 46 mm のブロックは Dynamixel サーボ(黒)、アームのその他の部品はブラケット(ライムグリーン)、車輪の 120 mm のリングはタイヤ、84 mm の円盤はハブです。変わるのは見た目だけです。コライダー、質量、ジョイントには手を加えません。

色とルール:isaac/common/looks.py
# name: (base colour as linear RGB, roughness, metallic, opacity) - UsdPreviewSurface values
COLOURS = {
    "black": ((0.005, 0.005, 0.005), 0.55, 0.0, 1.0),  # waffle plates, LiDAR, gripper
    "servo": ((0.008, 0.008, 0.008), 0.30, 0.0, 1.0),  # Dynamixel XM430 servos (slightly glossy)
    "lime": ((0.16, 0.62, 0.012), 0.45, 0.0, 1.0),  # 3D-printed PLA brackets
    "tyre": ((0.55, 0.65, 0.03), 0.20, 0.0, 0.85),  # translucent yellow-green tyres
    "hub": ((0.30, 0.62, 0.03), 0.40, 0.0, 1.0),  # lime wheel hubs
    "metal": ((0.60, 0.60, 0.62), 0.30, 1.0, 1.0),  # aluminium standoffs, screws
}
def classify(mesh_name: str, size: np.ndarray, faces: int) -> str:
    """Which colour is this solid? size = its sorted extents in mm, faces = its number of triangles."""
    small, middle, large = size
    if mesh_name == "tire":
        return "tyre" if large > 100 else "hub"  # the outer ring vs the inner disc
    if mesh_name == "ladar":
        return "lime" if small < 15 and large > 50 else "black"  # the LiDAR sits on a lime mount plate
    if mesh_name == "base":
        if small < 8 and middle < 8 and large > 15:
            return "metal"  # standoffs: thin rods
        return "black"  # plates, battery, boards
    if mesh_name.startswith("gripper") or mesh_name == "link7":
        return "black"  # the gripper and its servo
    if faces < 300 or large < 15:
        return "metal"  # screws, small parts
    if 26 <= small <= 31 and 33 <= middle <= 44 and 39 <= large <= 48:
        return "servo"  # Dynamixel XM430: 28.5 x 34 x 46.5 mm
    return "lime"  # brackets

インスタンス化されたメッシュ

インポーターは、各リンクのビジュアルメッシュをインスタンスとして保存します。インスタンスとは、共有された読み取り専用のコピーです。その一部に色を付けるため、スクリプトはまずビジュアルメッシュのインスタンス化をオフにします(SetInstanceable(False)、調整済みレイヤーでのオーバーライド)。コライダーはインスタンスのままです。

ソルバーの反復回数

アーティキュレーション(ロボットのジョイントのツリー)は反復計算で解かれます。アーティキュレーションの位置の反復回数を 32(デフォルト)から 64 に上げると、走行テストが少し正確になりました。上の実行では 0.847 m → 0.874 m です。速度の反復回数は 4 以下にしてください。PhysX の TGS ソルバーはそれより多い値の扱いを変更しており、警告を出します。

設定値

対象 設定
車輪 (×2) 速度ドライブ:剛性 0、減衰 100 N·m·s/rad、最大力 3 N·m (XM430-W210)
アームのジョイント (×6) 位置ドライブ:剛性 200 N·m/rad、減衰 10 N·m·s/rad、最大力 4.1 N·m(XM430-W350 のストールトルク)
アームの初期姿勢 SRDF の home 姿勢 [0, -1.10, 1.80, 0, 0.98, 0] rad を、ドライブの目標値とジョイントの初期状態の両方に使います(upstream は joint3 に 1.87 を使っていますが、これは upstream 自身の URDF の制限 1.8567 の外です。チュートリアル 12 では MoveIt がこれを拒否します。1.80 なら、重力でアームが垂れる分の余裕が残ります)
グリッパー(左) 位置ドライブ:剛性 1000 N/m、減衰 20 N·s/m、最大力 10 N
グリッパー(右) ドライブなし。mimic ジョイントで左の指に追従します
タイヤ / キャスター 摩擦 1.0 (average) / 摩擦 0.0 (min)
タイヤの衝突形状 URDF の円柱の代わりに球、r = 0.06 m
アーティキュレーション ソルバーの反復回数:位置 64 / 速度 4
見た目 黒いプレートとサーボ、ライムグリーンのブラケット、半透明の黄緑色のタイヤ、ライムグリーンのハブ、金属のスペーサー (common/looks.py)

調整してみる

チュートリアル 02 で作ったステージ my_stages/02_import.usd(ロボットをリファレンスで読み込み済み、Physics = physx、グラウンドプレーンあり)を開きます。

ドライブ: Stage パネルで turtlebot3_lime ▸ Physics を開き、ジョイントを 1 つ選びます(例えば joint2)。Property ▸ Drive ▸ Angular で Stiffness、Damping、Max Force を設定します(単位は度あたりです。上の表を参照してください)。Target Position は度で設定します。複数のジョイントを同時に選ぶ(Ctrl+クリック)と、まとめて編集できます。

joint2 の Property ▸ Drive ▸ Angular(調整済みの値、度あたりの単位)

Gain Tuner: Tools ▸ Robotics ▸ Asset Editors ▸ Gain Tuner は、選択したアーティキュレーションの全ジョイントを 1 つの表に表示します。テスト動作(正弦波やステップ)を再生して、各ジョイントがどう追従するかをプロットすることもできます。ゲインを確定する前に、その効果を確かめるのに使ってください。

Gain Tuner

摩擦: Create ▸ Physics ▸ Physics Material を選びます(剛体用)。その Rigid Body Material セクションで Static/Dynamic Friction を設定します。キャスター用のマテリアルでは、Material (PhysX) セクションで Friction Combine Mode を min にします。次に、キャスターの各コライダー (caster_back_*_link/box) を選び、Property ▸ Physics materials on selected models でそのマテリアルを選びます。Materials on selected models セクションは使わないでください。そちらは見た目用です。

球のタイヤ(この GUI の手順は、スクリプトが行う処理を説明したものです。動作が検証済みなのはスクリプトのほうです)。各 wheel_*_link について、その cylinder を選び、Collider ▸ Collision Enabled のチェックを外します。次にリンクを右クリックし、Create ▸ Shape ▸ Sphere を選びます。その Radius を 0.06、Purpose を guide(レンダリングされません)にします。Add ▸ Physics ▸ Collider でコライダーを追加し、タイヤの物理マテリアルを割り当てます。

ソルバー: base_link(アーティキュレーションのルート)を選びます。その Articulation Root / PhysxArticulationAPI のプロパティで、Solver Position Iteration Count = 64、Solver Velocity Iteration Count = 4 に設定します。

見た目(この GUI の手順は、スクリプトが行う処理を説明したものです。動作が検証済みなのはスクリプトのほうです)。色ごとに Create ▸ Material ▸ OmniPBR でマテリアルを作り、その Albedo の色を設定します。リンクのビジュアルのプリム(例えば link4/link4)を選び、Property パネルで Instanceable のチェックを外してから(インスタンス化されたプリムは読み取り専用です)、Materials on selected models でマテリアルを選びます。GUI ではメッシュ全体に色を付けます。メッシュの中のソリッドを別々に色分けする(サーボは黒、ブラケットはライムグリーン)のは、スクリプトが追加で行う処理です。

オーバーライドレイヤーとして保存: ステージはインポートしたロボットをリファレンスとして持っているので、ここまでの編集はインポートしたファイルを変更していません。編集内容は、リファレンスの上に重なる over としてステージに保存されています。Stop ■ を押してから、File ▸ Save As で my_stages/03_tune_robot.usd として保存します。下のスクリプトも同じ種類のレイヤーを作り、assets/usd/turtlebot3_lime_tuned.usda に書き出します。このファイルに上書き保存しないでください。以降のすべてのチュートリアルがこのファイルを読み込み、ステージ全体ではなく、ルートにロボットがあることを前提にしています。

source scripts/isaac_env.sh
python isaac/03_tune_robot.py --headless --test

スクリプトは assets/usd/turtlebot3_lime_tuned.usda を書き出します。これは、インポートしたアセットをリファレンスし、オーバーライドを追加する小さなレイヤーです。その後、このファイルを読み込んで結果をチェックします。

robot = stage.DefinePrim("/turtlebot3_lime", "Xform")
robot.GetReferences().AddReference("./turtlebot3_lime/turtlebot3_lime.usda")
robot.GetVariantSet("Physics").SetVariantSelection("physx")      # (1)!

drive = UsdPhysics.DriveAPI.Apply(joint_prim, "angular")
drive.CreateStiffnessAttr(200.0 * math.pi / 180.0)                # (2)!
drive.CreateDampingAttr(10.0 * math.pi / 180.0)
drive.CreateMaxForceAttr(4.1)
drive.CreateTargetPositionAttr(math.degrees(home))                 # (3)!

PhysxSchema.PhysxMaterialAPI.Apply(caster_material).CreateFrictionCombineModeAttr("min")

looks.paint_like_the_real_lime(stage, "/turtlebot3_lime")       # (4)!
  1. 調整済みファイルを使う側は、Physics バリアントを選ぶ必要がなくなります。
  2. N·m/rad → N·m/deg。
  3. USD のジョイント角も度で表します。
  4. 実機の色を、ソリッドごとに付けます(上の見た目を参照)。
スクリプト全体:isaac/03_tune_robot.py
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0

"""Tutorial 03 - Tune TurtleBot3 Lime: joint drives, wheel/caster friction, start pose.

    python isaac/03_tune_robot.py              # write the tuned asset, then try it in the GUI
    python isaac/03_tune_robot.py --headless --test

Right after the URDF import (tutorial 02) the robot is *not* ready to simulate:
  * every joint drive has stiffness = damping = 0, so the arm collapses under gravity and the
    wheels cannot be driven;
  * the two small caster pads use the default friction, so they drag on the floor when turning;
  * the arm starts stretched out at 0 rad instead of the folded "home" pose;
  * the URDF paints the whole robot grey - the real Lime is black and lime green.

This script writes the fixes into a NEW layer, assets/usd/turtlebot3_lime_tuned.usda, that *references*
the imported asset. The imported files stay untouched, so re-running tutorial 02 never loses the tuning.
Then it loads the tuned robot and checks that the arm holds its pose, the wheels follow a velocity
command and the gripper opens.
"""

import math
import os
import sys

from common.cli import parse_args

args = parse_args(__doc__.splitlines()[0])

from isaacsim import SimulationApp

simulation_app = SimulationApp({"headless": args.headless, "width": 1280, "height": 720})

import isaacsim.core.experimental.utils.app as app_utils
import isaacsim.core.experimental.utils.stage as stage_utils
import numpy as np
from common import lime, looks
from common.paths import LIME_IMPORTED_USD, LIME_USD
from isaacsim.core.experimental.objects import GroundPlane
from isaacsim.core.experimental.prims import Articulation
from isaacsim.core.simulation_manager import SimulationManager
from pxr import PhysxSchema, Sdf, Usd, UsdGeom, UsdLux, UsdPhysics, UsdShade

# ---------------------------------------------------------------------------------------------------
# Tuning values - SI units (radians, metres, N, N*m). Change them and re-run to see the effect.
# ---------------------------------------------------------------------------------------------------
WHEEL_DRIVE = dict(stiffness=0.0, damping=100.0, max_force=3.0)  # velocity control: stiffness MUST be 0
ARM_DRIVE = dict(stiffness=200.0, damping=10.0, max_force=4.1)  # position control (XM430 stall torque 4.1 N*m)
GRIPPER_DRIVE = dict(stiffness=1000.0, damping=20.0, max_force=10.0)  # position control, prismatic (N/m)
WHEEL_FRICTION = 1.0  # rubber tyres
CASTER_FRICTION = 0.0  # the caster pads should slide freely
SOLVER_ITERATIONS = (64, 4)  # (position, velocity) iterations; PhysX TGS wants <= 4 velocity iterations


def angular_gain_to_usd(gain_per_rad: float) -> float:
    """USD stores angular drive gains per DEGREE (N*m/deg); we think in N*m/rad."""
    return gain_per_rad * math.pi / 180.0


# ---------------------------------------------------------------------------------------------------
# 1. Create the tuned layer:   turtlebot3_lime_tuned.usda  --references-->  turtlebot3_lime/turtlebot3_lime.usda
# ---------------------------------------------------------------------------------------------------
if LIME_USD.exists():
    LIME_USD.unlink()
layer = Sdf.Layer.CreateNew(str(LIME_USD))
stage = Usd.Stage.Open(layer)
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
UsdGeom.SetStageMetersPerUnit(stage, 1.0)
UsdPhysics.SetStageKilogramsPerUnit(stage, 1.0)

robot = stage.DefinePrim("/turtlebot3_lime", "Xform")
stage.SetDefaultPrim(robot)
robot.GetReferences().AddReference("./" + os.path.relpath(LIME_IMPORTED_USD, LIME_USD.parent))
# Select PhysX physics by default (see tutorial 02) - users of this file no longer have to.
robot.GetVariantSet("Physics").SetVariantSelection("physx")


def joint(name: str) -> Usd.Prim:
    return stage.GetPrimAtPath(f"/turtlebot3_lime/Physics/{name}")


def set_drive(name: str, kind: str, stiffness: float, damping: float, max_force: float, target: float):
    """kind: 'angular' (revolute, target in rad) or 'linear' (prismatic, target in m)."""
    prim = joint(name)
    drive = UsdPhysics.DriveAPI.Apply(prim, kind)
    to_usd = angular_gain_to_usd if kind == "angular" else (lambda g: g)
    drive.CreateTypeAttr("force")
    drive.CreateStiffnessAttr(to_usd(stiffness))
    drive.CreateDampingAttr(to_usd(damping))
    drive.CreateMaxForceAttr(max_force)
    if stiffness > 0:  # position drive: target + initial joint position (USD angles are in degrees)
        value = math.degrees(target) if kind == "angular" else target
        drive.CreateTargetPositionAttr(value)
        prim.CreateAttribute(f"state:{kind}:physics:position", Sdf.ValueTypeNames.Float).Set(value)
    else:  # velocity drive
        drive.CreateTargetVelocityAttr(0.0)


# 2. Joint drives ------------------------------------------------------------------------------------
for name in lime.WHEEL_JOINTS:
    set_drive(name, "angular", **WHEEL_DRIVE, target=0.0)
for name, home in zip(lime.ARM_JOINTS, lime.ARM_HOME):
    set_drive(name, "angular", **ARM_DRIVE, target=home)
set_drive(lime.GRIPPER_JOINT, "linear", **GRIPPER_DRIVE, target=0.0)
# gripper_right_joint follows gripper_left_joint through its mimic joint (NewtonMimicAPI authored by the
# importer from the URDF <mimic> tag), so it gets no drive of its own.
set_drive(lime.GRIPPER_MIMIC_JOINT, "linear", stiffness=0.0, damping=0.0, max_force=GRIPPER_DRIVE["max_force"], target=0.0)

# 3. Physics materials (friction) -----------------------------------------------------------------------
def physics_material(path: str, friction: float, combine_mode: str = "average") -> UsdShade.Material:
    mat = UsdShade.Material.Define(stage, path)
    api = UsdPhysics.MaterialAPI.Apply(mat.GetPrim())
    api.CreateStaticFrictionAttr(friction)
    api.CreateDynamicFrictionAttr(friction)
    api.CreateRestitutionAttr(0.0)
    # When two materials touch, PhysX COMBINES their friction - by default it takes the AVERAGE.
    # A 0.0-friction caster on a floor with friction > 0 still gets friction > 0 and brakes the robot
    # (measured: 0.67 m instead of 0.87 m in the drive test below). "min" makes the caster's 0.0 win.
    PhysxSchema.PhysxMaterialAPI.Apply(mat.GetPrim()).CreateFrictionCombineModeAttr(combine_mode)
    return mat


wheel_mat = physics_material("/turtlebot3_lime/PhysicsMaterials/wheel", WHEEL_FRICTION)
caster_mat = physics_material("/turtlebot3_lime/PhysicsMaterials/caster", CASTER_FRICTION, combine_mode="min")
base = f"/turtlebot3_lime/{lime.BASE_LINK}"


def bind_physics_material(prim: Usd.Prim, mat: UsdShade.Material):
    UsdShade.MaterialBindingAPI.Apply(prim).Bind(mat, UsdShade.Tokens.weakerThanDescendants, "physics")


for link in ["caster_back_left_link", "caster_back_right_link"]:
    bind_physics_material(stage.GetPrimAtPath(f"{base}/{link}/box"), caster_mat)

# 3b. Wheel colliders: sphere instead of cylinder ------------------------------------------------------
# The URDF tyre is a 24 mm wide cylinder that touches the floor along a LINE. In a turn the inner and
# outer edge of that line want different speeds, the tyre scrubs, and the robot turns ~12 % slower than
# commanded. A sphere of the same radius touches the floor in one POINT, like the ideal wheel the
# differential-drive formula assumes (measured: 0.44 -> 0.50 rad/s for a 0.5 rad/s command).
for link in lime.WHEEL_JOINTS:
    link_path = f"{base}/{link.replace('_joint', '_link')}"
    UsdPhysics.CollisionAPI(stage.GetPrimAtPath(f"{link_path}/cylinder")).CreateCollisionEnabledAttr(False)
    sphere = UsdGeom.Sphere.Define(stage, f"{link_path}/sphere_collider")
    sphere.CreateRadiusAttr(lime.WHEEL_RADIUS)
    sphere.CreatePurposeAttr(UsdGeom.Tokens.guide)  # a collision shape only: not rendered
    UsdPhysics.CollisionAPI.Apply(sphere.GetPrim())
    bind_physics_material(sphere.GetPrim(), wheel_mat)

# 4. Articulation solver ---------------------------------------------------------------------------------
# More solver iterations = more accurate joints + contacts (default: 32 position iterations).
articulation = PhysxSchema.PhysxArticulationAPI.Apply(stage.GetPrimAtPath(f"/turtlebot3_lime/{lime.ARTICULATION_ROOT}"))
articulation.CreateSolverPositionIterationCountAttr(SOLVER_ITERATIONS[0])
articulation.CreateSolverVelocityIterationCountAttr(SOLVER_ITERATIONS[1])

# 4b. Looks: the colours of the real Lime ---------------------------------------------------------------
# Black plates and servos, lime-green brackets, translucent yellow-green tyres (common/looks.py).
painted = looks.paint_like_the_real_lime(stage, "/turtlebot3_lime")
print(f"[03] painted like the real Lime: {', '.join(f'{name} {n} faces' for name, n in painted.items())}", flush=True)

layer.Save()
print(f"[03] wrote tuned robot: {LIME_USD}")

# ---------------------------------------------------------------------------------------------------
# 5. Try the tuned robot
# ---------------------------------------------------------------------------------------------------
stage = stage_utils.create_new_stage(template="sunlight")
UsdLux.DomeLight.Define(stage, "/World/DomeLight").GetIntensityAttr().Set(500.0)
GroundPlane("/World/GroundPlane")
root_path = lime.add_lime("/World/turtlebot3_lime", position=(0.0, 0.0, 0.0))

recorder = None
if args.record:
    from common.recorder import Recorder

    recorder = Recorder(args.record, eye=(1.0, -1.0, 0.7), target=(0.2, 0.0, 0.2))

SimulationManager.setup_simulation(dt=1.0 / 60.0)
app_utils.play()
simulation_app.update()

robot = Articulation(root_path)
arm_idx = robot.get_dof_indices(lime.ARM_JOINTS)
wheel_idx = robot.get_dof_indices(lime.WHEEL_JOINTS)
grip_idx = robot.get_dof_indices([lime.GRIPPER_JOINT, lime.GRIPPER_MIMIC_JOINT])


def base_xy():
    return robot.get_world_poses()[0].numpy()[0, :2].copy()


results = {}
step = 0
WHEEL_SPEED = 5.0  # rad/s  -> 5 * 0.06 = 0.3 m/s
while simulation_app.is_running():
    t = step / 60.0
    if step == 120:  # t = 2 s: arm settled -> measure pose error, then drive forward
        q = robot.get_dof_positions(dof_indices=arm_idx).numpy()[0]
        results["arm_error"] = float(np.max(np.abs(q - np.array(lime.ARM_HOME))))
        results["start_xy"] = base_xy()
        robot.set_dof_velocity_targets([[WHEEL_SPEED, WHEEL_SPEED]], dof_indices=wheel_idx)
    if step == 300:  # t = 5 s: stop wheels, open the gripper
        results["distance"] = float(np.linalg.norm(base_xy() - results["start_xy"]))
        robot.set_dof_velocity_targets([[0.0, 0.0]], dof_indices=wheel_idx)
        robot.set_dof_position_targets([[lime.GRIPPER_OPEN]], dof_indices=robot.get_dof_indices([lime.GRIPPER_JOINT]))
    if step == 420:  # t = 7 s: check gripper
        results["gripper"] = robot.get_dof_positions(dof_indices=grip_idx).numpy()[0].tolist()
    simulation_app.update()
    if recorder:
        recorder.look_at(eye=(base_xy()[0] + 1.0, -1.0, 0.7), target=(base_xy()[0] + 0.1, base_xy()[1], 0.15))
        recorder.capture()
    step += 1
    if (args.test or args.record) and step > 430:
        break

ok = True
if "gripper" in results:
    expected = WHEEL_SPEED * lime.WHEEL_RADIUS * 3.0  # 3 s at 0.3 m/s = 0.9 m
    left, right = results["gripper"]
    print(f"[03] arm max error after 2 s : {results['arm_error']:.3f} rad")
    print(f"[03] distance in 3 s         : {results['distance']:.3f} m (ideal {expected:.2f} m)")
    print(f"[03] gripper left / right    : {left:.4f} / {right:.4f} m (target {lime.GRIPPER_OPEN})")
    if args.test:
        ok = (
            results["arm_error"] < 0.05
            and abs(results["distance"] - expected) < 0.2 * expected
            and abs(left - lime.GRIPPER_OPEN) < 0.003
        )
        print(f"[03][test] {'PASS' if ok else 'FAIL'}")

if recorder:
    recorder.save()
app_utils.stop()
simulation_app.close(exit_code=0 if ok else 1)
sys.exit(0 if ok else 1)

結果を確かめる

[03] painted like the real Lime: black 645338 faces, servo 38830 faces, lime 45098 faces, tyre 5848 faces, hub 8444 faces, metal 3864 faces
[03] arm max error after 2 s : 0.002 rad
[03] distance in 3 s         : 0.873 m (ideal 0.90 m)
[03] gripper left / right    : 0.0190 / 0.0190 m (target 0.019)
[03][test] PASS
  • アームは重力に逆らって、home を 0.002 rad (0.1°) 以内に保っています。
  • 5 rad/s × 0.06 m = 0.30 m/s なので、3 秒で 0.90 m です。足りない 2.6 cm は加速区間の分です。
  • 右の指は左の指を正確にコピーしています。mimic ジョイントが PhysX 上で機能しています。
調整済みのロボットで実行した 03_tune_robot.py:アームは姿勢を保ち、ロボットは走り、グリッパーは開きます。

実験してみる

ARM_DRIVE = dict(stiffness=200.0, ...) を stiffness=20.0 に変えて再実行すると、アームが垂れ下がります。キャスターの結合モードを "average" に戻すと、ロボットは約 0.67 m しか進まずに曲がり、走行距離のテストが失敗します。

調整前と調整後を並べて比べる

isaac/03_before_after.py は、このページ上部の動画を作るスクリプトです。インポートしたままのロボットを調整済みのロボットの隣に置き、両方で同じテストを実行します。2 つのアセットを読み込むだけなので、先に 03_tune_robot.py を実行しておいてください。

python isaac/03_before_after.py                     # with a window
python isaac/03_before_after.py --headless --test

左のロボットは、チュートリアル 02 でインポートしたとおりのアセットです。

# The robot as imported (tutorial 02): pick the PhysX variant, place it. Nothing else.
stage_utils.add_reference_to_stage(str(LIME_IMPORTED_USD), "/World/as_imported", variants=[("Physics", "physx")])
XformPrim("/World/as_imported", reset_xform_op_properties=True).set_world_poses(positions=[[0.0, LANES["as imported"], 0.0]])
# The tuned robot (tutorial 03).
lime.add_lime("/World/tuned", position=(0.0, LANES["tuned"], 0.0))

ただし、1 か所だけ変更しています。このアセットの車輪のドライブには減衰がないので、速度指令を出してもまったく何も起きません。そこでスクリプトは、実行中のシミュレーションの中でだけ、調整済みロボットの減衰を車輪のドライブに与えます。

# The ONE change to the imported robot: a velocity drive on the wheels (stiffness 0, damping as tuned).
# The Python API takes SI units (N*m*s/rad); it changes the running simulation only, not the asset.
before = robots["as imported"]
wheels = before.get_dof_indices(lime.WHEEL_JOINTS)
before.set_dof_gains(stiffnesses=[[0.0, 0.0]], dampings=[[WHEEL_DAMPING, WHEEL_DAMPING]], dof_indices=wheels)
[03vs] as imported : arm moved 1.819 rad in 2 s, drove 0.251 m (sideways +0.044 m, turned +17.5 deg), wheels 3.06 / 1.26 rad/s, gripper 1.1 mm
[03vs] tuned       : arm moved 0.001 rad in 2 s, drove 0.874 m (sideways +0.001 m, turned +0.1 deg), wheels 5.00 / 5.01 rad/s, gripper 19.0 mm
[03vs][check] ok   tuned: arm holds its pose (moved 0.001 rad)
[03vs][check] ok   tuned: drove 0.87 m (ideal 0.90 m)
[03vs][check] ok   tuned: gripper open (19.0 mm)
[03vs][check] ok   as imported: arm falls (moved 1.82 rad)
[03vs][check] ok   as imported: gripper does not open (1.1 mm)
[03vs][test] PASS
  • インポートしたままのアームには剛性がないので、最初の 2 秒で約 105° 倒れます。
  • インポートしたままの車輪は、5 rad/s ではなく約 3 rad/s と 1 rad/s でしか回らず、ロボットは 4 分の 1 メートルほど進んで進路がそれます。原因はキャスターのパッドです(摩擦と結合モードを参照)。
  • インポートしたままのグリッパーにはドライブがないので、開く指令を出しても何も起きません。
  • 左のロボットの走行は、シーンのわずかな変化に敏感です。ロボットの位置を数 cm ずらすと、0.23〜0.25 m、17〜19° になりました。そのため、左のロボットについては、チェックでアームとグリッパーだけをテストします。調整済みのロボットは、上と同じテストに合格する必要があります。
スクリプト全体:isaac/03_before_after.py
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0

"""Tutorial 03 - before and after: the robot as imported next to the tuned robot, same test.

    python isaac/03_before_after.py                     # watch it in the GUI
    python isaac/03_before_after.py --headless --test

Two Limes stand side by side and get the drive test of 03_tune_robot.py: wait 2 s, both wheels at 5 rad/s
for 3 s, then open the gripper.
  * "as imported": the asset exactly as tutorial 02 imported it, with ONE change: its wheels get the same
    velocity-drive damping as the tuned robot (set at runtime). Without it the wheels could not follow the
    speed command at all, and there would be nothing to compare.
  * "tuned": the robot from tutorial 03 (assets/usd/turtlebot3_lime_tuned.usda).
Run 03_tune_robot.py first: this script only reads the two assets, it writes none.
"""

import math
import sys

from common.cli import parse_args

args = parse_args(__doc__.splitlines()[0])

from isaacsim import SimulationApp

simulation_app = SimulationApp({"headless": args.headless, "width": 1280, "height": 720})

import isaacsim.core.experimental.utils.app as app_utils
import isaacsim.core.experimental.utils.stage as stage_utils
import numpy as np
from common import lime
from common.paths import LIME_IMPORTED_USD
from isaacsim.core.experimental.objects import GroundPlane
from isaacsim.core.experimental.prims import Articulation, XformPrim
from isaacsim.core.simulation_manager import SimulationManager
from pxr import Gf, UsdGeom, UsdLux

WHEEL_SPEED = 5.0  # rad/s, as in 03_tune_robot.py: 5 * 0.06 = 0.3 m/s, 0.9 m in 3 s
WHEEL_DAMPING = 100.0  # N*m*s/rad, the tuned robot's wheel drive (03_tune_robot.py: WHEEL_DRIVE)
LANES = {"as imported": -0.4, "tuned": 0.4}  # y of each robot's lane, m (seen from the front: left, right)

stage = stage_utils.create_new_stage(template="sunlight")
UsdLux.DomeLight.Define(stage, "/World/DomeLight").GetIntensityAttr().Set(500.0)
GroundPlane("/World/GroundPlane")

# The robot as imported (tutorial 02): pick the PhysX variant, place it. Nothing else.
stage_utils.add_reference_to_stage(str(LIME_IMPORTED_USD), "/World/as_imported", variants=[("Physics", "physx")])
XformPrim("/World/as_imported", reset_xform_op_properties=True).set_world_poses(positions=[[0.0, LANES["as imported"], 0.0]])
# The tuned robot (tutorial 03).
lime.add_lime("/World/tuned", position=(0.0, LANES["tuned"], 0.0))


def floor_line(path, x, y, length, colour):
    """A thin painted line on the floor across a lane (looks only: no collider)."""
    line = UsdGeom.Cube.Define(stage, path)
    line.CreateSizeAttr(1.0)
    line.CreateDisplayColorAttr([Gf.Vec3f(*colour)])
    xform = UsdGeom.Xformable(line.GetPrim())
    xform.AddTranslateOp().Set(Gf.Vec3d(x, y, 0.001))
    xform.AddScaleOp().Set(Gf.Vec3f(0.015, length, 0.002))


for name, y in LANES.items():
    tag = name.replace(" ", "_")
    floor_line(f"/World/Lines/start_{tag}", 0.0, y, 0.5, (0.1, 0.1, 0.1))
    floor_line(f"/World/Lines/ideal_{tag}", WHEEL_SPEED * lime.WHEEL_RADIUS * 3.0, y, 0.5, (0.9, 0.5, 0.05))

recorder = None
if args.record:
    from common.recorder import Recorder

    # A fixed camera in front of the two lanes: "as imported" on the left, "tuned" on the right.
    recorder = Recorder(args.record, eye=(4.0, 0.0, 1.75), target=(0.55, 0.0, 0.12), focal_length=24.0)

SimulationManager.setup_simulation(dt=1.0 / 60.0)
app_utils.play()
simulation_app.update()

robots = {
    "as imported": Articulation(f"/World/as_imported/{lime.ARTICULATION_ROOT}"),
    "tuned": Articulation(f"/World/tuned/{lime.ARTICULATION_ROOT}"),
}
# The ONE change to the imported robot: a velocity drive on the wheels (stiffness 0, damping as tuned).
# The Python API takes SI units (N*m*s/rad); it changes the running simulation only, not the asset.
before = robots["as imported"]
wheels = before.get_dof_indices(lime.WHEEL_JOINTS)
before.set_dof_gains(stiffnesses=[[0.0, 0.0]], dampings=[[WHEEL_DAMPING, WHEEL_DAMPING]], dof_indices=wheels)


def pose(robot):
    """x, y (m) and yaw (rad) of the robot's base."""
    p, q = robot.get_world_poses()
    w, x, y, z = q.numpy()[0]
    return float(p.numpy()[0, 0]), float(p.numpy()[0, 1]), math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))


def arm(robot):
    return robot.get_dof_positions(dof_indices=robot.get_dof_indices(lime.ARM_JOINTS)).numpy()[0]


def gripper(robot):
    return float(robot.get_dof_positions(dof_indices=robot.get_dof_indices([lime.GRIPPER_JOINT])).numpy()[0, 0])


start_arm = {name: arm(robot) for name, robot in robots.items()}
frames = []  # what the overlay prints on each recorded frame
results = {name: {"wheel_speeds": []} for name in robots}
step = 0
while simulation_app.is_running():
    for name, robot in robots.items():
        r = results[name]
        wheel_idx = robot.get_dof_indices(lime.WHEEL_JOINTS)
        if step == 120:  # t = 2 s: how far did the arm move by itself? Then drive.
            r["arm_moved"] = float(np.max(np.abs(arm(robot) - start_arm[name])))
            r["start"] = pose(robot)
            robot.set_dof_velocity_targets([[WHEEL_SPEED, WHEEL_SPEED]], dof_indices=wheel_idx)
        if 210 <= step < 300:  # the last 1.5 s of the drive: wheel speeds
            r["wheel_speeds"].append(robot.get_dof_velocities(dof_indices=wheel_idx).numpy()[0])
        if step == 300:  # t = 5 s: stop, open the gripper
            x0, y0, yaw0 = r["start"]
            x, y, yaw = pose(robot)
            r["distance"], r["drift"], r["turn"] = math.hypot(x - x0, y - y0), y - y0, math.degrees(yaw - yaw0)
            robot.set_dof_velocity_targets([[0.0, 0.0]], dof_indices=wheel_idx)
            robot.set_dof_position_targets([[lime.GRIPPER_OPEN]], dof_indices=robot.get_dof_indices([lime.GRIPPER_JOINT]))
        if step == 420:  # t = 7 s
            r["gripper"] = gripper(robot)
    simulation_app.update()
    if recorder:
        n = len(recorder.frames)
        recorder.capture()
        if len(recorder.frames) > n:  # a frame was recorded: note what to print on it
            live = {}
            for name, robot in robots.items():
                r = results[name]
                x, y, yaw = pose(robot)
                x0, y0, yaw0 = r.get("start", (x, y, yaw))
                driven, turn = (r["distance"], r["turn"]) if "distance" in r else (math.hypot(x - x0, y - y0), math.degrees(yaw - yaw0))
                live[name] = dict(arm=float(np.max(np.abs(arm(robot) - start_arm[name]))), driven=driven, turn=turn,
                                  gripper=gripper(robot))
            frames.append((step / 60.0, live))
    step += 1
    if (args.test or args.record) and step > 430:
        break

ok = True
if all("gripper" in r for r in results.values()):
    for name, r in results.items():
        left, right = np.mean(r["wheel_speeds"], axis=0)
        print(f"[03vs] {name:12s}: arm moved {r['arm_moved']:.3f} rad in 2 s, drove {r['distance']:.3f} m "
              f"(sideways {r['drift']:+.3f} m, turned {r['turn']:+.1f} deg), wheels {left:.2f} / {right:.2f} rad/s, "
              f"gripper {r['gripper'] * 1000:.1f} mm")
    if args.test:
        ideal = WHEEL_SPEED * lime.WHEEL_RADIUS * 3.0
        tuned, imported = results["tuned"], results["as imported"]
        checks = [  # the tuned robot passes tutorial 03's test; the imported one fails where it must
            (tuned["arm_moved"] < 0.05, f"tuned: arm holds its pose (moved {tuned['arm_moved']:.3f} rad)"),
            (abs(tuned["distance"] - ideal) < 0.2 * ideal, f"tuned: drove {tuned['distance']:.2f} m (ideal {ideal:.2f} m)"),
            (abs(tuned["gripper"] - lime.GRIPPER_OPEN) < 0.003, f"tuned: gripper open ({tuned['gripper'] * 1000:.1f} mm)"),
            (imported["arm_moved"] > 0.5, f"as imported: arm falls (moved {imported['arm_moved']:.2f} rad)"),
            (imported["gripper"] < 0.005, f"as imported: gripper does not open ({imported['gripper'] * 1000:.1f} mm)"),
        ]
        for passed, text in checks:
            print(f"[03vs][check] {'ok  ' if passed else 'FAIL'} {text}")
        ok = all(passed for passed, _ in checks)
        print(f"[03vs][test] {'PASS' if ok else 'FAIL'}")
else:
    ok = False

if recorder:
    # Print the live numbers on the frames, hold the last frame for 2 s, save.
    from PIL import Image, ImageDraw, ImageFont

    big, small = ImageFont.load_default(size=28), ImageFont.load_default(size=22)
    TITLES = {"as imported": "As imported (+ wheel drive)", "tuned": "Tuned"}

    def phase(t):
        if t < 2.0:
            return f"t = {t:.1f} s   waiting: does the arm hold its pose?"
        if t < 5.0:
            return f"t = {t:.1f} s   both wheels 5 rad/s for 3 s (ideal 0.90 m)"
        return f"t = {t:.1f} s   stop, open the gripper"

    def show(value, spec):
        """format() without a "-0.0" for values that round to zero."""
        return format(float(format(value, spec)) + 0.0, spec)

    def annotate(frame, t, live):
        img = Image.fromarray(frame)
        draw = ImageDraw.Draw(img, "RGBA")
        width, height = img.size
        text = phase(t)
        w = draw.textlength(text, font=big)
        draw.rounded_rectangle(((width - w) / 2 - 16, 14, (width + w) / 2 + 16, 62), 10, fill=(0, 0, 0, 160))
        draw.text(((width - w) / 2, 22), text, font=big, fill="white")
        for i, name in enumerate(TITLES):
            v = live[name]
            lines = [("arm moved", f"{show(math.degrees(v['arm']), '.1f')} deg"), ("driven", f"{show(v['driven'], '.2f')} m"),
                     ("turned", f"{show(v['turn'], '+.1f')} deg"), ("gripper", f"{show(v['gripper'] * 1000, '.1f')} mm")]
            x0 = 24 if i == 0 else width - 24 - 380
            draw.rounded_rectangle((x0, height - 176, x0 + 380, height - 20), 10, fill=(0, 0, 0, 160))
            draw.text((x0 + 16, height - 168), TITLES[name], font=big, fill=(255, 210, 120) if i == 0 else (170, 240, 120))
            for k, (label, value) in enumerate(lines):
                draw.text((x0 + 16, height - 128 + k * 26), label, font=small, fill="white")
                draw.text((x0 + 180, height - 128 + k * 26), value, font=small, fill="white")
        return np.asarray(img)

    recorder.frames = [annotate(f, t, live) for f, (t, live) in zip(recorder.frames, frames)]
    recorder.frames += [recorder.frames[-1]] * 60
    recorder.save()

app_utils.stop()
simulation_app.close(exit_code=0 if ok else 1)
sys.exit(0 if ok else 1)

これ以降のすべてのチュートリアルは assets/usd/turtlebot3_lime_tuned.usda を読み込みます。Python では common.lime.add_lime() がこれを行います。

次へ: 04 · Python でロボットを動かす