Source code for reli.executor

"""Action execution.

Primitives are executed on the robot one by one in a worker thread. A new motion plan preempts the
running one; STOP preempts everything. Query-only plans (pose, objects, images) run alongside motion
without interrupting it.

Each job reports through its own ``Reporter``, so progress messages of a plan stay in the language
of the turn that started it even if the user meanwhile switched language.
"""

from __future__ import annotations

import logging
import math
import threading
import time
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field

import numpy as np

from .actions import is_motion
from .config import ReLIConfig
from .perception import GroundedObject, Grounder
from .robot.base import MotionResult, Robot
from .safety import SafetyGuard
from .types import Action, Pose2D

log = logging.getLogger(__name__)


[docs] class Reporter: """Receives everything a job wants to tell the user. The default is silent."""
[docs] def say(self, key: str, **values) -> None: """Catalogue message ``key`` (rendered in the user's language by the agent)."""
[docs] def speak(self, text: str) -> None: """Free text that is already in the user's language."""
[docs] def image(self, image: np.ndarray) -> None: """A camera image (BGR) for the user."""
[docs] def status(self, data: dict) -> None: """Structured progress information."""
[docs] def narrate(self, evidence: list[str], image: np.ndarray | None) -> str | None: """Describe the scene in the user's language, or None to fall back to a list.""" return None
def fmt(value: float, digits: int = 2) -> str: """Compact number for spoken output: 2.0 -> '2', 0.25 -> '0.25'.""" text = f"{value:.{digits}f}" if "." in text: text = text.rstrip("0").rstrip(".") return "0" if text in ("-0", "") else text @dataclass class StepOutcome: index: int action: str success: bool reason: str = "" @dataclass class ExecutionReport: start_pose: Pose2D end_pose: Pose2D | None = None steps: list[StepOutcome] = field(default_factory=list) cancelled: bool = False started: float = field(default_factory=time.time) finished: float | None = None @property def success(self) -> bool: return not self.cancelled and all(s.success for s in self.steps) @dataclass class _Job: cancel: threading.Event thread: threading.Thread | None = None
[docs] class Executor: def __init__( self, cfg: ReLIConfig, robot: Robot, grounder: Grounder | None, guard: SafetyGuard, ): self.cfg = cfg self.robot = robot self.grounder = grounder self.guard = guard self.lim = cfg.robot.limits self._lock = threading.Lock() self._motion: _Job | None = None self._local = threading.local() # the reporter of the job running in this thread @property def _rep(self) -> Reporter: return getattr(self._local, "reporter", None) or Reporter() def say(self, key: str, **values) -> None: self._rep.say(key, **values) # ------------------------------------------------------------ scheduling @property def busy(self) -> bool: job = self._motion return bool(job and job.thread and job.thread.is_alive())
[docs] def submit( self, actions: Sequence[Action], reporter: Reporter | None = None, on_done: Callable[[ExecutionReport], None] = lambda r: None, ) -> None: """Run ``actions`` in the background (motion plans preempt each other).""" motion = is_motion(actions) job = _Job(threading.Event()) if motion: self.cancel_motion() with self._lock: self._motion = job def work() -> None: report = self.run(actions, job.cancel, reporter) on_done(report) job.thread = threading.Thread(target=work, name="reli-exec", daemon=True) job.thread.start()
def cancel_motion(self, timeout: float = 5.0) -> None: with self._lock: job, self._motion = self._motion, None if job is None: return job.cancel.set() self.robot.stop() if job.thread and job.thread is not threading.current_thread(): job.thread.join(timeout) def emergency_stop(self) -> None: self.cancel_motion(timeout=0.0) self.robot.stop() # ------------------------------------------------------------- execution
[docs] def run( self, actions: Sequence[Action], cancel: threading.Event | None = None, reporter: Reporter | None = None, ) -> ExecutionReport: """Execute synchronously; returns a report (also used by the evaluator).""" self._local.reporter = reporter cancel = cancel or threading.Event() report = ExecutionReport(self.robot.pose()) for i, a in enumerate(actions, 1): if cancel.is_set(): report.cancelled = True break try: result = self._dispatch(a, cancel) except Exception as exc: # one failing step must not kill the job log.exception("Step %d (%s) raised", i, a.name) result = MotionResult(False, str(exc)) report.steps.append(StepOutcome(i, a.name, result.success, result.reason)) self._rep.status( { "step": i, "total": len(actions), "action": a.name, "success": result.success, "pose": self.robot.pose().to_dict(), } ) if not result.success: if result.reason == "cancelled" or cancel.is_set(): report.cancelled = True elif not result.reported: self.say("step_failed", step=i, action=a.name, reason=result.reason) break # later steps assume this one succeeded report.end_pose = self.robot.pose() report.finished = time.time() return report
def _dispatch(self, a: Action, cancel: threading.Event) -> MotionResult: name = a.name speed = a.get("speed", self.lim.linear_speed_default) if name == "MOVE": d = a.params["distance"] * (-1.0 if a.get("direction") == "backward" else 1.0) res = self.robot.move(d, speed, cancel) if res.success: self.say("moved_backward" if d < 0 else "moved_forward", distance=fmt(abs(d))) return res if name == "TURN": left = a.get("direction", "left") == "left" angle = math.radians(a.params["angle"]) * (1.0 if left else -1.0) w = math.radians(a.get("angular_speed", self.lim.angular_speed_default_deg)) res = self.robot.turn(angle, w, cancel) if res.success: self.say("turned_left" if left else "turned_right", angle=fmt(a.params["angle"])) return res if name == "ARC": res = self.robot.arc( a.params["radius"], math.radians(a.get("angle", 360.0)), speed, a.get("direction", "left") == "left", cancel, ) if res.success: self.say("arc_done") return res if name == "GO_TO_COORDINATES": x, y, yaw = a.params["x"], a.params["y"], a.get("yaw") res = self.robot.navigate_to( x, y, None if yaw is None else math.radians(yaw), speed, cancel ) return self._report_nav(res, "arrived_coordinates", x=fmt(x), y=fmt(y)) if name == "GO_TO_DESTINATION": key = a.params["destination"] dest = self.cfg.destinations[key] yaw = None if dest.yaw_deg is None else math.radians(dest.yaw_deg) res = self.robot.navigate_to(dest.x, dest.y, yaw, speed, cancel) return self._report_nav(res, "arrived_destination", destination=dest.name or key) if name in ("GO_TO_OBJECT", "FACE_OBJECT", "CIRCLE_OBJECT"): return self._object_action(a, speed, cancel) if name == "DESCRIBE_SCENE": return self._describe() if name == "REPORT_POSE": p = self.robot.pose() self.say("pose_report", x=fmt(p.x), y=fmt(p.y), yaw=fmt(p.yaw_deg, 0)) return MotionResult(True) if name == "LOCATE_OBJECTS": return self._locate(a.get("object"), cancel) if name == "SEND_IMAGE": return self._send_image() if name == "WAIT": res = self.robot.wait(a.params["duration"], cancel) if res.success: self.say("waited", duration=fmt(a.params["duration"])) return res if name == "STOP": self.robot.stop() self.say("stopped") return MotionResult(True) return MotionResult(False, f"no executor for {name}") def _report_nav(self, res: MotionResult, key: str, **values) -> MotionResult: if res.success: self.say(key, **values) return res return self._nav_failed(res) def _nav_failed(self, res: MotionResult) -> MotionResult: if res.reason == "cancelled": return res self.say("navigation_failed", reason=res.reason) return MotionResult(False, res.reason, reported=True) # ------------------------------------------------------- object actions def _find(self, name: str, cancel: threading.Event) -> GroundedObject | None: """Ground ``name``: current view, then an active turn-in-place search, then memory.""" assert self.grounder is not None obs = self.grounder.observe([name]) if obs.objects: return obs.objects[0] search = self.cfg.perception.search if search.enabled: self.say("searching", object=name) w = math.radians(self.lim.angular_speed_default_deg) turned = 0.0 while turned + search.step_deg <= search.max_deg + 1e-6 and not cancel.is_set(): if not self.robot.turn(math.radians(search.step_deg), w, cancel).success: break turned += search.step_deg obs = self.grounder.observe([name]) if obs.objects: return obs.objects[0] remembered = self.grounder.remembered(name) return remembered[0] if remembered else None def _object_action(self, a: Action, speed: float, cancel: threading.Event) -> MotionResult: if self.grounder is None: self.say("no_camera") return MotionResult(False, "no perception", reported=True) name = a.params["object"] obj = self._find(name, cancel) if cancel.is_set(): return MotionResult(False, "cancelled") if obj is None: self.say("object_not_found", object=name) return MotionResult(False, f"{name} not found", reported=True) if obj.position is None: self.say("object_no_depth", object=name) return MotionResult(False, f"no depth for {name}", reported=True) ox, oy = float(obj.position[0]), float(obj.position[1]) radius = obj.radius_m or 0.0 w = math.radians(self.lim.angular_speed_default_deg) if a.name == "FACE_OBJECT": res = self.robot.face(ox, oy, w, cancel) if res.success: self.say("object_faced", object=name) return res pose = self.robot.pose() theta = math.atan2(oy - pose.y, ox - pose.x) if a.name == "GO_TO_OBJECT": standoff = radius + a.get("approach_distance", self.cfg.perception.approach_distance_m) if pose.distance_to(ox, oy) > standoff: gx, gy = ox - standoff * math.cos(theta), oy - standoff * math.sin(theta) if not self.guard.goal_allowed(gx, gy): return MotionResult(False, "object lies outside the workspace") res = self.robot.navigate_to(gx, gy, theta, speed, cancel) if not res.success: return self._nav_failed(res) res = self.robot.face(ox, oy, w, cancel) if res.success: self.say("object_reached", object=name) return res # CIRCLE_OBJECT: reach the circle on the robot's side, turn tangent, drive 360 deg. r = radius + a.get("clearance", 0.5) if not all( self.guard.goal_allowed(ox + dx, oy + dy) for dx, dy in ((r, 0), (-r, 0), (0, r), (0, -r)) ): return MotionResult(False, "the circle would leave the workspace") left = a.get("direction", "left") == "left" gx, gy = ox - r * math.cos(theta), oy - r * math.sin(theta) tangent = theta + (-math.pi / 2 if left else math.pi / 2) res = self.robot.navigate_to(gx, gy, tangent, speed, cancel) if not res.success: return self._nav_failed(res) res = self.robot.arc(r, 2 * math.pi, speed, left, cancel) if res.success: self.say("object_circled", object=name) return res # ---------------------------------------------------------------- queries def _evidence(self, objects: list[GroundedObject]) -> list[str]: lines = [] for o in objects: where = "" if o.range_m is not None and o.bearing_rad is not None: deg = math.degrees(o.bearing_rad) side = ( "ahead" if abs(deg) < 10 else ( f"{abs(deg):.0f} deg to the left" if deg > 0 else f"{abs(deg):.0f} deg to the right" ) ) where = f", {o.range_m:.1f} m away, {side}" lines.append(f"- {o.label} (confidence {o.score:.2f}{where})") return lines def _describe(self) -> MotionResult: if self.grounder is None: self.say("no_camera") return MotionResult(False, "no perception", reported=True) obs = self.grounder.observe(None) if obs.image is not None: self._rep.image(self.grounder.annotate(obs.image, obs.objects)) text = None if obs.objects or obs.image is not None: text = self._rep.narrate(self._evidence(obs.objects), obs.image) if text: self._rep.speak(text) elif obs.objects: self.say("object_list", objects=", ".join(o.label for o in obs.objects)) else: self.say("object_none") return MotionResult(True) def _locate(self, name: str | None, cancel: threading.Event) -> MotionResult: if self.grounder is None: self.say("no_camera") return MotionResult(False, "no perception", reported=True) if name is None: seen = self.grounder.observe(None).objects labels = {o.label for o in seen} seen += [o for o in self.grounder.remembered() if o.label not in labels] if not seen: self.say("object_none") else: self.say( "object_list", objects=", ".join( f"{o.label} ({fmt(o.range_m, 1)} m)" if o.range_m is not None else o.label for o in seen ), ) return MotionResult(True) obj = self._find(name, cancel) if obj is None: self.say("object_not_found", object=name) return MotionResult(True) # answering "not found" is a successful query if obj.position is None or obj.range_m is None or obj.bearing_rad is None: self.say("object_no_depth", object=name) return MotionResult(True) values = dict( object=name, distance=fmt(obj.range_m, 1), x=fmt(float(obj.position[0])), y=fmt(float(obj.position[1])), ) if obj.source == "memory": self.say("object_location_memory", age=fmt(obj.age_s, 0), **values) else: deg = math.degrees(obj.bearing_rad) if abs(deg) < 10: self.say("object_location_ahead", **values) else: self.say( "object_location_left" if deg > 0 else "object_location_right", angle=fmt(abs(deg), 0), **values, ) return MotionResult(True) def _send_image(self) -> MotionResult: frame = self.grounder.frame() if self.grounder is not None else None if frame is None: self.say("no_camera") return MotionResult(False, "no camera image", reported=True) self._rep.image(frame) self.say("image_sent") return MotionResult(True)