From 8a44572d7caaa864c30148816a70260d187f736f Mon Sep 17 00:00:00 2001 From: Neel Jawale Date: Mon, 16 Nov 2026 22:19:22 -0800 Subject: [PATCH 1/3] Add collision-aware trajectory scheduling Add simulator-independent segment and timing constraints with waypoint and block MILP scheduling. Support task precedence, collision conflicts, non-overlap, non-preemption, and optional maximum-wait minimization. Signed-off-by: Neel Jawale --- autodata_core/scheduling/__init__.py | 16 + autodata_core/scheduling/retiming.py | 783 ++++++++++++++++++ autodata_core/scheduling/types.py | 164 ++++ .../tasks/schedule_constraint_spec.py | 194 +++++ autodata_interfaces/tasks/segment_spec.py | 345 ++++++++ autodata_tests/core/test_scheduling.py | 136 +++ 6 files changed, 1638 insertions(+) create mode 100644 autodata_core/scheduling/__init__.py create mode 100644 autodata_core/scheduling/retiming.py create mode 100644 autodata_core/scheduling/types.py create mode 100644 autodata_interfaces/tasks/schedule_constraint_spec.py create mode 100644 autodata_interfaces/tasks/segment_spec.py create mode 100644 autodata_tests/core/test_scheduling.py diff --git a/autodata_core/scheduling/__init__.py b/autodata_core/scheduling/__init__.py new file mode 100644 index 0000000..2193c69 --- /dev/null +++ b/autodata_core/scheduling/__init__.py @@ -0,0 +1,16 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Collision-aware waypoint and block scheduling without simulator dependencies.""" + +from autodata_core.scheduling.retiming import schedule_paths +from autodata_core.scheduling.types import Schedule, ScheduleFailure, SchedulePath, SegmentWaypoint, WaypointConflict + +__all__ = [ + "Schedule", + "ScheduleFailure", + "SchedulePath", + "SegmentWaypoint", + "WaypointConflict", + "schedule_paths", +] diff --git a/autodata_core/scheduling/retiming.py b/autodata_core/scheduling/retiming.py new file mode 100644 index 0000000..2915298 --- /dev/null +++ b/autodata_core/scheduling/retiming.py @@ -0,0 +1,783 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Native waypoint retiming with collision and segment-order constraints.""" + +from __future__ import annotations + +import numpy as np +import time +from dataclasses import dataclass +from itertools import combinations +from scipy.optimize import Bounds, LinearConstraint, milp +from scipy.sparse import coo_array + +from autodata_core.scheduling.types import Schedule, ScheduleFailure, SchedulePath, SegmentWaypoint, WaypointConflict +from autodata_interfaces.tasks.schedule_constraint_spec import ( + NonOverlapConstraintSpec, + NonPreemptiveConstraintSpec, + PrecedenceConstraintSpec, + SchedulerStrategy, + SegmentAnchor, + SegmentAnchorPoint, + SegmentId, +) + +type _Expression = tuple[dict[int, float], float] +type _ConstraintRow = tuple[dict[int, float], float, float] +type _ConflictGroup = tuple[int, int, tuple[SegmentWaypoint, ...], tuple[SegmentWaypoint, ...]] + + +@dataclass(frozen=True) +class _Layout: + """Flattened persistent command lanes and solver-variable indices.""" + + paths: tuple[SchedulePath, ...] + paths_by_id: dict[SegmentId, SchedulePath] + lane_by_segment: dict[SegmentId, str] + waypoints_by_lane: dict[str, tuple[SegmentWaypoint, ...]] + time_by_waypoint: dict[SegmentWaypoint, _Expression] + group_by_waypoint: dict[SegmentWaypoint, int] + waypoints_by_group: dict[int, tuple[SegmentWaypoint, ...]] + successor_by_waypoint: dict[SegmentWaypoint, SegmentWaypoint | None] + + @property + def waypoint_count(self) -> int: + """Return the total number of commands across all lanes.""" + + return len(self.time_by_waypoint) + + @property + def time_variable_count(self) -> int: + """Return the number of independently timed waypoint groups.""" + + return len(self.waypoints_by_group) + + +def schedule_paths( + paths: tuple[SchedulePath, ...], + *, + conflicts: tuple[WaypointConflict, ...] = (), + precedence: tuple[PrecedenceConstraintSpec, ...] = (), + non_overlap: tuple[NonOverlapConstraintSpec, ...] = (), + non_preemptive: tuple[NonPreemptiveConstraintSpec, ...] = (), + strategy: SchedulerStrategy = SchedulerStrategy.WAYPOINT_RETIMING, + max_block_size: int = 0, + serialize_segments: bool = False, + time_limit_s: float | None = None, + minimize_max_wait: bool = True, +) -> Schedule | ScheduleFailure: + """Retime ordered segment paths without changing or dropping waypoints. + + Paths sharing a lane are concatenated in declaration order. Before its first + segment starts, a lane holds that segment's initial waypoint from tick zero. + Every waypoint is then held until the next waypoint on that lane begins, and + the final waypoint is held through the episode makespan. Collision conflicts + therefore constrain exact held-state intervals, including initial, + inter-segment, and terminal holds. + + A solver failure never produces an executable fallback schedule. + + Args: + paths: Segment path metadata in lane execution order. + conflicts: Cross-lane colliding waypoint pairs. + precedence: Segment start/end precedence constraints. + non_overlap: Unordered whole-segment non-overlap constraints. + non_preemptive: Contiguous same-lane segment sequences that may not acquire waits. + strategy: Singleton-waypoint retiming or conservative block scheduling. + max_block_size: Maximum waypoints per block; zero keeps each segment atomic. + serialize_segments: Whether all cross-lane segment intervals must be disjoint. + time_limit_s: Optional HiGHS wall-clock limit [s]. + minimize_max_wait: Whether equal-makespan schedules minimize their largest inserted wait. + + Returns: + Independently validated schedule, or a scheduling failure with no executable result. + """ + + assert isinstance(paths, tuple) and paths, "paths must be a non-empty tuple" + assert all(isinstance(path, SchedulePath) for path in paths), "paths must contain SchedulePath values" + assert isinstance(conflicts, tuple) and all( + isinstance(item, WaypointConflict) for item in conflicts + ), "conflicts must contain WaypointConflict values" + assert isinstance(precedence, tuple) and all( + isinstance(item, PrecedenceConstraintSpec) for item in precedence + ), "precedence must contain PrecedenceConstraintSpec values" + assert isinstance(non_overlap, tuple) and all( + isinstance(item, NonOverlapConstraintSpec) for item in non_overlap + ), "non_overlap must contain NonOverlapConstraintSpec values" + assert isinstance(non_preemptive, tuple) and all( + isinstance(item, NonPreemptiveConstraintSpec) for item in non_preemptive + ), "non_preemptive must contain NonPreemptiveConstraintSpec values" + assert isinstance(strategy, SchedulerStrategy), "strategy must be a SchedulerStrategy" + assert type(max_block_size) is int and max_block_size >= 0, "max_block_size must be non-negative" + assert ( + strategy == SchedulerStrategy.BLOCK_SCHEDULING or max_block_size == 0 + ), "max_block_size is supported only by block_scheduling" + assert isinstance(serialize_segments, bool), "serialize_segments must be a bool" + assert time_limit_s is None or time_limit_s > 0.0, "time_limit_s must be positive" + assert isinstance(minimize_max_wait, bool), "minimize_max_wait must be a bool" + + group_size = 1 if strategy == SchedulerStrategy.WAYPOINT_RETIMING else max_block_size + layout = _layout_create(paths, max_group_size=group_size) + conflicts = _conflicts_validate_and_deduplicate(layout, conflicts) + conflict_groups = _conflict_groups(layout, conflicts) + _precedence_validate(layout, precedence) + non_preemptive_pairs = _non_preemptive_pairs(layout, non_preemptive) + if serialize_segments: + non_overlap = ( + *non_overlap, + *( + NonOverlapConstraintSpec((first.segment_id, second.segment_id)) + for first, second in combinations(paths, 2) + if first.lane != second.lane + ), + ) + non_overlap = _non_overlap_resolve(layout, non_overlap) + + horizon_ticks = _horizon_ticks(layout, precedence) + makespan_variable = layout.time_variable_count + max_wait_variable = makespan_variable + 1 if minimize_max_wait else None + binary_offset = makespan_variable + 1 + int(minimize_max_wait) + non_overlap_binary_offset = binary_offset + len(conflict_groups) + variable_count = non_overlap_binary_offset + len(non_overlap) + time_lower_bounds, time_upper_bounds = _time_variable_bounds(layout, horizon_ticks) + rows: list[_ConstraintRow] = [] + + for lane_waypoints in layout.waypoints_by_lane.values(): + for first, second in zip(lane_waypoints, lane_waypoints[1:], strict=False): + if layout.group_by_waypoint[first] == layout.group_by_waypoint[second]: + continue + progress = _expressions_combine( + (1.0, layout.time_by_waypoint[second]), + (-1.0, layout.time_by_waypoint[first]), + ) + _constraint_add( + rows, + progress, + lower=1.0, + upper=1.0 if (first, second) in non_preemptive_pairs else None, + ) + if max_wait_variable is not None: + max_wait = _expressions_combine( + (1.0, _variable(max_wait_variable)), + (-1.0, progress), + ) + _constraint_add(rows, max_wait, lower=-1.0) + + terminal_progress = _expressions_combine( + (1.0, _variable(makespan_variable)), + (-1.0, layout.time_by_waypoint[lane_waypoints[-1]]), + ) + _constraint_add(rows, terminal_progress, lower=1.0) + + for constraint in precedence: + lag = _expressions_combine( + (1.0, _anchor_expression(layout, constraint.after)), + (-1.0, _anchor_expression(layout, constraint.before)), + ) + _constraint_add( + rows, + lag, + lower=float(constraint.min_lag_steps), + upper=None if constraint.max_lag_steps is None else float(constraint.max_lag_steps), + ) + + for conflict_index, (first_group, second_group, first_conflicts, second_conflicts) in enumerate(conflict_groups): + order_variable = binary_offset + conflict_index + first_start, first_end = _conflict_group_interval( + layout, + first_group, + first_conflicts, + makespan_variable, + ) + second_start, second_end = _conflict_group_interval( + layout, + second_group, + second_conflicts, + makespan_variable, + ) + + _non_overlap_rows_add( + rows, + first_start=first_start, + first_end=first_end, + second_start=second_start, + second_end=second_end, + order_variable=order_variable, + time_lower_bounds=time_lower_bounds, + time_upper_bounds=time_upper_bounds, + ) + + for constraint_index, constraint in enumerate(non_overlap): + first_id, second_id = constraint.segments + order_variable = non_overlap_binary_offset + constraint_index + _non_overlap_rows_add( + rows, + first_start=_anchor_expression(layout, SegmentAnchor(first_id, SegmentAnchorPoint.START)), + first_end=_anchor_expression(layout, SegmentAnchor(first_id, SegmentAnchorPoint.END)), + second_start=_anchor_expression(layout, SegmentAnchor(second_id, SegmentAnchorPoint.START)), + second_end=_anchor_expression(layout, SegmentAnchor(second_id, SegmentAnchorPoint.END)), + order_variable=order_variable, + time_lower_bounds=time_lower_bounds, + time_upper_bounds=time_upper_bounds, + ) + + objective = np.zeros(variable_count, dtype=np.float64) + objective[makespan_variable] = 1.0 + if max_wait_variable is not None: + objective[max_wait_variable] = 1.0 / (horizon_ticks + 1) + lower_bounds = np.zeros(variable_count, dtype=np.float64) + upper_bounds = np.full(variable_count, float(horizon_ticks), dtype=np.float64) + upper_bounds[: layout.time_variable_count] = float(horizon_ticks - 1) + upper_bounds[binary_offset:] = 1.0 + integrality = np.ones(variable_count, dtype=np.uint8) + linear_constraints = _scipy_constraints(rows, variable_count) + options: dict[str, float | bool] = {} + deadline = None if time_limit_s is None else time.monotonic() + time_limit_s + + try: + # The pinned HiGHS presolver can falsely report valid disjunctive models as infeasible. + for presolve in (True, False): + options["presolve"] = presolve + if deadline is not None: + remaining_time_s = deadline - time.monotonic() + if remaining_time_s <= 0.0: + return ScheduleFailure( + reason="limit_reached", + message="MILP time limit was exhausted before the solver attempt", + ) + options["time_limit"] = remaining_time_s + result = milp( + c=objective, + integrality=integrality, + bounds=Bounds(lower_bounds, upper_bounds), + constraints=linear_constraints, + options=options, + ) + if int(result.status) != 2: + break + except (RuntimeError, ValueError) as exc: + return ScheduleFailure(reason="solver_error", message=f"{type(exc).__name__}: {exc}") + + if int(result.status) != 0 or result.x is None: + reasons = {1: "limit_reached", 2: "infeasible", 3: "unbounded"} + reason = reasons.get(int(result.status), "solver_error") + message = str(result.message).strip() or f"MILP returned status {result.status}" + return ScheduleFailure(reason=reason, message=message) + + values = np.asarray(result.x, dtype=np.float64) + rounded = np.rint(values) + if not bool(np.allclose(values, rounded, atol=1.0e-6, rtol=0.0)): + return ScheduleFailure(reason="invalid_candidate", message="MILP returned a fractional integer candidate") + + ticks_by_segment = { + path.segment_id: tuple( + int(_expression_value(layout.time_by_waypoint[SegmentWaypoint(path.segment_id, waypoint_index)], rounded)) + for waypoint_index in range(path.waypoint_count) + ) + for path in paths + } + schedule = Schedule( + waypoint_ticks=ticks_by_segment, + makespan_ticks=int(rounded[makespan_variable]), + ) + validation_error = _schedule_validation_error( + layout, + conflicts, + precedence, + non_overlap, + non_preemptive, + schedule, + ) + if validation_error is not None: + return ScheduleFailure(reason="invalid_candidate", message=validation_error) + return schedule + + +def _layout_create(paths: tuple[SchedulePath, ...], *, max_group_size: int) -> _Layout: + """Assign time variables to fixed-rate groups and link consecutive lane commands. + + Args: + paths: Segments in execution order within each lane. + max_group_size: Maximum commands per fixed-rate group; zero groups each whole segment. + + Returns: + Waypoint expressions, group membership and successors across segment boundaries. + """ + + paths_by_id = {path.segment_id: path for path in paths} + assert len(paths_by_id) == len(paths), "segment IDs must be unique" + assert type(max_group_size) is int and max_group_size >= 0 + lane_by_segment = {path.segment_id: path.lane for path in paths} + lane_waypoint_lists: dict[str, list[SegmentWaypoint]] = {} + time_by_waypoint: dict[SegmentWaypoint, _Expression] = {} + group_by_waypoint: dict[SegmentWaypoint, int] = {} + waypoints_by_group: dict[int, tuple[SegmentWaypoint, ...]] = {} + for path in paths: + path_waypoints = tuple( + SegmentWaypoint(path.segment_id, waypoint_index) for waypoint_index in range(path.waypoint_count) + ) + lane_waypoint_lists.setdefault(path.lane, []).extend(path_waypoints) + group_size = path.waypoint_count if max_group_size == 0 else max_group_size + for start in range(0, path.waypoint_count, group_size): + group_waypoints = path_waypoints[start : start + group_size] + group_index = len(waypoints_by_group) + waypoints_by_group[group_index] = group_waypoints + for offset, waypoint in enumerate(group_waypoints): + time_by_waypoint[waypoint] = _variable(group_index, constant=float(offset)) + group_by_waypoint[waypoint] = group_index + waypoints_by_lane = {lane: tuple(waypoints) for lane, waypoints in lane_waypoint_lists.items()} + successor_by_waypoint: dict[SegmentWaypoint, SegmentWaypoint | None] = {} + for lane_waypoints in waypoints_by_lane.values(): + for waypoint, successor in zip(lane_waypoints, (*lane_waypoints[1:], None), strict=True): + successor_by_waypoint[waypoint] = successor + return _Layout( + paths=paths, + paths_by_id=paths_by_id, + lane_by_segment=lane_by_segment, + waypoints_by_lane=waypoints_by_lane, + time_by_waypoint=time_by_waypoint, + group_by_waypoint=group_by_waypoint, + waypoints_by_group=waypoints_by_group, + successor_by_waypoint=successor_by_waypoint, + ) + + +def _conflicts_validate_and_deduplicate( + layout: _Layout, + conflicts: tuple[WaypointConflict, ...], +) -> tuple[WaypointConflict, ...]: + """Validate cross-lane conflict indices and retain each unordered pair once.""" + + canonical: dict[tuple[SegmentWaypoint, SegmentWaypoint], WaypointConflict] = {} + for conflict in conflicts: + for waypoint in (conflict.first, conflict.second): + path = layout.paths_by_id.get(waypoint.segment_id) + assert path is not None, f"conflict references unknown segment {waypoint.segment_id}" + assert ( + waypoint.waypoint_index < path.waypoint_count + ), f"conflict waypoint {waypoint.waypoint_index} is outside segment {waypoint.segment_id}" + first_lane = layout.lane_by_segment[conflict.first.segment_id] + second_lane = layout.lane_by_segment[conflict.second.segment_id] + assert first_lane != second_lane, "waypoint conflicts must be cross-lane" + first, second = conflict.canonical_key + canonical.setdefault((first, second), WaypointConflict(first, second)) + return tuple(canonical.values()) + + +def _conflict_groups( + layout: _Layout, + conflicts: tuple[WaypointConflict, ...], +) -> tuple[_ConflictGroup, ...]: + """Return unique time-group pairs requiring conservative non-overlap.""" + + waypoints_by_pair: dict[tuple[int, int], tuple[set[SegmentWaypoint], set[SegmentWaypoint]]] = {} + for conflict in conflicts: + first_group = layout.group_by_waypoint[conflict.first] + second_group = layout.group_by_waypoint[conflict.second] + if first_group <= second_group: + pair = first_group, second_group + first, second = conflict.first, conflict.second + else: + pair = second_group, first_group + first, second = conflict.second, conflict.first + first_waypoints, second_waypoints = waypoints_by_pair.setdefault(pair, (set(), set())) + first_waypoints.add(first) + second_waypoints.add(second) + return tuple( + ( + first_group, + second_group, + tuple(sorted(first_waypoints)), + tuple(sorted(second_waypoints)), + ) + for (first_group, second_group), (first_waypoints, second_waypoints) in sorted(waypoints_by_pair.items()) + ) + + +def _precedence_validate(layout: _Layout, precedence: tuple[PrecedenceConstraintSpec, ...]) -> None: + """Require every precedence anchor to reference a segment in the problem.""" + + for constraint in precedence: + for anchor in (constraint.before, constraint.after): + assert ( + anchor.segment_id in layout.paths_by_id + ), f"precedence anchor references unknown segment {anchor.segment_id}" + + +def _non_preemptive_pairs( + layout: _Layout, + constraints: tuple[NonPreemptiveConstraintSpec, ...], +) -> set[tuple[SegmentWaypoint, SegmentWaypoint]]: + """Return adjacent command pairs that must execute exactly one tick apart. + + Each configured sequence must be contiguous and ordered within a single lane. Initial + waiting remains allowed; no wait can be inserted between the returned pairs. + """ + + pairs: set[tuple[SegmentWaypoint, SegmentWaypoint]] = set() + for constraint in constraints: + for segment_id in constraint.segments: + assert segment_id in layout.paths_by_id, f"non-preemptive references unknown segment {segment_id}" + lanes = {layout.lane_by_segment[segment_id] for segment_id in constraint.segments} + assert len(lanes) == 1, "non-preemptive segments must use one lane" + lane_waypoints = layout.waypoints_by_lane[lanes.pop()] + constrained = tuple( + SegmentWaypoint(segment_id, waypoint_index) + for segment_id in constraint.segments + for waypoint_index in range(layout.paths_by_id[segment_id].waypoint_count) + ) + start = lane_waypoints.index(constrained[0]) + assert ( + lane_waypoints[start : start + len(constrained)] == constrained + ), "non-preemptive segments must be contiguous and in lane order" + pairs.update(zip(constrained, constrained[1:], strict=False)) + return pairs + + +def _non_overlap_resolve( + layout: _Layout, + authored: tuple[NonOverlapConstraintSpec, ...], +) -> tuple[NonOverlapConstraintSpec, ...]: + """Combine authored and shared-resource mutexes into one deduplicated constraint tuple.""" + + constraints: list[NonOverlapConstraintSpec] = [] + seen_pairs: set[tuple[SegmentId, SegmentId]] = set() + + def append_pair(segments: tuple[SegmentId, SegmentId]) -> None: + """Append a validated cross-lane segment pair unless it is already present.""" + + for segment_id in segments: + assert segment_id in layout.paths_by_id, f"non-overlap references unknown segment {segment_id}" + pair = tuple(sorted(segments)) + if layout.lane_by_segment[pair[0]] == layout.lane_by_segment[pair[1]]: + return + if pair not in seen_pairs: + seen_pairs.add(pair) + constraints.append(NonOverlapConstraintSpec(pair)) + + for constraint in authored: + append_pair(constraint.segments) + + paths_by_resource: dict[str, list[SchedulePath]] = {} + for path in layout.paths: + for resource_id in path.resource_ids: + paths_by_resource.setdefault(resource_id, []).append(path) + for resource_id, resource_paths in sorted(paths_by_resource.items()): + lanes = {path.lane for path in resource_paths} + assert len(lanes) >= 2, f"resource {resource_id!r} must be claimed by segments on at least two lanes" + for first, second in combinations(sorted(resource_paths, key=lambda path: path.segment_id), 2): + if first.lane != second.lane: + append_pair((first.segment_id, second.segment_id)) + return tuple(constraints) + + +def _horizon_ticks(layout: _Layout, precedence: tuple[PrecedenceConstraintSpec, ...]) -> int: + """Bound schedule length by serialized commands plus all minimum precedence lags.""" + + serialized_path_ticks = sum(path.waypoint_count for path in layout.paths) + explicit_wait_ticks = sum(constraint.min_lag_steps for constraint in precedence) + return serialized_path_ticks + explicit_wait_ticks + 1 + + +def _time_variable_bounds(layout: _Layout, horizon_ticks: int) -> tuple[np.ndarray, np.ndarray]: + """Return lane-order-implied time bounds for numerically tight disjunctions.""" + + lower_bounds = np.zeros(layout.time_variable_count + 1, dtype=np.float64) + upper_bounds = np.full(layout.time_variable_count + 1, float(horizon_ticks), dtype=np.float64) + bounded_groups: set[int] = set() + for lane_waypoints in layout.waypoints_by_lane.values(): + lane_length = len(lane_waypoints) + for rank, waypoint in enumerate(lane_waypoints): + group = layout.group_by_waypoint[waypoint] + if group in bounded_groups: + continue + bounded_groups.add(group) + lower_bounds[group] = float(rank) + upper_bounds[group] = float(horizon_ticks - (lane_length - rank)) + return lower_bounds, upper_bounds + + +def _variable(index: int, *, constant: float = 0.0) -> _Expression: + """Represent one solver variable plus a constant as an affine expression.""" + + return {index: 1.0}, constant + + +def _expressions_combine(*terms: tuple[float, _Expression]) -> _Expression: + """Sum scaled affine expressions, removing zero coefficients.""" + + coefficients: dict[int, float] = {} + constant = 0.0 + for scale, (expression_coefficients, expression_constant) in terms: + constant += scale * expression_constant + for variable, coefficient in expression_coefficients.items(): + coefficients[variable] = coefficients.get(variable, 0.0) + scale * coefficient + return {variable: value for variable, value in coefficients.items() if value}, constant + + +def _expression_value(expression: _Expression, values: np.ndarray) -> float: + """Evaluate an affine expression at the supplied solver values.""" + + coefficients, constant = expression + return constant + sum(coefficient * values[variable] for variable, coefficient in coefficients.items()) + + +def _anchor_expression(layout: _Layout, anchor: SegmentAnchor) -> _Expression: + """Express a segment's first command tick or exclusive terminal tick.""" + + path = layout.paths_by_id[anchor.segment_id] + waypoint_index = 0 if anchor.point == SegmentAnchorPoint.START else path.waypoint_count - 1 + waypoint = SegmentWaypoint(path.segment_id, waypoint_index) + expression = layout.time_by_waypoint[waypoint] + if anchor.point == SegmentAnchorPoint.START: + return expression + return expression[0], expression[1] + 1.0 + + +def _waypoint_end_expression( + layout: _Layout, + waypoint: SegmentWaypoint, + makespan_variable: int, +) -> _Expression: + """Express occupancy end at the next lane command, or the episode makespan.""" + + successor = layout.successor_by_waypoint[waypoint] + if successor is None: + return _variable(makespan_variable) + return layout.time_by_waypoint[successor] + + +def _conflict_group_interval( + layout: _Layout, + group: int, + conflict_waypoints: tuple[SegmentWaypoint, ...], + makespan_variable: int, +) -> tuple[_Expression, _Expression]: + """Return a block interval, extending only holds covered by the collision conflict. + + Args: + layout: Solver variables and waypoint groups for the ordered paths. + group: Waypoint group whose occupied interval is needed. + conflict_waypoints: Group waypoints participating in this collision conflict. + makespan_variable: Solver variable used when the lane holds its final waypoint. + + Returns: + Affine expressions for the interval's start and exclusive end ticks. + """ + + waypoints = layout.waypoints_by_group[group] + first = waypoints[0] + last = waypoints[-1] + lane = layout.lane_by_segment[first.segment_id] + start = layout.time_by_waypoint[first] + if first in conflict_waypoints and first == layout.waypoints_by_lane[lane][0]: + start = {}, 0.0 + end = layout.time_by_waypoint[last][0], layout.time_by_waypoint[last][1] + 1.0 + if last in conflict_waypoints: + end = _waypoint_end_expression(layout, last, makespan_variable) + return start, end + + +def _non_overlap_rows_add( + rows: list[_ConstraintRow], + *, + first_start: _Expression, + first_end: _Expression, + second_start: _Expression, + second_end: _Expression, + order_variable: int, + time_lower_bounds: np.ndarray, + time_upper_bounds: np.ndarray, +) -> None: + """Append bounded big-M rows selecting one of two non-overlapping interval orders. + + The binary order variable selects first-before-second when one, and second-before-first + when zero. Each row uses its own expression bound rather than a shared arbitrary big-M. + """ + + first_before_second_difference = _expressions_combine( + (1.0, first_end), + (-1.0, second_start), + ) + first_before_second_m = max( + 0.0, + _expression_upper_bound(first_before_second_difference, time_lower_bounds, time_upper_bounds), + ) + first_before_second = _expressions_combine( + (1.0, first_before_second_difference), + (first_before_second_m, _variable(order_variable)), + ) + _constraint_add(rows, first_before_second, upper=first_before_second_m) + + second_before_first_difference = _expressions_combine( + (1.0, second_end), + (-1.0, first_start), + ) + second_before_first_m = max( + 0.0, + _expression_upper_bound(second_before_first_difference, time_lower_bounds, time_upper_bounds), + ) + second_before_first = _expressions_combine( + (1.0, second_before_first_difference), + (-second_before_first_m, _variable(order_variable)), + ) + _constraint_add(rows, second_before_first, upper=0.0) + + +def _expression_upper_bound( + expression: _Expression, + lower_bounds: np.ndarray, + upper_bounds: np.ndarray, +) -> float: + """Maximize an affine expression over independent variable bounds.""" + + coefficients, constant = expression + return constant + sum( + coefficient * (upper_bounds[variable] if coefficient > 0.0 else lower_bounds[variable]) + for variable, coefficient in coefficients.items() + ) + + +def _constraint_add( + rows: list[_ConstraintRow], + expression: _Expression, + *, + lower: float | None = None, + upper: float | None = None, +) -> None: + """Append a bounded linear row after moving the expression constant into its bounds.""" + + assert lower is not None or upper is not None, "a constraint requires at least one bound" + coefficients, constant = expression + rows.append(( + coefficients, + -np.inf if lower is None else lower - constant, + np.inf if upper is None else upper - constant, + )) + + +def _scipy_constraints(rows: list[_ConstraintRow], variable_count: int) -> LinearConstraint: + """Assemble affine constraint rows into the sparse matrix accepted by SciPy MILP.""" + + matrix_rows: list[int] = [] + matrix_columns: list[int] = [] + matrix_values: list[float] = [] + lower_bounds: list[float] = [] + upper_bounds: list[float] = [] + for row_index, (coefficients, lower, upper) in enumerate(rows): + for variable, coefficient in coefficients.items(): + matrix_rows.append(row_index) + matrix_columns.append(variable) + matrix_values.append(coefficient) + lower_bounds.append(lower) + upper_bounds.append(upper) + matrix = coo_array( + ( + np.asarray(matrix_values, dtype=np.float64), + (np.asarray(matrix_rows, dtype=np.int32), np.asarray(matrix_columns, dtype=np.int32)), + ), + shape=(len(rows), variable_count), + ).tocsc() + return LinearConstraint(matrix, np.asarray(lower_bounds), np.asarray(upper_bounds)) + + +def _schedule_validation_error( + layout: _Layout, + conflicts: tuple[WaypointConflict, ...], + precedence: tuple[PrecedenceConstraintSpec, ...], + non_overlap: tuple[NonOverlapConstraintSpec, ...], + non_preemptive: tuple[NonPreemptiveConstraintSpec, ...], + schedule: Schedule, +) -> str | None: + """Check the integer schedule independently of solver rows and tolerances. + + Args: + layout: Segment coverage, command order and persistent lane successors. + conflicts: Forbidden simultaneous waypoint occupancies, including initial/final holds. + precedence: Required lags between segment anchors. + non_overlap: Segment intervals that must be disjoint. + non_preemptive: Contiguous command sequences that cannot contain waits. + schedule: Rounded candidate schedule returned by the solver. + + Returns: + The first violated constraint, or ``None`` when all checks pass. + """ + + if set(schedule.waypoint_ticks) != set(layout.paths_by_id): + return "candidate segment coverage differs from the scheduling problem" + + for path in layout.paths: + ticks = schedule.ticks_for(path.segment_id) + if len(ticks) != path.waypoint_count: + return f"candidate waypoint count differs for segment {path.segment_id}" + for lane, lane_waypoints in layout.waypoints_by_lane.items(): + ticks = tuple(schedule.ticks_for(waypoint.segment_id)[waypoint.waypoint_index] for waypoint in lane_waypoints) + if any(second <= first for first, second in zip(ticks, ticks[1:], strict=False)): + return f"lane {lane!r} does not preserve strict waypoint order" + + expected_makespan = max(schedule.ticks_for(path.segment_id)[-1] + 1 for path in layout.paths) + if schedule.makespan_ticks != expected_makespan: + return "candidate makespan is not the latest segment end" + + for constraint in precedence: + before = _anchor_tick(schedule, constraint.before) + after = _anchor_tick(schedule, constraint.after) + lag = after - before + if lag < constraint.min_lag_steps: + return f"candidate violates precedence minimum lag for {constraint.before} -> {constraint.after}" + if constraint.max_lag_steps is not None and lag > constraint.max_lag_steps: + return f"candidate violates precedence maximum lag for {constraint.before} -> {constraint.after}" + + for constraint in non_overlap: + first_id, second_id = constraint.segments + first_interval = schedule.ticks_for(first_id)[0], schedule.ticks_for(first_id)[-1] + 1 + second_interval = schedule.ticks_for(second_id)[0], schedule.ticks_for(second_id)[-1] + 1 + if first_interval[0] < second_interval[1] and second_interval[0] < first_interval[1]: + return f"candidate overlaps constrained segments {first_id} and {second_id}" + + for constraint in non_preemptive: + ticks = tuple(tick for segment_id in constraint.segments for tick in schedule.ticks_for(segment_id)) + if any(second != first + 1 for first, second in zip(ticks, ticks[1:], strict=False)): + return f"candidate preempts constrained segment sequence {constraint.segments}" + + for conflict in conflicts: + first_interval = _occupancy_interval(layout, schedule, conflict.first) + second_interval = _occupancy_interval(layout, schedule, conflict.second) + if first_interval[0] < second_interval[1] and second_interval[0] < first_interval[1]: + return f"candidate retains collision between {conflict.first} and {conflict.second}" + return None + + +def _anchor_tick(schedule: Schedule, anchor: SegmentAnchor) -> int: + """Return the first command tick or exclusive terminal tick of a segment.""" + + ticks = schedule.ticks_for(anchor.segment_id) + return ticks[0] if anchor.point == SegmentAnchorPoint.START else ticks[-1] + 1 + + +def _occupancy_interval( + layout: _Layout, + schedule: Schedule, + waypoint: SegmentWaypoint, +) -> tuple[int, int]: + """Return a waypoint's half-open occupancy interval, including boundary holds. + + The first lane configuration occupies tick zero onward, even before its command tick. + Every configuration persists until its successor; the final one persists to makespan. + """ + + lane = layout.lane_by_segment[waypoint.segment_id] + start = ( + 0 + if waypoint == layout.waypoints_by_lane[lane][0] + else schedule.ticks_for(waypoint.segment_id)[waypoint.waypoint_index] + ) + successor = layout.successor_by_waypoint[waypoint] + if successor is None: + return start, schedule.makespan_ticks + end = schedule.ticks_for(successor.segment_id)[successor.waypoint_index] + return start, end + + +__all__ = ["schedule_paths"] diff --git a/autodata_core/scheduling/types.py b/autodata_core/scheduling/types.py new file mode 100644 index 0000000..cb12b8a --- /dev/null +++ b/autodata_core/scheduling/types.py @@ -0,0 +1,164 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Simulator-independent paths, collision conflicts and schedule results.""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, field +from types import MappingProxyType + +from autodata_interfaces.tasks.schedule_constraint_spec import SegmentId +from autodata_interfaces.tasks.segment_spec import validate_local_name + + +@dataclass(frozen=True) +class SchedulePath: + """Segment path metadata passed to the scheduling solver. + + Planned, demonstrated and scripted trajectories use the same ordered-path interface. + + Args: + segment_id: Stable task segment identity. + lane: Persistent command lane, normally an end-effector name. + waypoint_count: Number of configurations in the segment path. + resource_ids: Additional task-local resources held for the nominal segment interval. + """ + + segment_id: SegmentId + lane: str + waypoint_count: int + resource_ids: tuple[str, ...] = field(default_factory=tuple, kw_only=True) + + def __post_init__(self) -> None: + """Validate segment metadata, positive length and sorted unique resource names.""" + + assert isinstance(self.segment_id, SegmentId), "segment_id must be a SegmentId" + assert ( + isinstance(self.lane, str) and self.lane and self.lane == self.lane.strip() + ), "lane must be a non-empty, trimmed string" + assert type(self.waypoint_count) is int and self.waypoint_count > 0, "waypoint_count must be a positive integer" + assert isinstance(self.resource_ids, tuple), "resource_ids must be a tuple" + for resource_id in self.resource_ids: + validate_local_name(resource_id, field_name="resource_id") + assert len(self.resource_ids) == len(set(self.resource_ids)), "resource_ids must be unique" + assert self.resource_ids == tuple(sorted(self.resource_ids)), "resource_ids must be in sorted order" + + +@dataclass(frozen=True, order=True) +class SegmentWaypoint: + """A configuration within a segment path. + + Args: + segment_id: Segment containing the configuration. + waypoint_index: Zero-based index within the segment. + """ + + segment_id: SegmentId + waypoint_index: int + + def __post_init__(self) -> None: + """Validate the segment identity and nonnegative local waypoint index.""" + + assert isinstance(self.segment_id, SegmentId), "segment_id must be a SegmentId" + assert ( + type(self.waypoint_index) is int and self.waypoint_index >= 0 + ), "waypoint_index must be a non-negative integer" + + +@dataclass(frozen=True) +class WaypointConflict: + """Two configurations that may not be occupied at the same time. + + Args: + first: Waypoint on one command lane. + second: Conflicting waypoint on another command lane. + """ + + first: SegmentWaypoint + second: SegmentWaypoint + + def __post_init__(self) -> None: + """Require two distinct, typed waypoint references.""" + + assert isinstance(self.first, SegmentWaypoint) and isinstance( + self.second, SegmentWaypoint + ), "conflict endpoints must be SegmentWaypoint values" + assert self.first != self.second, "a waypoint cannot conflict with itself" + + @property + def canonical_key(self) -> tuple[SegmentWaypoint, SegmentWaypoint]: + """Return an order-independent conflict identity.""" + + return tuple(sorted((self.first, self.second))) + + +@dataclass(frozen=True) +class Schedule: + """Integer execution ticks for every segment waypoint. + + Args: + waypoint_ticks: Segment-local waypoint ticks, keyed by stable identity. + makespan_ticks: Exclusive terminal episode tick. + """ + + waypoint_ticks: Mapping[SegmentId, tuple[int, ...]] + makespan_ticks: int + + def __post_init__(self) -> None: + """Validate nonnegative command ticks and freeze a copy of the segment mapping.""" + + assert ( + isinstance(self.waypoint_ticks, Mapping) and self.waypoint_ticks + ), "waypoint_ticks must be a non-empty mapping" + canonical: dict[SegmentId, tuple[int, ...]] = {} + for segment_id, ticks in self.waypoint_ticks.items(): + assert isinstance(segment_id, SegmentId), "schedule keys must be SegmentId values" + assert isinstance(ticks, tuple) and ticks, "every scheduled path must contain waypoint ticks" + assert all( + type(tick) is int and tick >= 0 for tick in ticks + ), "waypoint ticks must be non-negative integers" + canonical[segment_id] = ticks + assert type(self.makespan_ticks) is int and self.makespan_ticks > 0, "makespan_ticks must be a positive integer" + object.__setattr__(self, "waypoint_ticks", MappingProxyType(canonical)) + + def ticks_for(self, segment_id: SegmentId) -> tuple[int, ...]: + """Return the execution ticks for one segment. + + Args: + segment_id: Segment to query. + + Returns: + Execution ticks in segment waypoint order. + """ + + return self.waypoint_ticks[segment_id] + + +@dataclass(frozen=True) +class ScheduleFailure: + """Scheduling failure with no executable result. + + Args: + reason: Short failure category. + message: Description of the failure. + """ + + reason: str + message: str + + def __post_init__(self) -> None: + """Require nonempty, trimmed failure descriptions.""" + + assert self.reason and self.reason == self.reason.strip(), "reason must be non-empty" + assert self.message and self.message == self.message.strip(), "message must be non-empty" + + +__all__ = [ + "Schedule", + "ScheduleFailure", + "SchedulePath", + "SegmentWaypoint", + "WaypointConflict", +] diff --git a/autodata_interfaces/tasks/schedule_constraint_spec.py b/autodata_interfaces/tasks/schedule_constraint_spec.py new file mode 100644 index 0000000..bdfe121 --- /dev/null +++ b/autodata_interfaces/tasks/schedule_constraint_spec.py @@ -0,0 +1,194 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Segment precedence and scheduling policy for ScheduleGen.""" + +from __future__ import annotations + +import enum +import math +from dataclasses import dataclass, field + +from autodata_interfaces.tasks.segment_spec import SegmentId + + +class SegmentAnchorPoint(enum.StrEnum): + """Endpoint of a trajectory segment.""" + + START = "start" + END = "end" + + +@dataclass(frozen=True, order=True) +class SegmentAnchor: + """Start or end of a scheduled segment. + + Args: + segment_id: Segment being referenced. + point: Start tick or exclusive end tick, one tick after the last waypoint starts. + """ + + segment_id: SegmentId + point: SegmentAnchorPoint + + @classmethod + def from_string(cls, value: str) -> SegmentAnchor: + """Parse an endpoint such as ``left.pick.transit.end``. + + Args: + value: End-effector, subtask, segment and endpoint names separated by dots. + + Returns: + Segment and endpoint referenced by the string. + """ + + parts = value.split(".") + assert len(parts) == 4, f"invalid segment anchor: {value!r}" + return cls(SegmentId.from_string(".".join(parts[:3])), SegmentAnchorPoint(parts[3])) + + +@dataclass(frozen=True) +class PrecedenceConstraintSpec: + """Bound the execution-tick lag from one segment endpoint to another. + + Args: + before: Earlier segment endpoint. + after: Later segment endpoint. + min_lag_steps: Minimum number of control steps between the endpoints. + max_lag_steps: Optional maximum number of control steps between the endpoints. + """ + + before: SegmentAnchor + after: SegmentAnchor + min_lag_steps: int = 0 + max_lag_steps: int | None = None + + def __post_init__(self) -> None: + """Require distinct anchors and ordered nonnegative lag bounds.""" + + assert self.before != self.after, "precedence anchors must differ" + assert type(self.min_lag_steps) is int and self.min_lag_steps >= 0 + if self.max_lag_steps is not None: + assert ( + type(self.max_lag_steps) is int and self.max_lag_steps >= self.min_lag_steps + ), "max_lag_steps must be an integer no smaller than min_lag_steps" + + @property + def referenced_segment_ids(self) -> tuple[SegmentId, SegmentId]: + """Return segment identities referenced by this constraint.""" + + return self.before.segment_id, self.after.segment_id + + +@dataclass(frozen=True) +class NonOverlapConstraintSpec: + """Prevent two scheduled segment intervals from overlapping. + + Collision checks also cover initial and terminal holds outside these intervals. + + Args: + segments: Pair of segments whose scheduled intervals must not overlap. + """ + + segments: tuple[SegmentId, SegmentId] + + def __post_init__(self) -> None: + """Require exactly two distinct segment identities.""" + + assert isinstance(self.segments, tuple) and len(self.segments) == 2, "non-overlap requires two segments" + assert all(isinstance(segment_id, SegmentId) for segment_id in self.segments) + assert self.segments[0] != self.segments[1], "non-overlap segments must differ" + + @property + def referenced_segment_ids(self) -> tuple[SegmentId, SegmentId]: + """Return segment identities referenced by this constraint.""" + + return self.segments + + +@dataclass(frozen=True) +class NonPreemptiveConstraintSpec: + """Prevent inserted waits within a same-lane segment sequence. + + The sequence may start late. Once it starts, every consecutive waypoint advances + by one control step, including the boundaries between its segments. + + Args: + segments: Consecutive segments on one command lane, listed in execution order. + """ + + segments: tuple[SegmentId, ...] + + def __post_init__(self) -> None: + """Require a nonempty sequence of unique segment identities.""" + + assert isinstance(self.segments, tuple) and self.segments, "non-preemptive requires segments" + assert all(isinstance(segment_id, SegmentId) for segment_id in self.segments) + assert len(self.segments) == len(set(self.segments)), "non-preemptive segments must be unique" + + @property + def referenced_segment_ids(self) -> tuple[SegmentId, ...]: + """Return segment identities referenced by this constraint.""" + + return self.segments + + +type ScheduleConstraintSpec = PrecedenceConstraintSpec | NonOverlapConstraintSpec | NonPreemptiveConstraintSpec + + +class SchedulerStrategy(enum.StrEnum): + """Choice between per-waypoint retiming and fixed-duration block scheduling.""" + + WAYPOINT_RETIMING = "waypoint_retiming" + BLOCK_SCHEDULING = "block_scheduling" + + +@dataclass(frozen=True) +class ScheduleSpec: + """Scheduling settings and task-authored constraints. + + Args: + strategy: Waypoint retiming or block scheduling. + constraints: Timing constraints, independent of how each segment was generated. + collision_margin_m: Collision clearance margin [m]. + time_limit_s: Optional solver wall-clock limit [s]. + max_block_size: Maximum waypoints per block; zero keeps each segment atomic. + minimize_max_wait: Whether equal-makespan schedules minimize their largest inserted wait. + """ + + strategy: SchedulerStrategy = SchedulerStrategy.WAYPOINT_RETIMING + constraints: tuple[ScheduleConstraintSpec, ...] = field(default_factory=tuple) + collision_margin_m: float = 0.0 + time_limit_s: float | None = None + max_block_size: int = 0 + minimize_max_wait: bool = True + + def __post_init__(self) -> None: + """Validate solver settings, constraint types and strategy-specific block size.""" + + assert isinstance(self.strategy, SchedulerStrategy) + assert isinstance(self.constraints, tuple) and all( + isinstance(item, (PrecedenceConstraintSpec, NonOverlapConstraintSpec, NonPreemptiveConstraintSpec)) + for item in self.constraints + ) + assert math.isfinite(self.collision_margin_m) and self.collision_margin_m >= 0.0 + if self.time_limit_s is not None: + assert math.isfinite(self.time_limit_s) and self.time_limit_s > 0.0 + assert type(self.max_block_size) is int and self.max_block_size >= 0 + assert ( + self.strategy == SchedulerStrategy.BLOCK_SCHEDULING or self.max_block_size == 0 + ), "max_block_size is supported only by block_scheduling" + assert isinstance(self.minimize_max_wait, bool), "minimize_max_wait must be a bool" + + +__all__ = [ + "NonOverlapConstraintSpec", + "NonPreemptiveConstraintSpec", + "PrecedenceConstraintSpec", + "ScheduleConstraintSpec", + "ScheduleSpec", + "SchedulerStrategy", + "SegmentAnchor", + "SegmentAnchorPoint", + "SegmentId", +] diff --git a/autodata_interfaces/tasks/segment_spec.py b/autodata_interfaces/tasks/segment_spec.py new file mode 100644 index 0000000..f2ca29e --- /dev/null +++ b/autodata_interfaces/tasks/segment_spec.py @@ -0,0 +1,345 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Trajectory segments used by complete-episode generation algorithms.""" + +from __future__ import annotations + +import enum +import math +import re +from dataclasses import dataclass, field + +_LOCAL_NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_]*$") + + +def validate_local_name(value: str, *, field_name: str) -> None: + """Check a lowercase descriptor name. + + Args: + value: Name to validate. + field_name: Field name included in validation errors. + """ + + assert isinstance(value, str) and _LOCAL_NAME_PATTERN.fullmatch( + value + ), f"{field_name} must match {_LOCAL_NAME_PATTERN.pattern!r}, got {value!r}" + + +@dataclass(frozen=True, order=True) +class SegmentId: + """Identify a segment by end effector, subtask and segment name. + + Args: + eef_name: End-effector name. + subtask_name: Subtask name within that end effector. + segment_name: Segment name within the subtask. + """ + + eef_name: str + subtask_name: str + segment_name: str + + def __post_init__(self) -> None: + """Validate each part of the descriptor-local segment name.""" + + validate_local_name(self.eef_name, field_name="eef_name") + validate_local_name(self.subtask_name, field_name="subtask_name") + validate_local_name(self.segment_name, field_name="segment_name") + + @classmethod + def from_string(cls, value: str) -> SegmentId: + """Parse a segment name such as ``left.pick.transit``. + + Args: + value: End-effector, subtask and segment names separated by dots. + + Returns: + Segment identified by the string. + """ + + assert isinstance(value, str), "segment ID must be a string" + parts = value.split(".") + assert len(parts) == 3, f"invalid segment ID: {value!r}" + return cls(*parts) + + def __str__(self) -> str: + """Return the dotted end-effector, subtask and segment name.""" + + return f"{self.eef_name}.{self.subtask_name}.{self.segment_name}" + + +class SegmentKind(enum.StrEnum): + """Semantic role of a trajectory segment.""" + + TRANSIT = "transit" + SKILL = "skill" + HOLD = "hold" + + +class SegmentProvider(enum.StrEnum): + """Source used to generate a segment trajectory.""" + + MOTION_PLANNER = "motion_planner" + DEMONSTRATION = "demonstration" + SCRIPTED = "scripted" + + +@dataclass(frozen=True) +class MotionGoalSpec: + """Tool-pose target for a motion-planned segment. + + The pose is expressed in the environment frame when ``object_ref`` is empty, otherwise in the + current frame of that logical scene object. + + Args: + position_m: Tool position [m]. + rotation_xyzw: Unit tool quaternion in ``(x, y, z, w)`` order. + object_ref: Optional logical scene object used as the reference frame. + object_pose_after_segment_id: Optional segment whose terminal released-object pose supplies + ``object_ref``. Empty uses the reset-time scene pose. + """ + + position_m: tuple[float, float, float] + rotation_xyzw: tuple[float, float, float, float] + object_ref: str = "" + object_pose_after_segment_id: SegmentId | None = field(default=None, kw_only=True) + + def __post_init__(self) -> None: + """Require a finite pose, unit XYZW quaternion and consistent object-frame reference.""" + + assert len(self.position_m) == 3, "motion goal position_m must contain three values" + assert len(self.rotation_xyzw) == 4, "motion goal rotation_xyzw must contain four values" + values = (*self.position_m, *self.rotation_xyzw) + assert all( + type(value) in {int, float} and math.isfinite(value) for value in values + ), "motion goal pose must contain finite numeric values" + quaternion_norm = math.sqrt(sum(value * value for value in self.rotation_xyzw)) + assert math.isclose( + quaternion_norm, 1.0, rel_tol=0.0, abs_tol=1.0e-5 + ), f"motion goal rotation_xyzw must be a unit quaternion, got norm {quaternion_norm:.6f}" + if self.object_ref: + validate_local_name(self.object_ref, field_name="motion goal object_ref") + assert self.object_pose_after_segment_id is None or isinstance( + self.object_pose_after_segment_id, SegmentId + ), "object_pose_after_segment_id must be a SegmentId" + assert ( + self.object_pose_after_segment_id is None or self.object_ref + ), "object_pose_after_segment_id requires object_ref" + + +class SegmentEventType(enum.StrEnum): + """Object-state transition on a segment boundary.""" + + ATTACH = "attach" + DETACH = "detach" + + +class SegmentEventPoint(enum.StrEnum): + """Location of an object event within its segment.""" + + START = "start" + END = "end" + SOURCE_ANNOTATION = "source_annotation" + + +@dataclass(frozen=True) +class DemonstrationSourceWindowSpec: + """Event-relative end of the prefix retained from a demonstration segment. + + Args: + anchor_annotation_key: Source annotation that anchors the retained endpoint. + post_event_sample_count: Number of source samples retained after the event sample. + """ + + anchor_annotation_key: str + post_event_sample_count: int + + def __post_init__(self) -> None: + """Validate the annotation name and nonnegative trailing sample count.""" + + validate_local_name(self.anchor_annotation_key, field_name="source-window anchor_annotation_key") + assert ( + type(self.post_event_sample_count) is int and self.post_event_sample_count >= 0 + ), "post_event_sample_count must be a non-negative integer" + + +@dataclass(frozen=True, order=True) +class SegmentWorldContactSpec: + """One object/fixture pair allowed to contact while a segment owns its lane. + + Args: + object_ref: Logical projected object name. + fixture_ref: Logical static world-object name. + """ + + object_ref: str + fixture_ref: str + + def __post_init__(self) -> None: + """Require distinct, valid logical object and fixture names.""" + + validate_local_name(self.object_ref, field_name="world-contact object_ref") + validate_local_name(self.fixture_ref, field_name="world-contact fixture_ref") + assert self.object_ref != self.fixture_ref, "world contact requires distinct object and fixture refs" + + +@dataclass(frozen=True) +class SegmentRobotContactSpec: + """Exact robot links allowed to contact one task object during a segment. + + Args: + object_ref: Logical task object name. + robot_link_names: Sorted robot collision-link names. + start_annotation_key: Optional same-segment source annotation that starts the permission. + clear_at_end: Whether the segment's final waypoint must be strictly clear of the object. + """ + + object_ref: str + robot_link_names: tuple[str, ...] + start_annotation_key: str = "" + clear_at_end: bool = False + + def __post_init__(self) -> None: + """Validate sorted unique link names and optional source-annotation timing.""" + + validate_local_name(self.object_ref, field_name="robot-contact object_ref") + assert ( + isinstance(self.robot_link_names, tuple) and self.robot_link_names + ), "robot_link_names must be a non-empty tuple" + assert all( + isinstance(name, str) and name and name.strip() == name for name in self.robot_link_names + ), "robot_link_names must contain non-empty trimmed strings" + assert len(self.robot_link_names) == len(set(self.robot_link_names)), "robot_link_names must be unique" + assert self.robot_link_names == tuple(sorted(self.robot_link_names)), "robot_link_names must be in sorted order" + if self.start_annotation_key: + validate_local_name(self.start_annotation_key, field_name="robot-contact start_annotation_key") + assert type(self.clear_at_end) is bool, "clear_at_end must be a bool" + + +@dataclass(frozen=True) +class SegmentEventSpec: + """Attach or detach an object at a stable segment boundary. + + Args: + event_type: Object-state transition. + object_ref: Logical task object name. + point: Boundary or source annotation carrying the event. + annotation_key: Dataset annotation used by ``SOURCE_ANNOTATION``. + attachment_frame: Robot link used by ``ATTACH``. + """ + + event_type: SegmentEventType + object_ref: str + point: SegmentEventPoint = SegmentEventPoint.END + annotation_key: str = "" + attachment_frame: str = "" + + def __post_init__(self) -> None: + """Validate annotation and attachment-frame fields for the selected event type.""" + + validate_local_name(self.object_ref, field_name="object_ref") + if self.point == SegmentEventPoint.SOURCE_ANNOTATION: + validate_local_name(self.annotation_key, field_name="annotation_key") + else: + assert not self.annotation_key, "annotation_key requires point='source_annotation'" + if self.event_type == SegmentEventType.ATTACH: + assert self.attachment_frame, "attach events require attachment_frame" + else: + assert not self.attachment_frame, "detach events do not use attachment_frame" + + +@dataclass(frozen=True) +class SegmentSpec: + """Declarative unit of a subtask path. + + Scheduling is provider-independent once the algorithm has built a segment's waypoint path. + Descriptor validation must reject providers the selected algorithm does not support. + + Args: + name: Stable descriptor-local segment name. + kind: Semantic role of the segment. + provider: Source used to build the segment. + goal_segment_id: Segment whose prepared entry target is consumed by motion planning. + motion_goal: Independent task-defined target consumed by motion planning. + resource_ids: Additional task-local resources held for the nominal segment interval. + events: Ordered object-state transitions on the segment. + world_contacts: Exact object/fixture contact permissions. + demonstration_source_window: Optional event-relative end of the retained demonstration. + duration_steps: Number of samples for a scripted segment. + passthrough_preset: Embodiment-owned auxiliary-joint target. + cartesian_offset_m: Scripted environment-frame Cartesian offset [m]. + robot_contacts: Exact robot/object contact permissions. + """ + + name: str + kind: SegmentKind + provider: SegmentProvider + goal_segment_id: SegmentId | None = field(default=None, kw_only=True) + motion_goal: MotionGoalSpec | None = field(default=None, kw_only=True) + resource_ids: tuple[str, ...] = field(default_factory=tuple, kw_only=True) + events: tuple[SegmentEventSpec, ...] = field(default_factory=tuple) + world_contacts: tuple[SegmentWorldContactSpec, ...] = field(default_factory=tuple) + demonstration_source_window: DemonstrationSourceWindowSpec | None = None + duration_steps: int = 0 + passthrough_preset: str = "" + cartesian_offset_m: tuple[float, ...] = field(default_factory=tuple) + robot_contacts: tuple[SegmentRobotContactSpec, ...] = field(default_factory=tuple) + + def __post_init__(self) -> None: + """Validate provider-specific goals, scripted commands, resources and contact permissions.""" + + validate_local_name(self.name, field_name="segment name") + assert isinstance(self.kind, SegmentKind), "kind must be a SegmentKind" + assert isinstance(self.provider, SegmentProvider), "provider must be a SegmentProvider" + if self.provider == SegmentProvider.MOTION_PLANNER: + has_segment_goal = isinstance(self.goal_segment_id, SegmentId) + has_motion_goal = isinstance(self.motion_goal, MotionGoalSpec) + assert ( + has_segment_goal ^ has_motion_goal + ), "motion-planner segments require a goal_segment_id or motion_goal, exclusively" + else: + assert self.goal_segment_id is None, "goal_segment_id is supported only by motion-planner segments" + assert self.motion_goal is None, "motion_goal is supported only by motion-planner segments" + assert isinstance(self.resource_ids, tuple), "resource_ids must be a tuple" + for resource_id in self.resource_ids: + validate_local_name(resource_id, field_name="resource_id") + assert len(self.resource_ids) == len(set(self.resource_ids)), "resource_ids must be unique" + assert self.resource_ids == tuple(sorted(self.resource_ids)), "resource_ids must be in sorted order" + assert all(isinstance(event, SegmentEventSpec) for event in self.events) + assert all(isinstance(contact, SegmentWorldContactSpec) for contact in self.world_contacts) + assert len(self.world_contacts) == len(set(self.world_contacts)), "world contacts must be unique per segment" + assert self.demonstration_source_window is None or isinstance( + self.demonstration_source_window, DemonstrationSourceWindowSpec + ), "demonstration_source_window must be a DemonstrationSourceWindowSpec" + assert ( + type(self.duration_steps) is int and self.duration_steps >= 0 + ), "duration_steps must be a non-negative integer" + assert isinstance(self.passthrough_preset, str), "passthrough_preset must be a string" + if self.passthrough_preset: + validate_local_name(self.passthrough_preset, field_name="passthrough_preset") + assert isinstance(self.cartesian_offset_m, tuple) and len(self.cartesian_offset_m) in { + 0, + 3, + }, "cartesian_offset_m must be empty or an XYZ tuple" + assert all( + type(value) in {int, float} and math.isfinite(value) for value in self.cartesian_offset_m + ), "cartesian_offset_m must contain finite numeric values" + assert all(isinstance(contact, SegmentRobotContactSpec) for contact in self.robot_contacts) + assert len(self.robot_contacts) == len(set(self.robot_contacts)), "robot contacts must be unique per segment" + + +__all__ = [ + "DemonstrationSourceWindowSpec", + "MotionGoalSpec", + "SegmentEventPoint", + "SegmentEventSpec", + "SegmentEventType", + "SegmentId", + "SegmentKind", + "SegmentProvider", + "SegmentRobotContactSpec", + "SegmentSpec", + "SegmentWorldContactSpec", + "validate_local_name", +] diff --git a/autodata_tests/core/test_scheduling.py b/autodata_tests/core/test_scheduling.py new file mode 100644 index 0000000..69e073d --- /dev/null +++ b/autodata_tests/core/test_scheduling.py @@ -0,0 +1,136 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Scheduling contracts independent of simulator and trajectory provider.""" + +from concurrent.futures import ThreadPoolExecutor + +import pytest + +from autodata_core.scheduling import ( + Schedule, + ScheduleFailure, + SchedulePath, + SegmentWaypoint, + WaypointConflict, + schedule_paths, +) +from autodata_interfaces.tasks.schedule_constraint_spec import ( + NonPreemptiveConstraintSpec, + PrecedenceConstraintSpec, + SchedulerStrategy, + SegmentAnchor, + SegmentAnchorPoint, + SegmentId, +) + + +@pytest.mark.parametrize("strategy", tuple(SchedulerStrategy)) +@pytest.mark.parametrize("minimize_max_wait", (False, True)) +def test_collision_conflicts_preserve_precedence_and_non_preemption(strategy, minimize_max_wait): + left = SegmentId.from_string("left.pour.transit") + right = SegmentId.from_string("right.pick.skill") + paths = (SchedulePath(left, "left", 4), SchedulePath(right, "right", 4)) + constraint = PrecedenceConstraintSpec( + before=SegmentAnchor.from_string("left.pour.transit.end"), + after=SegmentAnchor.from_string("right.pick.skill.end"), + ) + + result = schedule_paths( + paths, + conflicts=(WaypointConflict(SegmentWaypoint(left, 1), SegmentWaypoint(right, 1)),), + precedence=(constraint,), + non_preemptive=(NonPreemptiveConstraintSpec((right,)),), + strategy=strategy, + minimize_max_wait=minimize_max_wait, + ) + + assert isinstance(result, Schedule) + left_ticks, right_ticks = result.ticks_for(left), result.ticks_for(right) + assert left_ticks[-1] <= right_ticks[-1] + assert all(second - first == 1 for first, second in zip(right_ticks, right_ticks[1:])) + assert left_ticks[2] <= right_ticks[1] or right_ticks[2] <= left_ticks[1] + + +def test_independent_schedules_solve_in_parallel_without_sharing_results(): + left = SegmentId.from_string("left.pick.transit") + right = SegmentId.from_string("right.pick.transit") + + def solve(length): + return schedule_paths((SchedulePath(left, "left", length), SchedulePath(right, "right", length + 1))) + + with ThreadPoolExecutor(max_workers=2) as executor: + results = list(executor.map(solve, (3, 5, 4, 7))) + assert all(isinstance(result, Schedule) for result in results) + assert [result.makespan_ticks for result in results] == [4, 6, 5, 8] + + +def test_colliding_initial_states_fail_instead_of_delaying_occupied_endpoints(): + left = SegmentId.from_string("left.pick.transit") + right = SegmentId.from_string("right.pick.transit") + + result = schedule_paths( + (SchedulePath(left, "left", 3), SchedulePath(right, "right", 3)), + conflicts=(WaypointConflict(SegmentWaypoint(left, 0), SegmentWaypoint(right, 0)),), + ) + + assert isinstance(result, ScheduleFailure) + + +def test_equal_start_and_non_preemption_synchronize_equal_length_skills(): + """Existing endpoint and continuity constraints compose into fixed-rate synchronization.""" + left = SegmentId.from_string("left.cooperate.skill") + right = SegmentId.from_string("right.cooperate.skill") + paths = ( + SchedulePath(SegmentId.from_string("left.cooperate.transit"), "left", 3), + SchedulePath(left, "left", 4), + SchedulePath(SegmentId.from_string("right.cooperate.transit"), "right", 5), + SchedulePath(right, "right", 4), + ) + + result = schedule_paths( + paths, + precedence=( + PrecedenceConstraintSpec( + SegmentAnchor(left, SegmentAnchorPoint.START), + SegmentAnchor(right, SegmentAnchorPoint.START), + max_lag_steps=0, + ), + ), + non_preemptive=(NonPreemptiveConstraintSpec((left,)), NonPreemptiveConstraintSpec((right,))), + ) + + assert isinstance(result, Schedule) + assert result.ticks_for(left) == result.ticks_for(right) + assert result.makespan_ticks == 9 + + +def test_precedence_keeps_provider_at_hold_until_consumer_finishes(): + """Constrain departure, not the nominal hold end, when an arm sustains a resource.""" + hold = SegmentId.from_string("left.support.hold") + leave = SegmentId.from_string("left.support.departure") + work = SegmentId.from_string("right.insert.skill") + paths = ( + SchedulePath(SegmentId.from_string("left.support.transit"), "left", 2), + SchedulePath(hold, "left", 1), + SchedulePath(leave, "left", 2), + SchedulePath(SegmentId.from_string("right.insert.transit"), "right", 1), + SchedulePath(work, "right", 4), + ) + + result = schedule_paths( + paths, + precedence=( + PrecedenceConstraintSpec( + SegmentAnchor(hold, SegmentAnchorPoint.START), SegmentAnchor(work, SegmentAnchorPoint.START) + ), + PrecedenceConstraintSpec( + SegmentAnchor(work, SegmentAnchorPoint.END), SegmentAnchor(leave, SegmentAnchorPoint.START) + ), + ), + non_preemptive=(NonPreemptiveConstraintSpec((work,)),), + ) + + assert isinstance(result, Schedule) + assert result.ticks_for(hold)[0] <= result.ticks_for(work)[0] + assert result.ticks_for(leave)[0] >= result.ticks_for(work)[-1] + 1 From b0d0cb82b42530061e37b1312a1a02f8ec2c0ed0 Mon Sep 17 00:00:00 2001 From: Neel Jawale Date: Tue, 17 Nov 2026 17:08:59 -0800 Subject: [PATCH 2/3] Respect secondary scheduling costs Use a zero relative MILP gap so small wait penalties are not discarded by the default tolerance. Clarify shared-resource lane requirements. Signed-off-by: Neel Jawale --- autodata_core/scheduling/retiming.py | 2 +- autodata_core/scheduling/types.py | 1 + autodata_tests/core/test_scheduling.py | 17 +++++++++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/autodata_core/scheduling/retiming.py b/autodata_core/scheduling/retiming.py index 2915298..d73cf73 100644 --- a/autodata_core/scheduling/retiming.py +++ b/autodata_core/scheduling/retiming.py @@ -232,7 +232,7 @@ def schedule_paths( upper_bounds[binary_offset:] = 1.0 integrality = np.ones(variable_count, dtype=np.uint8) linear_constraints = _scipy_constraints(rows, variable_count) - options: dict[str, float | bool] = {} + options: dict[str, float | bool] = {"mip_rel_gap": 0.0} deadline = None if time_limit_s is None else time.monotonic() + time_limit_s try: diff --git a/autodata_core/scheduling/types.py b/autodata_core/scheduling/types.py index cb12b8a..7a16adc 100644 --- a/autodata_core/scheduling/types.py +++ b/autodata_core/scheduling/types.py @@ -24,6 +24,7 @@ class SchedulePath: lane: Persistent command lane, normally an end-effector name. waypoint_count: Number of configurations in the segment path. resource_ids: Additional task-local resources held for the nominal segment interval. + Each resource must be claimed on at least two lanes in the same scheduling call. """ segment_id: SegmentId diff --git a/autodata_tests/core/test_scheduling.py b/autodata_tests/core/test_scheduling.py index 69e073d..38a699b 100644 --- a/autodata_tests/core/test_scheduling.py +++ b/autodata_tests/core/test_scheduling.py @@ -7,6 +7,23 @@ import pytest + +def test_secondary_objective_is_not_hidden_by_a_relative_mip_gap(monkeypatch): + from autodata_core.scheduling import retiming + + original = retiming.milp + options = [] + + def solve(*args, **kwargs): + options.append(kwargs["options"].copy()) + return original(*args, **kwargs) + + monkeypatch.setattr(retiming, "milp", solve) + segment = SegmentId.from_string("left.move.transit") + assert isinstance(schedule_paths((SchedulePath(segment, "left", 2),)), Schedule) + assert options and all(value["mip_rel_gap"] == 0.0 for value in options) + + from autodata_core.scheduling import ( Schedule, ScheduleFailure, From 7e11352fa34ac6918b68cace0cc49917c45b2667 Mon Sep 17 00:00:00 2001 From: Neel Jawale Date: Thu, 19 Nov 2026 09:46:42 -0800 Subject: [PATCH 3/3] Explain retiming constraints and cover terminal conflicts Document the MILP variable layout, lane timing, collision ordering, and objective. Relax unnecessary keyword-only markers and test that colliding final poses are infeasible under both strategies. Signed-off-by: Neel Jawale --- autodata_core/scheduling/retiming.py | 11 +++++++++-- autodata_tests/core/test_scheduling.py | 12 ++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/autodata_core/scheduling/retiming.py b/autodata_core/scheduling/retiming.py index d73cf73..f4a449b 100644 --- a/autodata_core/scheduling/retiming.py +++ b/autodata_core/scheduling/retiming.py @@ -56,7 +56,6 @@ def time_variable_count(self) -> int: def schedule_paths( paths: tuple[SchedulePath, ...], - *, conflicts: tuple[WaypointConflict, ...] = (), precedence: tuple[PrecedenceConstraintSpec, ...] = (), non_overlap: tuple[NonOverlapConstraintSpec, ...] = (), @@ -117,6 +116,7 @@ def schedule_paths( assert time_limit_s is None or time_limit_s > 0.0, "time_limit_s must be positive" assert isinstance(minimize_max_wait, bool), "minimize_max_wait must be a bool" + # A group has one start-time variable; waypoints inside it retain fixed one-tick spacing. group_size = 1 if strategy == SchedulerStrategy.WAYPOINT_RETIMING else max_block_size layout = _layout_create(paths, max_group_size=group_size) conflicts = _conflicts_validate_and_deduplicate(layout, conflicts) @@ -134,6 +134,7 @@ def schedule_paths( ) non_overlap = _non_overlap_resolve(layout, non_overlap) + # Lay out the integer start times, makespan, optional wait cost, and binary order choices. horizon_ticks = _horizon_ticks(layout, precedence) makespan_variable = layout.time_variable_count max_wait_variable = makespan_variable + 1 if minimize_max_wait else None @@ -143,6 +144,7 @@ def schedule_paths( time_lower_bounds, time_upper_bounds = _time_variable_bounds(layout, horizon_ticks) rows: list[_ConstraintRow] = [] + # Preserve lane order. Non-preemptive pairs are consecutive; other pairs may acquire waits. for lane_waypoints in layout.waypoints_by_lane.values(): for first, second in zip(lane_waypoints, lane_waypoints[1:], strict=False): if layout.group_by_waypoint[first] == layout.group_by_waypoint[second]: @@ -170,6 +172,7 @@ def schedule_paths( ) _constraint_add(rows, terminal_progress, lower=1.0) + # Task ordering constrains segment boundary times, independent of collision ordering. for constraint in precedence: lag = _expressions_combine( (1.0, _anchor_expression(layout, constraint.after)), @@ -182,6 +185,7 @@ def schedule_paths( upper=None if constraint.max_lag_steps is None else float(constraint.max_lag_steps), ) + # Each binary chooses which colliding held-state interval must finish first. for conflict_index, (first_group, second_group, first_conflicts, second_conflicts) in enumerate(conflict_groups): order_variable = binary_offset + conflict_index first_start, first_end = _conflict_group_interval( @@ -208,6 +212,7 @@ def schedule_paths( time_upper_bounds=time_upper_bounds, ) + # Resource/task mutexes apply the same ordering choice to whole segments. for constraint_index, constraint in enumerate(non_overlap): first_id, second_id = constraint.segments order_variable = non_overlap_binary_offset + constraint_index @@ -222,6 +227,7 @@ def schedule_paths( time_upper_bounds=time_upper_bounds, ) + # An extra tick of makespan costs more than any possible improvement in the wait term. objective = np.zeros(variable_count, dtype=np.float64) objective[makespan_variable] = 1.0 if max_wait_variable is not None: @@ -265,6 +271,7 @@ def schedule_paths( message = str(result.message).strip() or f"MILP returned status {result.status}" return ScheduleFailure(reason=reason, message=message) + # Recheck the integer candidate independently before returning an executable schedule. values = np.asarray(result.x, dtype=np.float64) rounded = np.rint(values) if not bool(np.allclose(values, rounded, atol=1.0e-6, rtol=0.0)): @@ -294,7 +301,7 @@ def schedule_paths( return schedule -def _layout_create(paths: tuple[SchedulePath, ...], *, max_group_size: int) -> _Layout: +def _layout_create(paths: tuple[SchedulePath, ...], max_group_size: int) -> _Layout: """Assign time variables to fixed-rate groups and link consecutive lane commands. Args: diff --git a/autodata_tests/core/test_scheduling.py b/autodata_tests/core/test_scheduling.py index 38a699b..a93fe26 100644 --- a/autodata_tests/core/test_scheduling.py +++ b/autodata_tests/core/test_scheduling.py @@ -42,6 +42,18 @@ def solve(*args, **kwargs): ) +@pytest.mark.parametrize("strategy", tuple(SchedulerStrategy)) +def test_colliding_final_poses_are_infeasible(strategy): + left, right = (SegmentId.from_string(f"{arm}.move.transit") for arm in ("left", "right")) + result = schedule_paths( + (SchedulePath(left, "left", 2), SchedulePath(right, "right", 2)), + (WaypointConflict(SegmentWaypoint(left, 1), SegmentWaypoint(right, 1)),), + strategy=strategy, + ) + assert isinstance(result, ScheduleFailure) + assert result.reason == "infeasible" + + @pytest.mark.parametrize("strategy", tuple(SchedulerStrategy)) @pytest.mark.parametrize("minimize_max_wait", (False, True)) def test_collision_conflicts_preserve_precedence_and_non_preemption(strategy, minimize_max_wait):