feat(phase-5): implement battery model, charging queues, production deadlines, and safe reassignment

This commit is contained in:
2026-10-21 11:36:48 +05:30
parent 56806079a9
commit 1e50508f53
20 changed files with 2215 additions and 99 deletions
+18 -3
View File
@@ -199,7 +199,7 @@ def export_usd(config_dir: Optional[str] = None, output_path: Optional[str] = No
bundle = loader.load_all()
generator = WarehouseUSDGenerator.from_config_bundle(bundle, include_routing_network=True)
default_out = Path("omniverse/scenes/warehouse_phase4.usda")
default_out = Path("omniverse/scenes/warehouse_phase5.usda")
out_file = Path(output_path).resolve() if output_path else default_out.resolve()
saved_path = generator.export_usda(out_file)
@@ -314,6 +314,19 @@ def run_simulation(
print(f"Fleet Utilization: {metrics.fleet_utilization_percent:.1f}%")
print(f"Replenishment Triggers: {metrics.replenishment_triggers}")
print("-" * 65)
print("Charging & Operational Constraints (Phase 5):")
print(f" Missed Deadlines: {metrics.missed_deadlines}")
print(f" Stock-Out Events: {metrics.stockout_events}")
print(f" Reassigned Tasks: {metrics.reassigned_tasks}")
print(f" Mandatory Charges: {metrics.mandatory_charges}")
print(f" Opportunity Charges: {metrics.opportunity_charges}")
print(f" Total Energy Consumed: {metrics.total_energy_consumed_kwh:.3f} kWh")
print(f" Total Energy Charged: {metrics.total_energy_charged_kwh:.3f} kWh")
print(f" Fleet Battery SoC: Min {metrics.min_fleet_battery_percent:.1f}%, Avg {metrics.avg_fleet_battery_percent:.1f}%")
ch_m = metrics.charging_metrics
if ch_m:
print(f" Charging Sessions: {ch_m.get('total_charging_sessions', 0)} sessions (Avg queue wait: {ch_m.get('average_queue_wait_time_seconds', 0.0):.1f} s)")
print("-" * 65)
print("Traffic Management & Collision Avoidance (Phase 4):")
print(f" Conflicts Detected: {metrics.conflicts_detected}")
print(f" Yield Waits Executed: {metrics.yield_waits_count}")
@@ -322,9 +335,11 @@ def run_simulation(
print(f" Deadlocks Prevented: {metrics.deadlocks_prevented}")
print(f" Trajectory File: {traj_saved}")
print("-" * 65)
print("Per-Robot Utilization:")
print("Per-Robot Utilization & Battery Metrics:")
for r_id, r_stats in metrics.robot_metrics.items():
print(f" {r_id:14s}: distance={r_stats['distance_meters']:.1f}m, busy={r_stats['busy_seconds']:.1f}s, util={r_stats['utilization_percent']:.1f}%, battery={r_stats['battery_percent']:.1f}%")
min_b = r_stats.get("min_battery_percent", r_stats["battery_percent"])
e_cons = r_stats.get("energy_consumed_kwh", 0.0)
print(f" {r_id:14s}: dist={r_stats['distance_meters']:.1f}m, busy={r_stats['busy_seconds']:.1f}s, util={r_stats['utilization_percent']:.1f}%, SoC={r_stats['battery_percent']:.1f}% (min {min_b:.1f}%), consumed={e_cons:.3f}kWh")
print("=" * 65)
return 0
except Exception as err:
+6
View File
@@ -31,6 +31,12 @@ class SimulationEventType(str, Enum):
ROBOT_CHARGING_START = "ROBOT_CHARGING_STARTED"
ROBOT_CHARGING_COMPLETED = "ROBOT_CHARGING_COMPLETED"
ROBOT_CHARGING_COMPLETE = "ROBOT_CHARGING_COMPLETED"
CHARGING_QUEUED = "CHARGING_QUEUED"
BATTERY_LOW = "BATTERY_LOW"
BATTERY_CRITICAL = "BATTERY_CRITICAL"
TASK_ENERGY_INFEASIBLE = "TASK_ENERGY_INFEASIBLE"
TASK_REASSIGNED = "TASK_REASSIGNED"
DEADLINE_MISSED = "DEADLINE_MISSED"
INVENTORY_RESERVED = "INVENTORY_RESERVED"
INVENTORY_CONSUMED = "INVENTORY_CONSUMED"
+42 -3
View File
@@ -135,6 +135,9 @@ class Robot:
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
@classmethod
def from_fleet_dict(cls, fleet_data: Dict[str, Any], type_specs: Dict[str, RobotTypeSpec]) -> Robot:
@@ -147,7 +150,7 @@ class Robot:
battery_pct = float(fleet_data.get("initial_battery_percent", 100.0))
initial_battery = (battery_pct / 100.0) * spec.battery_capacity_kwh
return cls(
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])),
@@ -158,6 +161,8 @@ class Robot:
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:
@@ -280,19 +285,39 @@ class Robot:
"""Complete active task and clear binding."""
self.release_task()
def consume_energy(self, duration_seconds: float, mode: str = "moving_empty") -> float:
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.
"""
power_kw = self.energy_consumption.get(mode, 0.1)
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:
@@ -305,4 +330,18 @@ class Robot:
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
+14
View File
@@ -159,6 +159,19 @@ class Task:
effective_time = self.completion_time if self.completion_time is not None else sim_time
return effective_time > self.deadline
def reassign_back_to_pending(self, sim_time: float) -> None:
"""Safely reset task assignment back to PENDING status for redispatch."""
self.assigned_robot_id = None
self.start_time = None
self.transition_to(TaskStatus.PENDING, sim_time)
def lateness(self, sim_time: float) -> float:
"""Return seconds past deadline, or 0.0 if completed on-time or not yet overdue."""
if self.deadline is None:
return 0.0
effective_time = self.completion_time if self.completion_time is not None else sim_time
return max(0.0, effective_time - self.deadline)
def turnaround_time(self) -> Optional[float]:
"""Total duration from release to completion in seconds."""
if self.completion_time is None:
@@ -177,3 +190,4 @@ class Task:
if self.start_time is None or self.completion_time is None:
return None
return max(0.0, self.completion_time - self.start_time)
+25
View File
@@ -0,0 +1,25 @@
"""Fleet management subsystem: battery models, charging stations, queues, and task reassignment."""
from warehouse_twin.fleet.battery_model import (
BatteryModel,
InfeasibleEnergyMissionError,
MissionEnergyEstimate,
)
from warehouse_twin.fleet.charging_manager import (
ChargingBay,
ChargingManager,
)
from warehouse_twin.fleet.task_reassigner import (
TaskReassigner,
TaskReassignmentResult,
)
__all__ = [
"BatteryModel",
"InfeasibleEnergyMissionError",
"MissionEnergyEstimate",
"ChargingBay",
"ChargingManager",
"TaskReassigner",
"TaskReassignmentResult",
]
+222
View File
@@ -0,0 +1,222 @@
"""Battery dynamics, load-dependent power consumption, and mission energy feasibility validation."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, Tuple
from warehouse_twin.domain.robot import Robot
class InfeasibleEnergyMissionError(Exception):
"""Raised when a robot attempts to accept a mission that violates energy headroom limits."""
pass
@dataclass(frozen=True)
class MissionEnergyEstimate:
"""Detailed breakdown of energy requirements for an AMR work mission."""
empty_transit_kwh: float
pickup_handling_kwh: float
loaded_transit_kwh: float
dropoff_handling_kwh: float
charger_transit_kwh: float
total_required_kwh: float
projected_post_mission_soc_pct: float
is_feasible: bool
reserve_headroom_pct: float
class BatteryModel:
"""Physics-informed battery consumption, charging dynamics, and energy feasibility evaluator."""
def __init__(
self,
reserve_threshold_percent: float = 20.0,
critical_threshold_percent: float = 15.0,
opportunistic_threshold_percent: float = 60.0,
recharge_target_percent: float = 85.0,
charging_efficiency: float = 0.95,
) -> None:
"""Initialize battery model parameters.
Args:
reserve_threshold_percent: Minimum safety buffer percentage after mission completion.
critical_threshold_percent: Emergency threshold requiring immediate stop or recharge.
opportunistic_threshold_percent: Upper SoC threshold for top-up charging when idle.
recharge_target_percent: Target State of Charge for standard charging sessions.
charging_efficiency: Electrical conversion efficiency factor (0.0 - 1.0).
"""
self.reserve_threshold_percent = reserve_threshold_percent
self.critical_threshold_percent = critical_threshold_percent
self.opportunistic_threshold_percent = opportunistic_threshold_percent
self.recharge_target_percent = recharge_target_percent
self.charging_efficiency = max(0.1, min(1.0, charging_efficiency))
def calculate_power_kw(
self,
robot: Robot,
mode: str = "moving_empty",
payload_kg: float = 0.0,
) -> float:
"""Calculate electrical power draw in kilowatts for the active operational mode.
For 'moving_loaded', interpolates between empty and max-loaded power draw based on actual load.
Args:
robot: AMR entity with energy consumption specs.
mode: Operational state ('idle', 'moving_empty', 'moving_loaded', 'handling').
payload_kg: Carried payload weight in kilograms.
Returns:
Power consumption in kW.
"""
if mode == "moving_loaded":
p_empty = robot.energy_consumption.get("moving_empty", 0.35)
p_loaded_max = robot.energy_consumption.get("moving_loaded", 0.65)
if robot.payload_capacity > 0.0 and payload_kg > 0.0:
fraction = min(1.0, max(0.0, payload_kg / robot.payload_capacity))
return p_empty + (p_loaded_max - p_empty) * fraction
return p_loaded_max
return robot.energy_consumption.get(mode, 0.1)
def estimate_transit_energy_kwh(
self,
robot: Robot,
distance_meters: float,
is_loaded: bool = False,
payload_kg: float = 0.0,
average_speed_mps: Optional[float] = None,
) -> float:
"""Estimate energy required to traverse a spatial distance.
Args:
robot: AMR entity.
distance_meters: Travel distance in meters.
is_loaded: Whether the robot is carrying a payload.
payload_kg: Weight of payload in kg.
average_speed_mps: Mean traversal speed (defaults to robot rated speed).
Returns:
Energy required in kilowatt-hours (kWh).
"""
if distance_meters <= 0.0:
return 0.0
if average_speed_mps is None or average_speed_mps <= 0.0:
speed = robot.maximum_speed * (0.85 if is_loaded else 1.0)
else:
speed = min(robot.maximum_speed, average_speed_mps)
duration_seconds = distance_meters / max(speed, 0.1)
mode = "moving_loaded" if is_loaded else "moving_empty"
power_kw = self.calculate_power_kw(robot, mode=mode, payload_kg=payload_kg)
return (power_kw * duration_seconds) / 3600.0
def estimate_handling_energy_kwh(
self,
robot: Robot,
duration_seconds: float,
) -> float:
"""Estimate energy consumed during stationary pickup or dropoff handling."""
if duration_seconds <= 0.0:
return 0.0
power_kw = self.calculate_power_kw(robot, mode="handling")
return (power_kw * duration_seconds) / 3600.0
def estimate_mission_energy(
self,
robot: Robot,
dist_to_pickup: float,
dist_to_dropoff: float,
dist_drop_to_charger: float,
payload_kg: float = 0.0,
pickup_duration_seconds: float = 15.0,
dropoff_duration_seconds: float = 15.0,
) -> MissionEnergyEstimate:
"""Compute comprehensive energy estimate for a complete mission cycle.
Cycle includes:
1. Empty transit to source pick station.
2. Stationary pickup handling.
3. Loaded transit from source to destination dropoff.
4. Stationary dropoff handling.
5. Transit from destination to the nearest safety charging bay.
Returns:
MissionEnergyEstimate with breakdown and feasibility verdict.
"""
e_empty = self.estimate_transit_energy_kwh(robot, dist_to_pickup, is_loaded=False)
e_pick = self.estimate_handling_energy_kwh(robot, pickup_duration_seconds)
e_loaded = self.estimate_transit_energy_kwh(
robot, dist_to_dropoff, is_loaded=True, payload_kg=payload_kg
)
e_drop = self.estimate_handling_energy_kwh(robot, dropoff_duration_seconds)
e_charger = self.estimate_transit_energy_kwh(robot, dist_drop_to_charger, is_loaded=False)
total_req = e_empty + e_pick + e_loaded + e_drop + e_charger
remaining_kwh = max(0.0, robot.battery_level - total_req)
proj_soc_pct = (remaining_kwh / robot.battery_capacity) * 100.0 if robot.battery_capacity > 0 else 0.0
reserve_headroom_pct = proj_soc_pct - self.reserve_threshold_percent
is_feasible = (
proj_soc_pct >= self.reserve_threshold_percent
and (robot.battery_level - total_req) >= 0.0
)
return MissionEnergyEstimate(
empty_transit_kwh=e_empty,
pickup_handling_kwh=e_pick,
loaded_transit_kwh=e_loaded,
dropoff_handling_kwh=e_drop,
charger_transit_kwh=e_charger,
total_required_kwh=total_req,
projected_post_mission_soc_pct=proj_soc_pct,
is_feasible=is_feasible,
reserve_headroom_pct=reserve_headroom_pct,
)
def validate_mission_feasibility(
self,
robot: Robot,
dist_to_pickup: float,
dist_to_dropoff: float,
dist_drop_to_charger: float,
payload_kg: float = 0.0,
pickup_duration_seconds: float = 15.0,
dropoff_duration_seconds: float = 15.0,
) -> MissionEnergyEstimate:
"""Validate energy feasibility, raising InfeasibleEnergyMissionError if unviable."""
estimate = self.estimate_mission_energy(
robot=robot,
dist_to_pickup=dist_to_pickup,
dist_to_dropoff=dist_to_dropoff,
dist_drop_to_charger=dist_drop_to_charger,
payload_kg=payload_kg,
pickup_duration_seconds=pickup_duration_seconds,
dropoff_duration_seconds=dropoff_duration_seconds,
)
if not estimate.is_feasible:
raise InfeasibleEnergyMissionError(
f"Robot '{robot.robot_id}' (SoC: {robot.battery_percent:.1f}%) cannot accept mission: "
f"Requires {estimate.total_required_kwh:.3f}kWh, projected post-mission SoC "
f"{estimate.projected_post_mission_soc_pct:.1f}% violates {self.reserve_threshold_percent:.1f}% "
f"safety reserve threshold."
)
return estimate
def compute_charging_duration_seconds(
self,
current_kwh: float,
target_kwh: float,
charger_power_kw: float,
) -> float:
"""Calculate required charging time in seconds to reach target battery energy level.
Incorporates electrical conversion efficiency.
"""
if target_kwh <= current_kwh or charger_power_kw <= 0.0:
return 0.0
needed_kwh = target_kwh - current_kwh
effective_power_kw = charger_power_kw * self.charging_efficiency
return (needed_kwh / effective_power_kw) * 3600.0
@@ -0,0 +1,164 @@
"""Charging station resources, capacity-constrained queues, and automated bay allocation."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set, Tuple
import simpy
from warehouse_twin.domain.robot import Robot, RobotState
from warehouse_twin.domain.warehouse import ChargingStation, Position3D
from warehouse_twin.routing.path_planner import PathPlanner
@dataclass
class ChargingBay:
"""Capacity-constrained charging bay backed by a SimPy Resource."""
station_id: str
position: Position3D
charging_rate_kw: float
capacity: int
allowed_robot_types: Set[str]
resource: simpy.Resource
total_sessions: int = 0
total_charging_time_seconds: float = 0.0
total_queue_wait_time_seconds: float = 0.0
total_energy_delivered_kwh: float = 0.0
current_occupant_robot_id: Optional[str] = None
@property
def is_occupied(self) -> bool:
"""Check if bay currently has a robot plugged in."""
return self.resource.count >= self.capacity
@property
def queue_length(self) -> int:
"""Number of robots waiting in line for this bay."""
return len(self.resource.queue)
def utilization(self, simulation_duration_seconds: float) -> float:
"""Fraction of total simulation time this bay spent actively delivering charge."""
if simulation_duration_seconds <= 0.0:
return 0.0
return min(1.0, self.total_charging_time_seconds / simulation_duration_seconds)
class ChargingManager:
"""Manages warehouse charging bays, queue arbitration, and energy transfer."""
def __init__(
self,
env: simpy.Environment,
stations: List[ChargingStation],
policy_config: Optional[Dict[str, Any]] = None,
) -> None:
"""Initialize charging bays with SimPy resources.
Args:
env: SimPy simulation environment.
stations: List of warehouse charging station configurations.
policy_config: Optional charging strategy settings from dispatch_policies.json.
"""
self.env = env
self.policy_config = policy_config or {}
strat = self.policy_config.get("charging_strategy", {})
self.opportunistic_threshold = float(strat.get("opportunistic_charging_threshold_percent", 60.0))
self.mandatory_threshold = float(strat.get("mandatory_charging_threshold_percent", 25.0))
self.min_charge_duration = float(strat.get("min_charge_duration_seconds", 180.0))
self.recharge_target_percent = 85.0
self.bays: Dict[str, ChargingBay] = {}
for st in stations:
# High-power (>= 40kW) chargers are designed for heavy AMRs; 25kW for light AMRs
if st.charging_rate_kw >= 40.0:
allowed = {"heavy_amr", "light_amr"}
else:
allowed = {"light_amr"}
self.bays[st.station_id] = ChargingBay(
station_id=st.station_id,
position=st.position,
charging_rate_kw=st.charging_rate_kw,
capacity=max(1, st.capacity),
allowed_robot_types=allowed,
resource=simpy.Resource(env, capacity=max(1, st.capacity)),
)
def select_best_charging_bay(
self,
robot: Robot,
path_planner: Optional[PathPlanner] = None,
origin_position: Optional[Position3D] = None,
) -> ChargingBay:
"""Select the optimal charging bay for a robot based on rating, queue, and distance.
Prefers compatible bays with rate matching, idle status, and shortest path.
Args:
robot: Robot needing charge.
path_planner: Optional routing engine for precise distance calculation.
origin_position: Starting location (defaults to robot.position).
Returns:
Selected ChargingBay.
"""
pos = origin_position or robot.position
# Candidate bays: prefer bays designated for this robot class
compatible_bays = [
bay for bay in self.bays.values()
if robot.robot_type in bay.allowed_robot_types
]
if not compatible_bays:
compatible_bays = list(self.bays.values())
best_bay = None
best_score = float("inf")
for bay in compatible_bays:
# Compute distance
dist = pos.distance_to(bay.position)
# Queue penalty: occupied bay adds penalty; queued robots add heavy penalty
queue_penalty = (bay.queue_length * 200.0) + (80.0 if bay.is_occupied else 0.0)
# Rating match bonus: heavy AMR gets preference for 50kW bay
rate_penalty = 0.0
if "heavy" in robot.robot_type and bay.charging_rate_kw < 40.0:
rate_penalty = 150.0 # Strongly discourage slow charging for heavy battery
score = dist + queue_penalty + rate_penalty
if score < best_score:
best_score = score
best_bay = bay
return best_bay or list(self.bays.values())[0]
def get_metrics(self, simulation_duration_seconds: float) -> Dict[str, Any]:
"""Compile aggregated charging metrics and individual bay performance."""
total_sessions = sum(b.total_sessions for b in self.bays.values())
total_energy = sum(b.total_energy_delivered_kwh for b in self.bays.values())
total_charging_time = sum(b.total_charging_time_seconds for b in self.bays.values())
total_queue_wait = sum(b.total_queue_wait_time_seconds for b in self.bays.values())
avg_wait = total_queue_wait / total_sessions if total_sessions > 0 else 0.0
bay_details = {}
for bay_id, bay in self.bays.items():
bay_details[bay_id] = {
"charging_rate_kw": bay.charging_rate_kw,
"sessions": bay.total_sessions,
"energy_delivered_kwh": round(bay.total_energy_delivered_kwh, 2),
"active_time_seconds": round(bay.total_charging_time_seconds, 1),
"queue_wait_seconds": round(bay.total_queue_wait_time_seconds, 1),
"utilization_pct": round(bay.utilization(simulation_duration_seconds) * 100.0, 1),
}
return {
"total_charging_sessions": total_sessions,
"total_energy_delivered_kwh": round(total_energy, 2),
"total_charging_time_seconds": round(total_charging_time, 1),
"total_queue_wait_time_seconds": round(total_queue_wait, 1),
"average_queue_wait_time_seconds": round(avg_wait, 2),
"bay_metrics": bay_details,
}
+111
View File
@@ -0,0 +1,111 @@
"""Safe task reassignment, low-battery preemption, and queue recovery coordinator."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, List, Optional
from warehouse_twin.domain.robot import Robot, RobotState
from warehouse_twin.domain.task import Task, TaskStatus
from warehouse_twin.routing.reservations import TimeSpaceReservationGrid
@dataclass(frozen=True)
class TaskReassignmentResult:
"""Record of a safe task reassignment operation."""
reassigned: bool
task_id: str
previous_robot_id: str
new_robot_id: Optional[str]
reason: str
reassigned_at: float
class TaskReassigner:
"""Coordinates graceful task recovery, preemption, and queue re-insertion."""
def __init__(
self,
reservation_grid: Optional[TimeSpaceReservationGrid] = None,
) -> None:
"""Initialize task reassigner with optional reservation grid for cleanup."""
self.reservation_grid = reservation_grid
self.reassignment_history: List[TaskReassignmentResult] = []
def reassign_due_to_low_battery(
self,
robot: Robot,
task: Task,
sim_time: float,
reason: str = "Low battery safety abort",
) -> TaskReassignmentResult:
"""Safely detach task from robot when battery falls below mandatory threshold.
Releases spatial reservations, resets task to PENDING, and clears robot binding.
Args:
robot: Robot suffering battery deficit.
task: Currently assigned task.
sim_time: Current simulation timestamp in seconds.
reason: Diagnostic explanation.
Returns:
TaskReassignmentResult audit record.
"""
prev_robot_id = robot.robot_id
# 1. Clean up spatial reservations if grid is present
if self.reservation_grid is not None:
self.reservation_grid.release_reservations_for_robot(prev_robot_id)
# 2. Reset task back to PENDING status
task.reassign_back_to_pending(sim_time)
# 3. Release robot active binding
robot.release_task()
result = TaskReassignmentResult(
reassigned=True,
task_id=task.task_id,
previous_robot_id=prev_robot_id,
new_robot_id=None,
reason=reason,
reassigned_at=sim_time,
)
self.reassignment_history.append(result)
return result
def preempt_task_for_priority(
self,
urgent_task: Task,
candidate_robot: Robot,
existing_task: Task,
sim_time: float,
) -> TaskReassignmentResult:
"""Preempt an unstarted low-priority task to allocate candidate robot to critical mission.
Only permitted if existing task is in ASSIGNED state (transit to pick not yet loaded).
"""
prev_robot_id = candidate_robot.robot_id
if self.reservation_grid is not None:
self.reservation_grid.release_reservations_for_robot(prev_robot_id)
# Requeue existing task
existing_task.reassign_back_to_pending(sim_time)
candidate_robot.release_task()
# Assign urgent task
candidate_robot.assign_task(urgent_task, sim_time=sim_time)
urgent_task.assign_to_robot(prev_robot_id, sim_time)
result = TaskReassignmentResult(
reassigned=True,
task_id=existing_task.task_id,
previous_robot_id=prev_robot_id,
new_robot_id=None,
reason=f"Preempted by critical task '{urgent_task.task_id}'",
reassigned_at=sim_time,
)
self.reassignment_history.append(result)
return result
+31 -7
View File
@@ -18,6 +18,7 @@ import networkx as nx
from warehouse_twin.domain.robot import IncompatibleRobotTaskError, Robot, RobotState
from warehouse_twin.domain.task import Task, TaskPriority, TaskStatus
from warehouse_twin.domain.warehouse import Position3D
from warehouse_twin.fleet.battery_model import BatteryModel
from warehouse_twin.routing.path_planner import NoPathFoundError, PathPlanner
@@ -54,11 +55,13 @@ class FleetDispatcher:
settings: Optional[DispatcherSettings] = None,
graph: Optional[nx.DiGraph] = None,
path_planner: Optional[PathPlanner] = None,
battery_model: Optional[BatteryModel] = None,
) -> None:
"""Initialize dispatcher with policy settings, routing graph, and path planner."""
"""Initialize dispatcher with policy settings, routing graph, path planner, and energy model."""
self.settings = settings or DispatcherSettings()
self.graph = graph
self.path_planner = path_planner or (PathPlanner(graph) if graph is not None else None)
self.battery_model = battery_model or BatteryModel(reserve_threshold_percent=self.settings.min_battery_headroom_percent)
self.queue: List[Task] = []
self._station_to_node: Dict[str, str] = {}
@@ -184,16 +187,37 @@ class FleetDispatcher:
if src_node and dst_node and not self.path_planner.is_destination_reachable(src_node, dst_node, robot_type=robot.robot_type):
continue
# 5. Compute network transit distance
dist = self.calculate_distance(robot.position, task.source_station, robot_type=robot.robot_type)
# 5. Energy feasibility check under physics-based battery model
dist_to_src = self.calculate_distance(robot.position, task.source_station, robot_type=robot.robot_type)
src_node = self.get_node_for_entity(task.source_station)
src_pos = (
Position3D.from_iterable(self.graph.nodes[src_node]["pos"])
if (self.graph and src_node and self.graph.has_node(src_node) and "pos" in self.graph.nodes[src_node])
else robot.position
)
dist_to_dst = self.calculate_distance(src_pos, task.destination_station, robot_type=robot.robot_type)
estimate = self.battery_model.estimate_mission_energy(
robot=robot,
dist_to_pickup=dist_to_src,
dist_to_dropoff=dist_to_dst,
dist_drop_to_charger=15.0,
payload_kg=task.required_payload,
)
if not estimate.is_feasible:
continue
# 6. Heuristic score (lower is better)
deadline_urgency = 0.0
if task.deadline is not None:
time_remaining = max(0.0, task.deadline - sim_time)
deadline_urgency = max(0.0, 300.0 - time_remaining) * 0.1
# Heuristic score (lower is better)
if self.settings.policy_name == "nearest_idle":
score = dist
score = dist_to_src - deadline_urgency
elif self.settings.policy_name == "balanced_utilization":
score = 0.5 * dist + 0.5 * (robot.busy_time / max(sim_time, 1.0) * 100.0)
score = 0.5 * dist_to_src + 0.5 * (robot.busy_time / max(sim_time, 1.0) * 100.0) - deadline_urgency
else: # priority_nearest_idle
score = (self.settings.distance_weight * dist) + (self.settings.priority_weight * task.priority * 10.0)
score = (self.settings.distance_weight * dist_to_src) + (self.settings.priority_weight * task.priority * 10.0) - deadline_urgency
eligible_candidates.append((score, robot))
+202 -36
View File
@@ -28,6 +28,9 @@ from warehouse_twin.domain.inventory import InventoryCatalog
from warehouse_twin.domain.robot import Robot, RobotState, RobotTypeSpec
from warehouse_twin.domain.task import Task, TaskStatus, TaskType
from warehouse_twin.domain.warehouse import Position3D, WarehouseModel
from warehouse_twin.fleet.battery_model import BatteryModel
from warehouse_twin.fleet.charging_manager import ChargingBay, ChargingManager
from warehouse_twin.fleet.task_reassigner import TaskReassigner
from warehouse_twin.routing.graph_builder import WarehouseGraphBuilder
from warehouse_twin.routing.path_planner import NoPathFoundError, PathPlanner
from warehouse_twin.routing.reservations import TimeSpaceReservationGrid
@@ -60,6 +63,16 @@ class SimulationMetrics:
total_wait_time_seconds: float = 0.0
reroutes_count: int = 0
deadlocks_prevented: int = 0
# Phase 5 Charging & Operational Constraints Metrics
missed_deadlines: int = 0
stockout_events: int = 0
reassigned_tasks: int = 0
opportunity_charges: int = 0
mandatory_charges: int = 0
total_energy_charged_kwh: float = 0.0
min_fleet_battery_percent: float = 100.0
avg_fleet_battery_percent: float = 100.0
charging_metrics: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
"""Convert metrics to a structured dictionary for reporting and JSON export."""
@@ -77,13 +90,22 @@ class SimulationMetrics:
"overdue_task_count": self.overdue_task_count,
"fleet_utilization_percent": round(self.fleet_utilization_percent, 2),
"total_energy_consumed_kwh": round(self.total_energy_consumed_kwh, 4),
"total_energy_charged_kwh": round(self.total_energy_charged_kwh, 4),
"min_fleet_battery_percent": round(self.min_fleet_battery_percent, 1),
"avg_fleet_battery_percent": round(self.avg_fleet_battery_percent, 1),
"replenishment_triggers": self.replenishment_triggers,
"missed_deadlines": self.missed_deadlines,
"stockout_events": self.stockout_events,
"reassigned_tasks": self.reassigned_tasks,
"opportunity_charges": self.opportunity_charges,
"mandatory_charges": self.mandatory_charges,
"robot_metrics": self.robot_metrics,
"conflicts_detected": self.conflicts_detected,
"yield_waits_count": self.yield_waits_count,
"total_wait_time_seconds": round(self.total_wait_time_seconds, 2),
"reroutes_count": self.reroutes_count,
"deadlocks_prevented": self.deadlocks_prevented,
"charging_metrics": self.charging_metrics,
}
@@ -129,12 +151,24 @@ class SimulationEnvironment:
self.reservation_grid, self.path_planner
)
# Phase 5 Charging & Operational Constraints Subsystems
self.battery_model = BatteryModel(
reserve_threshold_percent=dispatcher_settings.min_battery_headroom_percent if dispatcher_settings else 20.0
)
self.charging_manager = ChargingManager(
self.env,
list(self.warehouse.charging_stations.values()),
dispatch_policies_config,
)
self.task_reassigner = TaskReassigner(self.reservation_grid)
# Components
self.generator = OrderGenerator(workload_config, catalog, warehouse, seed=seed)
self.dispatcher = FleetDispatcher(
settings=dispatcher_settings,
graph=self.graph,
path_planner=self.path_planner,
battery_model=self.battery_model,
)
# Operational tracking
@@ -142,6 +176,11 @@ class SimulationEnvironment:
self.completed_tasks: List[Task] = []
self.events: List[SimulationEvent] = []
self._event_counter: int = 0
self.missed_deadlines: int = 0
self.stockout_events: int = 0
self.reassigned_tasks: int = 0
self.opportunity_charges: int = 0
self.mandatory_charges: int = 0
self.event_log_path = Path(event_log_path).resolve() if event_log_path else None
self._log_file_handle = None
@@ -243,6 +282,19 @@ class SimulationEnvironment:
task = self.generator.generate_zone_a_task(self.env.now)
self.all_tasks[task.task_id] = task
# Check inventory availability & monitor stock-outs
if task.item_id and task.item_id in self.catalog.items:
item = self.catalog.items[task.item_id]
if item.available_quantity <= 0:
self.stockout_events += 1
self.record_event(
SimulationEventType.STOCKOUT_OCCURRED,
task_id=task.task_id,
zone="zone_a",
details={"item_id": item.item_id, "available": item.available_quantity},
)
self.dispatcher.enqueue_task(task)
self.record_event(
@@ -268,6 +320,19 @@ class SimulationEnvironment:
task = self.generator.generate_zone_b_task(self.env.now)
self.all_tasks[task.task_id] = task
# Check inventory availability & monitor stock-outs
if task.item_id and task.item_id in self.catalog.items:
item = self.catalog.items[task.item_id]
if item.available_quantity <= 0:
self.stockout_events += 1
self.record_event(
SimulationEventType.STOCKOUT_OCCURRED,
task_id=task.task_id,
zone="zone_b",
details={"item_id": item.item_id, "available": item.available_quantity},
)
self.dispatcher.enqueue_task(task)
self.record_event(
@@ -293,6 +358,19 @@ class SimulationEnvironment:
while True:
task = self.generator.generate_zone_c_task(self.env.now)
self.all_tasks[task.task_id] = task
# Check inventory availability & monitor stock-outs
if task.item_id and task.item_id in self.catalog.items:
item = self.catalog.items[task.item_id]
if item.available_quantity <= 0:
self.stockout_events += 1
self.record_event(
SimulationEventType.STOCKOUT_OCCURRED,
task_id=task.task_id,
zone="zone_c",
details={"item_id": item.item_id, "available": item.available_quantity},
)
self.dispatcher.enqueue_task(task)
self.record_event(
@@ -422,7 +500,8 @@ class SimulationEnvironment:
yield self.env.timeout(traversal_time)
robot.accumulated_distance += dist
power_mode = "moving_loaded" if is_loaded else "moving_empty"
robot.consume_energy(traversal_time, mode=power_mode)
payload_mass = getattr(task, "required_payload", 0.0) if (task and is_loaded) else 0.0
robot.consume_energy(traversal_time, mode=power_mode, payload_kg=payload_mass)
# Update coordinates to waypoint v
v_coords = self.graph.nodes[v]["pos"]
@@ -478,8 +557,28 @@ class SimulationEnvironment:
yield self.env.process(self._traverse_path(robot, path_to_pickup, task=task, is_loaded=False))
# ---------------------------------------------------------------------
# 2. Pickup / Loading Operation
# 2. Pickup / Loading Operation & Pre-Pick Battery Validation
# ---------------------------------------------------------------------
# If battery dropped below mandatory threshold during empty transit, abort and reassign
if robot.battery_percent <= self.charging_manager.mandatory_threshold:
self.record_event(
SimulationEventType.BATTERY_LOW,
robot_id=robot.robot_id,
details={"battery_percent": round(robot.battery_percent, 1)},
)
reassign_res = self.task_reassigner.reassign_due_to_low_battery(robot, task, self.env.now)
self.reassigned_tasks += 1
self.record_event(
SimulationEventType.TASK_REASSIGNED,
robot_id=robot.robot_id,
task_id=task.task_id,
details={"reason": reassign_res.reason},
)
self.dispatcher.enqueue_task(task)
self._trigger_dispatch()
yield self.env.process(self._robot_recharge_process(robot))
return
robot.transition_to(RobotState.PICKING, self.env.now)
task.start_execution(self.env.now)
self._record_trajectory_point(robot)
@@ -551,7 +650,7 @@ class SimulationEnvironment:
yield self.env.process(self._traverse_path(robot, path_to_drop, task=task, is_loaded=True))
# ---------------------------------------------------------------------
# 4. Dropoff / Unloading Operation
# 4. Dropoff / Unloading Operation & Deadline Verification
# ---------------------------------------------------------------------
robot.transition_to(RobotState.DROPPING, self.env.now)
self._record_trajectory_point(robot)
@@ -566,6 +665,19 @@ class SimulationEnvironment:
self.completed_tasks.append(task)
robot.complete_task()
if task.is_overdue(self.env.now):
self.missed_deadlines += 1
self.record_event(
SimulationEventType.DEADLINE_MISSED,
robot_id=robot.robot_id,
task_id=task.task_id,
details={
"deadline": task.deadline,
"completed_at": self.env.now,
"lateness_seconds": round(task.lateness(self.env.now), 1),
},
)
self.record_event(
SimulationEventType.TASK_COMPLETED,
robot_id=robot.robot_id,
@@ -578,9 +690,13 @@ class SimulationEnvironment:
)
# ---------------------------------------------------------------------
# 5. Opportunity or Mandatory Charging
# 5. Opportunity or Mandatory Charging Decision
# ---------------------------------------------------------------------
if robot.battery_percent < 25.0:
if robot.battery_percent <= self.charging_manager.mandatory_threshold:
self.mandatory_charges += 1
yield self.env.process(self._robot_recharge_process(robot))
elif robot.battery_percent <= self.charging_manager.opportunistic_threshold and self.dispatcher.queue_length == 0:
self.opportunity_charges += 1
yield self.env.process(self._robot_recharge_process(robot))
else:
robot.transition_to(RobotState.IDLE, self.env.now)
@@ -588,13 +704,13 @@ class SimulationEnvironment:
self._trigger_dispatch()
def _robot_recharge_process(self, robot: Robot) -> Any:
"""Send robot to nearest charging bay to recharge battery back to full capacity."""
ch_id = "charge_bay_1" if "light" in robot.robot_type else "charge_bay_3"
ch_pos = self.get_entity_position(ch_id)
"""Route robot to capacity-constrained charging bay, queue if occupied, and recharge."""
bay = self.charging_manager.select_best_charging_bay(robot, path_planner=self.path_planner)
bay_pos = bay.position
start_node = self.path_planner.get_closest_node(robot.position, robot.robot_type)
target_node = self.dispatcher.get_node_for_entity(ch_id)
target_node = self.dispatcher.get_node_for_entity(bay.station_id)
if not target_node:
target_node = self.path_planner.get_closest_node(ch_pos, robot.robot_type)
target_node = self.path_planner.get_closest_node(bay_pos, robot.robot_type)
robot.transition_to(RobotState.TRANSIT_TO_CHARGE, self.env.now)
try:
@@ -604,29 +720,66 @@ class SimulationEnvironment:
yield self.env.process(self._traverse_path(robot, path, task=None, is_loaded=False))
robot.transition_to(RobotState.CHARGING, self.env.now)
self._record_trajectory_point(robot)
self.record_event(
SimulationEventType.ROBOT_CHARGING_START,
robot_id=robot.robot_id,
details={"battery_percent": round(robot.battery_percent, 1), "charger": ch_id},
)
# Check queue if bay is currently occupied
queue_start = self.env.now
if bay.is_occupied:
self.record_event(
SimulationEventType.CHARGING_QUEUED,
robot_id=robot.robot_id,
details={
"bay_id": bay.station_id,
"queue_length": bay.queue_length,
"battery_percent": round(robot.battery_percent, 1),
},
)
# Fast charging at 10.0 kW to 95% SoC
needed_kwh = (0.95 * robot.battery_capacity) - robot.battery_level
charge_duration = max((needed_kwh / 10.0) * 3600.0, 30.0)
yield self.env.timeout(charge_duration)
with bay.resource.request() as req:
yield req
queue_wait = self.env.now - queue_start
bay.total_queue_wait_time_seconds += queue_wait
bay.current_occupant_robot_id = robot.robot_id
robot.charge_energy(charge_duration, charging_rate_kw=10.0)
self._record_trajectory_point(robot)
robot.transition_to(RobotState.IDLE, self.env.now)
self._record_trajectory_point(robot)
self.record_event(
SimulationEventType.ROBOT_CHARGING_COMPLETE,
robot_id=robot.robot_id,
details={"battery_percent": round(robot.battery_percent, 1)},
)
self._trigger_dispatch()
robot.transition_to(RobotState.CHARGING, self.env.now)
self._record_trajectory_point(robot)
self.record_event(
SimulationEventType.ROBOT_CHARGING_START,
robot_id=robot.robot_id,
details={
"battery_percent": round(robot.battery_percent, 1),
"charger": bay.station_id,
"rate_kw": bay.charging_rate_kw,
"queue_wait_seconds": round(queue_wait, 2),
},
)
target_soc = self.charging_manager.recharge_target_percent
target_kwh = (target_soc / 100.0) * robot.battery_capacity
needed_kwh = max(0.0, target_kwh - robot.battery_level)
charge_duration = max(
self.charging_manager.min_charge_duration,
(needed_kwh / max(bay.charging_rate_kw, 1.0)) * 3600.0,
)
yield self.env.timeout(charge_duration)
delivered = robot.charge_energy(charge_duration, charging_rate_kw=bay.charging_rate_kw)
bay.total_sessions += 1
bay.total_charging_time_seconds += charge_duration
bay.total_energy_delivered_kwh += delivered
bay.current_occupant_robot_id = None
self._record_trajectory_point(robot)
robot.transition_to(RobotState.IDLE, self.env.now)
self._record_trajectory_point(robot)
self.record_event(
SimulationEventType.ROBOT_CHARGING_COMPLETE,
robot_id=robot.robot_id,
details={
"battery_percent": round(robot.battery_percent, 1),
"energy_delivered_kwh": round(delivered, 3),
"charge_duration": round(charge_duration, 1),
},
)
self._trigger_dispatch()
# -------------------------------------------------------------------------
# Execution & KPI Collection
@@ -680,10 +833,10 @@ class SimulationEnvironment:
total_busy = sum(r.busy_time for r in self.robots.values())
fleet_util = (total_busy / (len(self.robots) * sim_duration)) * 100.0 if self.robots else 0.0
total_energy = sum(
r.battery_capacity - r.battery_level + (r.accumulated_distance * 0.0005)
for r in self.robots.values()
)
total_energy_consumed = sum(r.total_energy_consumed_kwh for r in self.robots.values())
total_energy_charged = sum(r.total_energy_charged_kwh for r in self.robots.values())
min_soc = min((r.min_battery_percent for r in self.robots.values()), default=100.0)
avg_soc = (sum(r.battery_percent for r in self.robots.values()) / len(self.robots)) if self.robots else 100.0
repl_count = sum(
1 for e in self.events if e.event_type == SimulationEventType.INVENTORY_REPLENISHMENT_TRIGGERED
@@ -695,10 +848,14 @@ class SimulationEnvironment:
"distance_meters": round(r.accumulated_distance, 2),
"busy_seconds": round(r.busy_time, 2),
"battery_percent": round(r.battery_percent, 1),
"min_battery_percent": round(r.min_battery_percent, 1),
"energy_consumed_kwh": round(r.total_energy_consumed_kwh, 4),
"energy_charged_kwh": round(r.total_energy_charged_kwh, 4),
"utilization_percent": round((r.busy_time / sim_duration) * 100.0, 1),
}
traffic_stats = self.traffic_manager.get_metrics()
charging_stats = self.charging_manager.get_metrics(sim_duration)
return SimulationMetrics(
duration_seconds=sim_duration,
@@ -713,12 +870,21 @@ class SimulationEnvironment:
on_time_delivery_percent=on_time_pct,
overdue_task_count=overdue_count,
fleet_utilization_percent=fleet_util,
total_energy_consumed_kwh=total_energy,
total_energy_consumed_kwh=total_energy_consumed,
total_energy_charged_kwh=total_energy_charged,
min_fleet_battery_percent=min_soc,
avg_fleet_battery_percent=avg_soc,
replenishment_triggers=repl_count,
missed_deadlines=self.missed_deadlines,
stockout_events=self.stockout_events,
reassigned_tasks=self.reassigned_tasks,
opportunity_charges=self.opportunity_charges,
mandatory_charges=self.mandatory_charges,
robot_metrics=r_metrics,
conflicts_detected=traffic_stats["conflicts_detected"],
yield_waits_count=traffic_stats["yield_waits_count"],
total_wait_time_seconds=traffic_stats["total_wait_time_seconds"],
reroutes_count=traffic_stats["reroutes_count"],
deadlocks_prevented=traffic_stats["deadlocks_prevented"],
charging_metrics=charging_stats,
)