"""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 min_battery_percent: float = 100.0 total_energy_consumed_kwh: float = 0.0 total_energy_charged_kwh: float = 0.0 loaded_distance: float = 0.0 empty_distance: float = 0.0 handling_time: float = 0.0 yield_wait_time: 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 robot = 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), ) robot.min_battery_percent = robot.battery_percent return robot @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)) @property def is_available(self) -> bool: """Check if robot is idle and ready to be assigned a new task.""" return self.current_state == RobotState.IDLE and self.current_task_id is None 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, is_loaded: bool = False, ) -> None: """Update robot spatial coordinates, travel distance (loaded/empty), and heading.""" self.position = new_position dist = max(0.0, distance_delta) self.accumulated_distance += dist if is_loaded: self.loaded_distance += dist else: self.empty_distance += dist 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, sim_time: Optional[float] = None) -> None: """Assign active task after verifying compatibility rules. Raises: IncompatibleRobotTaskError: If robot is incompatible with task payload or zone. """ # If task is already a Task object, validate compatibility if hasattr(task, "required_payload") or hasattr(task, "target_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 complete_task(self, sim_time: Optional[float] = None) -> None: """Complete active task and clear binding.""" self.release_task() def consume_energy( self, duration_seconds: float, mode: str = "moving_empty", payload_kg: float = 0.0, ) -> float: """Deduct energy consumed over duration according to active power mode. For 'moving_loaded', scales power consumption proportionally with actual payload. Args: duration_seconds: Time interval in seconds. mode: Power consumption mode ('idle', 'moving_empty', 'moving_loaded', 'handling'). payload_kg: Active payload weight in kg (used if mode is 'moving_loaded'). Returns: Energy consumed in kWh. """ if mode == "moving_loaded": p_empty = self.energy_consumption.get("moving_empty", 0.35) p_loaded_max = self.energy_consumption.get("moving_loaded", 0.65) if self.payload_capacity > 0.0 and payload_kg > 0.0: fraction = min(1.0, max(0.0, payload_kg / self.payload_capacity)) power_kw = p_empty + (p_loaded_max - p_empty) * fraction else: power_kw = p_loaded_max else: 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) self.total_energy_consumed_kwh += energy_kwh self.min_battery_percent = min(self.min_battery_percent, self.battery_percent) 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 self.total_energy_charged_kwh += added return added def is_low_battery(self, threshold_pct: float = 25.0) -> bool: """Check if State of Charge has reached or fallen below mandatory charging threshold.""" return self.battery_percent <= threshold_pct + 1e-4 def is_critical_battery(self, threshold_pct: float = 15.0) -> bool: """Check if State of Charge has dropped to critical emergency shutdown threshold.""" return self.battery_percent <= threshold_pct + 1e-4 def needs_opportunistic_charge(self, threshold_pct: float = 60.0) -> bool: """Check if robot is eligible for opportunistic top-up charging when idle.""" return self.battery_percent <= threshold_pct + 1e-4