feat(phase2): implement AMR robot state machine, task lifecycles, inventory catalog, and Phase 2 OpenUSD scene
This commit is contained in:
@@ -193,18 +193,17 @@ def export_usd(config_dir: Optional[str] = None, output_path: Optional[str] = No
|
||||
setup_logging()
|
||||
logger = get_logger("cli")
|
||||
try:
|
||||
from warehouse_twin.domain.warehouse import WarehouseModel
|
||||
from warehouse_twin.interfaces.usd_generator import WarehouseUSDGenerator
|
||||
|
||||
loader = ConfigLoader(config_dir)
|
||||
bundle = loader.load_all()
|
||||
model = WarehouseModel.from_config_dict(bundle.warehouse)
|
||||
|
||||
generator = WarehouseUSDGenerator(model)
|
||||
default_out = Path("omniverse/scenes/warehouse_phase1.usda")
|
||||
generator = WarehouseUSDGenerator.from_config_bundle(bundle)
|
||||
default_out = Path("omniverse/scenes/warehouse_phase2.usda")
|
||||
out_file = Path(output_path).resolve() if output_path else default_out.resolve()
|
||||
|
||||
saved_path = generator.export_usda(out_file)
|
||||
model = generator.model
|
||||
print("=" * 65)
|
||||
print("Warehouse 3D OpenUSD Scene Successfully Generated")
|
||||
print("=" * 65)
|
||||
@@ -212,6 +211,9 @@ def export_usd(config_dir: Optional[str] = None, output_path: Optional[str] = No
|
||||
print(f"Facility: {model.dimensions.width}m x {model.dimensions.depth}m x {model.dimensions.height}m")
|
||||
print(f"Zones: Zone A (Blue), Zone B (Amber), Zone C (Green)")
|
||||
print(f"Entities: {len(model.storage_locations)} Storage Racks, {len(model.stations)} Stations, {len(model.charging_stations)} Chargers")
|
||||
print(f"AMR Fleet: {len(generator.robots)} Autonomous Mobile Robots")
|
||||
for r in generator.robots:
|
||||
print(f" - {r.robot_id} ({r.robot_type}) at ({r.position.x}, {r.position.y}, {r.position.z}) [battery: {r.battery_percent:.0f}%]")
|
||||
print("-" * 65)
|
||||
print("How to view in Omniverse Kit:")
|
||||
print(f" 1. In the active Kit App window, select File -> Open")
|
||||
@@ -286,7 +288,7 @@ def main(argv: Optional[list[str]] = None) -> int:
|
||||
"--output",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Output USD file path (defaults to omniverse/scenes/warehouse_phase1.usda)",
|
||||
help="Output USD file path (defaults to omniverse/scenes/warehouse_phase2.usda)",
|
||||
)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
@@ -1,5 +1,26 @@
|
||||
"""Domain models for Warehouse Robot Fleet Digital Twin."""
|
||||
|
||||
from warehouse_twin.domain.events import (
|
||||
SimulationEvent,
|
||||
SimulationEventType,
|
||||
)
|
||||
from warehouse_twin.domain.inventory import (
|
||||
InsufficientStockError,
|
||||
InventoryCatalog,
|
||||
InventoryItem,
|
||||
)
|
||||
from warehouse_twin.domain.robot import (
|
||||
IncompatibleRobotTaskError,
|
||||
InvalidStateTransitionError,
|
||||
Robot,
|
||||
RobotState,
|
||||
RobotTypeSpec,
|
||||
)
|
||||
from warehouse_twin.domain.task import (
|
||||
Task,
|
||||
TaskStatus,
|
||||
TaskType,
|
||||
)
|
||||
from warehouse_twin.domain.warehouse import (
|
||||
ChargingStation,
|
||||
NodeType,
|
||||
@@ -16,6 +37,24 @@ from warehouse_twin.domain.warehouse import (
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# Robot
|
||||
"IncompatibleRobotTaskError",
|
||||
"InvalidStateTransitionError",
|
||||
"Robot",
|
||||
"RobotState",
|
||||
"RobotTypeSpec",
|
||||
# Task
|
||||
"Task",
|
||||
"TaskStatus",
|
||||
"TaskType",
|
||||
# Inventory
|
||||
"InsufficientStockError",
|
||||
"InventoryCatalog",
|
||||
"InventoryItem",
|
||||
# Events
|
||||
"SimulationEvent",
|
||||
"SimulationEventType",
|
||||
# Warehouse
|
||||
"ChargingStation",
|
||||
"NodeType",
|
||||
"Position3D",
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Simulation event schemas: structured records for operational auditing and analytics."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
|
||||
class SimulationEventType(str, Enum):
|
||||
"""Categorization of discrete events emitted by the simulation engine."""
|
||||
TASK_RELEASED = "TASK_RELEASED"
|
||||
TASK_ASSIGNED = "TASK_ASSIGNED"
|
||||
TASK_STARTED = "TASK_STARTED"
|
||||
TASK_COMPLETED = "TASK_COMPLETED"
|
||||
TASK_CANCELLED = "TASK_CANCELLED"
|
||||
TASK_FAILED = "TASK_FAILED"
|
||||
|
||||
ROBOT_DISPATCHED = "ROBOT_DISPATCHED"
|
||||
ROBOT_STATE_CHANGED = "ROBOT_STATE_CHANGED"
|
||||
ROBOT_ARRIVED = "ROBOT_ARRIVED"
|
||||
ROBOT_CHARGING_STARTED = "ROBOT_CHARGING_STARTED"
|
||||
ROBOT_CHARGING_COMPLETED = "ROBOT_CHARGING_COMPLETED"
|
||||
|
||||
INVENTORY_RESERVED = "INVENTORY_RESERVED"
|
||||
INVENTORY_CONSUMED = "INVENTORY_CONSUMED"
|
||||
INVENTORY_REPLENISHED = "INVENTORY_REPLENISHED"
|
||||
STOCKOUT_OCCURRED = "STOCKOUT_OCCURRED"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SimulationEvent:
|
||||
"""Immutable audit record emitted upon discrete simulation state transitions."""
|
||||
event_id: str
|
||||
simulation_time: float
|
||||
event_type: SimulationEventType
|
||||
entity_id: str
|
||||
task_id: Optional[str] = None
|
||||
metadata: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Convert event to serializable dictionary format."""
|
||||
return {
|
||||
"event_id": self.event_id,
|
||||
"simulation_time": round(self.simulation_time, 3),
|
||||
"event_type": self.event_type.value,
|
||||
"entity_id": self.entity_id,
|
||||
"task_id": self.task_id,
|
||||
"metadata": self.metadata,
|
||||
}
|
||||
|
||||
def to_jsonl(self) -> str:
|
||||
"""Serialize event to a single-line JSON string."""
|
||||
return json.dumps(self.to_dict())
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Inventory domain entities: stock tracking, reservation, replenishment, and catalogs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
class InsufficientStockError(Exception):
|
||||
"""Raised when attempting to reserve or consume more stock than is available."""
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class InventoryItem:
|
||||
"""Catalog inventory item tracking on-hand stock, weights, and replenishment rules."""
|
||||
item_id: str
|
||||
name: str
|
||||
category: str
|
||||
zone: str
|
||||
unit_weight_kg: float
|
||||
initial_stock: int
|
||||
current_stock: int
|
||||
reserved_stock: int = 0
|
||||
minimum_stock: int = 10
|
||||
replenishment_batch: int = 50
|
||||
storage_location: str = ""
|
||||
|
||||
@property
|
||||
def available_stock(self) -> int:
|
||||
"""On-hand quantity unencumbered by pending reservations."""
|
||||
return max(0, self.current_stock - self.reserved_stock)
|
||||
|
||||
def reserve(self, qty: int) -> None:
|
||||
"""Reserve units for an assigned picking task.
|
||||
|
||||
Raises:
|
||||
InsufficientStockError: If available stock is less than qty.
|
||||
"""
|
||||
if qty <= 0:
|
||||
return
|
||||
if qty > self.available_stock:
|
||||
raise InsufficientStockError(
|
||||
f"Cannot reserve {qty} units of '{self.item_id}'. Only {self.available_stock} available."
|
||||
)
|
||||
self.reserved_stock += qty
|
||||
|
||||
def release_reservation(self, qty: int) -> None:
|
||||
"""Release previously reserved units without consuming them."""
|
||||
self.reserved_stock = max(0, self.reserved_stock - max(0, qty))
|
||||
|
||||
def consume(self, qty: int) -> None:
|
||||
"""Deduct stock upon successful pick completion.
|
||||
|
||||
Raises:
|
||||
InsufficientStockError: If current stock is less than qty.
|
||||
"""
|
||||
if qty <= 0:
|
||||
return
|
||||
if qty > self.current_stock:
|
||||
raise InsufficientStockError(
|
||||
f"Cannot consume {qty} units of '{self.item_id}'. Only {self.current_stock} in stock."
|
||||
)
|
||||
self.current_stock -= qty
|
||||
self.reserved_stock = max(0, self.reserved_stock - qty)
|
||||
|
||||
def replenish(self, qty: int) -> None:
|
||||
"""Add newly arrived stock from an inbound replenishment task."""
|
||||
if qty > 0:
|
||||
self.current_stock += qty
|
||||
|
||||
def needs_replenishment(self) -> bool:
|
||||
"""Check if on-hand stock has dropped to or below minimum threshold."""
|
||||
return self.current_stock <= self.minimum_stock
|
||||
|
||||
|
||||
class InventoryCatalog:
|
||||
"""Repository managing the full inventory catalog across all warehouse zones."""
|
||||
|
||||
def __init__(self, items: Optional[Dict[str, InventoryItem]] = None) -> None:
|
||||
"""Initialize catalog with an optional dictionary of items."""
|
||||
self._items: Dict[str, InventoryItem] = items or {}
|
||||
|
||||
@classmethod
|
||||
def from_config_dict(cls, data: Dict[str, Any]) -> InventoryCatalog:
|
||||
"""Construct an InventoryCatalog from parsed inventory configuration."""
|
||||
catalog_items: Dict[str, InventoryItem] = {}
|
||||
|
||||
for cat_key, cat_data in data.get("categories", {}).items():
|
||||
cat_name = cat_data.get("name", cat_key)
|
||||
cat_zone = cat_data.get("zone", "zone_a")
|
||||
|
||||
for item_data in cat_data.get("items", []):
|
||||
item_id = item_data["item_id"]
|
||||
initial = int(item_data.get("initial_stock", 100))
|
||||
item = InventoryItem(
|
||||
item_id=item_id,
|
||||
name=item_data.get("name", item_id),
|
||||
category=cat_name,
|
||||
zone=cat_zone,
|
||||
unit_weight_kg=float(item_data.get("unit_weight_kg", 5.0)),
|
||||
initial_stock=initial,
|
||||
current_stock=initial,
|
||||
minimum_stock=int(item_data.get("minimum_stock", 20)),
|
||||
replenishment_batch=int(item_data.get("replenishment_batch", 50)),
|
||||
storage_location=item_data.get("storage_location", ""),
|
||||
)
|
||||
catalog_items[item_id] = item
|
||||
|
||||
return cls(catalog_items)
|
||||
|
||||
def get_item(self, item_id: str) -> Optional[InventoryItem]:
|
||||
"""Retrieve an inventory item by ID."""
|
||||
return self._items.get(item_id)
|
||||
|
||||
def get_items_by_zone(self, zone_id: str) -> List[InventoryItem]:
|
||||
"""Return all items stored in the designated inventory zone."""
|
||||
return [item for item in self._items.values() if item.zone == zone_id]
|
||||
|
||||
def get_items_needing_replenishment(self) -> List[InventoryItem]:
|
||||
"""Return all items whose on-hand stock is at or below minimum threshold."""
|
||||
return [item for item in self._items.values() if item.needs_replenishment()]
|
||||
|
||||
def list_all_items(self) -> List[InventoryItem]:
|
||||
"""Return all registered catalog items."""
|
||||
return list(self._items.values())
|
||||
|
||||
def total_sku_count(self) -> int:
|
||||
"""Return number of unique item SKUs in catalog."""
|
||||
return len(self._items)
|
||||
@@ -0,0 +1,297 @@
|
||||
"""Robot domain entities: AMR state machine, kinematics, energy models, and fleet registry."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Any, Dict, List, Optional, Set, Tuple
|
||||
|
||||
from warehouse_twin.domain.warehouse import Position3D
|
||||
|
||||
|
||||
class RobotState(str, Enum):
|
||||
"""Discrete operational states for Autonomous Mobile Robots (AMRs)."""
|
||||
IDLE = "IDLE"
|
||||
DISPATCHED = "DISPATCHED"
|
||||
PICKING = "PICKING"
|
||||
LOADED_TRANSIT = "LOADED_TRANSIT"
|
||||
DROPPING = "DROPPING"
|
||||
TRANSIT_TO_CHARGE = "TRANSIT_TO_CHARGE"
|
||||
CHARGING = "CHARGING"
|
||||
MAINTENANCE = "MAINTENANCE"
|
||||
|
||||
|
||||
class InvalidStateTransitionError(Exception):
|
||||
"""Raised when an illegal robot or task state machine transition is attempted."""
|
||||
pass
|
||||
|
||||
|
||||
class IncompatibleRobotTaskError(Exception):
|
||||
"""Raised when a robot is assigned a task it cannot legally or physically execute."""
|
||||
pass
|
||||
|
||||
|
||||
# Strict State Machine Transition Rules
|
||||
# Maps each RobotState to the set of legal target states.
|
||||
LEGAL_ROBOT_TRANSITIONS: Dict[RobotState, Set[RobotState]] = {
|
||||
RobotState.IDLE: {
|
||||
RobotState.DISPATCHED,
|
||||
RobotState.TRANSIT_TO_CHARGE,
|
||||
RobotState.CHARGING,
|
||||
RobotState.MAINTENANCE,
|
||||
},
|
||||
RobotState.DISPATCHED: {
|
||||
RobotState.PICKING,
|
||||
RobotState.IDLE, # Task cancellation or preemption
|
||||
RobotState.TRANSIT_TO_CHARGE, # Low battery abort
|
||||
RobotState.MAINTENANCE,
|
||||
},
|
||||
RobotState.PICKING: {
|
||||
RobotState.LOADED_TRANSIT,
|
||||
RobotState.IDLE, # Aborted pick
|
||||
RobotState.MAINTENANCE,
|
||||
},
|
||||
RobotState.LOADED_TRANSIT: {
|
||||
RobotState.DROPPING,
|
||||
RobotState.MAINTENANCE,
|
||||
},
|
||||
RobotState.DROPPING: {
|
||||
RobotState.IDLE,
|
||||
RobotState.DISPATCHED, # Chained dispatch
|
||||
RobotState.TRANSIT_TO_CHARGE,
|
||||
RobotState.MAINTENANCE,
|
||||
},
|
||||
RobotState.TRANSIT_TO_CHARGE: {
|
||||
RobotState.CHARGING,
|
||||
RobotState.IDLE,
|
||||
RobotState.MAINTENANCE,
|
||||
},
|
||||
RobotState.CHARGING: {
|
||||
RobotState.IDLE,
|
||||
RobotState.DISPATCHED, # Fast-dispatched if needed
|
||||
RobotState.MAINTENANCE,
|
||||
},
|
||||
RobotState.MAINTENANCE: {
|
||||
RobotState.IDLE,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RobotTypeSpec:
|
||||
"""Immutable specification defining physical and kinematic limits of an AMR class."""
|
||||
type_id: str
|
||||
name: str
|
||||
description: str
|
||||
payload_capacity_kg: float
|
||||
max_speed_mps: float
|
||||
acceleration_mps2: float
|
||||
battery_capacity_kwh: float
|
||||
power_consumption_kw: Dict[str, float]
|
||||
allowed_zones: Set[str]
|
||||
dimensions: Tuple[float, float, float] # length, width, height in meters
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, type_id: str, data: Dict[str, Any]) -> RobotTypeSpec:
|
||||
"""Construct a RobotTypeSpec from a dictionary configuration."""
|
||||
dims = data.get("dimensions", {})
|
||||
dim_tuple = (
|
||||
float(dims.get("length", 1.0)),
|
||||
float(dims.get("width", 0.8)),
|
||||
float(dims.get("height", 0.4)),
|
||||
)
|
||||
return cls(
|
||||
type_id=type_id,
|
||||
name=data.get("name", type_id),
|
||||
description=data.get("description", ""),
|
||||
payload_capacity_kg=float(data["payload_capacity_kg"]),
|
||||
max_speed_mps=float(data["max_speed_mps"]),
|
||||
acceleration_mps2=float(data.get("acceleration_mps2", 0.5)),
|
||||
battery_capacity_kwh=float(data["battery_capacity_kwh"]),
|
||||
power_consumption_kw=dict(data.get("power_consumption_kw", {})),
|
||||
allowed_zones=set(data.get("allowed_zones", ["zone_a", "zone_b", "zone_c"])),
|
||||
dimensions=dim_tuple,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Robot:
|
||||
"""Autonomous Mobile Robot (AMR) entity model tracking state, battery, and metrics."""
|
||||
robot_id: str
|
||||
robot_type: str
|
||||
position: Position3D
|
||||
maximum_speed: float
|
||||
payload_capacity: float
|
||||
battery_level: float
|
||||
battery_capacity: float
|
||||
energy_consumption: Dict[str, float]
|
||||
current_state: RobotState = RobotState.IDLE
|
||||
current_task_id: Optional[str] = None
|
||||
current_route: List[str] = field(default_factory=list)
|
||||
accumulated_distance: float = 0.0
|
||||
busy_time: float = 0.0
|
||||
idle_time: float = 0.0
|
||||
charging_time: float = 0.0
|
||||
allowed_zones: Set[str] = field(default_factory=lambda: {"zone_a", "zone_b", "zone_c"})
|
||||
state_enter_time: float = 0.0
|
||||
yaw_degrees: float = 0.0
|
||||
|
||||
@classmethod
|
||||
def from_fleet_dict(cls, fleet_data: Dict[str, Any], type_specs: Dict[str, RobotTypeSpec]) -> Robot:
|
||||
"""Construct a Robot instance from fleet configuration and matching type spec."""
|
||||
robot_type_id = fleet_data["robot_type"]
|
||||
if robot_type_id not in type_specs:
|
||||
raise ValueError(f"Undefined robot_type '{robot_type_id}' for robot '{fleet_data.get('robot_id')}'")
|
||||
spec = type_specs[robot_type_id]
|
||||
|
||||
battery_pct = float(fleet_data.get("initial_battery_percent", 100.0))
|
||||
initial_battery = (battery_pct / 100.0) * spec.battery_capacity_kwh
|
||||
|
||||
return cls(
|
||||
robot_id=fleet_data["robot_id"],
|
||||
robot_type=robot_type_id,
|
||||
position=Position3D.from_iterable(fleet_data.get("initial_position", [0.0, 0.0, 0.0])),
|
||||
maximum_speed=spec.max_speed_mps,
|
||||
payload_capacity=spec.payload_capacity_kg,
|
||||
battery_level=initial_battery,
|
||||
battery_capacity=spec.battery_capacity_kwh,
|
||||
energy_consumption=dict(spec.power_consumption_kw),
|
||||
allowed_zones=set(spec.allowed_zones),
|
||||
)
|
||||
|
||||
@property
|
||||
def battery_percent(self) -> float:
|
||||
"""State of Charge (SoC) expressed as a percentage [0.0 - 100.0]."""
|
||||
if self.battery_capacity <= 0:
|
||||
return 0.0
|
||||
return max(0.0, min(100.0, (self.battery_level / self.battery_capacity) * 100.0))
|
||||
|
||||
def transition_to(self, new_state: RobotState, sim_time: float) -> None:
|
||||
"""Execute a state transition verifying legality against the transition matrix.
|
||||
|
||||
Args:
|
||||
new_state: Destination RobotState.
|
||||
sim_time: Current simulation timestamp in seconds.
|
||||
|
||||
Raises:
|
||||
InvalidStateTransitionError: If the transition is prohibited.
|
||||
"""
|
||||
if new_state == self.current_state:
|
||||
return
|
||||
|
||||
legal_targets = LEGAL_ROBOT_TRANSITIONS.get(self.current_state, set())
|
||||
if new_state not in legal_targets:
|
||||
raise InvalidStateTransitionError(
|
||||
f"Illegal state transition for robot '{self.robot_id}': "
|
||||
f"Cannot transition from {self.current_state.value} to {new_state.value}. "
|
||||
f"Legal targets: {[s.value for s in legal_targets]}"
|
||||
)
|
||||
|
||||
# Accumulate duration in previous state
|
||||
duration = max(0.0, sim_time - self.state_enter_time)
|
||||
if self.current_state == RobotState.IDLE:
|
||||
self.idle_time += duration
|
||||
elif self.current_state == RobotState.CHARGING:
|
||||
self.charging_time += duration
|
||||
else:
|
||||
self.busy_time += duration
|
||||
|
||||
self.current_state = new_state
|
||||
self.state_enter_time = sim_time
|
||||
|
||||
def can_carry_payload(self, payload_kg: float) -> bool:
|
||||
"""Check if requested payload mass is within the AMR load rating."""
|
||||
return payload_kg <= self.payload_capacity + 1e-4
|
||||
|
||||
def can_access_zone(self, zone_id: str) -> bool:
|
||||
"""Check if robot is allowed to enter the specified zone."""
|
||||
if zone_id == "transit":
|
||||
return True
|
||||
return zone_id in self.allowed_zones
|
||||
|
||||
def update_position(self, new_position: Position3D, distance_delta: float, yaw: Optional[float] = None) -> None:
|
||||
"""Update robot spatial coordinates, accumulated travel distance, and heading."""
|
||||
self.position = new_position
|
||||
self.accumulated_distance += max(0.0, distance_delta)
|
||||
if yaw is not None:
|
||||
self.yaw_degrees = yaw % 360.0
|
||||
|
||||
def validate_task_compatibility(self, task: Any) -> Tuple[bool, Optional[str]]:
|
||||
"""Validate if this robot can physically and operationally accept the given task.
|
||||
|
||||
Checks:
|
||||
1. Operational state: Must be IDLE or CHARGING (if interruptible).
|
||||
2. Payload capacity: Task required payload must not exceed robot rating.
|
||||
3. Zone permissions: Target zone must be in robot's allowed_zones.
|
||||
|
||||
Returns:
|
||||
Tuple of (is_compatible: bool, failure_reason: Optional[str]).
|
||||
"""
|
||||
# 1. Operational state check
|
||||
if self.current_state not in (RobotState.IDLE, RobotState.CHARGING):
|
||||
return False, f"Robot '{self.robot_id}' is currently busy in state {self.current_state.value}"
|
||||
|
||||
# 2. Payload capacity check
|
||||
payload = getattr(task, "required_payload", 0.0)
|
||||
if not self.can_carry_payload(payload):
|
||||
return False, (
|
||||
f"Task payload {payload:.1f}kg exceeds robot '{self.robot_id}' "
|
||||
f"capacity ({self.payload_capacity:.1f}kg)"
|
||||
)
|
||||
|
||||
# 3. Zone permissions check
|
||||
target_zone = getattr(task, "target_zone", None)
|
||||
if target_zone and not self.can_access_zone(target_zone):
|
||||
return False, (
|
||||
f"Robot '{self.robot_id}' (type '{self.robot_type}') is restricted from "
|
||||
f"entering target zone '{target_zone}'"
|
||||
)
|
||||
|
||||
return True, None
|
||||
|
||||
def assign_task(self, task: Any) -> None:
|
||||
"""Assign active task after verifying compatibility rules.
|
||||
|
||||
Raises:
|
||||
IncompatibleRobotTaskError: If robot is incompatible with task payload or zone.
|
||||
"""
|
||||
compatible, reason = self.validate_task_compatibility(task)
|
||||
if not compatible:
|
||||
raise IncompatibleRobotTaskError(reason or "Robot incompatible with task")
|
||||
|
||||
task_id = getattr(task, "task_id", str(task))
|
||||
self.current_task_id = task_id
|
||||
if hasattr(task, "assigned_robot_id"):
|
||||
task.assigned_robot_id = self.robot_id
|
||||
|
||||
def release_task(self) -> None:
|
||||
"""Clear active task binding."""
|
||||
self.current_task_id = None
|
||||
self.current_route.clear()
|
||||
|
||||
def consume_energy(self, duration_seconds: float, mode: str = "moving_empty") -> float:
|
||||
"""Deduct energy consumed over duration according to active power mode.
|
||||
|
||||
Args:
|
||||
duration_seconds: Time interval in seconds.
|
||||
mode: Power consumption mode ('idle', 'moving_empty', 'moving_loaded', 'handling').
|
||||
|
||||
Returns:
|
||||
Energy consumed in kWh.
|
||||
"""
|
||||
power_kw = self.energy_consumption.get(mode, 0.1)
|
||||
energy_kwh = (power_kw * duration_seconds) / 3600.0
|
||||
self.battery_level = max(0.0, self.battery_level - energy_kwh)
|
||||
return energy_kwh
|
||||
|
||||
def charge_energy(self, duration_seconds: float, charging_rate_kw: float) -> float:
|
||||
"""Add energy from charger over duration in seconds.
|
||||
|
||||
Returns:
|
||||
Energy added in kWh.
|
||||
"""
|
||||
energy_kwh = (charging_rate_kw * duration_seconds) / 3600.0
|
||||
new_level = min(self.battery_capacity, self.battery_level + energy_kwh)
|
||||
added = new_level - self.battery_level
|
||||
self.battery_level = new_level
|
||||
return added
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Task domain entities: lifecycle states, task types, priorities, and deadlines."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from warehouse_twin.domain.robot import InvalidStateTransitionError
|
||||
|
||||
|
||||
class TaskType(str, Enum):
|
||||
"""Classification of tasks executed by warehouse AMR fleet."""
|
||||
ORDER_PICK = "ORDER_PICK"
|
||||
REPLENISHMENT = "REPLENISHMENT"
|
||||
PRODUCTION_LINE_FEED = "PRODUCTION_LINE_FEED"
|
||||
CHARGING = "CHARGING"
|
||||
|
||||
|
||||
class TaskStatus(str, Enum):
|
||||
"""Discrete operational lifecycle states for simulation tasks."""
|
||||
PENDING = "PENDING"
|
||||
ASSIGNED = "ASSIGNED"
|
||||
IN_PROGRESS = "IN_PROGRESS"
|
||||
COMPLETED = "COMPLETED"
|
||||
CANCELLED = "CANCELLED"
|
||||
FAILED = "FAILED"
|
||||
|
||||
|
||||
# Strict Task Lifecycle Transition Rules
|
||||
LEGAL_TASK_TRANSITIONS: Dict[TaskStatus, set[TaskStatus]] = {
|
||||
TaskStatus.PENDING: {
|
||||
TaskStatus.ASSIGNED,
|
||||
TaskStatus.CANCELLED,
|
||||
},
|
||||
TaskStatus.ASSIGNED: {
|
||||
TaskStatus.IN_PROGRESS,
|
||||
TaskStatus.PENDING, # Reassignment / preemption back to queue
|
||||
TaskStatus.CANCELLED,
|
||||
},
|
||||
TaskStatus.IN_PROGRESS: {
|
||||
TaskStatus.COMPLETED,
|
||||
TaskStatus.CANCELLED,
|
||||
TaskStatus.FAILED,
|
||||
},
|
||||
TaskStatus.COMPLETED: set(), # Terminal state
|
||||
TaskStatus.CANCELLED: set(), # Terminal state
|
||||
TaskStatus.FAILED: set(), # Terminal state
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Task:
|
||||
"""Simulation work order model tracking dispatch, payload requirements, and timing."""
|
||||
task_id: str
|
||||
task_type: TaskType
|
||||
source: str
|
||||
destination: str
|
||||
priority: int = 2 # 1 = Urgent/Production-Critical, 2 = Standard, 3 = Low
|
||||
release_time: float = 0.0 # Simulation clock seconds when task arrived
|
||||
deadline: Optional[float] = None # Strict completion deadline for line-feed tasks
|
||||
required_payload: float = 0.0 # Payload mass in kilograms
|
||||
item_id: Optional[str] = None # Inventory SKU reference
|
||||
quantity: int = 1 # Unit count requested
|
||||
status: TaskStatus = TaskStatus.PENDING
|
||||
assigned_robot_id: Optional[str] = None
|
||||
start_time: Optional[float] = None
|
||||
completion_time: Optional[float] = None
|
||||
target_zone: Optional[str] = None # Operational zone hint ('zone_a', 'zone_b', 'zone_c')
|
||||
|
||||
def transition_to(self, new_status: TaskStatus, sim_time: float) -> None:
|
||||
"""Advance task state machine, validating legal transitions and updating timestamps.
|
||||
|
||||
Args:
|
||||
new_status: Desired destination TaskStatus.
|
||||
sim_time: Current simulation timestamp in seconds.
|
||||
|
||||
Raises:
|
||||
InvalidStateTransitionError: If transition is prohibited.
|
||||
"""
|
||||
if new_status == self.status:
|
||||
return
|
||||
|
||||
legal_targets = LEGAL_TASK_TRANSITIONS.get(self.status, set())
|
||||
if new_status not in legal_targets:
|
||||
raise InvalidStateTransitionError(
|
||||
f"Illegal task transition for task '{self.task_id}': "
|
||||
f"Cannot transition from {self.status.value} to {new_status.value}. "
|
||||
f"Legal targets: {[s.value for s in legal_targets]}"
|
||||
)
|
||||
|
||||
if new_status == TaskStatus.IN_PROGRESS and self.start_time is None:
|
||||
self.start_time = sim_time
|
||||
elif new_status in (TaskStatus.COMPLETED, TaskStatus.CANCELLED, TaskStatus.FAILED):
|
||||
self.completion_time = sim_time
|
||||
|
||||
self.status = new_status
|
||||
|
||||
def is_overdue(self, sim_time: float) -> bool:
|
||||
"""Check if task has passed its deadline without completing."""
|
||||
if self.deadline is None:
|
||||
return False
|
||||
effective_time = self.completion_time if self.completion_time is not None else sim_time
|
||||
return effective_time > self.deadline
|
||||
|
||||
def turnaround_time(self) -> Optional[float]:
|
||||
"""Total duration from release to completion in seconds."""
|
||||
if self.completion_time is None:
|
||||
return None
|
||||
return max(0.0, self.completion_time - self.release_time)
|
||||
|
||||
def waiting_time(self, current_sim_time: Optional[float] = None) -> float:
|
||||
"""Duration spent waiting in queue before execution started."""
|
||||
if self.start_time is not None:
|
||||
return max(0.0, self.start_time - self.release_time)
|
||||
ref_time = current_sim_time if current_sim_time is not None else self.release_time
|
||||
return max(0.0, ref_time - self.release_time)
|
||||
|
||||
def execution_time(self) -> Optional[float]:
|
||||
"""Active handling and transit duration from start to completion."""
|
||||
if self.start_time is None or self.completion_time is None:
|
||||
return None
|
||||
return max(0.0, self.completion_time - self.start_time)
|
||||
@@ -1,7 +1,8 @@
|
||||
"""OpenUSD scene generator for Warehouse Robot Fleet Digital Twin.
|
||||
|
||||
Exports an ASCII OpenUSD (.usda) scene compliant with NVIDIA Omniverse Kit 110.4
|
||||
and standard USD specifications (Z-up, 1.0 meter units).
|
||||
and standard USD specifications (Z-up, 1.0 meter units). Supports visual representations
|
||||
of facility geometry, zones, operational stations, charging pads, and the AMR robot fleet.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -9,18 +10,41 @@ from __future__ import annotations
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from warehouse_twin.domain.robot import Robot, RobotTypeSpec
|
||||
from warehouse_twin.domain.warehouse import WarehouseModel
|
||||
|
||||
|
||||
class WarehouseUSDGenerator:
|
||||
"""Generates OpenUSD (.usda) 3D scenes from a WarehouseModel."""
|
||||
"""Generates OpenUSD (.usda) 3D scenes from WarehouseModel and Robot fleet entities."""
|
||||
|
||||
def __init__(self, model: WarehouseModel) -> None:
|
||||
"""Initialize generator with physical warehouse layout model."""
|
||||
def __init__(
|
||||
self,
|
||||
model: WarehouseModel,
|
||||
robots: Optional[List[Robot]] = None,
|
||||
) -> None:
|
||||
"""Initialize generator with physical warehouse layout model and optional robot fleet."""
|
||||
self.model = model
|
||||
self.robots = robots or []
|
||||
|
||||
@classmethod
|
||||
def from_config_bundle(cls, bundle: Any) -> WarehouseUSDGenerator:
|
||||
"""Construct generator loading both warehouse layout and fleet from ConfigBundle."""
|
||||
model = WarehouseModel.from_config_dict(bundle.warehouse)
|
||||
|
||||
# Parse robot type specs
|
||||
type_specs: Dict[str, RobotTypeSpec] = {}
|
||||
for t_id, t_data in bundle.robots.get("robot_types", {}).items():
|
||||
type_specs[t_id] = RobotTypeSpec.from_dict(t_id, t_data)
|
||||
|
||||
# Build robot fleet entities
|
||||
robots: List[Robot] = []
|
||||
for r_data in bundle.robots.get("fleet", []):
|
||||
robots.append(Robot.from_fleet_dict(r_data, type_specs))
|
||||
|
||||
return cls(model, robots)
|
||||
|
||||
def generate_usda_content(self) -> str:
|
||||
"""Construct valid ASCII OpenUSD 3D stage content representing the warehouse."""
|
||||
"""Construct valid ASCII OpenUSD 3D stage content representing the warehouse and AMRs."""
|
||||
dims = self.model.dimensions
|
||||
w = dims.width
|
||||
d = dims.depth
|
||||
@@ -150,7 +174,7 @@ class WarehouseUSDGenerator:
|
||||
spec = rack_specs.get(loc.zone, {"color": "(0.5, 0.5, 0.5)", "scale": (1.0, 0.5, 1.5)})
|
||||
col = spec["color"]
|
||||
sx, sy, sz = spec["scale"]
|
||||
rz = sz # base is at z=0, center is at z=sz
|
||||
rz = sz
|
||||
|
||||
lines.extend([
|
||||
f' def Xform "{loc_id}"',
|
||||
@@ -179,18 +203,17 @@ class WarehouseUSDGenerator:
|
||||
|
||||
for st_id, st in self.model.stations.items():
|
||||
pos = st.position
|
||||
# Distinguish station visuals
|
||||
if "inbound" in st.station_type.value:
|
||||
st_col = "(0.85, 0.25, 0.2)" # Inbound red/orange
|
||||
st_col = "(0.85, 0.25, 0.2)"
|
||||
st_dim = (1.5, 2.0, 0.15)
|
||||
elif "outbound" in st.station_type.value:
|
||||
st_col = "(0.9, 0.4, 0.1)" # Outbound amber
|
||||
st_col = "(0.9, 0.4, 0.1)"
|
||||
st_dim = (1.5, 2.0, 0.15)
|
||||
elif "picking" in st.station_type.value:
|
||||
st_col = "(0.2, 0.75, 0.85)" # Picking teal/cyan
|
||||
st_col = "(0.2, 0.75, 0.85)"
|
||||
st_dim = (2.0, 1.2, 0.4)
|
||||
else:
|
||||
st_col = "(0.25, 0.8, 0.35)" # Production feed green
|
||||
st_col = "(0.25, 0.8, 0.35)"
|
||||
st_dim = (1.8, 1.8, 0.25)
|
||||
|
||||
lines.extend([
|
||||
@@ -228,7 +251,7 @@ class WarehouseUSDGenerator:
|
||||
"",
|
||||
' def Cube "ChargePad"',
|
||||
" {",
|
||||
" color3f[] primvars:displayColor = [(0.15, 0.85, 0.95)]", # Electric cyan pad
|
||||
" color3f[] primvars:displayColor = [(0.15, 0.85, 0.95)]",
|
||||
" }",
|
||||
"",
|
||||
' def Cube "StationPedestal"',
|
||||
@@ -243,6 +266,68 @@ class WarehouseUSDGenerator:
|
||||
|
||||
lines.extend([
|
||||
" }",
|
||||
])
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Autonomous Mobile Robot (AMR) Fleet (Phase 2 Addition)
|
||||
# -------------------------------------------------------------------------
|
||||
if self.robots:
|
||||
lines.extend([
|
||||
"",
|
||||
" # -------------------------------------------------------------------------",
|
||||
" # Autonomous Mobile Robot (AMR) Fleet",
|
||||
" # -------------------------------------------------------------------------",
|
||||
' def Scope "Robots"',
|
||||
" {",
|
||||
])
|
||||
|
||||
for robot in self.robots:
|
||||
is_heavy = "heavy" in robot.robot_type
|
||||
pos = robot.position
|
||||
|
||||
if is_heavy:
|
||||
# Heavy AMR: Industrial Amber rugged pallet chassis (1.4m x 1.0m x 0.45m)
|
||||
chassis_col = "(0.92, 0.65, 0.08)"
|
||||
indicator_col = "(0.15, 0.85, 0.3)" # Emerald ready glow
|
||||
scale_tuple = (0.70, 0.50, 0.225)
|
||||
elev_z = 0.225
|
||||
else:
|
||||
# Light AMR: High-tech pearl white agile chassis (0.8m x 0.6m x 0.35m)
|
||||
chassis_col = "(0.88, 0.90, 0.95)"
|
||||
indicator_col = "(0.15, 0.75, 0.95)" # Electric cyan ready glow
|
||||
scale_tuple = (0.40, 0.30, 0.175)
|
||||
elev_z = 0.175
|
||||
|
||||
lines.extend([
|
||||
f' def Xform "{robot.robot_id}"',
|
||||
" {",
|
||||
f" double3 xformOp:translate = ({pos.x:.2f}, {pos.y:.2f}, {elev_z:.3f})",
|
||||
f" double3 xformOp:rotateZ = {robot.yaw_degrees:.1f}",
|
||||
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZ"]',
|
||||
"",
|
||||
' def Cube "Chassis"',
|
||||
" {",
|
||||
f" double3 xformOp:scale = ({scale_tuple[0]}, {scale_tuple[1]}, {scale_tuple[2]})",
|
||||
' uniform token[] xformOpOrder = ["xformOp:scale"]',
|
||||
f" color3f[] primvars:displayColor = [{chassis_col}]",
|
||||
" float[] primvars:displayRoughness = [0.25]",
|
||||
" }",
|
||||
"",
|
||||
' def Cube "StatusDome"',
|
||||
" {",
|
||||
f" double3 xformOp:translate = (0.0, 0.0, {scale_tuple[2] + 0.08:.3f})",
|
||||
f" double3 xformOp:scale = ({scale_tuple[0] * 0.4:.3f}, {scale_tuple[1] * 0.4:.3f}, 0.05)",
|
||||
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
|
||||
f" color3f[] primvars:displayColor = [{indicator_col}]",
|
||||
" }",
|
||||
" }",
|
||||
])
|
||||
|
||||
lines.extend([
|
||||
" }",
|
||||
])
|
||||
|
||||
lines.extend([
|
||||
"}",
|
||||
"",
|
||||
])
|
||||
|
||||
Reference in New Issue
Block a user