feat(phase-1): implement warehouse domain models, topological graph builder, connectivity validation, and export

This commit is contained in:
Warehouse Twin Dev
2026-10-19 15:12:38 +05:30
parent 7ef65ce65d
commit 88b922a3e1
13 changed files with 1535 additions and 50 deletions
+105
View File
@@ -111,6 +111,83 @@ def validate_config(config_dir: Optional[str] = None) -> int:
return 1
def validate_graph(config_dir: Optional[str] = None) -> int:
"""Build and validate the warehouse navigation graph and station connectivity."""
setup_logging()
logger = get_logger("cli")
try:
from warehouse_twin.routing.graph_builder import (
WarehouseGraphBuilder,
WarehouseGraphError,
)
loader = ConfigLoader(config_dir)
bundle = loader.load_all()
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
print("Building warehouse floor topological graph...")
graph = builder.build_graph()
report = builder.validate_connectivity(graph)
print("=" * 65)
print("Warehouse Navigation Graph Verification Report")
print("=" * 65)
print(f"Total Nodes: {report.total_nodes}")
print(f"Total Directed Edges: {report.total_edges}")
print(f"Strongly Connected: {report.is_strongly_connected}")
print(f"Connected Components: {report.component_count}")
print(f"Total Traversable Lanes: {report.total_lane_length_meters:.1f} meters")
print(f"Operational Stations: {report.stations_reachable} / {report.total_stations} reachable")
print(f"Charging Bays: {report.chargers_reachable} / {report.total_chargers} reachable")
print(f"Storage Racks: {report.storage_racks_reachable} / {report.total_storage_racks} reachable")
print("-" * 65)
print("Zone Node Distribution:")
for z_name, count in sorted(report.zone_node_distribution.items()):
print(f" - {z_name:12s}: {count:3d} nodes")
print("-" * 65)
print("Robot Type Accessibility:")
for r_type, status in report.robot_type_reachability.items():
status_str = "[OK] Validated" if status else "[WARN] Restricted"
print(f" - {r_type:12s}: {status_str}")
print("=" * 65)
print("Graph topology verification passed successfully!")
return 0
except WarehouseGraphError as err:
logger.error("Graph validation failed: %s", err)
print(f"[FAIL] Graph Error: {err}", file=sys.stderr)
return 1
def export_graph(config_dir: Optional[str] = None, output_path: Optional[str] = None) -> int:
"""Build and export the warehouse graph to a structured JSON file."""
setup_logging()
logger = get_logger("cli")
try:
from warehouse_twin.routing.graph_builder import (
WarehouseGraphBuilder,
WarehouseGraphError,
)
loader = ConfigLoader(config_dir)
bundle = loader.load_all()
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
graph = builder.build_graph()
builder.validate_connectivity(graph)
default_out = Path("results/reports/warehouse_graph.json")
out_file = Path(output_path).resolve() if output_path else default_out.resolve()
saved_path = builder.export_json(out_file, graph)
print(f"Exported warehouse graph ({graph.number_of_nodes()} nodes, {graph.number_of_edges()} edges) to:")
print(f" -> {saved_path}")
return 0
except WarehouseGraphError as err:
logger.error("Graph export failed: %s", err)
print(f"[FAIL] Graph Export Error: {err}", file=sys.stderr)
return 1
def main(argv: Optional[list[str]] = None) -> int:
"""Main CLI entry point."""
parser = argparse.ArgumentParser(
@@ -137,12 +214,40 @@ def main(argv: Optional[list[str]] = None) -> int:
help="Path to directory containing configuration JSON files",
)
# Subcommand: validate-graph
graph_val_parser = subparsers.add_parser("validate-graph", help="Build and validate warehouse graph connectivity")
graph_val_parser.add_argument(
"--config-dir",
type=str,
default=None,
help="Path to directory containing configuration JSON files",
)
# Subcommand: export-graph
graph_exp_parser = subparsers.add_parser("export-graph", help="Build and export warehouse graph to JSON")
graph_exp_parser.add_argument(
"--config-dir",
type=str,
default=None,
help="Path to directory containing configuration JSON files",
)
graph_exp_parser.add_argument(
"--output",
type=str,
default=None,
help="Output JSON file path (defaults to results/reports/warehouse_graph.json)",
)
args = parser.parse_args(argv)
if args.command == "validate-env":
return check_environment()
elif args.command == "validate-config":
return validate_config(args.config_dir)
elif args.command == "validate-graph":
return validate_graph(args.config_dir)
elif args.command == "export-graph":
return export_graph(args.config_dir, args.output)
else:
parser.print_help()
return 0
+16
View File
@@ -93,6 +93,22 @@ class ConfigLoader:
if "charging_stations" not in data or not isinstance(data["charging_stations"], list):
raise ConfigurationError("warehouse.json missing 'charging_stations' list.")
if "storage_locations" in data:
if not isinstance(data["storage_locations"], list):
raise ConfigurationError("warehouse.json 'storage_locations' must be a list.")
known_zones = set(data["zones"].keys())
for loc in data["storage_locations"]:
if "location_id" not in loc or not loc["location_id"]:
raise ConfigurationError("warehouse.json storage location missing 'location_id'.")
if "zone" not in loc or loc["zone"] not in known_zones:
raise ConfigurationError(
f"warehouse.json storage location '{loc.get('location_id')}' references unknown zone '{loc.get('zone')}'."
)
if "position" not in loc or len(loc["position"]) != 3:
raise ConfigurationError(
f"warehouse.json storage location '{loc.get('location_id')}' must specify a 3D [x, y, z] position."
)
def validate_robots(self, data: Dict[str, Any]) -> None:
"""Validate robot specifications and fleet registry."""
if "robot_types" not in data or not isinstance(data["robot_types"], dict) or not data["robot_types"]:
+31
View File
@@ -0,0 +1,31 @@
"""Domain models for Warehouse Robot Fleet Digital Twin."""
from warehouse_twin.domain.warehouse import (
ChargingStation,
NodeType,
Position3D,
Station,
StationType,
StorageLocation,
WarehouseDimensions,
WarehouseEdge,
WarehouseModel,
WarehouseNode,
ZoneArea,
ZoneDefinition,
)
__all__ = [
"ChargingStation",
"NodeType",
"Position3D",
"Station",
"StationType",
"StorageLocation",
"WarehouseDimensions",
"WarehouseEdge",
"WarehouseModel",
"WarehouseNode",
"ZoneArea",
"ZoneDefinition",
]
+231
View File
@@ -0,0 +1,231 @@
"""Warehouse domain models: spatial dimensions, zones, stations, and nodes."""
from __future__ import annotations
import math
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, List, Optional, Set, Tuple
class NodeType(str, Enum):
"""Categorization of warehouse graph vertices."""
WAYPOINT = "waypoint"
STORAGE_RACK = "storage_rack"
INBOUND_DOCK = "inbound_dock"
OUTBOUND_DOCK = "outbound_dock"
PICKING_STATION = "picking_station"
PRODUCTION_FEED = "production_feed"
CHARGING_BAY = "charging_bay"
class StationType(str, Enum):
"""Types of fixed operational stations."""
INBOUND_DOCK = "inbound_dock"
OUTBOUND_DOCK = "outbound_dock"
PICKING_STATION = "picking_station"
PRODUCTION_FEED = "production_feed"
@dataclass(frozen=True)
class Position3D:
"""3D Cartesian position in meters (X=East/Width, Y=North/Depth, Z=Up/Height)."""
x: float
y: float
z: float = 0.0
def distance_to(self, other: Position3D) -> float:
"""Calculate Euclidean distance to another 3D position."""
return math.sqrt(
(self.x - other.x) ** 2 +
(self.y - other.y) ** 2 +
(self.z - other.z) ** 2
)
def to_tuple(self) -> Tuple[float, float, float]:
"""Convert to a 3-element tuple."""
return (self.x, self.y, self.z)
def to_list(self) -> List[float]:
"""Convert to a 3-element list."""
return [self.x, self.y, self.z]
@classmethod
def from_iterable(cls, coords: Any) -> Position3D:
"""Create Position3D from list, tuple, or dict."""
if isinstance(coords, (list, tuple)):
z_val = coords[2] if len(coords) > 2 else 0.0
return cls(float(coords[0]), float(coords[1]), float(z_val))
elif isinstance(coords, dict):
return cls(float(coords["x"]), float(coords["y"]), float(coords.get("z", 0.0)))
raise ValueError(f"Cannot construct Position3D from {coords!r}")
@dataclass(frozen=True)
class WarehouseDimensions:
"""Bounding dimensions of warehouse interior in meters."""
width: float
depth: float
height: float
@dataclass(frozen=True)
class ZoneArea:
"""Rectangular 2D bounding box defining an inventory zone."""
x_min: float
x_max: float
y_min: float
y_max: float
def contains(self, pos: Position3D) -> bool:
"""Check if position is inside the zone boundaries."""
return (
self.x_min <= pos.x <= self.x_max and
self.y_min <= pos.y <= self.y_max
)
@dataclass(frozen=True)
class ZoneDefinition:
"""Inventory zone configuration and physical constraints."""
zone_id: str
name: str
description: str
area: ZoneArea
aisle_width: float
max_robot_speed: float
@dataclass
class Station:
"""Physical interaction station (dock, picking point, or assembly drop-off)."""
station_id: str
station_type: StationType
position: Position3D
capacity: int = 1
nearest_node_id: Optional[str] = None
@dataclass
class ChargingStation:
"""AMR charging station with power output rating and queue capacity."""
station_id: str
position: Position3D
charging_rate_kw: float
capacity: int = 1
nearest_node_id: Optional[str] = None
@dataclass
class StorageLocation:
"""Rack storage location for an inventory SKU."""
location_id: str
zone: str
position: Position3D
aisle_id: str = ""
nearest_node_id: Optional[str] = None
@dataclass
class WarehouseNode:
"""Topological graph vertex representing a traversable point or station access point."""
node_id: str
position: Position3D
node_type: NodeType
zone: str
allowed_robot_types: Set[str] = field(default_factory=set)
@dataclass
class WarehouseEdge:
"""Topological graph directed edge between two traversable vertices."""
source: str
target: str
distance: float
speed_limit: float
traversal_time: float
is_one_way: bool = False
allowed_robot_types: Set[str] = field(default_factory=set)
@dataclass
class WarehouseModel:
"""Complete in-memory model of warehouse floor physical layout."""
dimensions: WarehouseDimensions
zones: Dict[str, ZoneDefinition]
stations: Dict[str, Station]
charging_stations: Dict[str, ChargingStation]
storage_locations: Dict[str, StorageLocation]
coordinate_system: Dict[str, Any] = field(default_factory=dict)
grid_spacing: float = 2.0
corridor_speed_limit: float = 1.8
@classmethod
def from_config_dict(cls, data: Dict[str, Any]) -> WarehouseModel:
"""Factory constructor building WarehouseModel from validated dictionary."""
dims = WarehouseDimensions(
width=float(data["dimensions"]["width"]),
depth=float(data["dimensions"]["depth"]),
height=float(data["dimensions"]["height"]),
)
zones: Dict[str, ZoneDefinition] = {}
for z_id, z_data in data.get("zones", {}).items():
area_data = z_data["area"]
area = ZoneArea(
x_min=float(area_data["x_min"]),
x_max=float(area_data["x_max"]),
y_min=float(area_data["y_min"]),
y_max=float(area_data["y_max"]),
)
zones[z_id] = ZoneDefinition(
zone_id=z_id,
name=z_data["name"],
description=z_data.get("description", ""),
area=area,
aisle_width=float(z_data.get("aisle_width", 2.5)),
max_robot_speed=float(z_data.get("max_robot_speed", 1.5)),
)
stations: Dict[str, Station] = {}
for st_data in data.get("stations", []):
st_type = StationType(st_data["type"])
st = Station(
station_id=st_data["station_id"],
station_type=st_type,
position=Position3D.from_iterable(st_data["position"]),
capacity=int(st_data.get("capacity", 1)),
)
stations[st.station_id] = st
chargers: Dict[str, ChargingStation] = {}
for ch_data in data.get("charging_stations", []):
ch = ChargingStation(
station_id=ch_data["station_id"],
position=Position3D.from_iterable(ch_data["position"]),
charging_rate_kw=float(ch_data.get("charging_rate_kw", 25.0)),
capacity=int(ch_data.get("capacity", 1)),
)
chargers[ch.station_id] = ch
storage: Dict[str, StorageLocation] = {}
for loc_data in data.get("storage_locations", []):
loc = StorageLocation(
location_id=loc_data["location_id"],
zone=loc_data["zone"],
position=Position3D.from_iterable(loc_data["position"]),
aisle_id=loc_data.get("aisle_id", ""),
)
storage[loc.location_id] = loc
grid_cfg = data.get("grid", {})
return cls(
dimensions=dims,
zones=zones,
stations=stations,
charging_stations=chargers,
storage_locations=storage,
coordinate_system=data.get("coordinate_system", {}),
grid_spacing=float(grid_cfg.get("node_spacing", 2.0)),
corridor_speed_limit=float(grid_cfg.get("corridor_speed_limit", 1.8)),
)
+17
View File
@@ -0,0 +1,17 @@
"""Routing and warehouse topology package for Warehouse Digital Twin."""
from warehouse_twin.routing.graph_builder import (
ConnectivityReport,
DisconnectedGraphError,
UnreachableStationError,
WarehouseGraphBuilder,
WarehouseGraphError,
)
__all__ = [
"ConnectivityReport",
"DisconnectedGraphError",
"UnreachableStationError",
"WarehouseGraphBuilder",
"WarehouseGraphError",
]
+559
View File
@@ -0,0 +1,559 @@
"""Warehouse graph builder: transforms layout geometry into a directed navigation graph."""
from __future__ import annotations
import json
import math
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple
import networkx as nx
from warehouse_twin.domain.warehouse import (
ChargingStation,
NodeType,
Position3D,
Station,
StorageLocation,
WarehouseModel,
ZoneDefinition,
)
class WarehouseGraphError(Exception):
"""Base exception for warehouse graph generation and validation errors."""
pass
class DisconnectedGraphError(WarehouseGraphError):
"""Raised when the warehouse graph contains disconnected components."""
pass
class UnreachableStationError(WarehouseGraphError):
"""Raised when a required operational station, rack, or charger cannot be reached."""
pass
@dataclass
class ConnectivityReport:
"""Diagnostic report detailing graph structure and reachability metrics."""
total_nodes: int
total_edges: int
is_strongly_connected: bool
component_count: int
stations_reachable: int
total_stations: int
chargers_reachable: int
total_chargers: int
storage_racks_reachable: int
total_storage_racks: int
zone_node_distribution: Dict[str, int]
total_lane_length_meters: float
robot_type_reachability: Dict[str, bool] = field(default_factory=dict)
class WarehouseGraphBuilder:
"""Constructs, validates, and serializes a NetworkX DiGraph from a WarehouseModel."""
def __init__(self, model: WarehouseModel) -> None:
"""Initialize builder with a validated WarehouseModel."""
self.model = model
@classmethod
def from_config_dict(cls, config_dict: Dict[str, Any]) -> WarehouseGraphBuilder:
"""Convenience factory creating a builder from a raw configuration dictionary."""
model = WarehouseModel.from_config_dict(config_dict)
return cls(model)
def _determine_zone_for_point(self, pos: Position3D) -> str:
"""Determine which zone encompasses the given point, or 'transit' if in corridors."""
for zone_id, zone in self.model.zones.items():
if zone.area.contains(pos):
return zone_id
return "transit"
def _get_speed_limit(self, zone_id: str) -> float:
"""Retrieve maximum allowable velocity for a given zone or corridor."""
if zone_id in self.model.zones:
return self.model.zones[zone_id].max_robot_speed
return self.model.corridor_speed_limit
def build_graph(self) -> nx.DiGraph:
"""Generate a complete, directed navigation graph for the warehouse floor.
Constructs:
1. Perimeter highways: West dock corridor, South picking highway, North charger/feed highway.
2. Inter-zone transfer corridors: Vertical arteries at x=26.0 and x=46.0 between zones.
3. Zone grid networks: Traversable grid nodes and aisles within Zone A, Zone B, and Zone C.
4. Operational stations: Inbound/outbound docks, picking stations, production feed.
5. Charging bays: Connected to the North-West charging lane.
6. Storage racks: Connected to nearest traversable zone nodes.
"""
graph = nx.DiGraph()
spacing = self.model.grid_spacing
coord_to_node: Dict[Tuple[float, float], str] = {}
def get_or_add_waypoint(x: float, y: float, zone_id: str = "transit") -> str:
key = (round(float(x), 1), round(float(y), 1))
if key not in coord_to_node:
nid = f"wp_{int(round(key[0] * 10))}_{int(round(key[1] * 10))}"
coord_to_node[key] = nid
graph.add_node(
nid,
pos=(key[0], key[1], 0.0),
node_type=NodeType.WAYPOINT.value,
zone=zone_id,
x=key[0],
y=key[1],
z=0.0,
)
return coord_to_node[key]
def add_bidirectional_edge(
u: str,
v: str,
distance_override: Optional[float] = None,
allowed_types: Optional[Set[str]] = None,
speed_override: Optional[float] = None,
) -> None:
if u == v or not graph.has_node(u) or not graph.has_node(v):
return
u_pos = Position3D.from_iterable(graph.nodes[u]["pos"])
v_pos = Position3D.from_iterable(graph.nodes[v]["pos"])
dist = distance_override if distance_override is not None else max(u_pos.distance_to(v_pos), 0.2)
zone_u = graph.nodes[u].get("zone", "transit")
zone_v = graph.nodes[v].get("zone", "transit")
edge_zone = zone_u if zone_u == zone_v else "transit"
speed = speed_override or min(
self._get_speed_limit(zone_u),
self._get_speed_limit(zone_v)
)
traversal_time = dist / max(speed, 0.1)
types = allowed_types if allowed_types is not None else (
{"heavy_amr"} if edge_zone == "zone_b" else {"light_amr", "heavy_amr"}
)
for src, dst in ((u, v), (v, u)):
graph.add_edge(
src,
dst,
distance=round(dist, 3),
speed_limit=round(speed, 2),
traversal_time=round(traversal_time, 3),
is_one_way=False,
allowed_robot_types=types,
zone=edge_zone,
)
# -------------------------------------------------------------------------
# 1. Main Arterial Corridors & Highways
# -------------------------------------------------------------------------
# Vertical corridor lines at x=2.0 (West dock lane), x=26.0 (A-B transfer),
# x=46.0 (B-C transfer), and x=58.0 (East perimeter).
corridor_xs = [2.0, 26.0, 46.0, 58.0]
corridor_ys = [2.0, 38.0]
# Build vertical corridors
for x in corridor_xs:
cur_y = corridor_ys[0]
prev_node = None
while cur_y <= corridor_ys[1] + 1e-4:
wp = get_or_add_waypoint(x, cur_y, "transit")
if prev_node:
add_bidirectional_edge(prev_node, wp)
prev_node = wp
cur_y += spacing
# Build horizontal highways (South y=2.0 and North y=38.0)
for y in corridor_ys:
cur_x = 2.0
prev_node = None
while cur_x <= 58.0 + 1e-4:
wp = get_or_add_waypoint(cur_x, y, "transit")
if prev_node:
add_bidirectional_edge(prev_node, wp)
prev_node = wp
cur_x += spacing
# -------------------------------------------------------------------------
# 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"}),
]
for zid, x_min, x_max, y_min, y_max, allowed in zone_bounds:
z_speed = self._get_speed_limit(zid)
col_nodes: List[List[str]] = []
cur_x = x_min
while cur_x <= x_max + 1e-4:
col: List[str] = []
cur_y = y_min
while cur_y <= y_max + 1e-4:
wp = get_or_add_waypoint(cur_x, cur_y, zid)
col.append(wp)
cur_y += spacing
col_nodes.append(col)
cur_x += spacing
# Vertical edges along aisles within zone
for col in col_nodes:
for i in range(len(col) - 1):
add_bidirectional_edge(col[i], col[i+1], allowed_types=allowed, speed_override=z_speed)
# Horizontal cross-aisles within zone
for i in range(len(col_nodes) - 1):
col_a = col_nodes[i]
col_b = col_nodes[i+1]
for j in range(min(len(col_a), len(col_b))):
add_bidirectional_edge(col_a[j], col_b[j], allowed_types=allowed, speed_override=z_speed)
# Connect South end of zone aisles to South Highway (y=2.0 via y=4.0)
for col in col_nodes:
if col:
s_node = col[0]
sp = Position3D.from_iterable(graph.nodes[s_node]["pos"])
inter_wp = get_or_add_waypoint(sp.x, 4.0, "transit")
hway_wp = get_or_add_waypoint(sp.x, 2.0, "transit")
add_bidirectional_edge(s_node, inter_wp, allowed_types=allowed, speed_override=z_speed)
add_bidirectional_edge(inter_wp, hway_wp, allowed_types=allowed)
# Connect North end of zone aisles to North Highway (y=38.0 via y=36.0)
for col in col_nodes:
if col:
n_node = col[-1]
np = Position3D.from_iterable(graph.nodes[n_node]["pos"])
inter_wp = get_or_add_waypoint(np.x, 36.0, "transit")
hway_wp = get_or_add_waypoint(np.x, 38.0, "transit")
add_bidirectional_edge(n_node, inter_wp, allowed_types=allowed, speed_override=z_speed)
add_bidirectional_edge(inter_wp, hway_wp, allowed_types=allowed)
# Helper to find nearest waypoint to any target position
def find_nearest_waypoint(target_pos: Position3D, zone_filter: Optional[str] = None) -> Tuple[str, float]:
best_nid = None
min_dist = float("inf")
for nid, data in graph.nodes(data=True):
if data.get("node_type") != NodeType.WAYPOINT.value:
continue
if zone_filter and data.get("zone") != zone_filter:
continue
cand_pos = Position3D.from_iterable(data["pos"])
d = target_pos.distance_to(cand_pos)
if d < min_dist:
min_dist = d
best_nid = nid
if best_nid is None and zone_filter:
# Fallback to any waypoint if zone filter had no matches
return find_nearest_waypoint(target_pos, zone_filter=None)
return best_nid or next(iter(graph.nodes)), min_dist
# -------------------------------------------------------------------------
# 3. Operational Stations
# -------------------------------------------------------------------------
for st_id, st in self.model.stations.items():
node_id = f"station_{st_id}"
node_type = (
NodeType.INBOUND_DOCK if "inbound" in st.station_type.value
else NodeType.OUTBOUND_DOCK if "outbound" in st.station_type.value
else NodeType.PICKING_STATION if "picking" in st.station_type.value
else NodeType.PRODUCTION_FEED
)
graph.add_node(
node_id,
pos=st.position.to_tuple(),
node_type=node_type.value,
zone=self._determine_zone_for_point(st.position),
station_id=st_id,
capacity=st.capacity,
x=st.position.x,
y=st.position.y,
z=st.position.z,
)
st.nearest_node_id = node_id
near_wp, dist = find_nearest_waypoint(st.position)
add_bidirectional_edge(node_id, near_wp, distance_override=max(dist, 0.2))
# -------------------------------------------------------------------------
# 4. Charging Stations
# -------------------------------------------------------------------------
for ch_id, ch in self.model.charging_stations.items():
node_id = f"charger_{ch_id}"
graph.add_node(
node_id,
pos=ch.position.to_tuple(),
node_type=NodeType.CHARGING_BAY.value,
zone="transit",
station_id=ch_id,
charging_rate_kw=ch.charging_rate_kw,
capacity=ch.capacity,
x=ch.position.x,
y=ch.position.y,
z=ch.position.z,
)
ch.nearest_node_id = node_id
near_wp, dist = find_nearest_waypoint(ch.position)
add_bidirectional_edge(node_id, near_wp, distance_override=max(dist, 0.2))
# -------------------------------------------------------------------------
# 5. Storage Locations (Racks)
# -------------------------------------------------------------------------
for loc_id, loc in self.model.storage_locations.items():
node_id = f"rack_{loc_id}"
graph.add_node(
node_id,
pos=loc.position.to_tuple(),
node_type=NodeType.STORAGE_RACK.value,
zone=loc.zone,
location_id=loc_id,
aisle_id=loc.aisle_id,
x=loc.position.x,
y=loc.position.y,
z=loc.position.z,
)
loc.nearest_node_id = node_id
near_wp, dist = find_nearest_waypoint(loc.position, zone_filter=loc.zone)
allowed = {"heavy_amr"} if loc.zone == "zone_b" else {"light_amr", "heavy_amr"}
add_bidirectional_edge(
node_id,
near_wp,
distance_override=max(dist, 0.2),
allowed_types=allowed,
speed_override=self._get_speed_limit(loc.zone),
)
return graph
def validate_connectivity(
self,
graph: nx.DiGraph,
robot_types: Optional[List[str]] = None,
) -> ConnectivityReport:
"""Thoroughly validate topological graph reachability and structural constraints.
Verifies:
1. Graph has non-zero nodes and edges.
2. All operational stations, charging bays, and storage racks are connected.
3. Strongly connected components (for unrestricted robots).
4. Reachability from every inbound dock to every storage rack and outbound station.
5. Robot type specific accessibility (e.g. Zone B accessibility for heavy_amr).
Raises:
DisconnectedGraphError: If isolated subgraphs exist.
UnreachableStationError: If any station or charger cannot be reached.
"""
if graph.number_of_nodes() == 0:
raise WarehouseGraphError("Warehouse graph contains 0 nodes.")
# Total traversable lane length
total_len = sum(d.get("distance", 0.0) for _, _, d in graph.edges(data=True)) / 2.0
# Check strong connectivity on full graph
is_strongly_connected = nx.is_strongly_connected(graph)
num_components = nx.number_strongly_connected_components(graph)
if not is_strongly_connected:
components = list(nx.strongly_connected_components(graph))
raise DisconnectedGraphError(
f"Warehouse graph is disconnected into {num_components} separate components. "
f"Largest component has {len(max(components, key=len))} nodes out of {graph.number_of_nodes()} total nodes."
)
# Operational stations reachability check
stations_reachable = 0
total_stations = len(self.model.stations)
chargers_reachable = 0
total_chargers = len(self.model.charging_stations)
racks_reachable = 0
total_racks = len(self.model.storage_locations)
anchor_node = f"station_{next(iter(self.model.stations.keys()))}" if self.model.stations else next(iter(graph.nodes))
# Check stations
for st_id in self.model.stations:
st_node = f"station_{st_id}"
if not graph.has_node(st_node):
raise UnreachableStationError(f"Station node '{st_node}' was not created in graph.")
if not nx.has_path(graph, anchor_node, st_node) or not nx.has_path(graph, st_node, anchor_node):
raise UnreachableStationError(f"Station '{st_id}' (node '{st_node}') is unreachable from anchor '{anchor_node}'.")
stations_reachable += 1
# Check chargers
for ch_id in self.model.charging_stations:
ch_node = f"charger_{ch_id}"
if not graph.has_node(ch_node):
raise UnreachableStationError(f"Charging bay node '{ch_node}' was not created in graph.")
if not nx.has_path(graph, anchor_node, ch_node) or not nx.has_path(graph, ch_node, anchor_node):
raise UnreachableStationError(f"Charger '{ch_id}' (node '{ch_node}') is unreachable from anchor '{anchor_node}'.")
chargers_reachable += 1
# Check storage locations
for loc_id in self.model.storage_locations:
rack_node = f"rack_{loc_id}"
if not graph.has_node(rack_node):
raise UnreachableStationError(f"Storage rack node '{rack_node}' was not created in graph.")
if not nx.has_path(graph, anchor_node, rack_node) or not nx.has_path(graph, rack_node, anchor_node):
raise UnreachableStationError(f"Storage rack '{loc_id}' (node '{rack_node}') is unreachable.")
racks_reachable += 1
# Check zone node distribution
zone_counts: Dict[str, int] = {}
for _, data in graph.nodes(data=True):
z = data.get("zone", "unknown")
zone_counts[z] = zone_counts.get(z, 0) + 1
# Check robot-type specific reachability
robot_reach: Dict[str, bool] = {}
target_types = robot_types or ["light_amr", "heavy_amr"]
for r_type in target_types:
sub_edges = [
(u, v) for u, v, d in graph.edges(data=True)
if r_type in d.get("allowed_robot_types", set())
]
sub_g = graph.edge_subgraph(sub_edges)
if r_type == "heavy_amr":
all_reachable = all(
sub_g.has_node(f"station_{st}") and nx.has_path(sub_g, anchor_node, f"station_{st}")
for st in self.model.stations
) and all(
sub_g.has_node(f"rack_{loc_id}") and nx.has_path(sub_g, anchor_node, f"rack_{loc_id}")
for loc_id in self.model.storage_locations
)
robot_reach[r_type] = all_reachable
else:
# light_amr can reach Zone A and Zone C racks, but should NOT reach Zone B racks
zone_a_reachable = all(
sub_g.has_node(f"rack_{loc_id}") and nx.has_path(sub_g, anchor_node, f"rack_{loc_id}")
for loc_id, loc in self.model.storage_locations.items()
if loc.zone == "zone_a"
)
zone_b_blocked = not any(
sub_g.has_node(f"rack_{loc_id}") and nx.has_path(sub_g, anchor_node, f"rack_{loc_id}")
for loc_id, loc in self.model.storage_locations.items()
if loc.zone == "zone_b"
)
robot_reach[r_type] = zone_a_reachable and zone_b_blocked
return ConnectivityReport(
total_nodes=graph.number_of_nodes(),
total_edges=graph.number_of_edges(),
is_strongly_connected=is_strongly_connected,
component_count=num_components,
stations_reachable=stations_reachable,
total_stations=total_stations,
chargers_reachable=chargers_reachable,
total_chargers=total_chargers,
storage_racks_reachable=racks_reachable,
total_storage_racks=total_racks,
zone_node_distribution=zone_counts,
total_lane_length_meters=round(total_len, 2),
robot_type_reachability=robot_reach,
)
def export_topology_dict(self, graph: Optional[nx.DiGraph] = None) -> Dict[str, Any]:
"""Export serialized dictionary summary of graph nodes, edges, stations, and zones."""
g = graph if graph is not None else self.build_graph()
nodes_export = []
for n, d in g.nodes(data=True):
nodes_export.append({
"id": n,
"position": d.get("pos"),
"node_type": d.get("node_type"),
"zone": d.get("zone"),
})
edges_export = []
for u, v, d in g.edges(data=True):
edges_export.append({
"source": u,
"target": v,
"distance": d.get("distance"),
"speed_limit": d.get("speed_limit"),
"traversal_time": d.get("traversal_time"),
"allowed_robot_types": sorted(list(d.get("allowed_robot_types", []))),
"zone": d.get("zone"),
})
stations_export = {}
for st_id, st in self.model.stations.items():
stations_export[st_id] = {
"type": st.station_type.value,
"position": st.position.to_list(),
"node_id": st.nearest_node_id or f"station_{st_id}",
"capacity": st.capacity,
}
chargers_export = {}
for ch_id, ch in self.model.charging_stations.items():
chargers_export[ch_id] = {
"position": ch.position.to_list(),
"node_id": ch.nearest_node_id or f"charger_{ch_id}",
"charging_rate_kw": ch.charging_rate_kw,
"capacity": ch.capacity,
}
racks_export = {}
for loc_id, loc in self.model.storage_locations.items():
racks_export[loc_id] = {
"zone": loc.zone,
"position": loc.position.to_list(),
"node_id": loc.nearest_node_id or f"rack_{loc_id}",
}
return {
"metadata": {
"dimensions": {
"width": self.model.dimensions.width,
"depth": self.model.dimensions.depth,
"height": self.model.dimensions.height,
},
"coordinate_system": self.model.coordinate_system,
"node_count": g.number_of_nodes(),
"edge_count": g.number_of_edges(),
},
"zones": {
z_id: {
"name": z.name,
"max_robot_speed": z.max_robot_speed,
"aisle_width": z.aisle_width,
"area": {
"x_min": z.area.x_min,
"x_max": z.area.x_max,
"y_min": z.area.y_min,
"y_max": z.area.y_max,
},
}
for z_id, z in self.model.zones.items()
},
"stations": stations_export,
"charging_stations": chargers_export,
"storage_locations": racks_export,
"nodes": nodes_export,
"edges": edges_export,
}
def export_json(
self,
filepath: Path | str,
graph: Optional[nx.DiGraph] = None,
) -> Path:
"""Write graph topology dictionary to a formatted JSON file."""
target_path = Path(filepath).resolve()
target_path.parent.mkdir(parents=True, exist_ok=True)
data = self.export_topology_dict(graph)
with open(target_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
return target_path