15 · ビヘイビアツリー¶
目標: ビヘイビアツリーを学びます。ビヘイビアツリーは、Nav2 をはじめ多くのロボットが判断を組み立てるのに使っている仕組みです。まず Nav2 の中で動いているツリーを読み、その動きを観察します。次に、py_trees で自分のツリーを書きます。lime_room をパトロールし、(仮想の)バッテリーが少なくなると中断して、充電後に続きを再開するツリーです。チュートリアル 16 では、同じ部品を使ってもっと長い仕事をこなします。
なぜツリーなのか?¶
チュートリアル 13 のミッションはスクリプトです。ステップ 1、ステップ 2、ステップ 3 と進み、どこかで失敗したら止まります。バナナ 1 本ならこれで十分です。もっと長い仕事には、さらに次のようなことが必要になります。
- 何かが失敗したらもう一度試す(把持し損ねたとき)。
- 別のことを試す(その見回り地点にたどり着けないなら、飛ばす)。
- もっと重要なこと(バッテリー残量が少ない)のために今していることを中断し、あとで続きを再開する。
これを if とフラグで書くと、すぐに読みにくくなります。ビヘイビアツリーはこうしたパターンのそれぞれに名前を付けるので、ミッションは小さく再利用できる部品のツリーになります。
考え方¶
ツリーは 1 秒に約 10 回 tick されます。tick はルートから始まり、するべき仕事があるビヘイビアまで下りていきます。tick されたビヘイビアは、次の 3 つの言葉のどれかで答えます。
| ステータス | 意味 |
|---|---|
| SUCCESS | 完了、うまくいった |
| FAILURE | 完了、うまくいかなかった |
| RUNNING | まだ終わっていない:もう一度 tick してほしい |
葉(リーフ)は仕事をするか(充電器まで走る)、何かを確かめます(バッテリー残量は少ないか?)。その上にあるノードは、どの葉を tick するかを決めます。
| ノード | 記号 | 動作 |
|---|---|---|
| Sequence | → | 子を順番に tick します。1 つでも失敗したら、その時点で失敗します。「これをして、次にあれをする」 |
| Selector(Nav2 では Fallback) | ? | 子を順番に tick します。1 つでも成功したら、その時点で成功します。「これを試して、だめならあれ」 |
| デコレーター | ◇ | ただ 1 つの子が返す答えを変えます:Retry(失敗したらもう一度試す)、Repeat、Inverter(SUCCESS と FAILURE を入れ替える)、ForEach(リストの要素ごとに 1 回)など |
子の順番が、そのまま優先度になります。メモリ(memory)ありの Sequence や Selector は、前回の tick で RUNNING だった子から続けます。メモリなしの場合は、tick のたびに最初の子からやり直します。そのため、優先度の高い子が今度は成功すると(バッテリー残量が少ない)、実行中だった優先度の低い子(見回り地点まで走る)を中断できます。ツリーはこうして状況に反応します。
ビヘイビアどうしはブラックボードを通してデータを共有します。ブラックボードは、どのビヘイビアからも読み書きできる辞書です。バッテリー残量、次の見回り地点、拾い上げる物などを入れます。
パート 1:Nav2 の中のツリー¶
実は、チュートリアル 11 からずっとビヘイビアツリーを使っています。Nav2 の bt_navigator は、ゴールごとにツリーを 1 つ実行します。ツリーは BehaviorTree.CPP 用の XML で書かれていて、Jazzy にはいくつも同梱されています。NavigateToPose のデフォルトは navigate_to_pose_w_replanning_and_recovery.xml です。
flowchart TD
root{{"RecoveryNode · 6 retries<br/>NavigateRecovery"}} --> pipe["PipelineSequence<br/>NavigateWithReplanning"]
root --> rec["Sequence → ReactiveFallback<br/>(only if a recovery can help)"]
pipe --> rate["RateController · 1 Hz"] --> plan["ComputePathToPose<br/>(planner_server)"]
pipe --> follow["FollowPath<br/>(controller_server, MPPI)"]
rec --> rr["RoundRobin: one per failure"]
rr --> c1["clear both costmaps"]
rr --> c2["Spin 90°"]
rr --> c3["Wait 5 s"]
rr --> c4["BackUp 30 cm"]
- PipelineSequence は、プランナーとコントローラーを同時に tick します。
FollowPathがロボットを現在の経路に沿って動かし続ける一方で、RateController は 1 秒に 1 回、ComputePathToPoseに新しい経路を計画させます。チュートリアル 11 のカラーコーンを LiDAR が捉えると、Nav2 がすぐにそれを避けて進むのはこのためです。 - RecoveryNode は、子を 2 つ持つデコレーターに似たノードです。1 つ目の子が失敗すると、2 つ目の子(リカバリー)を tick してから 1 つ目をもう一度試します。これを最大 6 回繰り返します。
- RoundRobin は、呼ばれるたびに次のリカバリーを選びます。最初はコストマップをクリアし、次はその場で回転し、次は待機し、その次は後退します。
XML:nav2_bt_navigator/behavior_trees/navigate_to_pose_w_replanning_and_recovery.xml
<!--
This Behavior Tree replans the global path periodically at 1 Hz and it also has
recovery actions specific to planning / control as well as general system issues.
This will be continuous if a kinematically valid planner is selected.
-->
<root BTCPP_format="4" main_tree_to_execute="MainTree">
<BehaviorTree ID="MainTree">
<RecoveryNode number_of_retries="6" name="NavigateRecovery">
<PipelineSequence name="NavigateWithReplanning">
<ControllerSelector selected_controller="{selected_controller}" default_controller="FollowPath" topic_name="controller_selector"/>
<PlannerSelector selected_planner="{selected_planner}" default_planner="GridBased" topic_name="planner_selector"/>
<RateController hz="1.0">
<RecoveryNode number_of_retries="1" name="ComputePathToPose">
<ComputePathToPose goal="{goal}" path="{path}" planner_id="{selected_planner}" error_code_id="{compute_path_error_code}"/>
<Sequence>
<WouldAPlannerRecoveryHelp error_code="{compute_path_error_code}"/>
<ClearEntireCostmap name="ClearGlobalCostmap-Context" service_name="global_costmap/clear_entirely_global_costmap"/>
</Sequence>
</RecoveryNode>
</RateController>
<RecoveryNode number_of_retries="1" name="FollowPath">
<FollowPath path="{path}" controller_id="{selected_controller}" error_code_id="{follow_path_error_code}"/>
<Sequence>
<WouldAControllerRecoveryHelp error_code="{follow_path_error_code}"/>
<ClearEntireCostmap name="ClearLocalCostmap-Context" service_name="local_costmap/clear_entirely_local_costmap"/>
</Sequence>
</RecoveryNode>
</PipelineSequence>
<Sequence>
<Fallback>
<WouldAControllerRecoveryHelp error_code="{follow_path_error_code}"/>
<WouldAPlannerRecoveryHelp error_code="{compute_path_error_code}"/>
</Fallback>
<ReactiveFallback name="RecoveryFallback">
<GoalUpdated/>
<RoundRobin name="RecoveryActions">
<Sequence name="ClearingActions">
<ClearEntireCostmap name="ClearLocalCostmap-Subtree" service_name="local_costmap/clear_entirely_local_costmap"/>
<ClearEntireCostmap name="ClearGlobalCostmap-Subtree" service_name="global_costmap/clear_entirely_global_costmap"/>
</Sequence>
<Spin spin_dist="1.57" error_code_id="{spin_error_code}"/>
<Wait wait_duration="5.0"/>
<BackUp backup_dist="0.30" backup_speed="0.15" error_code_id="{backup_code_id}"/>
</RoundRobin>
</ReactiveFallback>
</Sequence>
</RecoveryNode>
</BehaviorTree>
</root>
tick の様子を見る¶
bt_navigator は、ステータスが変わるたびに /behavior_tree_log にパブリッシュします。チュートリアル 11 を起動し(Isaac Sim と navigation.launch.py)、3 つ目のターミナルで次を実行します。
チュートリアル 11 のゴールを送り、ノードが変化する様子を見てみましょう。各メッセージには、1 回の tick でステータスが変わったノードが並んでいます。ノード:変化前 → 変化後の形に要約すると、最初の 1 秒間は次のようになります。
# t = 12.77 s the goal arrives
NavigateRecovery IDLE -> RUNNING
RateController IDLE -> RUNNING
ComputePathToPose IDLE -> RUNNING (the planner starts)
NavigateWithReplanning IDLE -> RUNNING
# t = 12.80 s
ComputePathToPose RUNNING -> SUCCESS (a path)
RateController RUNNING -> SUCCESS
FollowPath IDLE -> RUNNING (the controller starts driving)
# t = 13.77 s one second later
ComputePathToPose IDLE -> RUNNING (plan again, while FollowPath keeps RUNNING)
# t = 13.78 s
ComputePathToPose RUNNING -> SUCCESS
これが PipelineSequence の働きです。FollowPath は走行中ずっと RUNNING のままで、RateController が 1 秒に 1 回 ComputePathToPose を再実行させます。(ComputePathToPose という名前のノードは 2 つあります。それを囲む RecoveryNode も同じ名前です。)このトピックがまだパブリッシュされていないときは、コマンドラインでメッセージ型を指定する必要があります。
ツリーを図で見る
Groot2(BehaviorTree.CPP の作者たちが無料で配布しています)を使うと、これらの XML ファイルを図として開き、編集できます。Nav2 は自分で書いた XML を実行することもできます。ゴールの behavior_tree フィールドにそのパスを入れるか、nav2_params.yaml で default_nav_to_pose_bt_xml を設定します。
パート 2:py_trees で自分のツリーを作る¶
Nav2 のツリーは、ロボットを 1 つのゴールまで走らせます。その上位にあるミッションが、どのゴールにどの順番で向かうか、何かがうまくいかなかったらどうするかを決めます。ミッションはナビゲーションよりも頻繁に変わるので、このチュートリアルではミッションを Python と py_trees(ROS 2 Jazzy のパッケージ ros-jazzy-py-trees。コンテナに導入済み)で書きます。
仕事の内容:4 つの見回り地点を回って、帰ってきます。Lime のバッテリーは仮想のもので、1 m 走るごとに 5 % 減ります。30 % を下回ると、ロボットはパトロールを中断して充電器まで走り、充電してから続きを再開します。
flowchart TD
root["→ Lime patrol<br/>(Sequence, no memory)"] --> bat(["Battery<br/>writes the level"])
root --> what["? What now?<br/>(Selector, no memory)"]
what --> then{{"◇ Then go on<br/>(SuccessIsRunning)"}} --> rech["→ Recharge"]
rech --> low(["Battery below 30 %?"])
rech --> gocharge(["Go to the charger<br/>Nav2"])
rech --> charge(["Charge"])
what --> patrol["→ Patrol"]
patrol --> each{{"◇ Every lookout<br/>(ForEach)"}} --> visit["? Visit it"]
visit --> been(["Been there already?"])
visit --> go["→ Go there"]
go --> nav(["Go to the lookout<br/>Nav2"])
go --> look(["Look around<br/>turn once"])
go --> off(["Check it off"])
patrol --> home(["Go home<br/>Nav2"])
ツリーが tick される順に、上から読んでいきましょう。
- Battery は tick のたびに実行され、バッテリー残量をブラックボードに書き込みます。これは判断ではなくセンサーなので、常に SUCCESS を返します。
- What now?(次は何をする?)はメモリなしの Selector です。tick のたびに、左の子から順に改めて問い合わせます。Recharge(充電)が最初にあるので、こちらが優先されます。バッテリーに問題がない間は Battery below 30 %?(バッテリーは 30 % 未満か?)が失敗するので Recharge も失敗し、Selector は Patrol に進みます。
- Patrol はすべての見回り地点を回り(ForEach が見回り地点を 1 つずつ順番に
lookoutとしてブラックボードに置きます)、それから帰ります。 - バッテリーが 30 % を下回ると、Recharge は最初の子が成功し、RUNNING を返します。Selector はそちらに切り替え、実行中のパトロールを止めます。py_trees が Go to the lookout(見回り地点へ行く)の
terminate()を呼び、それが Nav2 のゴールをキャンセルします。 - 充電が終わると Recharge は成功します。Then go on(そのあと続ける)がその SUCCESS を RUNNING に変えるので、ツリーは終了しません。次の tick で Selector が改めて問い合わせると Recharge は失敗し(バッテリーは満タン)、Patrol が最初の見回り地点からやり直します。Been there already?(もう行った?)がチェック済みの見回り地点を飛ばすので、パトロールは中断したところから続きます。
時間のかかるアクション:アクションごとにスレッドを 1 つ¶
tick はすばやく終わらなければなりませんが、見回り地点まで走るには 1 分ほどかかります。そこで、時間のかかるアクション (Action) はどれもバックグラウンドのスレッドで実行します。最初の tick でアクションを開始し、以降の tick では毎回「もう終わった?」と尋ね(終わるまでは RUNNING)、ツリーがアクションを中断するときは terminate() で停止を求めます。
lime_isaac_bringup/scripts/lime_bt.py の Action、TurnAround、NavigateTo
class Action(py_trees.behaviour.Behaviour):
"""A long action, in a background thread. Subclasses write run(): return True for success, False for
failure, and look at self.stop_requested now and then to stop early when the tree interrupts them."""
robot = threading.Lock() # one robot: one action at a time
def __init__(self, name):
super().__init__(name)
self.thread, self.result, self.stop_requested = None, None, False
def initialise(self): # first tick: start the action
self.result, self.stop_requested = None, False
self.thread = threading.Thread(target=self._run, daemon=True)
self.thread.start()
def _run(self):
try:
with Action.robot: # an interrupted action may still be stopping (cancelling its Nav2 goal)
self.result = bool(self.run())
except Exception as e: # an exception is a failure, not a crash of the whole tree
self.feedback_message = f"{type(e).__name__}: {e}"
self.result = False
def update(self): # every tick: done yet?
if self.thread.is_alive():
return Status.RUNNING
return Status.SUCCESS if self.result else Status.FAILURE
def terminate(self, new_status): # finished, or interrupted by the tree (new_status = INVALID)
if new_status == Status.INVALID and self.thread is not None and self.thread.is_alive():
self.stop_requested = True
self.thread.join()
def run(self) -> bool:
raise NotImplementedError
class TurnAround(Action):
"""Turn round once on the spot, in four quarter turns (with tutorial 13's turn_to(), odometry)."""
def __init__(self, name, lime):
super().__init__(name)
self.lime = lime
def run(self):
_, _, yaw = self.lime.pose()
for k in range(1, 5):
if self.stop_requested:
return False
self.lime.turn_to(yaw + k * math.pi / 2)
return True
class NavigateTo(Action):
"""Drive to a pose (x, y, yaw) in the map frame with Nav2. The pose comes from the blackboard (key) or is
fixed (pose). Interrupted, it cancels the Nav2 goal."""
def __init__(self, name, lime, key=None, pose=None):
super().__init__(name)
self.lime, self.pose = lime, pose
if key:
self.key = key
self.blackboard = self.attach_blackboard_client(name=name)
self.blackboard.register_key(key=key, access=py_trees.common.Access.READ)
def run(self):
x, y, yaw = self.pose if self.pose else self.blackboard.get(self.key)
goal = PoseStamped()
goal.header.frame_id = "map"
goal.header.stamp = self.lime.nav.get_clock().now().to_msg()
goal.pose.position.x, goal.pose.position.y = float(x), float(y)
goal.pose.orientation.z, goal.pose.orientation.w = math.sin(yaw / 2), math.cos(yaw / 2)
if not self.lime.nav.goToPose(goal):
return False
while not self.lime.nav.isTaskComplete(): # spins the node for up to 0.1 s
if self.stop_requested:
self.lime.nav.cancelTask()
return False
return self.lime.nav.getResult() == TaskResult.SUCCEEDED
バッテリーと見回り地点は、1 回の tick で終わる小さなビヘイビアです。
patrol.py の Battery、Charge、BeenThere、CheckOff
class Battery(py_trees.behaviour.Behaviour):
"""Writes the battery level to the blackboard on every tick. The Lime's battery is pretend: it runs down by
DRAIN % per metre driven (measured with odometry). Always SUCCESS: it is a sensor, not a decision."""
def __init__(self, lime):
super().__init__("Battery")
self.lime, self.last = lime, None
self.blackboard = self.attach_blackboard_client(name="Battery")
self.blackboard.register_key(key="battery", access=Access.WRITE)
self.blackboard.battery = 100.0
def update(self):
x, y, _ = self.lime.pose()
if self.last is not None:
self.blackboard.battery = max(0.0, self.blackboard.battery - DRAIN * math.hypot(x - self.last[0], y - self.last[1]))
self.last = (x, y)
self.feedback_message = f"{self.blackboard.battery:.0f} %"
return Status.SUCCESS
class Charge(py_trees.behaviour.Behaviour):
"""Charge until full: +20 % per second. RUNNING while charging."""
def __init__(self, log):
super().__init__("Charge")
self.log = log
self.blackboard = self.attach_blackboard_client(name="Charge")
self.blackboard.register_key(key="battery", access=Access.WRITE)
def update(self):
self.blackboard.battery = min(100.0, self.blackboard.battery + 2.0) # one tick = 0.1 s
if self.blackboard.battery < 100.0:
return Status.RUNNING
self.log.info("battery full")
return Status.SUCCESS
class BeenThere(py_trees.behaviour.Behaviour):
"""Condition: is the current lookout checked off already? (After a recharge the patrol starts again
from the first lookout, and skips the ones it has visited.)"""
def __init__(self):
super().__init__("Been there already?")
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="lookout", access=Access.READ)
self.blackboard.register_key(key="visited", access=Access.READ)
def update(self):
return Status.SUCCESS if self.blackboard.lookout in self.blackboard.visited else Status.FAILURE
class CheckOff(py_trees.behaviour.Behaviour):
def __init__(self, log):
super().__init__("Check it off")
self.log = log
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="lookout", access=Access.READ)
self.blackboard.register_key(key="visited", access=Access.WRITE)
self.blackboard.register_key(key="battery", access=Access.READ)
def update(self):
self.blackboard.visited = self.blackboard.visited + [self.blackboard.lookout]
x, y, _ = self.blackboard.lookout
self.log.info(f"lookout ({x}, {y}) checked, battery {self.blackboard.battery:.0f} %")
return Status.SUCCESS
そして、ツリー本体です。上の図のとおりに組み立てています。
def build_tree(lime, log):
blackboard = py_trees.blackboard.Client(name="patrol")
for key in ("lookouts", "visited"):
blackboard.register_key(key=key, access=Access.WRITE)
blackboard.lookouts, blackboard.visited = LOOKOUTS, []
battery_low = py_trees.behaviours.CheckBlackboardVariableValue(
name=f"Battery below {LOW:.0f} %?", check=ComparisonExpression(variable="battery", value=LOW, operator=operator.lt)
)
recharge = py_trees.composites.Sequence("Recharge", memory=True, children=[
battery_low,
NavigateTo("Go to the charger", lime, pose=CHARGER),
Charge(log),
])
visit = py_trees.composites.Selector("Visit it", memory=False, children=[
BeenThere(),
py_trees.composites.Sequence("Go there", memory=True, children=[
NavigateTo("Go to the lookout", lime, key="lookout"),
TurnAround("Look around", lime),
CheckOff(log),
]),
])
patrol = py_trees.composites.Sequence("Patrol", memory=True, children=[
py_trees.decorators.ForEach("Every lookout", visit, source_key="lookouts", target_key="lookout"),
NavigateTo("Go home", lime, pose=HOME),
])
what_now = py_trees.composites.Selector("What now?", memory=False, children=[
py_trees.decorators.SuccessIsRunning("Then go on", recharge), # after charging: carry on patrolling
patrol,
])
return py_trees.composites.Sequence("Lime patrol", memory=False, children=[Battery(lime), what_now])
run_tree() は、ルートが成功または失敗するまで、ツリーを 1 秒に 10 回 tick します。そして、開始した (...)、成功した (ok)、失敗した (FAIL)、ツリーに中断された (stop) ビヘイビアをすべて表示します。
lime_bt.py の run_tree()
def run_tree(root, log, period=0.1):
"""Tick the tree until it succeeds or fails. Print every behaviour that starts (...), succeeds (ok), fails
(FAIL) or is interrupted by the tree (stop)."""
tree = py_trees.trees.BehaviourTree(root)
tree.setup(timeout=15.0)
log.info("the tree:\n" + py_trees.display.unicode_tree(root))
before, started = {}, {}
while True:
tree.tick()
for b in root.iterate():
if isinstance(b, (py_trees.composites.Composite, py_trees.decorators.Decorator)) or b.status == before.get(b.id):
continue
if b.status == Status.RUNNING:
started[b.id] = time.time()
log.info(f"[bt] ... {b.name}")
elif b.status in (Status.SUCCESS, Status.FAILURE):
begin = started.pop(b.id, None)
took = f" ({time.time() - begin:.0f} s)" if begin and time.time() - begin > 1 else ""
# say why an action failed, or what a decision of ours chose (not py_trees' own condition messages)
ours = not type(b).__module__.startswith("py_trees")
why = f": {b.feedback_message}" if ours and b.feedback_message and (b.status == Status.FAILURE) == isinstance(b, Action) else ""
log.info(f"[bt] {'ok ' if b.status == Status.SUCCESS else 'FAIL'} {b.name}{took}{why}")
elif b.status == Status.INVALID and before.get(b.id) == Status.RUNNING:
started.pop(b.id, None)
log.info(f"[bt] stop {b.name} (interrupted)")
before[b.id] = b.status
if root.status in (Status.SUCCESS, Status.FAILURE):
log.info("the tree at the end:\n" + py_trees.display.unicode_tree(root, show_status=True))
return root.status
time.sleep(period)
実行してみる¶
ターミナル 1 では Isaac Sim を起動します(チュートリアル 11 のワールド:地図を作成済みの部屋とカラーコーン)。
ターミナル 2 では Nav2 + RViz を起動します(チュートリアル 11 のまま、変更なし)。
./scripts/build_ws.sh lime_isaac_bringup # once: installs the patrol
./docker/run_ros.sh ros2 launch lime_isaac_bringup navigation.launch.py
ターミナル 3 ではパトロールを起動します(ターミナル 2 に「Managed nodes are active」と表示されるまで待ってください)。
パトロールは、最初にツリーを 1 回表示します(py_trees の記号:[-] は Sequence、[o] は Selector、{-} はメモリありの Sequence、-^- はデコレーター、--> はビヘイビア)。その後、開始した (...)、成功した (ok)、失敗した (FAIL)、中断された (stop) ビヘイビアをすべて表示します。
[-] Lime patrol
--> Battery
[o] What now?
-^- Then go on
{-} Recharge
--> Battery below 30 %?
--> Go to the charger
--> Charge
{-} Patrol
-^- Every lookout
[o] Visit it
--> Been there already?
{-} Go there
--> Go to the lookout
--> Look around
--> Check it off
--> Go home
[bt] ok Battery: 100 %
[bt] FAIL Battery below 30 %?
[bt] FAIL Been there already?
[bt] ... Go to the lookout
[bt] ok Go to the lookout (20 s)
[bt] ... Look around
lookout (3.2, -1.8) checked, battery 80 %
[bt] ok Look around (20 s)
[bt] ok Check it off
[bt] ... Go to the lookout
[bt] ok Go to the lookout (16 s)
[bt] ... Look around
lookout (3.3, 1.9) checked, battery 62 %
[bt] ok Look around (20 s)
[bt] ok Check it off
[bt] ... Go to the lookout
[bt] ok Go to the lookout (30 s)
[bt] ... Look around
lookout (0.5, 1.9) checked, battery 40 %
[bt] ok Look around (19 s)
[bt] ok Check it off
[bt] ... Go to the lookout
[bt] ok Battery below 30 %?
[bt] ... Go to the charger
[bt] stop Go to the lookout (interrupted)
[bt] ok Go to the charger (8 s)
[bt] ... Charge
battery full
[bt] ok Charge (4 s)
[bt] FAIL Battery below 30 %?
[bt] ok Been there already?
[bt] FAIL Been there already?
[bt] ... Go to the lookout
[bt] ok Go to the lookout (10 s)
[bt] ... Look around
lookout (-1.3, -1.8) checked, battery 91 %
[bt] ok Look around (19 s)
[bt] ok Check it off
[bt] ... Go home
[bt] ok Go home (13 s)
patrol complete
中断の流れを追ってみましょう。見回り地点 4 へ向かう途中で Battery below 30 %? が成功します。Selector は Recharge に切り替え、実行中の Go to the lookout は止められます(その Nav2 のゴールはキャンセルされます)。充電後、パトロールは最初の見回り地点からやり直します。Been there already? は見回り地点 1〜3 では成功し(tick ごとに 1 つずつ。ログにはステータスが変わったときだけ表示されます)、見回り地点 4 では失敗するので、ロボットはそこへ向かいます。
自動チェック¶
python isaac/15_behavior_tree.py --headless --test は、シミュレーションの正解(ground truth)を使ってパトロールを追跡します。ロボットがたどり着いた見回り地点と充電器をすべて記録し、その順番をチェックします。tools/run_all_checks.sh 15 は Nav2 とパトロールを起動します。
[15] at lookout 1, t = 29 s
[15] at lookout 2, t = 63 s
[15] at lookout 3, t = 108 s
[15] at charger, t = 146 s
[15] at lookout 4, t = 160 s
[15] back home, t = 192 s
[15][check] ok the four lookouts in order (lookout 1, lookout 2, lookout 3, charger, lookout 4)
[15][check] ok one stop at the charger, between two lookouts
[15][check] ok back home at the end
[15][check] ok cone not touched (moved 0.0 cm)
[15][test] PASS
Isaac Sim 側:isaac/15_behavior_tree.py
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0
"""Tutorial 15 - Behavior trees: a patrol with Nav2, interrupted by a (pretend) low battery.
source scripts/isaac_env.sh
python isaac/15_behavior_tree.py
# ROS 2 container: Nav2 + RViz (tutorial 11), then the patrol - a behavior tree
./docker/run_ros.sh ros2 launch lime_isaac_bringup navigation.launch.py
./docker/run_ros.sh ros2 run lime_isaac_bringup patrol
The world of tutorial 11: the lime_room as it was mapped, plus the traffic cone that is not in the map.
Nothing new on the Isaac Sim side: the behavior tree runs in ROS 2 and only sends Nav2 goals.
--test follows the patrol with the simulation's ground truth: the four lookouts in order, one stop at the
charger, back home, and the cone not touched.
"""
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 graphs, lime, sensors
from common.scene import add_traffic_cone, build_lime_room
from isaacsim.core.experimental.prims import Articulation, XformPrim
from isaacsim.core.simulation_manager import SimulationManager
graphs.enable_ros2_realtime(simulation_app)
stage = stage_utils.create_new_stage(template="empty")
build_lime_room(stage, with_objects=False) # tutorial 11: the room as it was mapped
cone = add_traffic_cone(stage) # ... and the traffic cone that is not in the map
while stage_utils.is_stage_loading():
simulation_app.update()
robot_path = "/World/turtlebot3_lime"
articulation_root = lime.add_lime(robot_path)
graphs.create_clock_graph() # 06
graphs.create_drive_graph(articulation_root) # 06 /cmd_vel
graphs.create_odom_tf_joint_states_graph(articulation_root) # 07 /odom /tf /joint_states
graphs.create_lidar_graph(sensors.add_lds_lidar(robot_path)) # 09 /scan
recorder = None
if args.record:
from common.recorder import Recorder
recorder = Recorder(args.record, eye=(1.0, -4.6, 4.6), target=(0.9, 0.0, 0.0), every_n=12, fps=20)
SimulationManager.setup_simulation(dt=1.0 / 60.0)
app_utils.play()
simulation_app.update()
robot = Articulation(articulation_root)
print("[15] ready: start Nav2 (ros2 launch lime_isaac_bringup navigation.launch.py), then ros2 run lime_isaac_bringup patrol", flush=True)
# the places of the patrol (patrol.py): where the robot must stop, in this order (the charger somewhere in between)
PLACES = {"lookout 1": (3.2, -1.8), "lookout 2": (3.3, 1.9), "lookout 3": (0.5, 1.9), "lookout 4": (-1.3, -1.8), "charger": (-1.5, 0.0)}
HOME = np.array([0.0, 0.0])
visits, steps, here, still = [], 0, None, 0
cone_prim = XformPrim(cone)
rest = None
while simulation_app.is_running():
simulation_app.update()
steps += 1
if recorder:
recorder.capture()
if args.test or args.record:
if steps == 60: # the cone has settled
rest = cone_prim.get_world_poses()[0].numpy()[0].copy()
xy = robot.get_world_poses()[0].numpy()[0, :2]
near = next((name for name, p in PLACES.items() if np.linalg.norm(xy - p) < 0.3), None)
if near and near != here and visits[-1:] != [near]: # came to a place
visits.append(near)
print(f"[15] at {near}, t = {steps / 60:.0f} s", flush=True)
here = near
speed = np.linalg.norm(robot.get_velocities()[0].numpy()[0, :2])
home = len([v for v in visits if v.startswith("lookout")]) == 4 and np.linalg.norm(xy - HOME) < 0.3
still = still + 1 if home and speed < 0.02 else 0
if still == 60:
print(f"[15] back home, t = {steps / 60:.0f} s", flush=True)
if still > 180 or steps > 600 * 60:
break
ok = True
if args.test:
lookouts = [v for v in visits if v.startswith("lookout")]
checks = {
f"the four lookouts in order ({', '.join(visits)})": lookouts == ["lookout 1", "lookout 2", "lookout 3", "lookout 4"],
"one stop at the charger, between two lookouts": visits.count("charger") == 1 and 0 < visits.index("charger") < len(visits) - 1,
"back home at the end": still > 180,
}
moved = np.linalg.norm(cone_prim.get_world_poses()[0].numpy()[0] - rest)
checks[f"cone not touched (moved {moved * 100:.1f} cm)"] = moved < 0.01
for text, passed in checks.items():
print(f"[15][check] {'ok ' if passed else 'FAIL'} {text}")
ok = all(checks.values())
print(f"[15][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)
パトロール全体:lime_isaac_bringup/scripts/patrol.py
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0
"""Tutorial 15 mission: a patrol, written as a behavior tree (py_trees).
ros2 run lime_isaac_bringup patrol
ros2 run lime_isaac_bringup patrol --render DIR # only draw the tree (DIR/patrol.png), no robot needed
The Lime visits four lookouts with Nav2, looks around at each, then goes home. It has a (pretend) battery that runs down as it
drives. When the battery is low, the tree interrupts the patrol, sends the robot to the charger, and then
continues the patrol where it was interrupted.
"""
import argparse
import math
import operator
import os
import sys
import py_trees
import rclpy
from geometry_msgs.msg import PoseStamped
from py_trees.common import Access, ComparisonExpression, Status
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) # tutorial 13's mission.py, lime_bt.py
from lime_bt import NavigateTo, TurnAround, run_tree # noqa: E402
LOOKOUTS = [(3.2, -1.8, 0.0), (3.3, 1.9, math.pi / 2), (0.5, 1.9, math.pi), (-1.3, -1.8, -math.pi / 2)] # x, y, yaw
CHARGER = (-1.5, 0.0, math.pi)
HOME = (0.0, 0.0, 0.0)
DRAIN = 5.0 # % per metre driven (a pretend battery)
LOW = 30.0 # %
class Battery(py_trees.behaviour.Behaviour):
"""Writes the battery level to the blackboard on every tick. The Lime's battery is pretend: it runs down by
DRAIN % per metre driven (measured with odometry). Always SUCCESS: it is a sensor, not a decision."""
def __init__(self, lime):
super().__init__("Battery")
self.lime, self.last = lime, None
self.blackboard = self.attach_blackboard_client(name="Battery")
self.blackboard.register_key(key="battery", access=Access.WRITE)
self.blackboard.battery = 100.0
def update(self):
x, y, _ = self.lime.pose()
if self.last is not None:
self.blackboard.battery = max(0.0, self.blackboard.battery - DRAIN * math.hypot(x - self.last[0], y - self.last[1]))
self.last = (x, y)
self.feedback_message = f"{self.blackboard.battery:.0f} %"
return Status.SUCCESS
class Charge(py_trees.behaviour.Behaviour):
"""Charge until full: +20 % per second. RUNNING while charging."""
def __init__(self, log):
super().__init__("Charge")
self.log = log
self.blackboard = self.attach_blackboard_client(name="Charge")
self.blackboard.register_key(key="battery", access=Access.WRITE)
def update(self):
self.blackboard.battery = min(100.0, self.blackboard.battery + 2.0) # one tick = 0.1 s
if self.blackboard.battery < 100.0:
return Status.RUNNING
self.log.info("battery full")
return Status.SUCCESS
class BeenThere(py_trees.behaviour.Behaviour):
"""Condition: is the current lookout checked off already? (After a recharge the patrol starts again
from the first lookout, and skips the ones it has visited.)"""
def __init__(self):
super().__init__("Been there already?")
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="lookout", access=Access.READ)
self.blackboard.register_key(key="visited", access=Access.READ)
def update(self):
return Status.SUCCESS if self.blackboard.lookout in self.blackboard.visited else Status.FAILURE
class CheckOff(py_trees.behaviour.Behaviour):
def __init__(self, log):
super().__init__("Check it off")
self.log = log
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="lookout", access=Access.READ)
self.blackboard.register_key(key="visited", access=Access.WRITE)
self.blackboard.register_key(key="battery", access=Access.READ)
def update(self):
self.blackboard.visited = self.blackboard.visited + [self.blackboard.lookout]
x, y, _ = self.blackboard.lookout
self.log.info(f"lookout ({x}, {y}) checked, battery {self.blackboard.battery:.0f} %")
return Status.SUCCESS
def build_tree(lime, log):
blackboard = py_trees.blackboard.Client(name="patrol")
for key in ("lookouts", "visited"):
blackboard.register_key(key=key, access=Access.WRITE)
blackboard.lookouts, blackboard.visited = LOOKOUTS, []
battery_low = py_trees.behaviours.CheckBlackboardVariableValue(
name=f"Battery below {LOW:.0f} %?", check=ComparisonExpression(variable="battery", value=LOW, operator=operator.lt)
)
recharge = py_trees.composites.Sequence("Recharge", memory=True, children=[
battery_low,
NavigateTo("Go to the charger", lime, pose=CHARGER),
Charge(log),
])
visit = py_trees.composites.Selector("Visit it", memory=False, children=[
BeenThere(),
py_trees.composites.Sequence("Go there", memory=True, children=[
NavigateTo("Go to the lookout", lime, key="lookout"),
TurnAround("Look around", lime),
CheckOff(log),
]),
])
patrol = py_trees.composites.Sequence("Patrol", memory=True, children=[
py_trees.decorators.ForEach("Every lookout", visit, source_key="lookouts", target_key="lookout"),
NavigateTo("Go home", lime, pose=HOME),
])
what_now = py_trees.composites.Selector("What now?", memory=False, children=[
py_trees.decorators.SuccessIsRunning("Then go on", recharge), # after charging: carry on patrolling
patrol,
])
return py_trees.composites.Sequence("Lime patrol", memory=False, children=[Battery(lime), what_now])
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--render", metavar="DIR", help="only draw the tree into DIR (patrol.png / .svg / .dot)")
args, _ros = parser.parse_known_args()
if args.render:
py_trees.display.render_dot_tree(build_tree(None, None), target_directory=args.render, name="patrol")
return
from mission import Lime, wait_until_nav2_active # tutorial 13: Nav2 (BasicNavigator), TF, odometry pose
rclpy.init()
lime = Lime()
start = PoseStamped()
start.header.frame_id = "map"
start.header.stamp = lime.nav.get_clock().now().to_msg()
start.pose.orientation.w = 1.0
lime.nav.setInitialPose(start) # the robot starts at the map origin
wait_until_nav2_active(lime.nav)
status = run_tree(build_tree(lime, lime.log), lime.log)
lime.log.info("patrol complete" if status == Status.SUCCESS else "patrol FAILED")
lime.close()
sys.exit(0 if status == Status.SUCCESS else 1)
if __name__ == "__main__":
main()
トラブルシューティング¶
| 症状 | 対処 |
|---|---|
RuntimeError: Executor is already spinning |
2 つのアクションが同時にロボットの ROS ノードを使いました。py_trees は、中断されたアクションを止める前に新しいアクションを開始します。Action はロック (Action.robot) を取るので、新しいアクションは、古いアクションが Nav2 のゴールをキャンセルし終えるまで待ちます。 |
| 充電後、パトロールが最初の見回り地点からやり直す | ツリーはそのように動作します。Been there already? が訪問済みの見回り地点を飛ばす必要があります。Check it off が実行されているか確かめてください(Go there の最後の子です)。 |
ModuleNotFoundError: No module named 'py_trees' |
コンテナイメージが、py_trees を追加したチュートリアル 15 より古いものです。イメージを再ビルドし、コンテナを再起動してください。docker build -t lime_ros_jazzy:latest docker/ros_jazzy を実行してから docker stop lime_ros を実行します(次の ./docker/run_ros.sh で新しいコンテナが起動します)。 |
| 開始時からパトロールがずっと待ち続ける | Nav2 がまだアクティブになっていません。「Managed nodes are active」と表示されるまで待ってください。シミュレーションは再生中ですか? |