feat(phase-1): implement warehouse domain models, topological graph builder, connectivity validation, and export
This commit is contained in:
@@ -5,6 +5,28 @@ All notable changes to the Warehouse Robot Fleet Digital Twin will be documented
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.2.0] - 2026-10-19
|
||||
|
||||
### Added - Phase 1: Warehouse Model
|
||||
- Complete warehouse domain entities in `warehouse_twin.domain.warehouse`: `Position3D`, `WarehouseDimensions`, `ZoneArea`, `ZoneDefinition`, `Station`, `ChargingStation`, `StorageLocation`, `WarehouseNode`, `WarehouseEdge`, and `WarehouseModel`.
|
||||
- Topological navigation graph builder (`WarehouseGraphBuilder` in `warehouse_twin.routing.graph_builder`):
|
||||
- Unified coordinate hashing producing deterministic 540-node, 1,730-edge directed graph.
|
||||
- Multi-lane perimeter highway network (West, South, North, East) and inter-zone transfer corridors at $x=26\text{m}$ and $x=46\text{m}$.
|
||||
- Detailed internal grid networks across Zone A (fast-moving), Zone B (slow-moving/heavy), and Zone C (production supply).
|
||||
- Explicit bindings for 6 stations (2 inbound docks, 1 outbound pack dock, 2 picking stations, 1 production line feed).
|
||||
- Explicit bindings for 4 fast/heavy charging bays.
|
||||
- Explicit bindings for 13 storage rack locations mapped to inventory catalog items.
|
||||
- Operational zone restrictions: Zone B aisles restricted exclusively to `heavy_amr` AMR classes.
|
||||
- Connectivity and topology verification engine (`validate_connectivity`):
|
||||
- Strong connectivity verification ($1$ strongly connected component).
|
||||
- Complete station, charger, and rack reachability verification.
|
||||
- Sub-graph robot class access verification.
|
||||
- Custom exceptions `DisconnectedGraphError` and `UnreachableStationError`.
|
||||
- JSON graph topology serialization (`export_topology_dict`, `export_json` exporting to `results/reports/warehouse_graph.json`).
|
||||
- CLI subcommands: `warehouse-twin validate-graph` and `warehouse-twin export-graph`.
|
||||
- Unit test suite expanded to 26 tests (9 new graph unit tests, 100% pass rate in 0.21s).
|
||||
- Comprehensive Phase 1 implementation report in `docs/phases/phase_1_warehouse_model.md`.
|
||||
|
||||
## [0.1.0] - 2026-10-19
|
||||
|
||||
### Added - Phase 0: Environment and Project Foundation
|
||||
|
||||
@@ -49,6 +49,25 @@ warehouse-digital-twin/
|
||||
### 2.3 CLI Interface (`warehouse_twin.cli`)
|
||||
- **`check_environment() -> int`**: Tests Python version (>=3.10), checks disk space on `/` (warns if < 10 GB, fails if < 2 GB), checks core imports (`simpy`, `networkx`, `pytest`), verifies log directory writability, and detects Kit executable.
|
||||
- **`validate_config(config_dir: Optional[str]) -> int`**: Invokes `ConfigLoader` and prints validation summaries.
|
||||
- **`validate_graph(config_dir: Optional[str]) -> int`**: Builds the `networkx.DiGraph`, validates strong connectivity, tests robot class reachability, and prints a comprehensive topology report.
|
||||
- **`export_graph(config_dir: Optional[str], output_path: Optional[str]) -> int`**: Builds and exports the serialized graph topology to JSON.
|
||||
|
||||
### 2.4 Warehouse Domain Subsystem (`warehouse_twin.domain.warehouse`)
|
||||
- **`Position3D`**: Immutable 3D Cartesian coordinates `(x, y, z)` in meters with Euclidean metric calculation (`distance_to`).
|
||||
- **`WarehouseDimensions`**: Physical warehouse bounding box in meters (`width=60m, depth=40m, height=8m`).
|
||||
- **`ZoneArea` & `ZoneDefinition`**: Rectangular bounds and physical constraints (aisle width, maximum speed limit) for Zones A, B, and C.
|
||||
- **`Station` & `ChargingStation`**: Fixed operational stations (inbound docks, outbound dock, picking stations, production drop-off) and fast/heavy charging bays.
|
||||
- **`StorageLocation`**: Inventory rack locations with zone and aisle bindings.
|
||||
- **`WarehouseModel`**: Comprehensive physical facility model instantiated from configuration data.
|
||||
|
||||
### 2.5 Routing & Topological Graph Builder (`warehouse_twin.routing.graph_builder`)
|
||||
- **`WarehouseGraphBuilder`**:
|
||||
- `build_graph() -> nx.DiGraph`: Constructs a directed navigation network with 540 nodes and 1,730 edges.
|
||||
- Coordinate hashing: Waypoint node IDs are derived from discretized coordinates `(round(x, 1), round(y, 1))` to guarantee unified intersection nodes.
|
||||
- Edge weights: Euclidean distance, speed limit, traversal time (`dist / speed`), and `allowed_robot_types`.
|
||||
- Zone B restrictions: Edge attributes enforce `allowed_robot_types = {"heavy_amr"}` for Zone B aisles.
|
||||
- **`ConnectivityReport`**: Structured metrics detailing strong connectivity, reachable stations, chargers, racks, lane length, and robot type accessibility.
|
||||
- **`WarehouseGraphError`, `DisconnectedGraphError`, `UnreachableStationError`**: Fail-fast exceptions raised upon topological violations.
|
||||
|
||||
---
|
||||
|
||||
@@ -97,7 +116,11 @@ The testing architecture adheres to the following principles:
|
||||
|
||||
---
|
||||
|
||||
## 6. Current Limitations & Next Phase
|
||||
|
||||
- **Current Limitations**: Phase 0 provides the foundational architecture, configuration validation, logging, CLI, and test runner. Domain classes (`Robot`, `Task`, `WarehouseGraph`) will be instantiated in Phases 1 and 2.
|
||||
- **Phase 1 Target**: Implement the warehouse topological graph in `warehouse_twin.domain.warehouse` and `warehouse_twin.routing.graph_builder`, populate Zones A, B, and C nodes, validate station accessibility, and export graph connectivity metrics.
|
||||
## 6. Current Status & Next Phase
|
||||
|
||||
- **Completed**: Phase 0 (Environment and Foundation) and Phase 1 (Warehouse Model). The 540-node topological navigation graph is implemented, verified for strong connectivity and robot type restrictions, tested with 26 unit tests, and serializable to JSON.
|
||||
- **Phase 2 Target**: Implement Robot and Task Domain Models (`warehouse_twin.domain.robot`, `warehouse_twin.domain.task`, `warehouse_twin.domain.inventory`):
|
||||
- Robot state machine (`IDLE`, `DISPATCHED`, `PICKING`, `LOADED_TRANSIT`, `DROPPING`, `TRANSIT_TO_CHARGE`, `CHARGING`).
|
||||
- Task state machine and priority models (`ORDER_PICK`, `REPLENISHMENT`, `PRODUCTION_LINE_FEED`, `CHARGING`).
|
||||
- Payload capacity and robot type compatibility checks.
|
||||
- Deterministic test fixtures.
|
||||
|
||||
+40
-38
@@ -1,7 +1,7 @@
|
||||
# Project Status: Warehouse Robot Fleet Digital Twin
|
||||
|
||||
**Last Updated**: October 19, 2026
|
||||
**Current Phase**: **Phase 0: Environment and Project Foundation (COMPLETED)**
|
||||
**Current Phase**: **Phase 1: Warehouse Model (COMPLETED)**
|
||||
**Status**: Ready for User Review and Approval
|
||||
|
||||
---
|
||||
@@ -10,9 +10,9 @@
|
||||
|
||||
| Phase | Description | Status | Test Coverage |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Phase 0** | **Environment and project foundation** | **COMPLETED** | **17 passed (100%)** |
|
||||
| Phase 1 | Warehouse model | Planned (Pending Phase 0 approval) | - |
|
||||
| Phase 2 | Robot and task models | Planned | - |
|
||||
| **Phase 0** | **Environment and project foundation** | **COMPLETED** | **17 passed** |
|
||||
| **Phase 1** | **Warehouse model** | **COMPLETED** | **26 passed (100%)** |
|
||||
| Phase 2 | Robot and task models | Planned (Next) | - |
|
||||
| Phase 3 | Discrete-event simulation | Planned | - |
|
||||
| Phase 4 | Routing and fleet assignment | Planned | - |
|
||||
| Phase 5 | Charging and operational constraints | Planned | - |
|
||||
@@ -23,55 +23,57 @@
|
||||
|
||||
---
|
||||
|
||||
## 2. Completed Tasks (Phase 0)
|
||||
## 2. Completed Tasks (Phase 1)
|
||||
|
||||
- [x] Host environment inspected: Ubuntu 24.04.3 LTS, Python 3.12.3, NVIDIA RTX 5090 (Driver 580.178.04), 8.9 GB free disk space.
|
||||
- [x] NVIDIA Omniverse Kit inspected: Kit 110.4.0 running with `warehouse_twin.kit` at `/home/dmhai/nvidia-omniverse/kit-app-template`.
|
||||
- [x] Verified virtual environment (`.venv`) configured with `simpy` 4.1.2, `networkx` 3.7, `pytest` 9.1.1, and `setuptools` 84.0.0.
|
||||
- [x] Package metadata created in `pyproject.toml` and installed in editable mode (`warehouse-digital-twin` v0.1.0).
|
||||
- [x] `.gitignore` and `.env.example` created with secondary disk relocation support.
|
||||
- [x] Baseline configuration files created for all 5 domains in `config/`:
|
||||
- `warehouse.json` (60x40m, Zones A, B, C, stations, chargers)
|
||||
- `robots.json` (Light AMR, Heavy AMR, battery limits, fleet)
|
||||
- `inventory.json` (Zone A fast, Zone B heavy, Zone C production raw items)
|
||||
- `simulation.json` (3600s duration, seed 42, arrival rates)
|
||||
- `dispatch_policies.json` (active policy, reservation settings)
|
||||
- [x] Structured rotating logging implemented in `src/warehouse_twin/logging_config.py` with `application.log`, `simulation.log`, and `errors.log`.
|
||||
- [x] Configuration loader with detailed schema and integrity validation implemented in `src/warehouse_twin/config/loader.py`.
|
||||
- [x] CLI entry point implemented in `src/warehouse_twin/cli.py` (`warehouse-twin validate-env`, `warehouse-twin validate-config`).
|
||||
- [x] Automated verification scripts created: `scripts/check_environment.sh`, `scripts/run_tests.sh`.
|
||||
- [x] Unit test suite implemented in `tests/unit/`:
|
||||
- `test_environment.py` (5 tests)
|
||||
- `test_logging.py` (3 tests)
|
||||
- `test_config_loader.py` (9 tests)
|
||||
- [x] Comprehensive documentation delivered in `docs/` and `docs/phases/phase_0_foundation.md`.
|
||||
- [x] Defined complete warehouse domain models in `src/warehouse_twin/domain/warehouse.py`:
|
||||
- `Position3D` with Euclidean metric and formatting.
|
||||
- `ZoneArea`, `ZoneDefinition`, `WarehouseDimensions`.
|
||||
- `Station`, `ChargingStation`, `StorageLocation`, `WarehouseNode`, `WarehouseEdge`.
|
||||
- `WarehouseModel` constructor parsing raw configuration dictionaries.
|
||||
- [x] Created `WarehouseGraphBuilder` in `src/warehouse_twin/routing/graph_builder.py`:
|
||||
- Unified coordinate hashing to guarantee deterministic waypoint alignment.
|
||||
- Perimeter highways: South ($y=2.0$), North ($y=38.0$), West ($x=2.0$), East ($x=58.0$).
|
||||
- Vertical transfer corridors: $x=26.0$ (Zone A-B transfer), $x=46.0$ (Zone B-C transfer).
|
||||
- Zone internal grid networks for Zone A ($x \in [6, 24]$), Zone B ($x \in [30, 44]$), Zone C ($x \in [48, 56]$).
|
||||
- Operational stations: 2 inbound docks, 1 outbound dock, 2 picking stations, 1 production feed.
|
||||
- Charging bays: 4 charging stations.
|
||||
- Storage racks: 13 storage locations across Zones A, B, and C.
|
||||
- [x] Enforced operational movement restrictions:
|
||||
- Zone B internal edges restricted exclusively to `{"heavy_amr"}`.
|
||||
- Transit corridors and Zones A & C accessible to both `light_amr` and `heavy_amr`.
|
||||
- [x] Implemented connectivity validation:
|
||||
- Strong connectivity verification ($1$ component).
|
||||
- Operational reachability verification ($6/6$ stations, $4/4$ chargers, $13/13$ racks).
|
||||
- Sub-graph robot class reachability verification.
|
||||
- Raised `DisconnectedGraphError` and `UnreachableStationError` on malformed graphs.
|
||||
- [x] Implemented structured JSON graph export (`results/reports/warehouse_graph.json`, 526 KB).
|
||||
- [x] Added CLI commands: `warehouse-twin validate-graph` and `warehouse-twin export-graph`.
|
||||
- [x] Implemented comprehensive unit tests in `tests/unit/test_warehouse_graph.py` (9 tests, 100% pass rate).
|
||||
- [x] Created `docs/phases/phase_1_warehouse_model.md`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Test & Validation Summary
|
||||
|
||||
- **Total Unit Tests Executed**: 17
|
||||
- **Passed**: 17
|
||||
- **Total Unit Tests Executed**: 26
|
||||
- **Passed**: 26
|
||||
- **Failed**: 0
|
||||
- **Skipped**: 0
|
||||
- **Execution Time**: 0.09s
|
||||
- **CLI Verification**: Exit code 0, 0 failures, 1 warning (low disk space).
|
||||
- **Configuration Verification**: Exit code 0, all 5 configuration files valid.
|
||||
- **Execution Time**: 0.21s
|
||||
- **Graph Topology**: 540 nodes, 1,730 directed edges, 1,692m lane length, strongly connected.
|
||||
- **CLI Commands**: `validate-env`, `validate-config`, `validate-graph`, `export-graph` all exit with code 0.
|
||||
|
||||
---
|
||||
|
||||
## 4. Known Environment Constraints & Mitigations
|
||||
|
||||
- **Constrained Primary Disk (`/dev/nvme0n1p4`)**:
|
||||
- Capacity: 886 GB total, 832 GB used, **8.9 GB free (99% used)**.
|
||||
- Mitigations:
|
||||
- Rotating file logs capped at 10 MB each with 5 backups.
|
||||
- Large generated outputs ignored in Git.
|
||||
- `WAREHOUSE_TWIN_SECONDARY_DRIVE` environment variable supported to route logs and simulation output to an external mount if configured.
|
||||
- NVIDIA Isaac Sim installation omitted as required.
|
||||
- **Primary Disk Space (`/dev/nvme0n1p4`)**: 99% used (~8.85 GB free).
|
||||
- Graph JSON export is 526 KB.
|
||||
- Logs continue to rotate under 10 MB caps.
|
||||
- Standalone architecture preserves zero dependency on Isaac Sim.
|
||||
|
||||
---
|
||||
|
||||
## 5. Next Recommended Action
|
||||
|
||||
Obtain user approval for Phase 0 completion, then begin **Phase 1: Warehouse Model** (graph representation, Zone A/B/C nodes, docks, stations, connectivity validation, and export).
|
||||
Obtain user approval for Phase 1 completion, then begin **Phase 2: Robot and Task Models** (AMR state machine, task lifecycle, payload constraints, compatibility rules, and deterministic fixtures).
|
||||
|
||||
@@ -52,19 +52,23 @@ The system decouples discrete-event simulation from 3D visualization, enabling d
|
||||
|
||||
## 3. Features Implemented & Roadmap
|
||||
|
||||
### Currently Implemented (Phase 0)
|
||||
### Currently Implemented (Phases 0 & 1)
|
||||
- [x] Host environment and Omniverse Kit template inspection.
|
||||
- [x] Decoupled project structure adhering to modular standards.
|
||||
- [x] Standard Python packaging (`pyproject.toml`) and editable install.
|
||||
- [x] Multi-target rotating file logging (`application.log`, `simulation.log`, `errors.log`).
|
||||
- [x] Robust configuration loader and schema validator for all 5 domains.
|
||||
- [x] Automated environment verification script (`scripts/check_environment.sh`).
|
||||
- [x] CLI entry point with `validate-env` and `validate-config`.
|
||||
- [x] Comprehensive unit test suite (17 passed in 0.09s).
|
||||
- [x] Low-disk-space mitigation strategy (`WAREHOUSE_TWIN_SECONDARY_DRIVE`).
|
||||
- [x] CLI entry point with `validate-env`, `validate-config`, `validate-graph`, and `export-graph`.
|
||||
- [x] Warehouse domain models (`Position3D`, `WarehouseDimensions`, `ZoneArea`, `Station`, `StorageLocation`, `WarehouseModel`).
|
||||
- [x] Topological navigation graph builder (`WarehouseGraphBuilder`) with 540 nodes and 1,730 edges.
|
||||
- [x] Operational stations, charging bays, and storage racks mapped to geometric grid nodes.
|
||||
- [x] Movement constraints: Zone B aisles restricted exclusively to `heavy_amr`.
|
||||
- [x] Strong connectivity and multi-class robot reachability validation.
|
||||
- [x] Topological graph JSON export (`results/reports/warehouse_graph.json`).
|
||||
- [x] Comprehensive unit test suite (26 passed in 0.21s).
|
||||
|
||||
### Planned Roadmap
|
||||
- **Phase 1**: Warehouse topological graph, Zone A/B/C nodes, docks, and connectivity validation.
|
||||
- **Phase 2**: AMR state machine, payload validation, and task models.
|
||||
- **Phase 3**: SimPy discrete-event simulation engine and order generation.
|
||||
- **Phase 4**: NetworkX shortest-path routing, fleet dispatching, and aisle reservations.
|
||||
@@ -134,6 +138,18 @@ warehouse-twin validate-env
|
||||
warehouse-twin validate-config
|
||||
```
|
||||
|
||||
### Validate Navigation Graph & Connectivity
|
||||
```bash
|
||||
warehouse-twin validate-graph
|
||||
```
|
||||
|
||||
### Export Warehouse Graph to JSON
|
||||
```bash
|
||||
warehouse-twin export-graph
|
||||
# Or with custom output location:
|
||||
warehouse-twin export-graph --output results/reports/custom_graph.json
|
||||
```
|
||||
|
||||
### Run Automated Tests
|
||||
```bash
|
||||
./scripts/run_tests.sh
|
||||
@@ -169,5 +185,5 @@ The visualizer connects via file-based trajectory playback:
|
||||
|
||||
## 10. Current Implementation Phase
|
||||
|
||||
**Current Phase**: **Phase 0: Environment and Project Foundation (Completed)**.
|
||||
**Next Phase**: **Phase 1: Warehouse Model** (Awaiting user confirmation).
|
||||
**Current Phase**: **Phase 1: Warehouse Model (Completed)**.
|
||||
**Next Phase**: **Phase 2: Robot and Task Models** (Awaiting user confirmation).
|
||||
|
||||
+81
-1
@@ -115,9 +115,89 @@
|
||||
"capacity": 1
|
||||
}
|
||||
],
|
||||
"storage_locations": [
|
||||
{
|
||||
"location_id": "rack_a_01",
|
||||
"zone": "zone_a",
|
||||
"position": [8.0, 10.0, 0.0],
|
||||
"aisle_id": "aisle_a_1"
|
||||
},
|
||||
{
|
||||
"location_id": "rack_a_02",
|
||||
"zone": "zone_a",
|
||||
"position": [8.0, 20.0, 0.0],
|
||||
"aisle_id": "aisle_a_1"
|
||||
},
|
||||
{
|
||||
"location_id": "rack_a_03",
|
||||
"zone": "zone_a",
|
||||
"position": [16.0, 10.0, 0.0],
|
||||
"aisle_id": "aisle_a_2"
|
||||
},
|
||||
{
|
||||
"location_id": "rack_a_04",
|
||||
"zone": "zone_a",
|
||||
"position": [16.0, 20.0, 0.0],
|
||||
"aisle_id": "aisle_a_2"
|
||||
},
|
||||
{
|
||||
"location_id": "rack_a_05",
|
||||
"zone": "zone_a",
|
||||
"position": [20.0, 30.0, 0.0],
|
||||
"aisle_id": "aisle_a_3"
|
||||
},
|
||||
{
|
||||
"location_id": "rack_b_01",
|
||||
"zone": "zone_b",
|
||||
"position": [34.0, 10.0, 0.0],
|
||||
"aisle_id": "aisle_b_1"
|
||||
},
|
||||
{
|
||||
"location_id": "rack_b_02",
|
||||
"zone": "zone_b",
|
||||
"position": [34.0, 22.0, 0.0],
|
||||
"aisle_id": "aisle_b_1"
|
||||
},
|
||||
{
|
||||
"location_id": "rack_b_03",
|
||||
"zone": "zone_b",
|
||||
"position": [40.0, 10.0, 0.0],
|
||||
"aisle_id": "aisle_b_2"
|
||||
},
|
||||
{
|
||||
"location_id": "rack_b_04",
|
||||
"zone": "zone_b",
|
||||
"position": [40.0, 22.0, 0.0],
|
||||
"aisle_id": "aisle_b_2"
|
||||
},
|
||||
{
|
||||
"location_id": "rack_c_01",
|
||||
"zone": "zone_c",
|
||||
"position": [50.0, 10.0, 0.0],
|
||||
"aisle_id": "aisle_c_1"
|
||||
},
|
||||
{
|
||||
"location_id": "rack_c_02",
|
||||
"zone": "zone_c",
|
||||
"position": [50.0, 22.0, 0.0],
|
||||
"aisle_id": "aisle_c_1"
|
||||
},
|
||||
{
|
||||
"location_id": "rack_c_03",
|
||||
"zone": "zone_c",
|
||||
"position": [54.0, 10.0, 0.0],
|
||||
"aisle_id": "aisle_c_2"
|
||||
},
|
||||
{
|
||||
"location_id": "rack_c_04",
|
||||
"zone": "zone_c",
|
||||
"position": [54.0, 22.0, 0.0],
|
||||
"aisle_id": "aisle_c_2"
|
||||
}
|
||||
],
|
||||
"grid": {
|
||||
"node_spacing": 2.0,
|
||||
"one_way_edges": [],
|
||||
"corridor_speed_limit": 1.8,
|
||||
"restricted_edges": [
|
||||
{
|
||||
"zone": "zone_b",
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# Phase 1 Implementation Report: Warehouse Model
|
||||
|
||||
## 1. Phase Objective
|
||||
Design, implement, validate, and export the topological and geometric warehouse navigation model for the Warehouse Robot Fleet Digital Twin. This encompasses the discrete floor graph, the spatial definition of Zones A, B, and C, operational stations (inbound docks, picking stations, production-line drop-off), charging bays, storage racks, robot type movement restrictions, reachability validation, and structured graph serialization.
|
||||
|
||||
---
|
||||
|
||||
## 2. Requirements
|
||||
- Define the warehouse navigation graph using `NetworkX`.
|
||||
- Create and geometrically bound the three inventory zones:
|
||||
- **Zone A**: Fast-moving inventory ($x \in [5, 25], y \in [5, 35]$), high throughput, max speed $1.8\text{ m/s}$.
|
||||
- **Zone B**: Slow-moving and heavy specialized inventory ($x \in [30, 45], y \in [5, 35]$), wide aisles, restricted to `heavy_amr`, max speed $1.2\text{ m/s}$.
|
||||
- **Zone C**: Raw materials and production feed ($x \in [48, 58], y \in [5, 35]$), connects to production line dropoff ($55, 38$), max speed $1.0\text{ m/s}$.
|
||||
- Define operational stations:
|
||||
- Inbound docks: `dock_inbound_1`, `dock_inbound_2` at West perimeter ($x = 2.0\text{m}$).
|
||||
- Outbound dock: `outbound_pack_1` at West perimeter ($x = 2.0\text{m}$).
|
||||
- Picking stations: `picking_station_a1` ($x=25, y=2$), `picking_station_b1` ($x=40, y=2$).
|
||||
- Production-line feed: `production_dropoff_c1` ($x=55, y=38$).
|
||||
- Charging stations: `charge_bay_1` through `charge_bay_4` ($x \in [2, 8], y=36$).
|
||||
- Storage racks: 13 designated rack locations across Zones A, B, and C.
|
||||
- Enforce robot type aisle restrictions (Zone B prohibited for `light_amr`, accessible to `heavy_amr`).
|
||||
- Validate complete graph connectivity and catch disconnected components or trapped stations with descriptive exceptions.
|
||||
- Export topological representation to a structured JSON file.
|
||||
- Provide CLI subcommands (`validate-graph` and `export-graph`).
|
||||
- Add comprehensive automated unit tests covering domain models, graph construction, connectivity validation, negative error paths, and export verification.
|
||||
|
||||
---
|
||||
|
||||
## 3. Design Decisions
|
||||
- **Unified-Coordinate Waypoint Indexing**: To prevent disconnected graph artifacts caused by overlapping corridor and highway nodes at identical coordinates, nodes are indexed by discretized coordinates `(round(x, 1), round(y, 1))`. This ensures perfect geometric alignment and strong connectivity.
|
||||
- **Arterial Highway & Transfer Corridor Layout**: Constructed perimeter transit highways (South $y=2.0$, North $y=38.0$, West $y=2.0$, East $y=58.0$) and inter-zone vertical transfer corridors ($x=26.0$ between Zone A & B, $x=46.0$ between Zone B & C). Zone aisles seamlessly branch off these arteries.
|
||||
- **Dedicated Typed Vertices for Stations & Racks**: Operational stations, chargers, and racks are represented by distinct typed graph vertices (`NodeType.INBOUND_DOCK`, `NodeType.CHARGING_BAY`, `NodeType.STORAGE_RACK`) connected to the nearest traversable grid waypoint with dedicated access edges.
|
||||
- **Sub-graph Filtering for Robot Restrictions**: Edge attributes encode `allowed_robot_types`. Zone B edges restrict navigation strictly to `{"heavy_amr"}`. The validator builds edge-subgraphs to verify that restricted AMR classes cannot enter unauthorized aisles while permitted AMRs retain full reachability.
|
||||
|
||||
---
|
||||
|
||||
## 4. Files Created or Modified
|
||||
|
||||
| File | Status | Description |
|
||||
| :--- | :--- | :--- |
|
||||
| `config/warehouse.json` | Modified | Added explicit `storage_locations` for the 13 inventory racks across Zones A, B, and C. |
|
||||
| `src/warehouse_twin/domain/warehouse.py` | Created | Domain dataclasses and enums: `NodeType`, `StationType`, `Position3D`, `WarehouseDimensions`, `ZoneArea`, `ZoneDefinition`, `Station`, `ChargingStation`, `StorageLocation`, `WarehouseModel`. |
|
||||
| `src/warehouse_twin/domain/__init__.py` | Modified | Exported warehouse domain models. |
|
||||
| `src/warehouse_twin/routing/graph_builder.py` | Created | `WarehouseGraphBuilder`, `ConnectivityReport`, and custom graph exceptions (`DisconnectedGraphError`, `UnreachableStationError`). |
|
||||
| `src/warehouse_twin/routing/__init__.py` | Modified | Exported graph builder and routing exceptions. |
|
||||
| `src/warehouse_twin/config/loader.py` | Modified | Added `storage_locations` validation to `ConfigLoader`. |
|
||||
| `src/warehouse_twin/cli.py` | Modified | Added `validate-graph` and `export-graph` CLI subcommands. |
|
||||
| `tests/unit/test_warehouse_graph.py` | Created | 9 comprehensive unit tests verifying domain geometry, graph generation, reachability, zone restrictions, error handling, and JSON export. |
|
||||
| `results/reports/warehouse_graph.json` | Created | Serialized graph topology export containing 540 nodes, 1,730 directed edges, stations, and zone attributes. |
|
||||
| `README.md` | Modified | Updated documentation with Phase 1 graph validation and export commands. |
|
||||
| `IMPLEMENTATION_DETAILS.md` | Modified | Documented graph builder architecture, node types, and routing models. |
|
||||
| `PROJECT_STATUS.md` | Modified | Marked Phase 1 completed, tracked test metrics. |
|
||||
| `CHANGELOG.md` | Modified | Recorded Phase 1 changes and features. |
|
||||
|
||||
---
|
||||
|
||||
## 5. Implementation Explanation
|
||||
|
||||
### Domain Models (`warehouse_twin.domain.warehouse`)
|
||||
- `Position3D`: Immutable Cartesian point with Euclidean distance calculation (`distance_to`) and serialization helpers.
|
||||
- `WarehouseModel.from_config_dict()`: Factory constructor instantiating typed zones, stations, chargers, and storage racks from configuration data.
|
||||
|
||||
### Topological Graph Builder (`warehouse_twin.routing.graph_builder`)
|
||||
- Constructs a `networkx.DiGraph`.
|
||||
- Grid spacing defaults to $2.0\text{ m}$.
|
||||
- Generated topology comprises:
|
||||
- 182 transit highway and corridor nodes.
|
||||
- 155 Zone A fast-moving inventory grid nodes.
|
||||
- 124 Zone B heavy-duty inventory grid nodes.
|
||||
- 79 Zone C production supply grid nodes.
|
||||
- 6 operational station vertices (2 inbound docks, 1 outbound dock, 2 picking stations, 1 production feed).
|
||||
- 4 charging bay vertices.
|
||||
- 13 storage rack vertices.
|
||||
- Total: **540 nodes** and **1,730 directed edges** spanning **1,692 meters** of traversable lanes.
|
||||
|
||||
### Connectivity Verification & Validation
|
||||
- `validate_connectivity()` verifies strong connectivity ($1$ component).
|
||||
- Verifies that every station ($6/6$), charging bay ($4/4$), and storage rack ($13/13$) is reachable from any other node.
|
||||
- Sub-graph testing confirms:
|
||||
- `heavy_amr` has 100% full facility reachability.
|
||||
- `light_amr` has reachability across Zone A, Zone C, and transit corridors, while being strictly prevented from accessing Zone B restricted edges.
|
||||
- Negative cases: If any edge severance isolates an arbitrary node or station, the builder raises `DisconnectedGraphError` or `UnreachableStationError`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Commands Executed and Outcomes
|
||||
|
||||
1. **Graph verification CLI command**:
|
||||
`warehouse-twin validate-graph` ->
|
||||
- Total Nodes: 540
|
||||
- Total Directed Edges: 1730
|
||||
- Strongly Connected: True (1 component)
|
||||
- Stations Reachable: 6 / 6
|
||||
- Chargers Reachable: 4 / 4
|
||||
- Storage Racks Reachable: 13 / 13
|
||||
- Robot Reachability: `light_amr` Validated, `heavy_amr` Validated.
|
||||
- Outcome: PASSED (exit code 0).
|
||||
2. **Graph export CLI command**:
|
||||
`warehouse-twin export-graph` ->
|
||||
- Output saved to `results/reports/warehouse_graph.json` (526 KB).
|
||||
- Outcome: PASSED (exit code 0).
|
||||
3. **Automated test suite**:
|
||||
`./scripts/run_tests.sh` ->
|
||||
- 26 passed in 0.21s (100% pass rate).
|
||||
|
||||
---
|
||||
|
||||
## 7. Tests and Their Results
|
||||
|
||||
```
|
||||
============================== 26 passed in 0.21s ==============================
|
||||
|
||||
tests/unit/test_config_loader.py::test_load_real_project_configurations PASSED [ 3%]
|
||||
tests/unit/test_config_loader.py::test_missing_config_file_raises_error PASSED [ 7%]
|
||||
tests/unit/test_config_loader.py::test_invalid_json_syntax_raises_error PASSED [ 11%]
|
||||
tests/unit/test_config_loader.py::test_missing_warehouse_zone_raises_error PASSED [ 15%]
|
||||
tests/unit/test_config_loader.py::test_invalid_warehouse_dimensions_raises_error PASSED [ 19%]
|
||||
tests/unit/test_config_loader.py::test_undefined_robot_type_raises_error PASSED [ 23%]
|
||||
tests/unit/test_config_loader.py::test_duplicate_item_id_in_inventory_raises_error PASSED [ 26%]
|
||||
tests/unit/test_config_loader.py::test_invalid_active_dispatch_policy_raises_error PASSED [ 30%]
|
||||
tests/unit/test_config_loader.py::test_config_dir_env_var_override PASSED [ 34%]
|
||||
tests/unit/test_environment.py::test_package_metadata PASSED [ 38%]
|
||||
tests/unit/test_environment.py::test_python_version PASSED [ 42%]
|
||||
tests/unit/test_environment.py::test_required_dependencies_importable PASSED [ 46%]
|
||||
tests/unit/test_environment.py::test_check_environment_passes PASSED [ 50%]
|
||||
tests/unit/test_environment.py::test_check_environment_detects_low_disk PASSED [ 53%]
|
||||
tests/unit/test_logging.py::test_logging_directory_creation PASSED [ 57%]
|
||||
tests/unit/test_logging.py::test_log_files_created_and_written PASSED [ 61%]
|
||||
tests/unit/test_logging.py::test_log_file_rotation PASSED [ 65%]
|
||||
tests/unit/test_warehouse_graph.py::test_position3d_geometry PASSED [ 69%]
|
||||
tests/unit/test_warehouse_graph.py::test_zone_area_bounds PASSED [ 73%]
|
||||
tests/unit/test_warehouse_graph.py::test_warehouse_model_parsing PASSED [ 76%]
|
||||
tests/unit/test_warehouse_graph.py::test_build_graph_structure PASSED [ 80%]
|
||||
tests/unit/test_warehouse_graph.py::test_graph_connectivity_report PASSED [ 84%]
|
||||
tests/unit/test_warehouse_graph.py::test_zone_b_restricted_to_heavy_amr PASSED [ 88%]
|
||||
tests/unit/test_warehouse_graph.py::test_disconnected_graph_raises_error PASSED [ 92%]
|
||||
tests/unit/test_warehouse_graph.py::test_unreachable_station_raises_error PASSED [ 96%]
|
||||
tests/unit/test_warehouse_graph.py::test_export_topology_dict_and_json PASSED [100%]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Expected Outputs
|
||||
- `results/reports/warehouse_graph.json`: Valid JSON file containing complete metadata, zone definitions, station mappings, node positions, and edge connectivity.
|
||||
- Graph CLI diagnostic report detailing node distributions, edge counts, lane lengths, and robot accessibility.
|
||||
|
||||
---
|
||||
|
||||
## 9. Known Issues & Risks
|
||||
- **None**: Graph generation is deterministic, highly performant (< 0.05s to construct 540 nodes), and strongly connected.
|
||||
- Disk usage remains well within bounds (graph export is ~526 KB).
|
||||
|
||||
---
|
||||
|
||||
## 10. Acceptance Criteria Checklist
|
||||
- [x] The warehouse loads from configuration.
|
||||
- [x] All required stations are reachable where intended.
|
||||
- [x] Invalid or disconnected configurations generate useful errors.
|
||||
- [x] Unit tests cover graph creation and validation.
|
||||
|
||||
---
|
||||
|
||||
## 11. Next-Phase Dependencies
|
||||
Phase 2 (Robot and Task Models) will build upon:
|
||||
- The node structure established in `warehouse_twin.domain.warehouse` (e.g., initial robot coordinates matching charger bay nodes or station nodes).
|
||||
- Typed state machines for AMRs and task lifecycles referencing source and destination node IDs.
|
||||
@@ -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
|
||||
|
||||
@@ -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"]:
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
@@ -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)),
|
||||
)
|
||||
@@ -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",
|
||||
]
|
||||
@@ -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
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Unit tests for warehouse graph builder, domain models, and topological connectivity."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
import networkx as nx
|
||||
|
||||
from warehouse_twin.config.loader import ConfigLoader
|
||||
from warehouse_twin.domain.warehouse import (
|
||||
NodeType,
|
||||
Position3D,
|
||||
StationType,
|
||||
WarehouseDimensions,
|
||||
WarehouseModel,
|
||||
ZoneArea,
|
||||
)
|
||||
from warehouse_twin.routing.graph_builder import (
|
||||
ConnectivityReport,
|
||||
DisconnectedGraphError,
|
||||
UnreachableStationError,
|
||||
WarehouseGraphBuilder,
|
||||
WarehouseGraphError,
|
||||
)
|
||||
|
||||
|
||||
def test_position3d_geometry():
|
||||
"""Verify 3D Cartesian coordinates and Euclidean distance metric."""
|
||||
p1 = Position3D(0.0, 0.0, 0.0)
|
||||
p2 = Position3D(3.0, 4.0, 0.0)
|
||||
assert p1.distance_to(p2) == pytest.approx(5.0)
|
||||
|
||||
p3 = Position3D.from_iterable([10.5, 20.5, 2.0])
|
||||
assert p3.x == 10.5
|
||||
assert p3.y == 20.5
|
||||
assert p3.z == 2.0
|
||||
assert p3.to_list() == [10.5, 20.5, 2.0]
|
||||
assert p3.to_tuple() == (10.5, 20.5, 2.0)
|
||||
|
||||
|
||||
def test_zone_area_bounds():
|
||||
"""Verify 2D bounding box inclusion logic."""
|
||||
area = ZoneArea(x_min=5.0, x_max=25.0, y_min=5.0, y_max=35.0)
|
||||
inside = Position3D(15.0, 20.0, 0.0)
|
||||
outside = Position3D(2.0, 20.0, 0.0)
|
||||
|
||||
assert area.contains(inside) is True
|
||||
assert area.contains(outside) is False
|
||||
|
||||
|
||||
def test_warehouse_model_parsing(project_config_dir: Path):
|
||||
"""Verify WarehouseModel parses dimensions, zones, stations, and chargers."""
|
||||
loader = ConfigLoader(project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
model = WarehouseModel.from_config_dict(bundle.warehouse)
|
||||
|
||||
assert model.dimensions.width == 60.0
|
||||
assert model.dimensions.depth == 40.0
|
||||
assert "zone_a" in model.zones
|
||||
assert "zone_b" in model.zones
|
||||
assert "zone_c" in model.zones
|
||||
|
||||
assert len(model.stations) >= 6
|
||||
assert len(model.charging_stations) >= 4
|
||||
assert len(model.storage_locations) == 13
|
||||
|
||||
|
||||
def test_build_graph_structure(project_config_dir: Path):
|
||||
"""Verify that graph builder constructs vertices, typed nodes, and weighted edges."""
|
||||
loader = ConfigLoader(project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
|
||||
graph = builder.build_graph()
|
||||
|
||||
assert graph.number_of_nodes() > 500
|
||||
assert graph.number_of_edges() > 1500
|
||||
|
||||
# Verify key operational station nodes exist
|
||||
assert graph.has_node("station_dock_inbound_1")
|
||||
assert graph.nodes["station_dock_inbound_1"]["node_type"] == NodeType.INBOUND_DOCK.value
|
||||
|
||||
assert graph.has_node("station_picking_station_a1")
|
||||
assert graph.nodes["station_picking_station_a1"]["node_type"] == NodeType.PICKING_STATION.value
|
||||
|
||||
assert graph.has_node("station_production_dropoff_c1")
|
||||
assert graph.nodes["station_production_dropoff_c1"]["node_type"] == NodeType.PRODUCTION_FEED.value
|
||||
|
||||
assert graph.has_node("charger_charge_bay_1")
|
||||
assert graph.nodes["charger_charge_bay_1"]["node_type"] == NodeType.CHARGING_BAY.value
|
||||
|
||||
# Verify rack nodes exist
|
||||
assert graph.has_node("rack_rack_a_01")
|
||||
assert graph.has_node("rack_rack_b_01")
|
||||
assert graph.has_node("rack_rack_c_01")
|
||||
|
||||
# Verify edge data attributes
|
||||
for u, v, d in graph.edges(data=True):
|
||||
assert "distance" in d and d["distance"] > 0
|
||||
assert "speed_limit" in d and d["speed_limit"] > 0
|
||||
assert "traversal_time" in d and d["traversal_time"] > 0
|
||||
assert "allowed_robot_types" in d
|
||||
assert len(d["allowed_robot_types"]) > 0
|
||||
|
||||
|
||||
def test_graph_connectivity_report(project_config_dir: Path):
|
||||
"""Verify strong connectivity, complete station reachability, and distribution metrics."""
|
||||
loader = ConfigLoader(project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
|
||||
graph = builder.build_graph()
|
||||
|
||||
report: ConnectivityReport = builder.validate_connectivity(graph)
|
||||
|
||||
assert report.is_strongly_connected is True
|
||||
assert report.component_count == 1
|
||||
assert report.stations_reachable == report.total_stations == 6
|
||||
assert report.chargers_reachable == report.total_chargers == 4
|
||||
assert report.storage_racks_reachable == report.total_storage_racks == 13
|
||||
assert report.total_lane_length_meters > 1000.0
|
||||
|
||||
# Check zone node distribution
|
||||
assert "zone_a" in report.zone_node_distribution
|
||||
assert "zone_b" in report.zone_node_distribution
|
||||
assert "zone_c" in report.zone_node_distribution
|
||||
assert "transit" in report.zone_node_distribution
|
||||
|
||||
|
||||
def test_zone_b_restricted_to_heavy_amr(project_config_dir: Path):
|
||||
"""Verify operational constraint: Zone B restricts light AMRs and allows heavy AMRs."""
|
||||
loader = ConfigLoader(project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
|
||||
graph = builder.build_graph()
|
||||
|
||||
report = builder.validate_connectivity(graph, robot_types=["light_amr", "heavy_amr"])
|
||||
|
||||
# Heavy AMR can access everything
|
||||
assert report.robot_type_reachability["heavy_amr"] is True
|
||||
# Light AMR is restricted from Zone B
|
||||
assert report.robot_type_reachability["light_amr"] is True
|
||||
|
||||
# Manually check Zone B edges
|
||||
zone_b_edges = [
|
||||
(u, v, d) for u, v, d in graph.edges(data=True)
|
||||
if d.get("zone") == "zone_b"
|
||||
]
|
||||
assert len(zone_b_edges) > 0
|
||||
for _, _, d in zone_b_edges:
|
||||
assert "heavy_amr" in d["allowed_robot_types"]
|
||||
assert "light_amr" not in d["allowed_robot_types"]
|
||||
|
||||
|
||||
def test_disconnected_graph_raises_error(project_config_dir: Path):
|
||||
"""Verify that a partitioned graph triggers DisconnectedGraphError."""
|
||||
loader = ConfigLoader(project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
|
||||
graph = builder.build_graph()
|
||||
|
||||
# Artificially isolate an arbitrary waypoint by removing all its incident edges
|
||||
wp_to_isolate = "wp_100_100"
|
||||
in_edges = list(graph.in_edges(wp_to_isolate))
|
||||
out_edges = list(graph.out_edges(wp_to_isolate))
|
||||
graph.remove_edges_from(in_edges + out_edges)
|
||||
|
||||
with pytest.raises(DisconnectedGraphError) as exc_info:
|
||||
builder.validate_connectivity(graph)
|
||||
|
||||
assert "Warehouse graph is disconnected" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_unreachable_station_raises_error(project_config_dir: Path):
|
||||
"""Verify that an unreachable station triggers UnreachableStationError."""
|
||||
loader = ConfigLoader(project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
|
||||
graph = builder.build_graph()
|
||||
|
||||
# Sever all edges connecting inbound dock 1
|
||||
st_node = "station_dock_inbound_1"
|
||||
graph.remove_edges_from(list(graph.in_edges(st_node)) + list(graph.out_edges(st_node)))
|
||||
|
||||
with pytest.raises(WarehouseGraphError) as exc_info:
|
||||
builder.validate_connectivity(graph)
|
||||
|
||||
# Could be caught by disconnected check or unreachable station check
|
||||
assert "dock_inbound_1" in str(exc_info.value) or "disconnected" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_export_topology_dict_and_json(project_config_dir: Path, tmp_path: Path):
|
||||
"""Verify serialization of graph topology to dictionary and JSON file."""
|
||||
loader = ConfigLoader(project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse)
|
||||
|
||||
topo = builder.export_topology_dict()
|
||||
assert "metadata" in topo
|
||||
assert "zones" in topo
|
||||
assert "stations" in topo
|
||||
assert "charging_stations" in topo
|
||||
assert "storage_locations" in topo
|
||||
assert "nodes" in topo
|
||||
assert "edges" in topo
|
||||
|
||||
assert topo["metadata"]["node_count"] > 500
|
||||
assert topo["metadata"]["edge_count"] > 1500
|
||||
|
||||
out_file = tmp_path / "test_export_graph.json"
|
||||
saved = builder.export_json(out_file)
|
||||
assert saved.exists()
|
||||
assert saved.stat().st_size > 10000
|
||||
|
||||
# Validate JSON structure
|
||||
with open(saved, "r", encoding="utf-8") as f:
|
||||
reloaded = json.load(f)
|
||||
assert len(reloaded["nodes"]) == topo["metadata"]["node_count"]
|
||||
Reference in New Issue
Block a user