feat(phase3): implement SimPy discrete-event simulation engine, multi-zone order generation, fleet dispatcher, and wider Zone B aisles
This commit is contained in:
@@ -226,6 +226,98 @@ def export_usd(config_dir: Optional[str] = None, output_path: Optional[str] = No
|
||||
return 1
|
||||
|
||||
|
||||
def run_simulation(
|
||||
config_dir: Optional[str] = None,
|
||||
duration: Optional[float] = None,
|
||||
seed: Optional[int] = None,
|
||||
events_output: Optional[str] = None,
|
||||
) -> int:
|
||||
"""Run discrete-event simulation and report operational KPIs."""
|
||||
setup_logging()
|
||||
logger = get_logger("cli")
|
||||
try:
|
||||
from warehouse_twin.domain.inventory import InventoryCatalog
|
||||
from warehouse_twin.domain.robot import Robot, RobotTypeSpec
|
||||
from warehouse_twin.domain.warehouse import WarehouseModel
|
||||
from warehouse_twin.simulation.dispatcher import DispatcherSettings
|
||||
from warehouse_twin.simulation.order_generator import WorkloadConfig
|
||||
from warehouse_twin.simulation.sim_engine import SimulationEnvironment
|
||||
|
||||
loader = ConfigLoader(config_dir)
|
||||
bundle = loader.load_all()
|
||||
|
||||
sim_cfg = bundle.simulation.get("simulation", {})
|
||||
sim_duration = duration if duration is not None else float(sim_cfg.get("duration_seconds", 3600.0))
|
||||
sim_seed = seed if seed is not None else int(sim_cfg.get("random_seed", 42))
|
||||
|
||||
# Model entities
|
||||
warehouse = WarehouseModel.from_config_dict(bundle.warehouse)
|
||||
catalog = InventoryCatalog.from_config_dict(bundle.inventory)
|
||||
|
||||
# Parse robot types and build fleet
|
||||
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)
|
||||
|
||||
fleet: List[Robot] = []
|
||||
for r_data in bundle.robots.get("fleet", []):
|
||||
fleet.append(Robot.from_fleet_dict(r_data, type_specs))
|
||||
|
||||
workload = WorkloadConfig.from_dict(bundle.simulation)
|
||||
dispatch_settings = DispatcherSettings.from_dict(bundle.dispatch_policies)
|
||||
|
||||
# Log path
|
||||
log_out = Path(events_output).resolve() if events_output else Path("logs/simulation_events.jsonl").resolve()
|
||||
|
||||
print("=" * 65)
|
||||
print("Starting Warehouse Robot Fleet Discrete-Event Simulation")
|
||||
print("=" * 65)
|
||||
print(f"Duration: {sim_duration:.1f} simulated seconds ({sim_duration / 3600.0:.2f} hours)")
|
||||
print(f"Random Seed: {sim_seed}")
|
||||
print(f"Fleet Size: {len(fleet)} AMRs")
|
||||
print(f"Inventory: {len(catalog.items)} SKUs")
|
||||
print(f"Zone B Aisles: 4.0m wide aisles (slow-moving & specialized)")
|
||||
print(f"Telemetry Log: {log_out}")
|
||||
print("-" * 65)
|
||||
|
||||
sim_env = SimulationEnvironment(
|
||||
warehouse=warehouse,
|
||||
catalog=catalog,
|
||||
fleet=fleet,
|
||||
workload_config=workload,
|
||||
dispatcher_settings=dispatch_settings,
|
||||
event_log_path=log_out,
|
||||
seed=sim_seed,
|
||||
)
|
||||
|
||||
metrics = sim_env.run(until=sim_duration)
|
||||
|
||||
print("Simulation Completed Successfully!")
|
||||
print("=" * 65)
|
||||
print("OPERATIONAL KPI REPORT")
|
||||
print("=" * 65)
|
||||
print(f"Tasks Created: {metrics.tasks_created}")
|
||||
print(f"Tasks Completed: {metrics.tasks_completed}")
|
||||
print(f"Tasks Pending: {metrics.tasks_pending}")
|
||||
print(f"Throughput: {metrics.throughput_tasks_per_hour:.2f} tasks/hr")
|
||||
print(f"Avg Turnaround Time: {metrics.average_turnaround_time:.1f} s")
|
||||
print(f"Avg Waiting Time: {metrics.average_wait_time:.1f} s")
|
||||
print(f"Avg Execution Time: {metrics.average_execution_time:.1f} s")
|
||||
print(f"On-Time Delivery Rate: {metrics.on_time_delivery_percent:.1f}%")
|
||||
print(f"Fleet Utilization: {metrics.fleet_utilization_percent:.1f}%")
|
||||
print(f"Replenishment Triggers: {metrics.replenishment_triggers}")
|
||||
print("-" * 65)
|
||||
print("Per-Robot Utilization:")
|
||||
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}%")
|
||||
print("=" * 65)
|
||||
return 0
|
||||
except Exception as err:
|
||||
logger.error("Simulation run failed: %s", err)
|
||||
print(f"[FAIL] Simulation Run Error: {err}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
def main(argv: Optional[list[str]] = None) -> int:
|
||||
"""Main CLI entry point."""
|
||||
parser = argparse.ArgumentParser(
|
||||
@@ -291,6 +383,33 @@ def main(argv: Optional[list[str]] = None) -> int:
|
||||
help="Output USD file path (defaults to omniverse/scenes/warehouse_phase2.usda)",
|
||||
)
|
||||
|
||||
# Subcommand: run-sim
|
||||
sim_parser = subparsers.add_parser("run-sim", help="Run SimPy discrete-event simulation")
|
||||
sim_parser.add_argument(
|
||||
"--config-dir",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Path to directory containing configuration JSON files",
|
||||
)
|
||||
sim_parser.add_argument(
|
||||
"--duration",
|
||||
type=float,
|
||||
default=None,
|
||||
help="Simulation duration in seconds (defaults to simulation.json)",
|
||||
)
|
||||
sim_parser.add_argument(
|
||||
"--seed",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Random seed for reproducible simulation (defaults to simulation.json)",
|
||||
)
|
||||
sim_parser.add_argument(
|
||||
"--output-events",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Output path for telemetry events JSONL (defaults to logs/simulation_events.jsonl)",
|
||||
)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.command == "validate-env":
|
||||
@@ -303,6 +422,8 @@ def main(argv: Optional[list[str]] = None) -> int:
|
||||
return export_graph(args.config_dir, args.output)
|
||||
elif args.command == "export-usd":
|
||||
return export_usd(args.config_dir, args.output)
|
||||
elif args.command == "run-sim":
|
||||
return run_simulation(args.config_dir, args.duration, args.seed, args.output_events)
|
||||
else:
|
||||
parser.print_help()
|
||||
return 0
|
||||
|
||||
@@ -5,12 +5,13 @@ from __future__ import annotations
|
||||
import json
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
|
||||
class SimulationEventType(str, Enum):
|
||||
"""Categorization of discrete events emitted by the simulation engine."""
|
||||
TASK_RELEASED = "TASK_RELEASED"
|
||||
TASK_CREATED = "TASK_RELEASED"
|
||||
TASK_ASSIGNED = "TASK_ASSIGNED"
|
||||
TASK_STARTED = "TASK_STARTED"
|
||||
TASK_COMPLETED = "TASK_COMPLETED"
|
||||
@@ -21,11 +22,14 @@ class SimulationEventType(str, Enum):
|
||||
ROBOT_STATE_CHANGED = "ROBOT_STATE_CHANGED"
|
||||
ROBOT_ARRIVED = "ROBOT_ARRIVED"
|
||||
ROBOT_CHARGING_STARTED = "ROBOT_CHARGING_STARTED"
|
||||
ROBOT_CHARGING_START = "ROBOT_CHARGING_STARTED"
|
||||
ROBOT_CHARGING_COMPLETED = "ROBOT_CHARGING_COMPLETED"
|
||||
ROBOT_CHARGING_COMPLETE = "ROBOT_CHARGING_COMPLETED"
|
||||
|
||||
INVENTORY_RESERVED = "INVENTORY_RESERVED"
|
||||
INVENTORY_CONSUMED = "INVENTORY_CONSUMED"
|
||||
INVENTORY_REPLENISHED = "INVENTORY_REPLENISHED"
|
||||
INVENTORY_REPLENISHMENT_TRIGGERED = "INVENTORY_REPLENISHED"
|
||||
STOCKOUT_OCCURRED = "STOCKOUT_OCCURRED"
|
||||
|
||||
|
||||
@@ -38,6 +42,8 @@ class SimulationEvent:
|
||||
entity_id: str
|
||||
task_id: Optional[str] = None
|
||||
metadata: Dict[str, Any] = field(default_factory=dict)
|
||||
position: Optional[Tuple[float, float, float]] = None
|
||||
zone: Optional[str] = None
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Convert event to serializable dictionary format."""
|
||||
|
||||
@@ -31,6 +31,11 @@ class InventoryItem:
|
||||
"""On-hand quantity unencumbered by pending reservations."""
|
||||
return max(0, self.current_stock - self.reserved_stock)
|
||||
|
||||
@property
|
||||
def available_quantity(self) -> int:
|
||||
"""Alias for available_stock."""
|
||||
return self.available_stock
|
||||
|
||||
def reserve(self, qty: int) -> None:
|
||||
"""Reserve units for an assigned picking task.
|
||||
|
||||
@@ -69,6 +74,10 @@ class InventoryItem:
|
||||
if qty > 0:
|
||||
self.current_stock += qty
|
||||
|
||||
def restock(self, qty: int) -> None:
|
||||
"""Alias for replenish."""
|
||||
self.replenish(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
|
||||
@@ -109,6 +118,11 @@ class InventoryCatalog:
|
||||
|
||||
return cls(catalog_items)
|
||||
|
||||
@property
|
||||
def items(self) -> Dict[str, InventoryItem]:
|
||||
"""Dictionary of all items keyed by SKU item_id."""
|
||||
return self._items
|
||||
|
||||
def get_item(self, item_id: str) -> Optional[InventoryItem]:
|
||||
"""Retrieve an inventory item by ID."""
|
||||
return self._items.get(item_id)
|
||||
|
||||
@@ -166,6 +166,11 @@ class Robot:
|
||||
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.
|
||||
|
||||
@@ -249,15 +254,17 @@ class Robot:
|
||||
|
||||
return True, None
|
||||
|
||||
def assign_task(self, task: Any) -> 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.
|
||||
"""
|
||||
compatible, reason = self.validate_task_compatibility(task)
|
||||
if not compatible:
|
||||
raise IncompatibleRobotTaskError(reason or "Robot incompatible with task")
|
||||
# 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
|
||||
@@ -269,6 +276,10 @@ class Robot:
|
||||
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") -> float:
|
||||
"""Deduct energy consumed over duration according to active power mode.
|
||||
|
||||
|
||||
@@ -12,11 +12,22 @@ from warehouse_twin.domain.robot import InvalidStateTransitionError
|
||||
class TaskType(str, Enum):
|
||||
"""Classification of tasks executed by warehouse AMR fleet."""
|
||||
ORDER_PICK = "ORDER_PICK"
|
||||
OUTBOUND_PICKING = "ORDER_PICK"
|
||||
INBOUND_TRANSPORT = "INBOUND_TRANSPORT"
|
||||
REPLENISHMENT = "REPLENISHMENT"
|
||||
PRODUCTION_LINE_FEED = "PRODUCTION_LINE_FEED"
|
||||
PRODUCTION_FEED = "PRODUCTION_LINE_FEED"
|
||||
CHARGING = "CHARGING"
|
||||
|
||||
|
||||
class TaskPriority(int, Enum):
|
||||
"""Priority ranking for warehouse tasks (1 is highest, 4 is lowest)."""
|
||||
CRITICAL = 1
|
||||
HIGH = 2
|
||||
MEDIUM = 3
|
||||
LOW = 4
|
||||
|
||||
|
||||
class TaskStatus(str, Enum):
|
||||
"""Discrete operational lifecycle states for simulation tasks."""
|
||||
PENDING = "PENDING"
|
||||
@@ -68,6 +79,51 @@ class Task:
|
||||
completion_time: Optional[float] = None
|
||||
target_zone: Optional[str] = None # Operational zone hint ('zone_a', 'zone_b', 'zone_c')
|
||||
|
||||
@property
|
||||
def source_station(self) -> str:
|
||||
return self.source
|
||||
|
||||
@source_station.setter
|
||||
def source_station(self, val: str) -> None:
|
||||
self.source = val
|
||||
|
||||
@property
|
||||
def destination_station(self) -> str:
|
||||
return self.destination
|
||||
|
||||
@destination_station.setter
|
||||
def destination_station(self, val: str) -> None:
|
||||
self.destination = val
|
||||
|
||||
@property
|
||||
def payload_weight(self) -> float:
|
||||
return self.required_payload
|
||||
|
||||
@payload_weight.setter
|
||||
def payload_weight(self, val: float) -> None:
|
||||
self.required_payload = val
|
||||
|
||||
@property
|
||||
def created_at(self) -> float:
|
||||
return self.release_time
|
||||
|
||||
@created_at.setter
|
||||
def created_at(self, val: float) -> None:
|
||||
self.release_time = val
|
||||
|
||||
def assign_to_robot(self, robot_id: str, sim_time: float) -> None:
|
||||
"""Assign task to an AMR and transition to ASSIGNED status."""
|
||||
self.assigned_robot_id = robot_id
|
||||
self.transition_to(TaskStatus.ASSIGNED, sim_time)
|
||||
|
||||
def start_execution(self, sim_time: float) -> None:
|
||||
"""Transition task to IN_PROGRESS status."""
|
||||
self.transition_to(TaskStatus.IN_PROGRESS, sim_time)
|
||||
|
||||
def complete(self, sim_time: float) -> None:
|
||||
"""Transition task to COMPLETED status."""
|
||||
self.transition_to(TaskStatus.COMPLETED, sim_time)
|
||||
|
||||
def transition_to(self, new_status: TaskStatus, sim_time: float) -> None:
|
||||
"""Advance task state machine, validating legal transitions and updating timestamps.
|
||||
|
||||
|
||||
@@ -184,12 +184,13 @@ class WarehouseGraphBuilder:
|
||||
# 2. Zone Internal Aisle Grids
|
||||
# -------------------------------------------------------------------------
|
||||
zone_bounds = [
|
||||
("zone_a", 6.0, 24.0, 6.0, 34.0, {"light_amr", "heavy_amr"}),
|
||||
("zone_b", 30.0, 44.0, 6.0, 34.0, {"heavy_amr"}),
|
||||
("zone_c", 48.0, 56.0, 6.0, 34.0, {"light_amr", "heavy_amr"}),
|
||||
("zone_a", 6.0, 24.0, 6.0, 34.0, spacing, {"light_amr", "heavy_amr"}),
|
||||
# Zone B: Slow-moving and heavy specialized items configured with wider aisles (4.0m)
|
||||
("zone_b", 32.0, 44.0, 6.0, 34.0, 4.0, {"heavy_amr"}),
|
||||
("zone_c", 48.0, 56.0, 6.0, 34.0, spacing, {"light_amr", "heavy_amr"}),
|
||||
]
|
||||
|
||||
for zid, x_min, x_max, y_min, y_max, allowed in zone_bounds:
|
||||
for zid, x_min, x_max, y_min, y_max, x_step, allowed in zone_bounds:
|
||||
z_speed = self._get_speed_limit(zid)
|
||||
col_nodes: List[List[str]] = []
|
||||
cur_x = x_min
|
||||
@@ -201,7 +202,7 @@ class WarehouseGraphBuilder:
|
||||
col.append(wp)
|
||||
cur_y += spacing
|
||||
col_nodes.append(col)
|
||||
cur_x += spacing
|
||||
cur_x += x_step
|
||||
|
||||
# Vertical edges along aisles within zone
|
||||
for col in col_nodes:
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Warehouse Robot Fleet discrete-event simulation engine and workload package."""
|
||||
|
||||
from warehouse_twin.simulation.dispatcher import DispatcherSettings, FleetDispatcher
|
||||
from warehouse_twin.simulation.order_generator import OrderGenerator, WorkloadConfig
|
||||
from warehouse_twin.simulation.sim_engine import SimulationEnvironment, SimulationMetrics
|
||||
|
||||
__all__ = [
|
||||
"DispatcherSettings",
|
||||
"FleetDispatcher",
|
||||
"OrderGenerator",
|
||||
"WorkloadConfig",
|
||||
"SimulationEnvironment",
|
||||
"SimulationMetrics",
|
||||
]
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Fleet dispatching engine: task queue prioritization and AMR allocation.
|
||||
|
||||
Supports pluggable dispatching heuristics:
|
||||
- Priority-aware nearest idle (default)
|
||||
- Pure nearest idle
|
||||
- Balanced fleet utilization
|
||||
Enforces strict robot-task compatibility (payload rating, battery headroom, and Zone B wide aisle restrictions).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import heapq
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
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
|
||||
|
||||
|
||||
@dataclass
|
||||
class DispatcherSettings:
|
||||
"""Configurable weights and thresholds for the fleet dispatching policy."""
|
||||
policy_name: str = "priority_nearest_idle"
|
||||
priority_weight: float = 0.6
|
||||
distance_weight: float = 0.4
|
||||
min_battery_headroom_percent: float = 20.0
|
||||
opportunistic_charge_percent: float = 60.0
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> DispatcherSettings:
|
||||
"""Construct DispatcherSettings from dispatch_policies.json data."""
|
||||
active = data.get("active_policy", "priority_nearest_idle")
|
||||
settings = data.get("policy_settings", {}).get(active, {})
|
||||
ch_strategy = data.get("charging_strategy", {})
|
||||
|
||||
return cls(
|
||||
policy_name=active,
|
||||
priority_weight=float(settings.get("priority_weight", 0.6)),
|
||||
distance_weight=float(settings.get("distance_weight", 0.4)),
|
||||
min_battery_headroom_percent=float(ch_strategy.get("mandatory_charging_threshold_percent", 20.0)),
|
||||
opportunistic_charge_percent=float(ch_strategy.get("opportunistic_charging_threshold_percent", 60.0)),
|
||||
)
|
||||
|
||||
|
||||
class FleetDispatcher:
|
||||
"""Coordinates task queueing and assigns optimal, compatible AMRs to pending tasks."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: Optional[DispatcherSettings] = None,
|
||||
graph: Optional[nx.DiGraph] = None,
|
||||
) -> None:
|
||||
"""Initialize dispatcher with policy settings and routing graph."""
|
||||
self.settings = settings or DispatcherSettings()
|
||||
self.graph = graph
|
||||
self.queue: List[Task] = []
|
||||
self._station_to_node: Dict[str, str] = {}
|
||||
|
||||
if self.graph:
|
||||
self._cache_station_nodes()
|
||||
|
||||
def _cache_station_nodes(self) -> None:
|
||||
"""Cache mapping from station/rack ID to graph node ID for fast shortest path lookups."""
|
||||
for nid, data in self.graph.nodes(data=True):
|
||||
if "station_id" in data:
|
||||
self._station_to_node[data["station_id"]] = nid
|
||||
elif "rack_id" in data:
|
||||
self._station_to_node[data["rack_id"]] = nid
|
||||
elif "charger_id" in data:
|
||||
self._station_to_node[data["charger_id"]] = nid
|
||||
|
||||
def get_node_for_entity(self, entity_id: str) -> Optional[str]:
|
||||
"""Resolve entity ID (station, rack, or bay) to graph node ID."""
|
||||
if entity_id in self._station_to_node:
|
||||
return self._station_to_node[entity_id]
|
||||
# Check standard prefixed names
|
||||
for prefix in ("station_", "rack_", "charger_"):
|
||||
candidate = f"{prefix}{entity_id}"
|
||||
if self.graph and self.graph.has_node(candidate):
|
||||
self._station_to_node[entity_id] = candidate
|
||||
return candidate
|
||||
return None
|
||||
|
||||
def calculate_distance(self, from_pos: Position3D, to_entity_id: str) -> float:
|
||||
"""Compute network routing distance or fallback Euclidean distance to target entity."""
|
||||
target_node = self.get_node_for_entity(to_entity_id)
|
||||
if self.graph and target_node and self.graph.has_node(target_node):
|
||||
# Find nearest node to current robot position
|
||||
best_node = None
|
||||
best_dist = float("inf")
|
||||
for nid, data in self.graph.nodes(data=True):
|
||||
p = data.get("pos")
|
||||
if p:
|
||||
d = (from_pos.x - p[0])**2 + (from_pos.y - p[1])**2
|
||||
if d < best_dist:
|
||||
best_dist = d
|
||||
best_node = nid
|
||||
if best_node:
|
||||
try:
|
||||
return nx.shortest_path_length(self.graph, best_node, target_node, weight="distance")
|
||||
except (nx.NetworkXNoPath, nx.NodeNotFound):
|
||||
pass
|
||||
|
||||
# Fallback target position approximation if graph lookup fails
|
||||
if self.graph and target_node and "pos" in self.graph.nodes[target_node]:
|
||||
p = self.graph.nodes[target_node]["pos"]
|
||||
return from_pos.distance_to(Position3D(p[0], p[1], p[2]))
|
||||
return 10.0 # Default nominal distance
|
||||
|
||||
def enqueue_task(self, task: Task) -> None:
|
||||
"""Add a newly created task to the pending dispatch queue, sorted by priority."""
|
||||
self.queue.append(task)
|
||||
self._sort_queue()
|
||||
|
||||
def _sort_queue(self) -> None:
|
||||
"""Sort tasks by priority (lower number = higher priority), deadline, and creation time."""
|
||||
self.queue.sort(key=lambda t: (
|
||||
t.priority,
|
||||
t.deadline if t.deadline is not None else float("inf"),
|
||||
t.created_at,
|
||||
))
|
||||
|
||||
@property
|
||||
def queue_length(self) -> int:
|
||||
"""Number of pending tasks waiting in queue."""
|
||||
return len(self.queue)
|
||||
|
||||
def select_best_robot(
|
||||
self,
|
||||
task: Task,
|
||||
available_robots: List[Robot],
|
||||
sim_time: float,
|
||||
) -> Optional[Robot]:
|
||||
"""Select the optimal robot for task based on compatibility, distance, and fleet policy."""
|
||||
eligible_candidates: List[Tuple[float, Robot]] = []
|
||||
|
||||
for robot in available_robots:
|
||||
# 1. State check: must be IDLE
|
||||
if robot.current_state != RobotState.IDLE:
|
||||
continue
|
||||
|
||||
# 2. Battery threshold check
|
||||
if robot.battery_percent < self.settings.min_battery_headroom_percent:
|
||||
continue
|
||||
|
||||
# 3. Payload and Zone accessibility compatibility check
|
||||
try:
|
||||
robot.validate_task_compatibility(task)
|
||||
except IncompatibleRobotTaskError:
|
||||
continue
|
||||
|
||||
# 4. Compute transit distance
|
||||
dist = self.calculate_distance(robot.position, task.source_station)
|
||||
|
||||
# Heuristic score (lower is better)
|
||||
if self.settings.policy_name == "nearest_idle":
|
||||
score = dist
|
||||
elif self.settings.policy_name == "balanced_utilization":
|
||||
score = 0.5 * dist + 0.5 * (robot.busy_time / max(sim_time, 1.0) * 100.0)
|
||||
else: # priority_nearest_idle
|
||||
score = (self.settings.distance_weight * dist) + (self.settings.priority_weight * task.priority * 10.0)
|
||||
|
||||
eligible_candidates.append((score, robot))
|
||||
|
||||
if not eligible_candidates:
|
||||
return None
|
||||
|
||||
# Return robot with lowest score
|
||||
eligible_candidates.sort(key=lambda x: x[0])
|
||||
return eligible_candidates[0][1]
|
||||
|
||||
def dispatch_next_batch(
|
||||
self,
|
||||
all_robots: List[Robot],
|
||||
sim_time: float,
|
||||
) -> List[Tuple[Robot, Task]]:
|
||||
"""Evaluate pending task queue and dispatch compatible available robots."""
|
||||
dispatches: List[Tuple[Robot, Task]] = []
|
||||
available_robots = [r for r in all_robots if r.is_available]
|
||||
|
||||
if not available_robots or not self.queue:
|
||||
return dispatches
|
||||
|
||||
remaining_tasks: List[Task] = []
|
||||
|
||||
for task in self.queue:
|
||||
if not available_robots:
|
||||
remaining_tasks.append(task)
|
||||
continue
|
||||
|
||||
chosen_robot = self.select_best_robot(task, available_robots, sim_time)
|
||||
if chosen_robot:
|
||||
# Bind task and robot
|
||||
chosen_robot.assign_task(task.task_id, sim_time)
|
||||
task.assign_to_robot(chosen_robot.robot_id, sim_time)
|
||||
available_robots.remove(chosen_robot)
|
||||
dispatches.append((chosen_robot, task))
|
||||
else:
|
||||
remaining_tasks.append(task)
|
||||
|
||||
self.queue = remaining_tasks
|
||||
return dispatches
|
||||
@@ -0,0 +1,183 @@
|
||||
"""Workload order generation for discrete-event warehouse simulation.
|
||||
|
||||
Generates realistic, multi-zone operational tasks:
|
||||
1. Zone A (Fast-moving): High-frequency Poisson arrival process for agile AMRs.
|
||||
2. Zone B (Slow-moving & Heavy): Low-frequency Gaussian arrival process with heavy payloads
|
||||
navigating wider aisles, restricted to Heavy AMRs.
|
||||
3. Zone C (Raw materials): Deterministic scheduled batch deliveries feeding production lines
|
||||
with strict SLA lead times.
|
||||
4. Replenishment: Automatically triggered when inventory drops below reorder thresholds.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Dict, Iterator, List, Optional
|
||||
|
||||
from warehouse_twin.domain.inventory import InventoryCatalog, InventoryItem
|
||||
from warehouse_twin.domain.task import Task, TaskPriority, TaskStatus, TaskType
|
||||
from warehouse_twin.domain.warehouse import WarehouseModel
|
||||
|
||||
|
||||
@dataclass
|
||||
class WorkloadConfig:
|
||||
"""Configurable workload parameters controlling order arrival rates and peak multipliers."""
|
||||
zone_a_arrival_rate_per_hour: float = 60.0
|
||||
zone_b_arrival_rate_per_hour: float = 15.0
|
||||
zone_c_scheduled_feed_interval_seconds: float = 600.0
|
||||
peak_demand_multiplier: float = 1.5
|
||||
peak_start_second: float = 1200.0
|
||||
peak_end_second: float = 2400.0
|
||||
pickup_time_seconds: float = 15.0
|
||||
dropoff_time_seconds: float = 15.0
|
||||
heavy_pickup_overhead_seconds: float = 30.0
|
||||
line_feed_lead_time_seconds: float = 300.0
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> WorkloadConfig:
|
||||
"""Construct WorkloadConfig from simulation.json workload and operational_times blocks."""
|
||||
w = data.get("workload", {})
|
||||
o = data.get("operational_times", {})
|
||||
return cls(
|
||||
zone_a_arrival_rate_per_hour=float(w.get("zone_a_arrival_rate_per_hour", 60.0)),
|
||||
zone_b_arrival_rate_per_hour=float(w.get("zone_b_arrival_rate_per_hour", 15.0)),
|
||||
zone_c_scheduled_feed_interval_seconds=float(w.get("zone_c_scheduled_feed_interval_seconds", 600.0)),
|
||||
peak_demand_multiplier=float(w.get("peak_demand_multiplier", 1.5)),
|
||||
peak_start_second=float(w.get("peak_start_second", 1200.0)),
|
||||
peak_end_second=float(w.get("peak_end_second", 2400.0)),
|
||||
pickup_time_seconds=float(o.get("pickup_time_seconds", 15.0)),
|
||||
dropoff_time_seconds=float(o.get("dropoff_time_seconds", 15.0)),
|
||||
heavy_pickup_overhead_seconds=float(o.get("heavy_pickup_overhead_seconds", 30.0)),
|
||||
line_feed_lead_time_seconds=float(o.get("line_feed_lead_time_seconds", 300.0)),
|
||||
)
|
||||
|
||||
|
||||
class OrderGenerator:
|
||||
"""Stochastic and scheduled order generator producing Task entities across warehouse zones."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: WorkloadConfig,
|
||||
inventory_catalog: InventoryCatalog,
|
||||
warehouse: WarehouseModel,
|
||||
seed: int = 42,
|
||||
) -> None:
|
||||
"""Initialize generator with workload specifications, item catalog, and random seed."""
|
||||
self.config = config
|
||||
self.catalog = inventory_catalog
|
||||
self.warehouse = warehouse
|
||||
self.rng = random.Random(seed)
|
||||
self._task_counter: int = 0
|
||||
|
||||
# Group items by zone for efficient retrieval
|
||||
self.zone_a_items: List[InventoryItem] = [
|
||||
it for it in self.catalog.items.values() if it.zone == "zone_a"
|
||||
]
|
||||
self.zone_b_items: List[InventoryItem] = [
|
||||
it for it in self.catalog.items.values() if it.zone == "zone_b"
|
||||
]
|
||||
self.zone_c_items: List[InventoryItem] = [
|
||||
it for it in self.catalog.items.values() if it.zone == "zone_c"
|
||||
]
|
||||
|
||||
def _next_task_id(self, prefix: str) -> str:
|
||||
self._task_counter += 1
|
||||
return f"task_{prefix}_{self._task_counter:04d}"
|
||||
|
||||
def is_peak_demand(self, sim_time: float) -> bool:
|
||||
"""Check if simulation time falls within peak traffic demand window."""
|
||||
return self.config.peak_start_second <= sim_time <= self.config.peak_end_second
|
||||
|
||||
def get_arrival_multiplier(self, sim_time: float) -> float:
|
||||
"""Get workload intensity factor based on peak demand schedule."""
|
||||
if self.is_peak_demand(sim_time):
|
||||
return self.config.peak_demand_multiplier
|
||||
return 1.0
|
||||
|
||||
def generate_zone_a_task(self, sim_time: float) -> Task:
|
||||
"""Generate a fast-moving inventory picking task in Zone A."""
|
||||
item = self.rng.choice(self.zone_a_items)
|
||||
task_id = self._next_task_id("za")
|
||||
dest = "picking_station_a1" if self.rng.random() < 0.7 else "outbound_pack_1"
|
||||
deadline = sim_time + 480.0 # 8 minutes SLA
|
||||
|
||||
return Task(
|
||||
task_id=task_id,
|
||||
task_type=TaskType.OUTBOUND_PICKING,
|
||||
source=item.storage_location,
|
||||
destination=dest,
|
||||
required_payload=item.unit_weight_kg,
|
||||
item_id=item.item_id,
|
||||
quantity=1,
|
||||
release_time=sim_time,
|
||||
deadline=deadline,
|
||||
priority=TaskPriority.LOW.value, # Standard pick priority 4
|
||||
target_zone="zone_a",
|
||||
)
|
||||
|
||||
def generate_zone_b_task(self, sim_time: float) -> Task:
|
||||
"""Generate a slow-moving heavy specialized inventory task in Zone B.
|
||||
|
||||
Requires navigation through wider aisles (4.0m) and is restricted to Heavy AMRs.
|
||||
"""
|
||||
item = self.rng.choice(self.zone_b_items)
|
||||
task_id = self._next_task_id("zb")
|
||||
dest = "picking_station_b1"
|
||||
deadline = sim_time + 720.0 # 12 minutes SLA
|
||||
|
||||
return Task(
|
||||
task_id=task_id,
|
||||
task_type=TaskType.OUTBOUND_PICKING,
|
||||
source=item.storage_location,
|
||||
destination=dest,
|
||||
required_payload=item.unit_weight_kg,
|
||||
item_id=item.item_id,
|
||||
quantity=1,
|
||||
release_time=sim_time,
|
||||
deadline=deadline,
|
||||
priority=TaskPriority.MEDIUM.value, # Priority 3 (heavier component)
|
||||
target_zone="zone_b", # Strict Zone B wider aisles restriction
|
||||
)
|
||||
|
||||
def generate_zone_c_task(self, sim_time: float) -> Task:
|
||||
"""Generate a scheduled production-line material feed task in Zone C."""
|
||||
item = self.rng.choice(self.zone_c_items)
|
||||
task_id = self._next_task_id("zc")
|
||||
dest = "production_dropoff_c1"
|
||||
deadline = sim_time + self.config.line_feed_lead_time_seconds # Strict 5-min lead time
|
||||
|
||||
return Task(
|
||||
task_id=task_id,
|
||||
task_type=TaskType.PRODUCTION_FEED,
|
||||
source=item.storage_location,
|
||||
destination=dest,
|
||||
required_payload=item.unit_weight_kg,
|
||||
item_id=item.item_id,
|
||||
quantity=1,
|
||||
release_time=sim_time,
|
||||
deadline=deadline,
|
||||
priority=TaskPriority.CRITICAL.value, # Priority 1: High-priority line feed
|
||||
target_zone="zone_c",
|
||||
)
|
||||
|
||||
def generate_replenishment_task(self, item: InventoryItem, sim_time: float) -> Task:
|
||||
"""Generate an inbound stock replenishment task when item falls below reorder point."""
|
||||
task_id = self._next_task_id("repl")
|
||||
inbound_dock = "dock_inbound_1" if self.rng.random() < 0.5 else "dock_inbound_2"
|
||||
total_weight = item.unit_weight_kg * item.replenishment_batch
|
||||
|
||||
return Task(
|
||||
task_id=task_id,
|
||||
task_type=TaskType.REPLENISHMENT,
|
||||
source=inbound_dock,
|
||||
destination=item.storage_location,
|
||||
required_payload=min(total_weight, 1200.0),
|
||||
item_id=item.item_id,
|
||||
quantity=item.replenishment_batch,
|
||||
release_time=sim_time,
|
||||
deadline=sim_time + 600.0,
|
||||
priority=TaskPriority.HIGH.value, # Priority 2: Replenishment before stock-out
|
||||
target_zone=item.zone,
|
||||
)
|
||||
@@ -0,0 +1,496 @@
|
||||
"""Discrete-event simulation engine for the Warehouse Robot Fleet Digital Twin.
|
||||
|
||||
Orchestrates:
|
||||
1. SimPy discrete-event simulation environment and master clock.
|
||||
2. Multi-zone stochastic and scheduled order arrival processes.
|
||||
3. Fleet dispatcher with AMR capability matching and wide aisle navigation in Zone B.
|
||||
4. Real-time robot agent mission execution (transit, pick, loaded transit, dropoff, opportunity charging).
|
||||
5. Inventory decrement, stock reservations, and automated replenishment triggers.
|
||||
6. Structured simulation telemetry event streaming to JSONL.
|
||||
7. High-level KPI analytics and metric aggregation.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
import networkx as nx
|
||||
import simpy
|
||||
|
||||
from warehouse_twin.domain.events import SimulationEvent, SimulationEventType
|
||||
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.routing.graph_builder import WarehouseGraphBuilder
|
||||
from warehouse_twin.simulation.dispatcher import DispatcherSettings, FleetDispatcher
|
||||
from warehouse_twin.simulation.order_generator import OrderGenerator, WorkloadConfig
|
||||
|
||||
|
||||
@dataclass
|
||||
class SimulationMetrics:
|
||||
"""Aggregated operational Key Performance Indicators (KPIs) from a simulation run."""
|
||||
duration_seconds: float = 0.0
|
||||
tasks_created: int = 0
|
||||
tasks_completed: int = 0
|
||||
tasks_cancelled: int = 0
|
||||
tasks_pending: int = 0
|
||||
throughput_tasks_per_hour: float = 0.0
|
||||
average_turnaround_time: float = 0.0
|
||||
average_wait_time: float = 0.0
|
||||
average_execution_time: float = 0.0
|
||||
on_time_delivery_percent: float = 100.0
|
||||
overdue_task_count: int = 0
|
||||
fleet_utilization_percent: float = 0.0
|
||||
total_energy_consumed_kwh: float = 0.0
|
||||
replenishment_triggers: int = 0
|
||||
robot_metrics: Dict[str, Dict[str, float]] = field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Convert metrics to a structured dictionary for reporting and JSON export."""
|
||||
return {
|
||||
"duration_seconds": round(self.duration_seconds, 2),
|
||||
"tasks_created": self.tasks_created,
|
||||
"tasks_completed": self.tasks_completed,
|
||||
"tasks_cancelled": self.tasks_cancelled,
|
||||
"tasks_pending": self.tasks_pending,
|
||||
"throughput_tasks_per_hour": round(self.throughput_tasks_per_hour, 2),
|
||||
"average_turnaround_time_seconds": round(self.average_turnaround_time, 2),
|
||||
"average_wait_time_seconds": round(self.average_wait_time, 2),
|
||||
"average_execution_time_seconds": round(self.average_execution_time, 2),
|
||||
"on_time_delivery_percent": round(self.on_time_delivery_percent, 2),
|
||||
"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),
|
||||
"replenishment_triggers": self.replenishment_triggers,
|
||||
"robot_metrics": self.robot_metrics,
|
||||
}
|
||||
|
||||
|
||||
class SimulationEnvironment:
|
||||
"""SimPy-driven discrete-event simulation coordinator for warehouse AMR fleet operations."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
warehouse: WarehouseModel,
|
||||
catalog: InventoryCatalog,
|
||||
fleet: List[Robot],
|
||||
workload_config: WorkloadConfig,
|
||||
dispatcher_settings: Optional[DispatcherSettings] = None,
|
||||
graph: Optional[nx.DiGraph] = None,
|
||||
event_log_path: Optional[Path | str] = None,
|
||||
seed: int = 42,
|
||||
) -> None:
|
||||
"""Initialize simulation environment with warehouse domain entities and SimPy clock."""
|
||||
self.env = simpy.Environment()
|
||||
self.warehouse = warehouse
|
||||
self.catalog = catalog
|
||||
self.robots: Dict[str, Robot] = {r.robot_id: r for r in fleet}
|
||||
self.workload_config = workload_config
|
||||
self.seed = seed
|
||||
|
||||
# Build or use provided graph
|
||||
if graph is not None:
|
||||
self.graph = graph
|
||||
else:
|
||||
builder = WarehouseGraphBuilder(warehouse)
|
||||
self.graph = builder.build_graph()
|
||||
|
||||
# Components
|
||||
self.generator = OrderGenerator(workload_config, catalog, warehouse, seed=seed)
|
||||
self.dispatcher = FleetDispatcher(dispatcher_settings, self.graph)
|
||||
|
||||
# Operational tracking
|
||||
self.all_tasks: Dict[str, Task] = {}
|
||||
self.completed_tasks: List[Task] = []
|
||||
self.events: List[SimulationEvent] = []
|
||||
self._event_counter: int = 0
|
||||
self.event_log_path = Path(event_log_path).resolve() if event_log_path else None
|
||||
self._log_file_handle = None
|
||||
|
||||
if self.event_log_path:
|
||||
self.event_log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._log_file_handle = open(self.event_log_path, "w", encoding="utf-8")
|
||||
|
||||
# Entity position resolver
|
||||
self._entity_positions: Dict[str, Position3D] = {}
|
||||
self._build_position_cache()
|
||||
|
||||
# SimPy wakeup event for dispatcher
|
||||
self._dispatch_trigger = self.env.event()
|
||||
|
||||
# Start master simulation processes
|
||||
self.env.process(self._zone_a_order_stream())
|
||||
self.env.process(self._zone_b_order_stream())
|
||||
self.env.process(self._zone_c_order_stream())
|
||||
self.env.process(self._dispatcher_daemon())
|
||||
|
||||
def _build_position_cache(self) -> None:
|
||||
"""Cache coordinates of racks, stations, and charging bays."""
|
||||
for loc_id, loc in self.warehouse.storage_locations.items():
|
||||
self._entity_positions[loc_id] = loc.position
|
||||
for st_id, st in self.warehouse.stations.items():
|
||||
self._entity_positions[st_id] = st.position
|
||||
for ch_id, ch in self.warehouse.charging_stations.items():
|
||||
self._entity_positions[ch_id] = ch.position
|
||||
|
||||
def get_entity_position(self, entity_id: str) -> Position3D:
|
||||
"""Resolve entity position, falling back to warehouse origin."""
|
||||
return self._entity_positions.get(entity_id, Position3D(0.0, 0.0, 0.0))
|
||||
|
||||
def record_event(
|
||||
self,
|
||||
event_type: SimulationEventType,
|
||||
robot_id: Optional[str] = None,
|
||||
task_id: Optional[str] = None,
|
||||
zone: Optional[str] = None,
|
||||
details: Optional[Dict[str, Any]] = None,
|
||||
) -> None:
|
||||
"""Record and serialize a discrete simulation telemetry event."""
|
||||
pos = None
|
||||
if robot_id and robot_id in self.robots:
|
||||
p = self.robots[robot_id].position
|
||||
pos = (p.x, p.y, p.z)
|
||||
|
||||
self._event_counter += 1
|
||||
entity = robot_id or task_id or "system"
|
||||
evt = SimulationEvent(
|
||||
event_id=f"evt_{self._event_counter:06d}",
|
||||
simulation_time=self.env.now,
|
||||
event_type=event_type,
|
||||
entity_id=entity,
|
||||
task_id=task_id,
|
||||
metadata=details or {},
|
||||
position=pos,
|
||||
zone=zone,
|
||||
)
|
||||
self.events.append(evt)
|
||||
|
||||
if self._log_file_handle:
|
||||
self._log_file_handle.write(json.dumps(evt.to_dict()) + "\n")
|
||||
self._log_file_handle.flush()
|
||||
|
||||
def _trigger_dispatch(self) -> None:
|
||||
"""Notify the dispatcher loop that new tasks or newly idle robots are available."""
|
||||
if not self._dispatch_trigger.triggered:
|
||||
self._dispatch_trigger.succeed()
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Order Arrival Processes (Zone A, Zone B, Zone C)
|
||||
# -------------------------------------------------------------------------
|
||||
def _zone_a_order_stream(self) -> Any:
|
||||
"""Stochastic Poisson arrival stream for fast-moving inventory in Zone A."""
|
||||
base_rate = self.workload_config.zone_a_arrival_rate_per_hour / 3600.0 # orders/sec
|
||||
|
||||
while True:
|
||||
# Scale by peak multiplier
|
||||
multiplier = self.generator.get_arrival_multiplier(self.env.now)
|
||||
effective_rate = max(base_rate * multiplier, 1e-4)
|
||||
interarrival = self.generator.rng.expovariate(effective_rate)
|
||||
yield self.env.timeout(interarrival)
|
||||
|
||||
task = self.generator.generate_zone_a_task(self.env.now)
|
||||
self.all_tasks[task.task_id] = task
|
||||
self.dispatcher.enqueue_task(task)
|
||||
|
||||
self.record_event(
|
||||
SimulationEventType.TASK_CREATED,
|
||||
task_id=task.task_id,
|
||||
zone="zone_a",
|
||||
details={"item_id": task.item_id, "priority": task.priority},
|
||||
)
|
||||
self._trigger_dispatch()
|
||||
|
||||
def _zone_b_order_stream(self) -> Any:
|
||||
"""Stochastic arrival stream for slow-moving heavy inventory in Zone B.
|
||||
|
||||
Navigates wider aisles (4.0m) and strictly matches Heavy AMRs.
|
||||
"""
|
||||
base_rate = self.workload_config.zone_b_arrival_rate_per_hour / 3600.0
|
||||
mean_interval = 1.0 / max(base_rate, 1e-4)
|
||||
|
||||
while True:
|
||||
multiplier = self.generator.get_arrival_multiplier(self.env.now)
|
||||
# Gaussian variation around interval (clamped)
|
||||
interval = max(20.0, self.generator.rng.gauss(mean_interval / multiplier, mean_interval * 0.2))
|
||||
yield self.env.timeout(interval)
|
||||
|
||||
task = self.generator.generate_zone_b_task(self.env.now)
|
||||
self.all_tasks[task.task_id] = task
|
||||
self.dispatcher.enqueue_task(task)
|
||||
|
||||
self.record_event(
|
||||
SimulationEventType.TASK_CREATED,
|
||||
task_id=task.task_id,
|
||||
zone="zone_b",
|
||||
details={"item_id": task.item_id, "weight_kg": task.payload_weight, "priority": task.priority},
|
||||
)
|
||||
self._trigger_dispatch()
|
||||
|
||||
def _zone_c_order_stream(self) -> Any:
|
||||
"""Scheduled deterministic batch deliveries feeding production lines in Zone C."""
|
||||
interval = self.workload_config.zone_c_scheduled_feed_interval_seconds
|
||||
|
||||
# Initial offset
|
||||
yield self.env.timeout(60.0)
|
||||
|
||||
while True:
|
||||
task = self.generator.generate_zone_c_task(self.env.now)
|
||||
self.all_tasks[task.task_id] = task
|
||||
self.dispatcher.enqueue_task(task)
|
||||
|
||||
self.record_event(
|
||||
SimulationEventType.TASK_CREATED,
|
||||
task_id=task.task_id,
|
||||
zone="zone_c",
|
||||
details={"item_id": task.item_id, "deadline": task.deadline, "priority": task.priority},
|
||||
)
|
||||
self._trigger_dispatch()
|
||||
yield self.env.timeout(interval)
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Dispatcher Daemon
|
||||
# -------------------------------------------------------------------------
|
||||
def _dispatcher_daemon(self) -> Any:
|
||||
"""Continuous dispatcher loop matching pending tasks to idle, compatible AMRs."""
|
||||
while True:
|
||||
# Wait for event trigger or periodic tick (2.0s)
|
||||
yield self.env.any_of([self._dispatch_trigger, self.env.timeout(2.0)])
|
||||
self._dispatch_trigger = self.env.event()
|
||||
|
||||
dispatches = self.dispatcher.dispatch_next_batch(list(self.robots.values()), self.env.now)
|
||||
for robot, task in dispatches:
|
||||
self.record_event(
|
||||
SimulationEventType.TASK_ASSIGNED,
|
||||
robot_id=robot.robot_id,
|
||||
task_id=task.task_id,
|
||||
details={"priority": task.priority, "source": task.source_station, "dest": task.destination_station},
|
||||
)
|
||||
self.env.process(self._robot_mission_process(robot, task))
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Robot Mission Execution Process
|
||||
# -------------------------------------------------------------------------
|
||||
def _robot_mission_process(self, robot: Robot, task: Task) -> Any:
|
||||
"""Execute full operational mission lifecycle for an assigned robot and task."""
|
||||
# ---------------------------------------------------------------------
|
||||
# 1. Travel to Pickup Location (Empty Transit)
|
||||
# ---------------------------------------------------------------------
|
||||
src_pos = self.get_entity_position(task.source_station)
|
||||
dist_to_src = self.dispatcher.calculate_distance(robot.position, task.source_station)
|
||||
speed = min(robot.maximum_speed, 1.5)
|
||||
transit_time_empty = max(dist_to_src / speed, 1.0)
|
||||
|
||||
robot.transition_to(RobotState.DISPATCHED, self.env.now)
|
||||
self.record_event(
|
||||
SimulationEventType.ROBOT_DISPATCHED,
|
||||
robot_id=robot.robot_id,
|
||||
task_id=task.task_id,
|
||||
details={"dist_meters": round(dist_to_src, 2), "eta_seconds": round(transit_time_empty, 2)},
|
||||
)
|
||||
|
||||
yield self.env.timeout(transit_time_empty)
|
||||
|
||||
# Update robot position and consume empty moving power
|
||||
robot.position = src_pos
|
||||
robot.accumulated_distance += dist_to_src
|
||||
robot.consume_energy(transit_time_empty, mode="moving_empty")
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# 2. Pickup / Loading Operation
|
||||
# ---------------------------------------------------------------------
|
||||
robot.transition_to(RobotState.PICKING, self.env.now)
|
||||
task.start_execution(self.env.now)
|
||||
|
||||
pick_duration = self.workload_config.pickup_time_seconds
|
||||
if task.payload_weight > 150.0:
|
||||
pick_duration += self.workload_config.heavy_pickup_overhead_seconds
|
||||
|
||||
self.record_event(
|
||||
SimulationEventType.ROBOT_ARRIVED,
|
||||
robot_id=robot.robot_id,
|
||||
task_id=task.task_id,
|
||||
details={"station": task.source_station, "duration": pick_duration},
|
||||
)
|
||||
|
||||
yield self.env.timeout(pick_duration)
|
||||
|
||||
# Consume idle/loading power
|
||||
robot.consume_energy(pick_duration, mode="idle")
|
||||
|
||||
# Handle inventory reservation and consumption
|
||||
if task.item_id and task.item_id in self.catalog.items:
|
||||
item = self.catalog.items[task.item_id]
|
||||
if task.task_type == TaskType.REPLENISHMENT:
|
||||
# Restocking operation
|
||||
item.restock(task.quantity)
|
||||
else:
|
||||
# Picking operation
|
||||
if item.available_quantity >= task.quantity:
|
||||
item.reserve(task.quantity)
|
||||
item.consume(task.quantity)
|
||||
|
||||
# Check if stock triggers a replenishment order
|
||||
if item.needs_replenishment():
|
||||
repl_task = self.generator.generate_replenishment_task(item, self.env.now)
|
||||
self.all_tasks[repl_task.task_id] = repl_task
|
||||
self.dispatcher.enqueue_task(repl_task)
|
||||
self.record_event(
|
||||
SimulationEventType.INVENTORY_REPLENISHMENT_TRIGGERED,
|
||||
task_id=repl_task.task_id,
|
||||
details={"item_id": item.item_id, "current_stock": item.current_stock},
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# 3. Loaded Transit to Destination
|
||||
# ---------------------------------------------------------------------
|
||||
dst_pos = self.get_entity_position(task.destination_station)
|
||||
dist_to_dst = self.dispatcher.calculate_distance(robot.position, task.destination_station)
|
||||
# Slower speed when fully loaded
|
||||
loaded_speed = min(robot.maximum_speed * 0.85, 1.2)
|
||||
transit_time_loaded = max(dist_to_dst / loaded_speed, 1.0)
|
||||
|
||||
robot.transition_to(RobotState.LOADED_TRANSIT, self.env.now)
|
||||
yield self.env.timeout(transit_time_loaded)
|
||||
|
||||
robot.position = dst_pos
|
||||
robot.accumulated_distance += dist_to_dst
|
||||
robot.consume_energy(transit_time_loaded, mode="moving_loaded")
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# 4. Dropoff Operation
|
||||
# ---------------------------------------------------------------------
|
||||
robot.transition_to(RobotState.DROPPING, self.env.now)
|
||||
drop_duration = self.workload_config.dropoff_time_seconds
|
||||
yield self.env.timeout(drop_duration)
|
||||
|
||||
robot.consume_energy(drop_duration, mode="idle")
|
||||
|
||||
# Complete task and robot
|
||||
task.complete(self.env.now)
|
||||
robot.complete_task(self.env.now)
|
||||
self.completed_tasks.append(task)
|
||||
|
||||
self.record_event(
|
||||
SimulationEventType.TASK_COMPLETED,
|
||||
robot_id=robot.robot_id,
|
||||
task_id=task.task_id,
|
||||
details={
|
||||
"turnaround_seconds": round(task.turnaround_time() or 0.0, 2),
|
||||
"wait_seconds": round(task.waiting_time(), 2),
|
||||
"is_overdue": task.is_overdue(self.env.now),
|
||||
},
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# 5. Opportunity or Mandatory Charging
|
||||
# ---------------------------------------------------------------------
|
||||
if robot.battery_percent < 25.0:
|
||||
yield self.env.process(self._robot_recharge_process(robot))
|
||||
else:
|
||||
robot.transition_to(RobotState.IDLE, self.env.now)
|
||||
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)
|
||||
dist = robot.position.distance_to(ch_pos)
|
||||
transit_time = max(dist / robot.maximum_speed, 2.0)
|
||||
|
||||
robot.transition_to(RobotState.TRANSIT_TO_CHARGE, self.env.now)
|
||||
yield self.env.timeout(transit_time)
|
||||
|
||||
robot.position = ch_pos
|
||||
robot.transition_to(RobotState.CHARGING, self.env.now)
|
||||
self.record_event(
|
||||
SimulationEventType.ROBOT_CHARGING_START,
|
||||
robot_id=robot.robot_id,
|
||||
details={"battery_percent": round(robot.battery_percent, 1), "charger": ch_id},
|
||||
)
|
||||
|
||||
# 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)
|
||||
|
||||
robot.charge_energy(charge_duration, charging_rate_kw=10.0)
|
||||
robot.transition_to(RobotState.IDLE, self.env.now)
|
||||
self.record_event(
|
||||
SimulationEventType.ROBOT_CHARGING_COMPLETE,
|
||||
robot_id=robot.robot_id,
|
||||
details={"battery_percent": round(robot.battery_percent, 1)},
|
||||
)
|
||||
self._trigger_dispatch()
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Execution & KPI Collection
|
||||
# -------------------------------------------------------------------------
|
||||
def run(self, until: float = 3600.0) -> SimulationMetrics:
|
||||
"""Run discrete-event simulation until specified duration and return collected KPIs."""
|
||||
self.env.run(until=until)
|
||||
if self._log_file_handle:
|
||||
self._log_file_handle.close()
|
||||
self._log_file_handle = None
|
||||
|
||||
return self.collect_metrics()
|
||||
|
||||
def collect_metrics(self) -> SimulationMetrics:
|
||||
"""Compute aggregate throughput, latency, fleet utilization, and energy KPIs."""
|
||||
sim_duration = max(self.env.now, 1.0)
|
||||
total_created = len(self.all_tasks)
|
||||
total_completed = len(self.completed_tasks)
|
||||
throughput_hr = (total_completed / sim_duration) * 3600.0
|
||||
|
||||
turnarounds = [t.turnaround_time() for t in self.completed_tasks if t.turnaround_time() is not None]
|
||||
waits = [t.waiting_time() for t in self.completed_tasks]
|
||||
execs = [t.execution_time() for t in self.completed_tasks if t.execution_time() is not None]
|
||||
|
||||
avg_turnaround = sum(turnarounds) / len(turnarounds) if turnarounds else 0.0
|
||||
avg_wait = sum(waits) / len(waits) if waits else 0.0
|
||||
avg_exec = sum(execs) / len(execs) if execs else 0.0
|
||||
|
||||
overdue_count = sum(1 for t in self.completed_tasks if t.is_overdue(self.env.now))
|
||||
on_time_pct = ((total_completed - overdue_count) / total_completed * 100.0) if total_completed > 0 else 100.0
|
||||
|
||||
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()
|
||||
)
|
||||
|
||||
repl_count = sum(
|
||||
1 for e in self.events if e.event_type == SimulationEventType.INVENTORY_REPLENISHMENT_TRIGGERED
|
||||
)
|
||||
|
||||
r_metrics: Dict[str, Dict[str, float]] = {}
|
||||
for r_id, r in self.robots.items():
|
||||
r_metrics[r_id] = {
|
||||
"distance_meters": round(r.accumulated_distance, 2),
|
||||
"busy_seconds": round(r.busy_time, 2),
|
||||
"battery_percent": round(r.battery_percent, 1),
|
||||
"utilization_percent": round((r.busy_time / sim_duration) * 100.0, 1),
|
||||
}
|
||||
|
||||
return SimulationMetrics(
|
||||
duration_seconds=sim_duration,
|
||||
tasks_created=total_created,
|
||||
tasks_completed=total_completed,
|
||||
tasks_cancelled=0,
|
||||
tasks_pending=self.dispatcher.queue_length,
|
||||
throughput_tasks_per_hour=throughput_hr,
|
||||
average_turnaround_time=avg_turnaround,
|
||||
average_wait_time=avg_wait,
|
||||
average_execution_time=avg_exec,
|
||||
on_time_delivery_percent=on_time_pct,
|
||||
overdue_task_count=overdue_count,
|
||||
fleet_utilization_percent=fleet_util,
|
||||
total_energy_consumed_kwh=total_energy,
|
||||
replenishment_triggers=repl_count,
|
||||
robot_metrics=r_metrics,
|
||||
)
|
||||
Reference in New Issue
Block a user