Datasets:
Download code/robohome/src/engine/source/packages/evaluator/engine.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 16.8 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/source/packages/evaluator/engine.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome/code/robohome/src/engine/source/packages/evaluator/engine.py
-
curl -L -o engine.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/source/packages/evaluator/engine.py
16.8 kB
| from __future__ import annotations | |
| from dataclasses import dataclass, field | |
| from math import degrees, radians | |
| from typing import Any, Protocol | |
| from packages.schemas.models import ( | |
| EvaluationResult, | |
| PredicateResult, | |
| PredicateSpec, | |
| StageEvaluationResult, | |
| TaskSpec, | |
| TaskStageSpec, | |
| ) | |
| class FactProvider(Protocol): | |
| def evaluate(self, predicate: PredicateSpec) -> tuple[bool, dict[str, Any]]: ... | |
| class ObservationFrame: | |
| time_s: float | |
| facts: dict[tuple[str, str, str | None], bool] | |
| values: dict[str, float] | |
| evidence: dict[tuple[str, str, str | None], dict[str, Any] | list[dict[str, Any]]] = field( | |
| default_factory=dict | |
| ) | |
| value_units: dict[str, str] = field(default_factory=dict) | |
| class TraceFactProvider: | |
| """Evaluate terminal and temporal predicates from simulator observations.""" | |
| frames: list[ObservationFrame] | |
| def _joint_value(predicate: PredicateSpec, frame: ObservationFrame, joint: str) -> float: | |
| value = frame.values[joint] | |
| source_unit = frame.value_units.get(joint) | |
| target_unit = predicate.params.get("unit") | |
| if source_unit == "radians" and target_unit == "degrees": | |
| return degrees(value) | |
| if source_unit == "degrees" and target_unit == "radians": | |
| return radians(value) | |
| return value | |
| def _contact_evidence_matches(predicate: PredicateSpec, frame: ObservationFrame) -> bool: | |
| expected_body = predicate.params.get("subject_body") | |
| expected_link = predicate.params.get("object_link") | |
| if expected_body is None and expected_link is None: | |
| return True | |
| key = (predicate.name, predicate.subject, predicate.object) | |
| raw_records = frame.evidence.get(key) | |
| if raw_records is None: | |
| return False | |
| records = raw_records if isinstance(raw_records, list) else [raw_records] | |
| allowed_bodies = ( | |
| {"left_foot", "right_foot"} | |
| if expected_body == "left_or_right_foot" | |
| else {str(expected_body)} | |
| ) | |
| return any( | |
| (expected_body is None or record.get("subject_body") in allowed_bodies) | |
| and (expected_link is None or record.get("object_link") == expected_link) | |
| for record in records | |
| ) | |
| def _passes_at(predicate: PredicateSpec, frame: ObservationFrame) -> bool: | |
| if predicate.name in {"pressed", "open"}: | |
| joint = str(predicate.params.get("joint", "")) | |
| if joint in frame.values: | |
| threshold = float(predicate.params.get("threshold", 0.0)) | |
| value = TraceFactProvider._joint_value(predicate, frame, joint) | |
| return ( | |
| value <= threshold | |
| if predicate.params.get("direction") == "lte" | |
| else value >= threshold | |
| ) | |
| key = (predicate.name, predicate.subject, predicate.object) | |
| passed = bool(frame.facts.get(key, False)) | |
| if passed and predicate.name == "contact": | |
| passed = TraceFactProvider._contact_evidence_matches(predicate, frame) | |
| return passed | |
| def _matching_frames(self, predicate: PredicateSpec) -> list[ObservationFrame]: | |
| return [frame for frame in self.frames if self._passes_at(predicate, frame)] | |
| def evaluate(self, predicate: PredicateSpec) -> tuple[bool, dict[str, Any]]: | |
| if not self.frames: | |
| return False, {"source": "simulator_trace", "reason": "empty_trace"} | |
| key = (predicate.name, predicate.subject, predicate.object) | |
| temporal = str(predicate.params.get("temporal", "current")) | |
| candidates = self.frames if temporal in {"ever", "always"} else self.frames[-1:] | |
| matched = [frame for frame in candidates if self._passes_at(predicate, frame)] | |
| observed: dict[str, Any] = { | |
| "fact_key": key, | |
| "source": "simulator_trace", | |
| "temporal": temporal, | |
| } | |
| if matched: | |
| observed["first_match_time_s"] = matched[0].time_s | |
| if predicate.hold_seconds > 0: | |
| held, hold_observed = self._evaluate_hold(predicate, temporal) | |
| observed.update(hold_observed) | |
| return held, observed | |
| if temporal == "always": | |
| observed["matched_frame_count"] = len(matched) | |
| observed["total_frame_count"] = len(candidates) | |
| return len(matched) == len(candidates), observed | |
| if predicate.name in {"pressed", "open"}: | |
| joint = str(predicate.params.get("joint", "")) | |
| threshold = float(predicate.params.get("threshold", 0.0)) | |
| direction = str(predicate.params.get("direction", "gte")) | |
| values = [ | |
| self._joint_value(predicate, frame, joint) | |
| for frame in candidates | |
| if joint in frame.values | |
| ] | |
| if values: | |
| observed.update( | |
| joint=joint, | |
| observed_min=min(values), | |
| observed_max=max(values), | |
| ) | |
| joint_passed = ( | |
| any(value <= threshold for value in values) | |
| if direction == "lte" | |
| else any(value >= threshold for value in values) | |
| ) | |
| return joint_passed, observed | |
| return bool(matched), observed | |
| def _evaluate_hold( | |
| self, predicate: PredicateSpec, temporal: str | |
| ) -> tuple[bool, dict[str, Any]]: | |
| runs: list[tuple[float, float]] = [] | |
| run_start: float | None = None | |
| run_end: float | None = None | |
| for frame in self.frames: | |
| if self._passes_at(predicate, frame): | |
| run_start = frame.time_s if run_start is None else run_start | |
| run_end = frame.time_s | |
| elif run_start is not None and run_end is not None: | |
| runs.append((run_start, run_end)) | |
| run_start = run_end = None | |
| if run_start is not None and run_end is not None: | |
| runs.append((run_start, run_end)) | |
| required = predicate.hold_seconds | |
| eligible = [run for run in runs if run[1] - run[0] >= required] | |
| if temporal == "current": | |
| eligible = [run for run in eligible if run[1] == self.frames[-1].time_s] | |
| best_duration = max((end - start for start, end in runs), default=0.0) | |
| return bool(eligible), { | |
| "hold_seconds_required": required, | |
| "longest_hold_seconds": best_duration, | |
| "hold_interval_s": list(eligible[0]) if eligible else None, | |
| } | |
| def evaluate_synchronized( | |
| self, predicates: list[PredicateSpec], window_s: float | |
| ) -> tuple[bool, dict[str, Any]]: | |
| matches = [self._matching_frames(predicate) for predicate in predicates] | |
| if any(not frames for frames in matches): | |
| return False, { | |
| "source": "simulator_trace", | |
| "reason": "synchronized_predicate_missing", | |
| "window_s": window_s, | |
| } | |
| event_times = sorted({frame.time_s for frames in matches for frame in frames}) | |
| for start in event_times: | |
| end = start + window_s | |
| selected = [ | |
| next((frame.time_s for frame in frames if start <= frame.time_s <= end), None) | |
| for frames in matches | |
| ] | |
| if all(value is not None for value in selected): | |
| matched_times = [value for value in selected if value is not None] | |
| return True, { | |
| "source": "simulator_trace", | |
| "window_s": window_s, | |
| "matched_times_s": matched_times, | |
| "synchronized_interval_s": [start, max(matched_times)], | |
| } | |
| return False, { | |
| "source": "simulator_trace", | |
| "reason": "events_outside_synchronization_window", | |
| "window_s": window_s, | |
| "candidate_times_s": [[frame.time_s for frame in frames] for frames in matches], | |
| } | |
| class MappingFactProvider: | |
| facts: dict[tuple[str, str, str | None], bool] | |
| def evaluate(self, predicate: PredicateSpec) -> tuple[bool, dict[str, Any]]: | |
| key = (predicate.name, predicate.subject, predicate.object) | |
| value = self.facts.get(key, False) | |
| if predicate.name == "not": | |
| value = not value | |
| return value, {"fact_key": key, "source": "simulator_truth"} | |
| class DeterministicEvaluator: | |
| def evaluate_task(self, task: TaskSpec, provider: FactProvider) -> EvaluationResult: | |
| result = self.evaluate(task.goal_predicates, task.safety_predicates, provider) | |
| stage_results: list[StageEvaluationResult] = [] | |
| completion_indices: dict[str, int] = {} | |
| for stage in task.stages: | |
| missing = [ | |
| dependency | |
| for dependency in stage.depends_on | |
| if dependency not in completion_indices | |
| ] | |
| if missing: | |
| stage_results.append( | |
| StageEvaluationResult( | |
| stage_id=stage.stage_id, | |
| passed=False, | |
| score=0.0, | |
| predicate_results=[], | |
| failure_reason=f"dependency_failed:{','.join(missing)}", | |
| ) | |
| ) | |
| continue | |
| start_index = ( | |
| max(completion_indices[dependency] for dependency in stage.depends_on) + 1 | |
| if stage.depends_on | |
| else 0 | |
| ) | |
| stage_result, completion_index = self._evaluate_stage( | |
| stage, provider, start_index=start_index | |
| ) | |
| stage_results.append(stage_result) | |
| if completion_index is not None: | |
| completion_indices[stage.stage_id] = completion_index | |
| total_weight = sum(stage.weight for stage in task.stages) | |
| achieved_weight = sum( | |
| stage.weight * stage_result.score | |
| for stage, stage_result in zip(task.stages, stage_results, strict=True) | |
| ) | |
| progress = achieved_weight / total_weight if total_weight else result.final_score | |
| return result.model_copy( | |
| update={"stage_results": stage_results, "stage_progress": progress} | |
| ) | |
| def evaluate( | |
| self, | |
| goals: list[PredicateSpec], | |
| safety: list[PredicateSpec], | |
| provider: FactProvider, | |
| ) -> EvaluationResult: | |
| goal_results = [self._evaluate(item, provider) for item in goals] | |
| goal_results = self._enforce_synchronization(goals, goal_results, provider) | |
| safety_results = [self._evaluate(item, provider) for item in safety] | |
| passed_goals = sum(item.passed for item in goal_results) | |
| score = passed_goals / len(goal_results) if goal_results else 0.0 | |
| safety_events = [ | |
| f"failed:{item.predicate.name}:{item.predicate.subject}" | |
| for item in safety_results | |
| if not item.passed | |
| ] | |
| success = bool(goal_results) and score == 1.0 and not safety_events | |
| first_success_time_s = None | |
| if success and isinstance(provider, TraceFactProvider) and provider.frames: | |
| first_success_time_s = self._first_trace_success_time(goals, safety, provider) | |
| return EvaluationResult( | |
| success=success, | |
| final_score=score, | |
| predicate_results=[*goal_results, *safety_results], | |
| safety_events=safety_events, | |
| first_success_time_s=first_success_time_s, | |
| terminal_reason="success" if success else "predicate_failed", | |
| ) | |
| def _evaluate_stage( | |
| cls, | |
| stage: TaskStageSpec, | |
| provider: FactProvider, | |
| *, | |
| start_index: int = 0, | |
| ) -> tuple[StageEvaluationResult, int | None]: | |
| evaluation_provider = provider | |
| completion_index: int | None = None | |
| first_success_time_s: float | None = None | |
| if isinstance(provider, TraceFactProvider): | |
| for endpoint in range(start_index, len(provider.frames)): | |
| window = TraceFactProvider(provider.frames[start_index : endpoint + 1]) | |
| completion = [cls._evaluate(item, window) for item in stage.completion_predicates] | |
| completion = cls._enforce_synchronization( | |
| stage.completion_predicates, completion, window | |
| ) | |
| invariants = [cls._evaluate(item, window) for item in stage.invariants] | |
| if all(item.passed for item in [*completion, *invariants]): | |
| evaluation_provider = window | |
| completion_index = endpoint | |
| first_success_time_s = provider.frames[endpoint].time_s | |
| break | |
| else: | |
| evaluation_provider = TraceFactProvider(provider.frames[start_index:]) | |
| completion = [ | |
| cls._evaluate(item, evaluation_provider) for item in stage.completion_predicates | |
| ] | |
| completion = cls._enforce_synchronization( | |
| stage.completion_predicates, completion, evaluation_provider | |
| ) | |
| invariants = [cls._evaluate(item, evaluation_provider) for item in stage.invariants] | |
| results = [*completion, *invariants] | |
| score = sum(item.passed for item in results) / len(results) if results else 0.0 | |
| passed = bool(results) and all(item.passed for item in results) | |
| if passed and completion_index is None: | |
| completion_index = start_index | |
| return ( | |
| StageEvaluationResult( | |
| stage_id=stage.stage_id, | |
| passed=passed, | |
| score=score, | |
| predicate_results=results, | |
| first_success_time_s=first_success_time_s, | |
| failure_reason=None if passed else "stage_predicate_failed", | |
| ), | |
| completion_index if passed else None, | |
| ) | |
| def _first_trace_success_time( | |
| cls, | |
| goals: list[PredicateSpec], | |
| safety: list[PredicateSpec], | |
| provider: TraceFactProvider, | |
| ) -> float | None: | |
| for endpoint in range(len(provider.frames)): | |
| prefix = TraceFactProvider(provider.frames[: endpoint + 1]) | |
| goal_results = [cls._evaluate(item, prefix) for item in goals] | |
| goal_results = cls._enforce_synchronization(goals, goal_results, prefix) | |
| safety_results = [cls._evaluate(item, prefix) for item in safety] | |
| if ( | |
| goal_results | |
| and all(item.passed for item in goal_results) | |
| and all(item.passed for item in safety_results) | |
| ): | |
| return provider.frames[endpoint].time_s | |
| return None | |
| def _enforce_synchronization( | |
| predicates: list[PredicateSpec], | |
| results: list[PredicateResult], | |
| provider: FactProvider, | |
| ) -> list[PredicateResult]: | |
| groups: dict[str, list[int]] = {} | |
| for index, predicate in enumerate(predicates): | |
| group = predicate.params.get("synchronization_group") | |
| if group: | |
| groups.setdefault(str(group), []).append(index) | |
| for group, indices in groups.items(): | |
| windows = { | |
| float(predicates[index].params.get("synchronization_window_s", 0.0)) | |
| for index in indices | |
| } | |
| window_s = min(windows) | |
| evaluator = getattr(provider, "evaluate_synchronized", None) | |
| if evaluator is None: | |
| passed, observed = ( | |
| False, | |
| { | |
| "reason": "provider_has_no_synchronized_trace", | |
| "window_s": window_s, | |
| }, | |
| ) | |
| else: | |
| passed, observed = evaluator([predicates[index] for index in indices], window_s) | |
| for index in indices: | |
| details = dict(results[index].observed) | |
| details["synchronization_group"] = group | |
| details["synchronization"] = observed | |
| results[index] = results[index].model_copy( | |
| update={"passed": results[index].passed and passed, "observed": details} | |
| ) | |
| return results | |
| def _evaluate(predicate: PredicateSpec, provider: FactProvider) -> PredicateResult: | |
| passed, observed = provider.evaluate(predicate) | |
| return PredicateResult(predicate=predicate, passed=passed, observed=observed) | |