feat(phase2): implement AMR robot state machine, task lifecycles, inventory catalog, and Phase 2 OpenUSD scene
This commit is contained in:
@@ -5,6 +5,30 @@ 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.3.0] - 2026-10-19
|
||||
|
||||
### Added - Phase 2: Robot and Task Models
|
||||
- Domain entity models for Autonomous Mobile Robots (`warehouse_twin.domain.robot`):
|
||||
- `RobotState` enum representing operational lifecycle states (`IDLE`, `DISPATCHED`, `PICKING`, `LOADED_TRANSIT`, `DROPPING`, `TRANSIT_TO_CHARGE`, `CHARGING`, `MAINTENANCE`).
|
||||
- Strict transition lookup table `LEGAL_ROBOT_TRANSITIONS` preventing illegal state transitions with `InvalidStateTransitionError`.
|
||||
- `RobotTypeSpec` parsing `config/robots.json` specifications for light and heavy AMRs.
|
||||
- `Robot` model managing kinematics, battery capacity, linear energy consumption (idle, moving, loaded), fast-charging, active tasks, routes, and allowed zones.
|
||||
- Pre-assignment validation `Robot.validate_task_compatibility(task)` enforcing payload capacity and zone restrictions (`IncompatibleRobotTaskError`).
|
||||
- Domain models for warehouse tasks (`warehouse_twin.domain.task`):
|
||||
- `TaskType` enum (`INBOUND_TRANSPORT`, `OUTBOUND_PICKING`, `PRODUCTION_FEED`, `REPLENISHMENT`, `CHARGING`).
|
||||
- `TaskStatus` enum (`PENDING`, `ASSIGNED`, `IN_PROGRESS`, `COMPLETED`, `CANCELLED`, `FAILED`) enforced by `LEGAL_TASK_TRANSITIONS`.
|
||||
- `Task` dataclass tracking creation time, assignment time, start/completion times, turnaround time, queue wait time, execution duration, and SLA deadline overdue checks.
|
||||
- Inventory item and catalog models (`warehouse_twin.domain.inventory`):
|
||||
- `InventoryItem` with available/reserved quantities, unit weight, reorder threshold, and restocking amounts.
|
||||
- `InventoryCatalog` loading 13 SKUs from `config/inventory.json` with stock reservation, consumption, and replenishment trigger checks.
|
||||
- Event telemetry models (`warehouse_twin.domain.events`):
|
||||
- `SimulationEventType` and `SimulationEvent` dataclass with ISO8601 formatting and JSONL serialization.
|
||||
- OpenUSD generator enhancements (`warehouse_twin.interfaces.usd_generator`):
|
||||
- `WarehouseUSDGenerator.from_config_bundle` now renders the active AMR fleet with realistic geometry (pearl white for light AMRs, industrial amber for heavy AMRs, with illuminated status domes).
|
||||
- Exported OpenUSD 3D stage `omniverse/scenes/warehouse_phase2.usda`.
|
||||
- 30 new unit tests covering robot states, task lifecycles, inventory dynamics, telemetry events, and USD robot generation (56 total unit tests passing in 0.24s).
|
||||
- Implementation report in `docs/phases/phase_2_robot_and_task_models.md`.
|
||||
|
||||
## [0.2.0] - 2026-10-19
|
||||
|
||||
### Added - Phase 1: Warehouse Model
|
||||
|
||||
@@ -118,9 +118,13 @@ The testing architecture adheres to the following principles:
|
||||
|
||||
## 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.
|
||||
- **Completed**:
|
||||
- **Phase 0 (Environment and Foundation)**: Core architecture, rotating file logs, configuration loaders, environment verification.
|
||||
- **Phase 1 (Warehouse Model)**: 540-node topological navigation graph, reachability validation, zone restrictions, graph JSON export.
|
||||
- **Phase 2 (Robot and Task Models)**: Robot state machine (`IDLE` through `CHARGING`), legal transition tables, task priority & lifecycle models, inventory catalog with stock reservation & replenishment, telemetry events, and OpenUSD robot fleet visualization. 56 passing unit tests.
|
||||
- **Phase 3 Target**: Implement Discrete-Event Simulation Engine (`warehouse_twin.simulation`):
|
||||
- SimPy simulation environment managing clock time.
|
||||
- Dynamic order arrival processes for Zone A (Poisson), Zone B (Normal), and Zone C (Deterministic batch).
|
||||
- Task queueing and priority dispatcher assigning compatible AMRs.
|
||||
- Full simulation lifecycle execution with KPI collection.
|
||||
|
||||
|
||||
+44
-47
@@ -1,7 +1,7 @@
|
||||
# Project Status: Warehouse Robot Fleet Digital Twin
|
||||
|
||||
**Last Updated**: October 19, 2026
|
||||
**Current Phase**: **Phase 1: Warehouse Model (COMPLETED)**
|
||||
**Current Phase**: **Phase 2: Robot and Task Models (COMPLETED)**
|
||||
**Status**: Ready for User Review and Approval
|
||||
|
||||
---
|
||||
@@ -11,9 +11,9 @@
|
||||
| Phase | Description | Status | Test Coverage |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **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 1** | **Warehouse model** | **COMPLETED** | **26 passed** |
|
||||
| **Phase 2** | **Robot and task models** | **COMPLETED** | **56 passed (100%)** |
|
||||
| Phase 3 | Discrete-event simulation | Planned (Next) | - |
|
||||
| Phase 4 | Routing and fleet assignment | Planned | - |
|
||||
| Phase 5 | Charging and operational constraints | Planned | - |
|
||||
| Phase 6 | Analytics and experiment framework | Planned | - |
|
||||
@@ -23,57 +23,54 @@
|
||||
|
||||
---
|
||||
|
||||
## 2. Completed Tasks (Phase 1)
|
||||
## 2. Completed Tasks (Phase 2)
|
||||
|
||||
- [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`.
|
||||
- [x] Defined complete robot domain models in `src/warehouse_twin/domain/robot.py`:
|
||||
- `RobotState` enum (`IDLE`, `DISPATCHED`, `PICKING`, `LOADED_TRANSIT`, `DROPPING`, `TRANSIT_TO_CHARGE`, `CHARGING`, `MAINTENANCE`).
|
||||
- `LEGAL_ROBOT_TRANSITIONS` lookup table enforcing valid state machine jumps.
|
||||
- `RobotTypeSpec` data model parsing `config/robots.json`.
|
||||
- `Robot` model tracking position, SoC battery level, energy consumption, kinematics, active tasks, and routes.
|
||||
- `Robot.validate_task_compatibility()` enforcing payload capacity limits and zone accessibility.
|
||||
- `Robot.assign_task()` and `Robot.complete_task()`.
|
||||
- Linear energy consumption and fast-charging modeling.
|
||||
- [x] Defined warehouse task models in `src/warehouse_twin/domain/task.py`:
|
||||
- `TaskType` enum (`INBOUND_TRANSPORT`, `OUTBOUND_PICKING`, `PRODUCTION_FEED`, `REPLENISHMENT`, `CHARGING`).
|
||||
- `TaskStatus` enum (`PENDING`, `ASSIGNED`, `IN_PROGRESS`, `COMPLETED`, `CANCELLED`, `FAILED`).
|
||||
- `LEGAL_TASK_TRANSITIONS` table preventing invalid state jumps.
|
||||
- `Task` dataclass tracking turnaround time, queue waiting time, execution duration, and SLA deadline overdues.
|
||||
- [x] Defined inventory models in `src/warehouse_twin/domain/inventory.py`:
|
||||
- `InventoryItem` tracking stock levels, reservations, reorder thresholds, and restocking amounts.
|
||||
- `InventoryCatalog` loading 13 SKUs across Fast Moving, Slow Moving/Heavy, and Raw Material categories.
|
||||
- [x] Defined simulation telemetry in `src/warehouse_twin/domain/events.py`:
|
||||
- `SimulationEventType` enum and `SimulationEvent` dataclass with JSONL serialization.
|
||||
- [x] Integrated AMR fleet into 3D OpenUSD generator (`src/warehouse_twin/interfaces/usd_generator.py`):
|
||||
- Added visual prims for `light_amr` (pearl white chassis, cyan status dome) and `heavy_amr` (industrial amber chassis, emerald status dome).
|
||||
- Exported OpenUSD scene `omniverse/scenes/warehouse_phase2.usda`.
|
||||
- [x] Added 30 new unit tests (56 total unit tests passing in 0.24s).
|
||||
- [x] Created `docs/phases/phase_2_robot_and_task_models.md`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Test & Validation Summary
|
||||
|
||||
- **Total Unit Tests Executed**: 26
|
||||
- **Passed**: 26
|
||||
- **Total Unit Tests Executed**: 56
|
||||
- **Passed**: 56
|
||||
- **Failed**: 0
|
||||
- **Skipped**: 0
|
||||
- **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.
|
||||
- **Execution Time**: ~0.24 seconds
|
||||
- **Test Suites**:
|
||||
- `test_environment.py`: 5 passed
|
||||
- `test_logging.py`: 3 passed
|
||||
- `test_config_loader.py`: 9 passed
|
||||
- `test_warehouse_graph.py`: 11 passed
|
||||
- `test_robot_model.py`: 14 passed
|
||||
- `test_task_model.py`: 9 passed
|
||||
- `test_inventory_model.py`: 4 passed
|
||||
- `test_events_model.py`: 1 passed
|
||||
|
||||
---
|
||||
|
||||
## 4. Known Environment Constraints & Mitigations
|
||||
## 4. Environment & Constraints Compliance
|
||||
|
||||
- **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 1 completion, then begin **Phase 2: Robot and Task Models** (AMR state machine, task lifecycle, payload constraints, compatibility rules, and deterministic fixtures).
|
||||
- **Storage**: Root NVMe partition at 99% capacity (~8.8 GB available). Maintained zero uncontrolled growth.
|
||||
- **USD Export**: `omniverse/scenes/warehouse_phase2.usda` (19 KB) generated cleanly without GPU dependencies.
|
||||
- **Active Omniverse Kit Instance**: Running PID 74367 (`warehouse_twin.kit`) on RTX 5090.
|
||||
|
||||
@@ -52,24 +52,28 @@ The system decouples discrete-event simulation from 3D visualization, enabling d
|
||||
|
||||
## 3. Features Implemented & Roadmap
|
||||
|
||||
### Currently Implemented (Phases 0 & 1)
|
||||
### Currently Implemented (Phases 0, 1 & 2)
|
||||
- [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`, `validate-config`, `validate-graph`, and `export-graph`.
|
||||
- [x] CLI entry point with `validate-env`, `validate-config`, `validate-graph`, `export-graph`, and `export-usd`.
|
||||
- [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).
|
||||
- [x] Autonomous Mobile Robot (AMR) domain models (`Robot`, `RobotState`, `RobotTypeSpec`, `LEGAL_ROBOT_TRANSITIONS`).
|
||||
- [x] Task domain models (`Task`, `TaskType`, `TaskStatus`, `LEGAL_TASK_TRANSITIONS`, turnaround, execution, SLA deadline tracking).
|
||||
- [x] Inventory domain models (`InventoryItem`, `InventoryCatalog` with 13 SKUs, stock reservation, consumption, replenishment triggers).
|
||||
- [x] Event telemetry streaming models (`SimulationEvent`, `SimulationEventType`, JSONL formatting).
|
||||
- [x] OpenUSD 3D scene export with AMR fleet entities positioned at charging bays (`omniverse/scenes/warehouse_phase2.usda`).
|
||||
- [x] Comprehensive unit test suite (56 passed in 0.24s).
|
||||
|
||||
### Planned Roadmap
|
||||
- **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.
|
||||
- **Phase 5**: Battery discharge/recharge dynamics, charging queues, and production deadlines.
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
# Phase 2 Implementation Report: Robot and Task Models
|
||||
|
||||
## 1. Phase Name and Objective
|
||||
**Phase 2: Robot and Task Models**
|
||||
|
||||
The objective of Phase 2 is to design, implement, test, and document the core discrete entities of the warehouse digital twin:
|
||||
1. Autonomous Mobile Robots (AMRs) with kinematic parameters, state machines, battery charge/discharge energy models, and zone access constraints.
|
||||
2. Warehouse operational tasks (Inbound Transport, Outbound Picking, Production Feed, Replenishment, Charging) with priority levels, lifecycle state machines, execution time tracking, and SLA deadline monitoring.
|
||||
3. Inventory items, categories, SKU definitions, and storage rack allocations, supporting reservation, consumption, and automatic replenishment triggers.
|
||||
4. Structured simulation event definitions for event-driven logging and telemetry streaming.
|
||||
5. 3D OpenUSD scene export (`warehouse_phase2.usda`) integrating the active AMR fleet with realistic geometry and status indicator domes positioned on charging bays.
|
||||
|
||||
---
|
||||
|
||||
## 2. Deliverables Completed
|
||||
|
||||
| Deliverable | Status | Description |
|
||||
| :--- | :--- | :--- |
|
||||
| `src/warehouse_twin/domain/robot.py` | Complete | `RobotState` enum, `RobotTypeSpec`, `Robot` model, legal transition lookup `LEGAL_ROBOT_TRANSITIONS`, `validate_task_compatibility()`, `assign_task()`, energy consumption and charging calculation. |
|
||||
| `src/warehouse_twin/domain/task.py` | Complete | `TaskType` and `TaskStatus` enums, `LEGAL_TASK_TRANSITIONS`, `Task` model with turnaround, waiting, execution time, and SLA deadline overdue checks. |
|
||||
| `src/warehouse_twin/domain/inventory.py` | Complete | `InventoryItem` and `InventoryCatalog` loading all 13 items from `config/inventory.json`, stock reservation, consumption, and replenishment threshold logic. |
|
||||
| `src/warehouse_twin/domain/events.py` | Complete | `SimulationEventType` enum and `SimulationEvent` dataclass with ISO8601 timestamps and JSONL serialization. |
|
||||
| `src/warehouse_twin/interfaces/usd_generator.py` | Complete | Enhanced `WarehouseUSDGenerator.from_config_bundle` to generate 3D OpenUSD primitives for the AMR fleet (pearl white for light AMRs, industrial amber for heavy AMRs, with cyan/green status domes). |
|
||||
| `tests/unit/test_robot_model.py` | Complete | 14 unit tests validating AMR kinematics, full state cycles, illegal state transitions, payload capacity rejections, zone restrictions, and energy dynamics. |
|
||||
| `tests/unit/test_task_model.py` | Complete | 9 unit tests validating task lifecycle transitions, cancellation, preemption, illegal state jumps, and SLA deadline overdue tracking. |
|
||||
| `tests/unit/test_inventory_model.py` | Complete | 4 unit tests verifying stock reservation lifecycle, insufficient stock errors, replenishment triggers, and full catalog loading. |
|
||||
| `tests/unit/test_events_model.py` | Complete | Unit test validating telemetry event serialization and JSONL formatting. |
|
||||
| `tests/unit/test_warehouse_graph.py` | Complete | Added `test_export_usda_with_robots` verifying AMR fleet prim generation. |
|
||||
| `omniverse/scenes/warehouse_phase2.usda` | Complete | Exported OpenUSD scene containing the complete facility, zones, racks, stations, and AMR fleet ready for NVIDIA Omniverse Kit. |
|
||||
|
||||
---
|
||||
|
||||
## 3. Configuration Parameters Used
|
||||
|
||||
- **`config/robots.json`**:
|
||||
- `light_amr`: Max speed $1.5\text{ m/s}$, acceleration $0.8\text{ m/s}^2$, turning rate $90^\circ/\text{s}$, payload capacity $150\text{ kg}$, battery capacity $2.5\text{ kWh}$, power consumption ($1.2\text{ kW}$ moving, $0.15\text{ kW}$ idle, $0.3\text{ kW}$ loaded), allowed zones `["zone_a", "zone_c"]`.
|
||||
- `heavy_amr`: Max speed $1.0\text{ m/s}$, acceleration $0.5\text{ m/s}^2$, turning rate $60^\circ/\text{s}$, payload capacity $1200\text{ kg}$, battery capacity $6.0\text{ kWh}$, power consumption ($2.5\text{ kW}$ moving, $0.25\text{ kW}$ idle, $0.8\text{ kW}$ loaded), allowed zones `["zone_a", "zone_b", "zone_c"]`.
|
||||
- Fleet: 4 AMRs (`amr_light_01`, `amr_light_02`, `amr_heavy_01`, `amr_heavy_02`) initialized at charging bays 1–4.
|
||||
- **`config/inventory.json`**:
|
||||
- 13 distinct SKUs across 3 categories (fast moving, slow moving / heavy, raw materials).
|
||||
- **`config/simulation.json`**:
|
||||
- Duration 3,600s, random seed 42, warm-up 300s, dispatch interval 5.0s, low-battery threshold 20%, charge-complete threshold 95%.
|
||||
|
||||
---
|
||||
|
||||
## 4. Architecture and Design Decisions
|
||||
|
||||
1. **Explicit Discrete State Machine Transitions**:
|
||||
- `LEGAL_ROBOT_TRANSITIONS` and `LEGAL_TASK_TRANSITIONS` enforce strict operational lifecycles.
|
||||
- Any disallowed jump (e.g., `IDLE -> DROPPING` or `COMPLETED -> IN_PROGRESS`) raises `InvalidStateTransitionError`.
|
||||
2. **Pre-Assignment Compatibility Checks**:
|
||||
- `Robot.validate_task_compatibility(task)` checks both payload capacity and spatial accessibility. If a `light_amr` is assigned a $650\text{ kg}$ engine transmission or a task located in `zone_b`, an `IncompatibleRobotTaskError` is raised before dispatch.
|
||||
3. **State of Charge (SoC) and Linear Energy Dynamics**:
|
||||
- Robot battery consumption scales with operational mode (`kw * hours`) and charges at the rate of the station ($10\text{ kW}$ DC fast-charging). Battery percent is clamped safely between $0.0\%$ and $100.0\%$.
|
||||
4. **Decoupled Event Streaming Model**:
|
||||
- `SimulationEvent` encapsulates structured event telemetry with ISO8601 formatting and JSONL serialization, enabling zero-overhead disk streaming without memory buildup.
|
||||
5. **OpenUSD Composition Architecture**:
|
||||
- Generated OpenUSD `.usda` files use Z-up, 1.0m units, standard transforms (`xformOp:translate`, `xformOp:rotateZ`, `xformOp:scale`), and display colors compatible with Omniverse Kit 110.4.
|
||||
|
||||
---
|
||||
|
||||
## 5. Code Structure and Module Descriptions
|
||||
|
||||
```
|
||||
src/warehouse_twin/
|
||||
├── domain/
|
||||
│ ├── __init__.py # Re-exports all domain models
|
||||
│ ├── events.py # SimulationEventType and SimulationEvent telemetry
|
||||
│ ├── inventory.py # InventoryItem and InventoryCatalog
|
||||
│ ├── robot.py # RobotState, RobotTypeSpec, Robot model, legal transitions
|
||||
│ ├── task.py # TaskType, TaskStatus, Task model, legal transitions
|
||||
│ └── warehouse.py # Spatial layout, ZoneArea, Station, StorageLocation
|
||||
└── interfaces/
|
||||
└── usd_generator.py # WarehouseUSDGenerator with AMR fleet rendering
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Integration Points with Previous Phases
|
||||
|
||||
- **Phase 0 (Foundation)**: Consumes configuration bundles loaded by `ConfigLoader` (`ConfigBundle.robots`, `ConfigBundle.inventory`, `ConfigBundle.simulation`). Utilizes rotating file logging (`application.log`, `simulation.log`).
|
||||
- **Phase 1 (Warehouse Model)**: Coordinates robot positions with warehouse coordinate spaces (`Position3D`) and validates zone compatibility against zone definitions established in `WarehouseModel`.
|
||||
|
||||
---
|
||||
|
||||
## 7. Verification and Testing Results
|
||||
|
||||
- **Unit Test Suite**: 56 passing tests across 8 test suites in 0.24 seconds.
|
||||
```
|
||||
tests/unit/test_config_loader.py 9 passed
|
||||
tests/unit/test_environment.py 5 passed
|
||||
tests/unit/test_events_model.py 1 passed
|
||||
tests/unit/test_inventory_model.py 4 passed
|
||||
tests/unit/test_logging.py 3 passed
|
||||
tests/unit/test_robot_model.py 14 passed
|
||||
tests/unit/test_task_model.py 9 passed
|
||||
tests/unit/test_warehouse_graph.py 11 passed
|
||||
============================== 56 passed in 0.24s ==============================
|
||||
```
|
||||
- **CLI Validation**:
|
||||
- `warehouse-twin validate-config`: PASSED (5/5 configs valid).
|
||||
- `warehouse-twin validate-graph`: PASSED (540 nodes, 1730 edges, strongly connected).
|
||||
- `warehouse-twin export-usd`: PASSED (exported `omniverse/scenes/warehouse_phase2.usda`).
|
||||
|
||||
---
|
||||
|
||||
## 8. Known Limitations and Assumptions
|
||||
|
||||
- Kinematics in Phase 2 use simplified acceleration and average traversal speed formulas. Multi-agent collision avoidance (RVO2/ORCA) and dynamic path conflict resolution are slated for Phase 4.
|
||||
- Charging rate is modeled as constant current up to capacity; non-linear battery degradation curves are not implemented.
|
||||
|
||||
---
|
||||
|
||||
## 9. Instructions for Running and Validating
|
||||
|
||||
### Run the Test Suite
|
||||
```bash
|
||||
./.venv/bin/pytest tests/
|
||||
```
|
||||
|
||||
### Validate Config and Export Phase 2 USD Scene
|
||||
```bash
|
||||
./.venv/bin/warehouse-twin validate-config
|
||||
./.venv/bin/warehouse-twin export-usd --output omniverse/scenes/warehouse_phase2.usda
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. Next Phase Dependencies and Handoff
|
||||
|
||||
- **Phase 3 (Discrete-Event Simulation)** will consume:
|
||||
- `Robot` instances and `RobotState` transitions to drive SimPy simulation processes.
|
||||
- `Task` queueing, generation processes, and SLA timeout timers.
|
||||
- `InventoryCatalog` for replenishment triggers when picking tasks decrement inventory below reorder thresholds.
|
||||
- Event telemetry generator for discrete logging.
|
||||
|
||||
---
|
||||
|
||||
## 11. Artifacts and Output Files
|
||||
|
||||
- `omniverse/scenes/warehouse_phase2.usda`: OpenUSD 3D stage with facility and 4 AMRs.
|
||||
- `results/reports/warehouse_graph.json`: Serialized topological navigation graph.
|
||||
- `logs/application.log`: Application logging output.
|
||||
@@ -0,0 +1,514 @@
|
||||
#usda 1.0
|
||||
(
|
||||
defaultPrim = "World"
|
||||
metersPerUnit = 1.0
|
||||
upAxis = "Z"
|
||||
doc = "Warehouse Robot Fleet Digital Twin - 3D Facility Model"
|
||||
)
|
||||
|
||||
def Xform "World"
|
||||
{
|
||||
# -------------------------------------------------------------------------
|
||||
# Environment Lighting
|
||||
# -------------------------------------------------------------------------
|
||||
def DistantLight "SunLight"
|
||||
{
|
||||
float inputs:intensity = 3500.0
|
||||
color3f inputs:color = (0.98, 0.96, 0.92)
|
||||
float inputs:angle = 1.0
|
||||
double3 xformOp:rotateXYZ = (-45.0, 30.0, 0.0)
|
||||
uniform token[] xformOpOrder = ["xformOp:rotateXYZ"]
|
||||
}
|
||||
|
||||
def DomeLight "SkyLight"
|
||||
{
|
||||
float inputs:intensity = 800.0
|
||||
color3f inputs:color = (0.85, 0.90, 0.98)
|
||||
}
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Facility Shell: Ground Floor & Boundary Markers
|
||||
# -------------------------------------------------------------------------
|
||||
def Scope "Architecture"
|
||||
{
|
||||
def Mesh "GroundFloor"
|
||||
{
|
||||
float3[] extent = [(-2.0, -2.0, -0.2), (62.0, 42.0, 0.0)]
|
||||
int[] faceVertexCounts = [4]
|
||||
int[] faceVertexIndices = [0, 1, 2, 3]
|
||||
point3f[] points = [(-2.0, -2.0, 0.0), (62.0, -2.0, 0.0), (62.0, 42.0, 0.0), (-2.0, 42.0, 0.0)]
|
||||
normal3f[] normals = [(0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0)]
|
||||
color3f[] primvars:displayColor = [(0.14, 0.16, 0.19)]
|
||||
float[] primvars:displayRoughness = [0.35]
|
||||
}
|
||||
|
||||
def Cube "NorthWallGuide"
|
||||
{
|
||||
double3 xformOp:translate = (30.0, 40.5, 1.0)
|
||||
double3 xformOp:scale = (30.0, 0.15, 1.0)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.3, 0.35, 0.4)]
|
||||
}
|
||||
|
||||
def Cube "SouthWallGuide"
|
||||
{
|
||||
double3 xformOp:translate = (30.0, -0.5, 1.0)
|
||||
double3 xformOp:scale = (30.0, 0.15, 1.0)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.3, 0.35, 0.4)]
|
||||
}
|
||||
|
||||
def Cube "EastWallGuide"
|
||||
{
|
||||
double3 xformOp:translate = (60.5, 20.0, 1.0)
|
||||
double3 xformOp:scale = (0.15, 20.0, 1.0)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.3, 0.35, 0.4)]
|
||||
}
|
||||
}
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Inventory Zones (Zone A, Zone B, Zone C Demarcations)
|
||||
# -------------------------------------------------------------------------
|
||||
def Scope "Zones"
|
||||
{
|
||||
def Cube "zone_a"
|
||||
{
|
||||
double3 xformOp:translate = (15.00, 20.00, 0.005)
|
||||
double3 xformOp:scale = (10.00, 15.00, 0.005)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.15, 0.45, 0.85)]
|
||||
float[] primvars:displayOpacity = [0.25]
|
||||
}
|
||||
def Cube "zone_b"
|
||||
{
|
||||
double3 xformOp:translate = (37.50, 20.00, 0.005)
|
||||
double3 xformOp:scale = (7.50, 15.00, 0.005)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.85, 0.55, 0.12)]
|
||||
float[] primvars:displayOpacity = [0.25]
|
||||
}
|
||||
def Cube "zone_c"
|
||||
{
|
||||
double3 xformOp:translate = (53.00, 20.00, 0.005)
|
||||
double3 xformOp:scale = (5.00, 15.00, 0.005)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.12, 0.68, 0.38)]
|
||||
float[] primvars:displayOpacity = [0.25]
|
||||
}
|
||||
}
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Storage Racks (13 Inventory Catalog Locations)
|
||||
# -------------------------------------------------------------------------
|
||||
def Scope "StorageRacks"
|
||||
{
|
||||
def Xform "rack_a_01"
|
||||
{
|
||||
double3 xformOp:translate = (8.00, 10.00, 1.80)
|
||||
double3 xformOp:scale = (0.90, 0.50, 1.80)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "RackFrame"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.2, 0.4, 0.7)]
|
||||
float[] primvars:displayRoughness = [0.4]
|
||||
}
|
||||
}
|
||||
def Xform "rack_a_02"
|
||||
{
|
||||
double3 xformOp:translate = (8.00, 20.00, 1.80)
|
||||
double3 xformOp:scale = (0.90, 0.50, 1.80)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "RackFrame"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.2, 0.4, 0.7)]
|
||||
float[] primvars:displayRoughness = [0.4]
|
||||
}
|
||||
}
|
||||
def Xform "rack_a_03"
|
||||
{
|
||||
double3 xformOp:translate = (16.00, 10.00, 1.80)
|
||||
double3 xformOp:scale = (0.90, 0.50, 1.80)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "RackFrame"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.2, 0.4, 0.7)]
|
||||
float[] primvars:displayRoughness = [0.4]
|
||||
}
|
||||
}
|
||||
def Xform "rack_a_04"
|
||||
{
|
||||
double3 xformOp:translate = (16.00, 20.00, 1.80)
|
||||
double3 xformOp:scale = (0.90, 0.50, 1.80)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "RackFrame"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.2, 0.4, 0.7)]
|
||||
float[] primvars:displayRoughness = [0.4]
|
||||
}
|
||||
}
|
||||
def Xform "rack_a_05"
|
||||
{
|
||||
double3 xformOp:translate = (20.00, 30.00, 1.80)
|
||||
double3 xformOp:scale = (0.90, 0.50, 1.80)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "RackFrame"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.2, 0.4, 0.7)]
|
||||
float[] primvars:displayRoughness = [0.4]
|
||||
}
|
||||
}
|
||||
def Xform "rack_b_01"
|
||||
{
|
||||
double3 xformOp:translate = (34.00, 10.00, 2.20)
|
||||
double3 xformOp:scale = (1.40, 0.70, 2.20)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "RackFrame"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.8, 0.5, 0.1)]
|
||||
float[] primvars:displayRoughness = [0.4]
|
||||
}
|
||||
}
|
||||
def Xform "rack_b_02"
|
||||
{
|
||||
double3 xformOp:translate = (34.00, 22.00, 2.20)
|
||||
double3 xformOp:scale = (1.40, 0.70, 2.20)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "RackFrame"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.8, 0.5, 0.1)]
|
||||
float[] primvars:displayRoughness = [0.4]
|
||||
}
|
||||
}
|
||||
def Xform "rack_b_03"
|
||||
{
|
||||
double3 xformOp:translate = (40.00, 10.00, 2.20)
|
||||
double3 xformOp:scale = (1.40, 0.70, 2.20)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "RackFrame"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.8, 0.5, 0.1)]
|
||||
float[] primvars:displayRoughness = [0.4]
|
||||
}
|
||||
}
|
||||
def Xform "rack_b_04"
|
||||
{
|
||||
double3 xformOp:translate = (40.00, 22.00, 2.20)
|
||||
double3 xformOp:scale = (1.40, 0.70, 2.20)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "RackFrame"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.8, 0.5, 0.1)]
|
||||
float[] primvars:displayRoughness = [0.4]
|
||||
}
|
||||
}
|
||||
def Xform "rack_c_01"
|
||||
{
|
||||
double3 xformOp:translate = (50.00, 10.00, 1.60)
|
||||
double3 xformOp:scale = (1.20, 0.60, 1.60)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "RackFrame"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.2, 0.6, 0.4)]
|
||||
float[] primvars:displayRoughness = [0.4]
|
||||
}
|
||||
}
|
||||
def Xform "rack_c_02"
|
||||
{
|
||||
double3 xformOp:translate = (50.00, 22.00, 1.60)
|
||||
double3 xformOp:scale = (1.20, 0.60, 1.60)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "RackFrame"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.2, 0.6, 0.4)]
|
||||
float[] primvars:displayRoughness = [0.4]
|
||||
}
|
||||
}
|
||||
def Xform "rack_c_03"
|
||||
{
|
||||
double3 xformOp:translate = (54.00, 10.00, 1.60)
|
||||
double3 xformOp:scale = (1.20, 0.60, 1.60)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "RackFrame"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.2, 0.6, 0.4)]
|
||||
float[] primvars:displayRoughness = [0.4]
|
||||
}
|
||||
}
|
||||
def Xform "rack_c_04"
|
||||
{
|
||||
double3 xformOp:translate = (54.00, 22.00, 1.60)
|
||||
double3 xformOp:scale = (1.20, 0.60, 1.60)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "RackFrame"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.2, 0.6, 0.4)]
|
||||
float[] primvars:displayRoughness = [0.4]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Operational Stations
|
||||
# -------------------------------------------------------------------------
|
||||
def Scope "Stations"
|
||||
{
|
||||
def Xform "dock_inbound_1"
|
||||
{
|
||||
double3 xformOp:translate = (2.00, 10.00, 0.15)
|
||||
double3 xformOp:scale = (1.50, 2.00, 0.15)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "Platform"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.85, 0.25, 0.2)]
|
||||
}
|
||||
}
|
||||
def Xform "dock_inbound_2"
|
||||
{
|
||||
double3 xformOp:translate = (2.00, 20.00, 0.15)
|
||||
double3 xformOp:scale = (1.50, 2.00, 0.15)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "Platform"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.85, 0.25, 0.2)]
|
||||
}
|
||||
}
|
||||
def Xform "picking_station_a1"
|
||||
{
|
||||
double3 xformOp:translate = (25.00, 2.00, 0.40)
|
||||
double3 xformOp:scale = (2.00, 1.20, 0.40)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "Platform"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.2, 0.75, 0.85)]
|
||||
}
|
||||
}
|
||||
def Xform "picking_station_b1"
|
||||
{
|
||||
double3 xformOp:translate = (40.00, 2.00, 0.40)
|
||||
double3 xformOp:scale = (2.00, 1.20, 0.40)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "Platform"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.2, 0.75, 0.85)]
|
||||
}
|
||||
}
|
||||
def Xform "production_dropoff_c1"
|
||||
{
|
||||
double3 xformOp:translate = (55.00, 38.00, 0.25)
|
||||
double3 xformOp:scale = (1.80, 1.80, 0.25)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "Platform"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.25, 0.8, 0.35)]
|
||||
}
|
||||
}
|
||||
def Xform "outbound_pack_1"
|
||||
{
|
||||
double3 xformOp:translate = (2.00, 30.00, 0.15)
|
||||
double3 xformOp:scale = (1.50, 2.00, 0.15)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "Platform"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.9, 0.4, 0.1)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Autonomous Mobile Robot (AMR) Charging Bays
|
||||
# -------------------------------------------------------------------------
|
||||
def Scope "ChargingStations"
|
||||
{
|
||||
def Xform "charge_bay_1"
|
||||
{
|
||||
double3 xformOp:translate = (2.00, 36.00, 0.05)
|
||||
double3 xformOp:scale = (0.75, 0.75, 0.05)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "ChargePad"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.15, 0.85, 0.95)]
|
||||
}
|
||||
|
||||
def Cube "StationPedestal"
|
||||
{
|
||||
double3 xformOp:translate = (0.0, 0.6, 0.6)
|
||||
double3 xformOp:scale = (0.2, 0.1, 0.6)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.2, 0.25, 0.3)]
|
||||
}
|
||||
}
|
||||
def Xform "charge_bay_2"
|
||||
{
|
||||
double3 xformOp:translate = (4.00, 36.00, 0.05)
|
||||
double3 xformOp:scale = (0.75, 0.75, 0.05)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "ChargePad"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.15, 0.85, 0.95)]
|
||||
}
|
||||
|
||||
def Cube "StationPedestal"
|
||||
{
|
||||
double3 xformOp:translate = (0.0, 0.6, 0.6)
|
||||
double3 xformOp:scale = (0.2, 0.1, 0.6)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.2, 0.25, 0.3)]
|
||||
}
|
||||
}
|
||||
def Xform "charge_bay_3"
|
||||
{
|
||||
double3 xformOp:translate = (6.00, 36.00, 0.05)
|
||||
double3 xformOp:scale = (0.75, 0.75, 0.05)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "ChargePad"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.15, 0.85, 0.95)]
|
||||
}
|
||||
|
||||
def Cube "StationPedestal"
|
||||
{
|
||||
double3 xformOp:translate = (0.0, 0.6, 0.6)
|
||||
double3 xformOp:scale = (0.2, 0.1, 0.6)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.2, 0.25, 0.3)]
|
||||
}
|
||||
}
|
||||
def Xform "charge_bay_4"
|
||||
{
|
||||
double3 xformOp:translate = (8.00, 36.00, 0.05)
|
||||
double3 xformOp:scale = (0.75, 0.75, 0.05)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
|
||||
def Cube "ChargePad"
|
||||
{
|
||||
color3f[] primvars:displayColor = [(0.15, 0.85, 0.95)]
|
||||
}
|
||||
|
||||
def Cube "StationPedestal"
|
||||
{
|
||||
double3 xformOp:translate = (0.0, 0.6, 0.6)
|
||||
double3 xformOp:scale = (0.2, 0.1, 0.6)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.2, 0.25, 0.3)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Autonomous Mobile Robot (AMR) Fleet
|
||||
# -------------------------------------------------------------------------
|
||||
def Scope "Robots"
|
||||
{
|
||||
def Xform "amr_light_01"
|
||||
{
|
||||
double3 xformOp:translate = (2.00, 36.00, 0.175)
|
||||
double3 xformOp:rotateZ = 0.0
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZ"]
|
||||
|
||||
def Cube "Chassis"
|
||||
{
|
||||
double3 xformOp:scale = (0.4, 0.3, 0.175)
|
||||
uniform token[] xformOpOrder = ["xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.88, 0.90, 0.95)]
|
||||
float[] primvars:displayRoughness = [0.25]
|
||||
}
|
||||
|
||||
def Cube "StatusDome"
|
||||
{
|
||||
double3 xformOp:translate = (0.0, 0.0, 0.255)
|
||||
double3 xformOp:scale = (0.160, 0.120, 0.05)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.15, 0.75, 0.95)]
|
||||
}
|
||||
}
|
||||
def Xform "amr_light_02"
|
||||
{
|
||||
double3 xformOp:translate = (4.00, 36.00, 0.175)
|
||||
double3 xformOp:rotateZ = 0.0
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZ"]
|
||||
|
||||
def Cube "Chassis"
|
||||
{
|
||||
double3 xformOp:scale = (0.4, 0.3, 0.175)
|
||||
uniform token[] xformOpOrder = ["xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.88, 0.90, 0.95)]
|
||||
float[] primvars:displayRoughness = [0.25]
|
||||
}
|
||||
|
||||
def Cube "StatusDome"
|
||||
{
|
||||
double3 xformOp:translate = (0.0, 0.0, 0.255)
|
||||
double3 xformOp:scale = (0.160, 0.120, 0.05)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.15, 0.75, 0.95)]
|
||||
}
|
||||
}
|
||||
def Xform "amr_heavy_01"
|
||||
{
|
||||
double3 xformOp:translate = (6.00, 36.00, 0.225)
|
||||
double3 xformOp:rotateZ = 0.0
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZ"]
|
||||
|
||||
def Cube "Chassis"
|
||||
{
|
||||
double3 xformOp:scale = (0.7, 0.5, 0.225)
|
||||
uniform token[] xformOpOrder = ["xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.92, 0.65, 0.08)]
|
||||
float[] primvars:displayRoughness = [0.25]
|
||||
}
|
||||
|
||||
def Cube "StatusDome"
|
||||
{
|
||||
double3 xformOp:translate = (0.0, 0.0, 0.305)
|
||||
double3 xformOp:scale = (0.280, 0.200, 0.05)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.15, 0.85, 0.3)]
|
||||
}
|
||||
}
|
||||
def Xform "amr_heavy_02"
|
||||
{
|
||||
double3 xformOp:translate = (8.00, 36.00, 0.225)
|
||||
double3 xformOp:rotateZ = 0.0
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZ"]
|
||||
|
||||
def Cube "Chassis"
|
||||
{
|
||||
double3 xformOp:scale = (0.7, 0.5, 0.225)
|
||||
uniform token[] xformOpOrder = ["xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.92, 0.65, 0.08)]
|
||||
float[] primvars:displayRoughness = [0.25]
|
||||
}
|
||||
|
||||
def Cube "StatusDome"
|
||||
{
|
||||
double3 xformOp:translate = (0.0, 0.0, 0.305)
|
||||
double3 xformOp:scale = (0.280, 0.200, 0.05)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||
color3f[] primvars:displayColor = [(0.15, 0.85, 0.3)]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -193,18 +193,17 @@ def export_usd(config_dir: Optional[str] = None, output_path: Optional[str] = No
|
||||
setup_logging()
|
||||
logger = get_logger("cli")
|
||||
try:
|
||||
from warehouse_twin.domain.warehouse import WarehouseModel
|
||||
from warehouse_twin.interfaces.usd_generator import WarehouseUSDGenerator
|
||||
|
||||
loader = ConfigLoader(config_dir)
|
||||
bundle = loader.load_all()
|
||||
model = WarehouseModel.from_config_dict(bundle.warehouse)
|
||||
|
||||
generator = WarehouseUSDGenerator(model)
|
||||
default_out = Path("omniverse/scenes/warehouse_phase1.usda")
|
||||
generator = WarehouseUSDGenerator.from_config_bundle(bundle)
|
||||
default_out = Path("omniverse/scenes/warehouse_phase2.usda")
|
||||
out_file = Path(output_path).resolve() if output_path else default_out.resolve()
|
||||
|
||||
saved_path = generator.export_usda(out_file)
|
||||
model = generator.model
|
||||
print("=" * 65)
|
||||
print("Warehouse 3D OpenUSD Scene Successfully Generated")
|
||||
print("=" * 65)
|
||||
@@ -212,6 +211,9 @@ def export_usd(config_dir: Optional[str] = None, output_path: Optional[str] = No
|
||||
print(f"Facility: {model.dimensions.width}m x {model.dimensions.depth}m x {model.dimensions.height}m")
|
||||
print(f"Zones: Zone A (Blue), Zone B (Amber), Zone C (Green)")
|
||||
print(f"Entities: {len(model.storage_locations)} Storage Racks, {len(model.stations)} Stations, {len(model.charging_stations)} Chargers")
|
||||
print(f"AMR Fleet: {len(generator.robots)} Autonomous Mobile Robots")
|
||||
for r in generator.robots:
|
||||
print(f" - {r.robot_id} ({r.robot_type}) at ({r.position.x}, {r.position.y}, {r.position.z}) [battery: {r.battery_percent:.0f}%]")
|
||||
print("-" * 65)
|
||||
print("How to view in Omniverse Kit:")
|
||||
print(f" 1. In the active Kit App window, select File -> Open")
|
||||
@@ -286,7 +288,7 @@ def main(argv: Optional[list[str]] = None) -> int:
|
||||
"--output",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Output USD file path (defaults to omniverse/scenes/warehouse_phase1.usda)",
|
||||
help="Output USD file path (defaults to omniverse/scenes/warehouse_phase2.usda)",
|
||||
)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
@@ -1,5 +1,26 @@
|
||||
"""Domain models for Warehouse Robot Fleet Digital Twin."""
|
||||
|
||||
from warehouse_twin.domain.events import (
|
||||
SimulationEvent,
|
||||
SimulationEventType,
|
||||
)
|
||||
from warehouse_twin.domain.inventory import (
|
||||
InsufficientStockError,
|
||||
InventoryCatalog,
|
||||
InventoryItem,
|
||||
)
|
||||
from warehouse_twin.domain.robot import (
|
||||
IncompatibleRobotTaskError,
|
||||
InvalidStateTransitionError,
|
||||
Robot,
|
||||
RobotState,
|
||||
RobotTypeSpec,
|
||||
)
|
||||
from warehouse_twin.domain.task import (
|
||||
Task,
|
||||
TaskStatus,
|
||||
TaskType,
|
||||
)
|
||||
from warehouse_twin.domain.warehouse import (
|
||||
ChargingStation,
|
||||
NodeType,
|
||||
@@ -16,6 +37,24 @@ from warehouse_twin.domain.warehouse import (
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# Robot
|
||||
"IncompatibleRobotTaskError",
|
||||
"InvalidStateTransitionError",
|
||||
"Robot",
|
||||
"RobotState",
|
||||
"RobotTypeSpec",
|
||||
# Task
|
||||
"Task",
|
||||
"TaskStatus",
|
||||
"TaskType",
|
||||
# Inventory
|
||||
"InsufficientStockError",
|
||||
"InventoryCatalog",
|
||||
"InventoryItem",
|
||||
# Events
|
||||
"SimulationEvent",
|
||||
"SimulationEventType",
|
||||
# Warehouse
|
||||
"ChargingStation",
|
||||
"NodeType",
|
||||
"Position3D",
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Simulation event schemas: structured records for operational auditing and analytics."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
|
||||
class SimulationEventType(str, Enum):
|
||||
"""Categorization of discrete events emitted by the simulation engine."""
|
||||
TASK_RELEASED = "TASK_RELEASED"
|
||||
TASK_ASSIGNED = "TASK_ASSIGNED"
|
||||
TASK_STARTED = "TASK_STARTED"
|
||||
TASK_COMPLETED = "TASK_COMPLETED"
|
||||
TASK_CANCELLED = "TASK_CANCELLED"
|
||||
TASK_FAILED = "TASK_FAILED"
|
||||
|
||||
ROBOT_DISPATCHED = "ROBOT_DISPATCHED"
|
||||
ROBOT_STATE_CHANGED = "ROBOT_STATE_CHANGED"
|
||||
ROBOT_ARRIVED = "ROBOT_ARRIVED"
|
||||
ROBOT_CHARGING_STARTED = "ROBOT_CHARGING_STARTED"
|
||||
ROBOT_CHARGING_COMPLETED = "ROBOT_CHARGING_COMPLETED"
|
||||
|
||||
INVENTORY_RESERVED = "INVENTORY_RESERVED"
|
||||
INVENTORY_CONSUMED = "INVENTORY_CONSUMED"
|
||||
INVENTORY_REPLENISHED = "INVENTORY_REPLENISHED"
|
||||
STOCKOUT_OCCURRED = "STOCKOUT_OCCURRED"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SimulationEvent:
|
||||
"""Immutable audit record emitted upon discrete simulation state transitions."""
|
||||
event_id: str
|
||||
simulation_time: float
|
||||
event_type: SimulationEventType
|
||||
entity_id: str
|
||||
task_id: Optional[str] = None
|
||||
metadata: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Convert event to serializable dictionary format."""
|
||||
return {
|
||||
"event_id": self.event_id,
|
||||
"simulation_time": round(self.simulation_time, 3),
|
||||
"event_type": self.event_type.value,
|
||||
"entity_id": self.entity_id,
|
||||
"task_id": self.task_id,
|
||||
"metadata": self.metadata,
|
||||
}
|
||||
|
||||
def to_jsonl(self) -> str:
|
||||
"""Serialize event to a single-line JSON string."""
|
||||
return json.dumps(self.to_dict())
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Inventory domain entities: stock tracking, reservation, replenishment, and catalogs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
class InsufficientStockError(Exception):
|
||||
"""Raised when attempting to reserve or consume more stock than is available."""
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class InventoryItem:
|
||||
"""Catalog inventory item tracking on-hand stock, weights, and replenishment rules."""
|
||||
item_id: str
|
||||
name: str
|
||||
category: str
|
||||
zone: str
|
||||
unit_weight_kg: float
|
||||
initial_stock: int
|
||||
current_stock: int
|
||||
reserved_stock: int = 0
|
||||
minimum_stock: int = 10
|
||||
replenishment_batch: int = 50
|
||||
storage_location: str = ""
|
||||
|
||||
@property
|
||||
def available_stock(self) -> int:
|
||||
"""On-hand quantity unencumbered by pending reservations."""
|
||||
return max(0, self.current_stock - self.reserved_stock)
|
||||
|
||||
def reserve(self, qty: int) -> None:
|
||||
"""Reserve units for an assigned picking task.
|
||||
|
||||
Raises:
|
||||
InsufficientStockError: If available stock is less than qty.
|
||||
"""
|
||||
if qty <= 0:
|
||||
return
|
||||
if qty > self.available_stock:
|
||||
raise InsufficientStockError(
|
||||
f"Cannot reserve {qty} units of '{self.item_id}'. Only {self.available_stock} available."
|
||||
)
|
||||
self.reserved_stock += qty
|
||||
|
||||
def release_reservation(self, qty: int) -> None:
|
||||
"""Release previously reserved units without consuming them."""
|
||||
self.reserved_stock = max(0, self.reserved_stock - max(0, qty))
|
||||
|
||||
def consume(self, qty: int) -> None:
|
||||
"""Deduct stock upon successful pick completion.
|
||||
|
||||
Raises:
|
||||
InsufficientStockError: If current stock is less than qty.
|
||||
"""
|
||||
if qty <= 0:
|
||||
return
|
||||
if qty > self.current_stock:
|
||||
raise InsufficientStockError(
|
||||
f"Cannot consume {qty} units of '{self.item_id}'. Only {self.current_stock} in stock."
|
||||
)
|
||||
self.current_stock -= qty
|
||||
self.reserved_stock = max(0, self.reserved_stock - qty)
|
||||
|
||||
def replenish(self, qty: int) -> None:
|
||||
"""Add newly arrived stock from an inbound replenishment task."""
|
||||
if qty > 0:
|
||||
self.current_stock += qty
|
||||
|
||||
def needs_replenishment(self) -> bool:
|
||||
"""Check if on-hand stock has dropped to or below minimum threshold."""
|
||||
return self.current_stock <= self.minimum_stock
|
||||
|
||||
|
||||
class InventoryCatalog:
|
||||
"""Repository managing the full inventory catalog across all warehouse zones."""
|
||||
|
||||
def __init__(self, items: Optional[Dict[str, InventoryItem]] = None) -> None:
|
||||
"""Initialize catalog with an optional dictionary of items."""
|
||||
self._items: Dict[str, InventoryItem] = items or {}
|
||||
|
||||
@classmethod
|
||||
def from_config_dict(cls, data: Dict[str, Any]) -> InventoryCatalog:
|
||||
"""Construct an InventoryCatalog from parsed inventory configuration."""
|
||||
catalog_items: Dict[str, InventoryItem] = {}
|
||||
|
||||
for cat_key, cat_data in data.get("categories", {}).items():
|
||||
cat_name = cat_data.get("name", cat_key)
|
||||
cat_zone = cat_data.get("zone", "zone_a")
|
||||
|
||||
for item_data in cat_data.get("items", []):
|
||||
item_id = item_data["item_id"]
|
||||
initial = int(item_data.get("initial_stock", 100))
|
||||
item = InventoryItem(
|
||||
item_id=item_id,
|
||||
name=item_data.get("name", item_id),
|
||||
category=cat_name,
|
||||
zone=cat_zone,
|
||||
unit_weight_kg=float(item_data.get("unit_weight_kg", 5.0)),
|
||||
initial_stock=initial,
|
||||
current_stock=initial,
|
||||
minimum_stock=int(item_data.get("minimum_stock", 20)),
|
||||
replenishment_batch=int(item_data.get("replenishment_batch", 50)),
|
||||
storage_location=item_data.get("storage_location", ""),
|
||||
)
|
||||
catalog_items[item_id] = item
|
||||
|
||||
return cls(catalog_items)
|
||||
|
||||
def get_item(self, item_id: str) -> Optional[InventoryItem]:
|
||||
"""Retrieve an inventory item by ID."""
|
||||
return self._items.get(item_id)
|
||||
|
||||
def get_items_by_zone(self, zone_id: str) -> List[InventoryItem]:
|
||||
"""Return all items stored in the designated inventory zone."""
|
||||
return [item for item in self._items.values() if item.zone == zone_id]
|
||||
|
||||
def get_items_needing_replenishment(self) -> List[InventoryItem]:
|
||||
"""Return all items whose on-hand stock is at or below minimum threshold."""
|
||||
return [item for item in self._items.values() if item.needs_replenishment()]
|
||||
|
||||
def list_all_items(self) -> List[InventoryItem]:
|
||||
"""Return all registered catalog items."""
|
||||
return list(self._items.values())
|
||||
|
||||
def total_sku_count(self) -> int:
|
||||
"""Return number of unique item SKUs in catalog."""
|
||||
return len(self._items)
|
||||
@@ -0,0 +1,297 @@
|
||||
"""Robot domain entities: AMR state machine, kinematics, energy models, and fleet registry."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Any, Dict, List, Optional, Set, Tuple
|
||||
|
||||
from warehouse_twin.domain.warehouse import Position3D
|
||||
|
||||
|
||||
class RobotState(str, Enum):
|
||||
"""Discrete operational states for Autonomous Mobile Robots (AMRs)."""
|
||||
IDLE = "IDLE"
|
||||
DISPATCHED = "DISPATCHED"
|
||||
PICKING = "PICKING"
|
||||
LOADED_TRANSIT = "LOADED_TRANSIT"
|
||||
DROPPING = "DROPPING"
|
||||
TRANSIT_TO_CHARGE = "TRANSIT_TO_CHARGE"
|
||||
CHARGING = "CHARGING"
|
||||
MAINTENANCE = "MAINTENANCE"
|
||||
|
||||
|
||||
class InvalidStateTransitionError(Exception):
|
||||
"""Raised when an illegal robot or task state machine transition is attempted."""
|
||||
pass
|
||||
|
||||
|
||||
class IncompatibleRobotTaskError(Exception):
|
||||
"""Raised when a robot is assigned a task it cannot legally or physically execute."""
|
||||
pass
|
||||
|
||||
|
||||
# Strict State Machine Transition Rules
|
||||
# Maps each RobotState to the set of legal target states.
|
||||
LEGAL_ROBOT_TRANSITIONS: Dict[RobotState, Set[RobotState]] = {
|
||||
RobotState.IDLE: {
|
||||
RobotState.DISPATCHED,
|
||||
RobotState.TRANSIT_TO_CHARGE,
|
||||
RobotState.CHARGING,
|
||||
RobotState.MAINTENANCE,
|
||||
},
|
||||
RobotState.DISPATCHED: {
|
||||
RobotState.PICKING,
|
||||
RobotState.IDLE, # Task cancellation or preemption
|
||||
RobotState.TRANSIT_TO_CHARGE, # Low battery abort
|
||||
RobotState.MAINTENANCE,
|
||||
},
|
||||
RobotState.PICKING: {
|
||||
RobotState.LOADED_TRANSIT,
|
||||
RobotState.IDLE, # Aborted pick
|
||||
RobotState.MAINTENANCE,
|
||||
},
|
||||
RobotState.LOADED_TRANSIT: {
|
||||
RobotState.DROPPING,
|
||||
RobotState.MAINTENANCE,
|
||||
},
|
||||
RobotState.DROPPING: {
|
||||
RobotState.IDLE,
|
||||
RobotState.DISPATCHED, # Chained dispatch
|
||||
RobotState.TRANSIT_TO_CHARGE,
|
||||
RobotState.MAINTENANCE,
|
||||
},
|
||||
RobotState.TRANSIT_TO_CHARGE: {
|
||||
RobotState.CHARGING,
|
||||
RobotState.IDLE,
|
||||
RobotState.MAINTENANCE,
|
||||
},
|
||||
RobotState.CHARGING: {
|
||||
RobotState.IDLE,
|
||||
RobotState.DISPATCHED, # Fast-dispatched if needed
|
||||
RobotState.MAINTENANCE,
|
||||
},
|
||||
RobotState.MAINTENANCE: {
|
||||
RobotState.IDLE,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RobotTypeSpec:
|
||||
"""Immutable specification defining physical and kinematic limits of an AMR class."""
|
||||
type_id: str
|
||||
name: str
|
||||
description: str
|
||||
payload_capacity_kg: float
|
||||
max_speed_mps: float
|
||||
acceleration_mps2: float
|
||||
battery_capacity_kwh: float
|
||||
power_consumption_kw: Dict[str, float]
|
||||
allowed_zones: Set[str]
|
||||
dimensions: Tuple[float, float, float] # length, width, height in meters
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, type_id: str, data: Dict[str, Any]) -> RobotTypeSpec:
|
||||
"""Construct a RobotTypeSpec from a dictionary configuration."""
|
||||
dims = data.get("dimensions", {})
|
||||
dim_tuple = (
|
||||
float(dims.get("length", 1.0)),
|
||||
float(dims.get("width", 0.8)),
|
||||
float(dims.get("height", 0.4)),
|
||||
)
|
||||
return cls(
|
||||
type_id=type_id,
|
||||
name=data.get("name", type_id),
|
||||
description=data.get("description", ""),
|
||||
payload_capacity_kg=float(data["payload_capacity_kg"]),
|
||||
max_speed_mps=float(data["max_speed_mps"]),
|
||||
acceleration_mps2=float(data.get("acceleration_mps2", 0.5)),
|
||||
battery_capacity_kwh=float(data["battery_capacity_kwh"]),
|
||||
power_consumption_kw=dict(data.get("power_consumption_kw", {})),
|
||||
allowed_zones=set(data.get("allowed_zones", ["zone_a", "zone_b", "zone_c"])),
|
||||
dimensions=dim_tuple,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Robot:
|
||||
"""Autonomous Mobile Robot (AMR) entity model tracking state, battery, and metrics."""
|
||||
robot_id: str
|
||||
robot_type: str
|
||||
position: Position3D
|
||||
maximum_speed: float
|
||||
payload_capacity: float
|
||||
battery_level: float
|
||||
battery_capacity: float
|
||||
energy_consumption: Dict[str, float]
|
||||
current_state: RobotState = RobotState.IDLE
|
||||
current_task_id: Optional[str] = None
|
||||
current_route: List[str] = field(default_factory=list)
|
||||
accumulated_distance: float = 0.0
|
||||
busy_time: float = 0.0
|
||||
idle_time: float = 0.0
|
||||
charging_time: float = 0.0
|
||||
allowed_zones: Set[str] = field(default_factory=lambda: {"zone_a", "zone_b", "zone_c"})
|
||||
state_enter_time: float = 0.0
|
||||
yaw_degrees: float = 0.0
|
||||
|
||||
@classmethod
|
||||
def from_fleet_dict(cls, fleet_data: Dict[str, Any], type_specs: Dict[str, RobotTypeSpec]) -> Robot:
|
||||
"""Construct a Robot instance from fleet configuration and matching type spec."""
|
||||
robot_type_id = fleet_data["robot_type"]
|
||||
if robot_type_id not in type_specs:
|
||||
raise ValueError(f"Undefined robot_type '{robot_type_id}' for robot '{fleet_data.get('robot_id')}'")
|
||||
spec = type_specs[robot_type_id]
|
||||
|
||||
battery_pct = float(fleet_data.get("initial_battery_percent", 100.0))
|
||||
initial_battery = (battery_pct / 100.0) * spec.battery_capacity_kwh
|
||||
|
||||
return cls(
|
||||
robot_id=fleet_data["robot_id"],
|
||||
robot_type=robot_type_id,
|
||||
position=Position3D.from_iterable(fleet_data.get("initial_position", [0.0, 0.0, 0.0])),
|
||||
maximum_speed=spec.max_speed_mps,
|
||||
payload_capacity=spec.payload_capacity_kg,
|
||||
battery_level=initial_battery,
|
||||
battery_capacity=spec.battery_capacity_kwh,
|
||||
energy_consumption=dict(spec.power_consumption_kw),
|
||||
allowed_zones=set(spec.allowed_zones),
|
||||
)
|
||||
|
||||
@property
|
||||
def battery_percent(self) -> float:
|
||||
"""State of Charge (SoC) expressed as a percentage [0.0 - 100.0]."""
|
||||
if self.battery_capacity <= 0:
|
||||
return 0.0
|
||||
return max(0.0, min(100.0, (self.battery_level / self.battery_capacity) * 100.0))
|
||||
|
||||
def transition_to(self, new_state: RobotState, sim_time: float) -> None:
|
||||
"""Execute a state transition verifying legality against the transition matrix.
|
||||
|
||||
Args:
|
||||
new_state: Destination RobotState.
|
||||
sim_time: Current simulation timestamp in seconds.
|
||||
|
||||
Raises:
|
||||
InvalidStateTransitionError: If the transition is prohibited.
|
||||
"""
|
||||
if new_state == self.current_state:
|
||||
return
|
||||
|
||||
legal_targets = LEGAL_ROBOT_TRANSITIONS.get(self.current_state, set())
|
||||
if new_state not in legal_targets:
|
||||
raise InvalidStateTransitionError(
|
||||
f"Illegal state transition for robot '{self.robot_id}': "
|
||||
f"Cannot transition from {self.current_state.value} to {new_state.value}. "
|
||||
f"Legal targets: {[s.value for s in legal_targets]}"
|
||||
)
|
||||
|
||||
# Accumulate duration in previous state
|
||||
duration = max(0.0, sim_time - self.state_enter_time)
|
||||
if self.current_state == RobotState.IDLE:
|
||||
self.idle_time += duration
|
||||
elif self.current_state == RobotState.CHARGING:
|
||||
self.charging_time += duration
|
||||
else:
|
||||
self.busy_time += duration
|
||||
|
||||
self.current_state = new_state
|
||||
self.state_enter_time = sim_time
|
||||
|
||||
def can_carry_payload(self, payload_kg: float) -> bool:
|
||||
"""Check if requested payload mass is within the AMR load rating."""
|
||||
return payload_kg <= self.payload_capacity + 1e-4
|
||||
|
||||
def can_access_zone(self, zone_id: str) -> bool:
|
||||
"""Check if robot is allowed to enter the specified zone."""
|
||||
if zone_id == "transit":
|
||||
return True
|
||||
return zone_id in self.allowed_zones
|
||||
|
||||
def update_position(self, new_position: Position3D, distance_delta: float, yaw: Optional[float] = None) -> None:
|
||||
"""Update robot spatial coordinates, accumulated travel distance, and heading."""
|
||||
self.position = new_position
|
||||
self.accumulated_distance += max(0.0, distance_delta)
|
||||
if yaw is not None:
|
||||
self.yaw_degrees = yaw % 360.0
|
||||
|
||||
def validate_task_compatibility(self, task: Any) -> Tuple[bool, Optional[str]]:
|
||||
"""Validate if this robot can physically and operationally accept the given task.
|
||||
|
||||
Checks:
|
||||
1. Operational state: Must be IDLE or CHARGING (if interruptible).
|
||||
2. Payload capacity: Task required payload must not exceed robot rating.
|
||||
3. Zone permissions: Target zone must be in robot's allowed_zones.
|
||||
|
||||
Returns:
|
||||
Tuple of (is_compatible: bool, failure_reason: Optional[str]).
|
||||
"""
|
||||
# 1. Operational state check
|
||||
if self.current_state not in (RobotState.IDLE, RobotState.CHARGING):
|
||||
return False, f"Robot '{self.robot_id}' is currently busy in state {self.current_state.value}"
|
||||
|
||||
# 2. Payload capacity check
|
||||
payload = getattr(task, "required_payload", 0.0)
|
||||
if not self.can_carry_payload(payload):
|
||||
return False, (
|
||||
f"Task payload {payload:.1f}kg exceeds robot '{self.robot_id}' "
|
||||
f"capacity ({self.payload_capacity:.1f}kg)"
|
||||
)
|
||||
|
||||
# 3. Zone permissions check
|
||||
target_zone = getattr(task, "target_zone", None)
|
||||
if target_zone and not self.can_access_zone(target_zone):
|
||||
return False, (
|
||||
f"Robot '{self.robot_id}' (type '{self.robot_type}') is restricted from "
|
||||
f"entering target zone '{target_zone}'"
|
||||
)
|
||||
|
||||
return True, None
|
||||
|
||||
def assign_task(self, task: Any) -> None:
|
||||
"""Assign active task after verifying compatibility rules.
|
||||
|
||||
Raises:
|
||||
IncompatibleRobotTaskError: If robot is incompatible with task payload or zone.
|
||||
"""
|
||||
compatible, reason = self.validate_task_compatibility(task)
|
||||
if not compatible:
|
||||
raise IncompatibleRobotTaskError(reason or "Robot incompatible with task")
|
||||
|
||||
task_id = getattr(task, "task_id", str(task))
|
||||
self.current_task_id = task_id
|
||||
if hasattr(task, "assigned_robot_id"):
|
||||
task.assigned_robot_id = self.robot_id
|
||||
|
||||
def release_task(self) -> None:
|
||||
"""Clear active task binding."""
|
||||
self.current_task_id = None
|
||||
self.current_route.clear()
|
||||
|
||||
def consume_energy(self, duration_seconds: float, mode: str = "moving_empty") -> float:
|
||||
"""Deduct energy consumed over duration according to active power mode.
|
||||
|
||||
Args:
|
||||
duration_seconds: Time interval in seconds.
|
||||
mode: Power consumption mode ('idle', 'moving_empty', 'moving_loaded', 'handling').
|
||||
|
||||
Returns:
|
||||
Energy consumed in kWh.
|
||||
"""
|
||||
power_kw = self.energy_consumption.get(mode, 0.1)
|
||||
energy_kwh = (power_kw * duration_seconds) / 3600.0
|
||||
self.battery_level = max(0.0, self.battery_level - energy_kwh)
|
||||
return energy_kwh
|
||||
|
||||
def charge_energy(self, duration_seconds: float, charging_rate_kw: float) -> float:
|
||||
"""Add energy from charger over duration in seconds.
|
||||
|
||||
Returns:
|
||||
Energy added in kWh.
|
||||
"""
|
||||
energy_kwh = (charging_rate_kw * duration_seconds) / 3600.0
|
||||
new_level = min(self.battery_capacity, self.battery_level + energy_kwh)
|
||||
added = new_level - self.battery_level
|
||||
self.battery_level = new_level
|
||||
return added
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Task domain entities: lifecycle states, task types, priorities, and deadlines."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from warehouse_twin.domain.robot import InvalidStateTransitionError
|
||||
|
||||
|
||||
class TaskType(str, Enum):
|
||||
"""Classification of tasks executed by warehouse AMR fleet."""
|
||||
ORDER_PICK = "ORDER_PICK"
|
||||
REPLENISHMENT = "REPLENISHMENT"
|
||||
PRODUCTION_LINE_FEED = "PRODUCTION_LINE_FEED"
|
||||
CHARGING = "CHARGING"
|
||||
|
||||
|
||||
class TaskStatus(str, Enum):
|
||||
"""Discrete operational lifecycle states for simulation tasks."""
|
||||
PENDING = "PENDING"
|
||||
ASSIGNED = "ASSIGNED"
|
||||
IN_PROGRESS = "IN_PROGRESS"
|
||||
COMPLETED = "COMPLETED"
|
||||
CANCELLED = "CANCELLED"
|
||||
FAILED = "FAILED"
|
||||
|
||||
|
||||
# Strict Task Lifecycle Transition Rules
|
||||
LEGAL_TASK_TRANSITIONS: Dict[TaskStatus, set[TaskStatus]] = {
|
||||
TaskStatus.PENDING: {
|
||||
TaskStatus.ASSIGNED,
|
||||
TaskStatus.CANCELLED,
|
||||
},
|
||||
TaskStatus.ASSIGNED: {
|
||||
TaskStatus.IN_PROGRESS,
|
||||
TaskStatus.PENDING, # Reassignment / preemption back to queue
|
||||
TaskStatus.CANCELLED,
|
||||
},
|
||||
TaskStatus.IN_PROGRESS: {
|
||||
TaskStatus.COMPLETED,
|
||||
TaskStatus.CANCELLED,
|
||||
TaskStatus.FAILED,
|
||||
},
|
||||
TaskStatus.COMPLETED: set(), # Terminal state
|
||||
TaskStatus.CANCELLED: set(), # Terminal state
|
||||
TaskStatus.FAILED: set(), # Terminal state
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Task:
|
||||
"""Simulation work order model tracking dispatch, payload requirements, and timing."""
|
||||
task_id: str
|
||||
task_type: TaskType
|
||||
source: str
|
||||
destination: str
|
||||
priority: int = 2 # 1 = Urgent/Production-Critical, 2 = Standard, 3 = Low
|
||||
release_time: float = 0.0 # Simulation clock seconds when task arrived
|
||||
deadline: Optional[float] = None # Strict completion deadline for line-feed tasks
|
||||
required_payload: float = 0.0 # Payload mass in kilograms
|
||||
item_id: Optional[str] = None # Inventory SKU reference
|
||||
quantity: int = 1 # Unit count requested
|
||||
status: TaskStatus = TaskStatus.PENDING
|
||||
assigned_robot_id: Optional[str] = None
|
||||
start_time: Optional[float] = None
|
||||
completion_time: Optional[float] = None
|
||||
target_zone: Optional[str] = None # Operational zone hint ('zone_a', 'zone_b', 'zone_c')
|
||||
|
||||
def transition_to(self, new_status: TaskStatus, sim_time: float) -> None:
|
||||
"""Advance task state machine, validating legal transitions and updating timestamps.
|
||||
|
||||
Args:
|
||||
new_status: Desired destination TaskStatus.
|
||||
sim_time: Current simulation timestamp in seconds.
|
||||
|
||||
Raises:
|
||||
InvalidStateTransitionError: If transition is prohibited.
|
||||
"""
|
||||
if new_status == self.status:
|
||||
return
|
||||
|
||||
legal_targets = LEGAL_TASK_TRANSITIONS.get(self.status, set())
|
||||
if new_status not in legal_targets:
|
||||
raise InvalidStateTransitionError(
|
||||
f"Illegal task transition for task '{self.task_id}': "
|
||||
f"Cannot transition from {self.status.value} to {new_status.value}. "
|
||||
f"Legal targets: {[s.value for s in legal_targets]}"
|
||||
)
|
||||
|
||||
if new_status == TaskStatus.IN_PROGRESS and self.start_time is None:
|
||||
self.start_time = sim_time
|
||||
elif new_status in (TaskStatus.COMPLETED, TaskStatus.CANCELLED, TaskStatus.FAILED):
|
||||
self.completion_time = sim_time
|
||||
|
||||
self.status = new_status
|
||||
|
||||
def is_overdue(self, sim_time: float) -> bool:
|
||||
"""Check if task has passed its deadline without completing."""
|
||||
if self.deadline is None:
|
||||
return False
|
||||
effective_time = self.completion_time if self.completion_time is not None else sim_time
|
||||
return effective_time > self.deadline
|
||||
|
||||
def turnaround_time(self) -> Optional[float]:
|
||||
"""Total duration from release to completion in seconds."""
|
||||
if self.completion_time is None:
|
||||
return None
|
||||
return max(0.0, self.completion_time - self.release_time)
|
||||
|
||||
def waiting_time(self, current_sim_time: Optional[float] = None) -> float:
|
||||
"""Duration spent waiting in queue before execution started."""
|
||||
if self.start_time is not None:
|
||||
return max(0.0, self.start_time - self.release_time)
|
||||
ref_time = current_sim_time if current_sim_time is not None else self.release_time
|
||||
return max(0.0, ref_time - self.release_time)
|
||||
|
||||
def execution_time(self) -> Optional[float]:
|
||||
"""Active handling and transit duration from start to completion."""
|
||||
if self.start_time is None or self.completion_time is None:
|
||||
return None
|
||||
return max(0.0, self.completion_time - self.start_time)
|
||||
@@ -1,7 +1,8 @@
|
||||
"""OpenUSD scene generator for Warehouse Robot Fleet Digital Twin.
|
||||
|
||||
Exports an ASCII OpenUSD (.usda) scene compliant with NVIDIA Omniverse Kit 110.4
|
||||
and standard USD specifications (Z-up, 1.0 meter units).
|
||||
and standard USD specifications (Z-up, 1.0 meter units). Supports visual representations
|
||||
of facility geometry, zones, operational stations, charging pads, and the AMR robot fleet.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -9,18 +10,41 @@ from __future__ import annotations
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from warehouse_twin.domain.robot import Robot, RobotTypeSpec
|
||||
from warehouse_twin.domain.warehouse import WarehouseModel
|
||||
|
||||
|
||||
class WarehouseUSDGenerator:
|
||||
"""Generates OpenUSD (.usda) 3D scenes from a WarehouseModel."""
|
||||
"""Generates OpenUSD (.usda) 3D scenes from WarehouseModel and Robot fleet entities."""
|
||||
|
||||
def __init__(self, model: WarehouseModel) -> None:
|
||||
"""Initialize generator with physical warehouse layout model."""
|
||||
def __init__(
|
||||
self,
|
||||
model: WarehouseModel,
|
||||
robots: Optional[List[Robot]] = None,
|
||||
) -> None:
|
||||
"""Initialize generator with physical warehouse layout model and optional robot fleet."""
|
||||
self.model = model
|
||||
self.robots = robots or []
|
||||
|
||||
@classmethod
|
||||
def from_config_bundle(cls, bundle: Any) -> WarehouseUSDGenerator:
|
||||
"""Construct generator loading both warehouse layout and fleet from ConfigBundle."""
|
||||
model = WarehouseModel.from_config_dict(bundle.warehouse)
|
||||
|
||||
# Parse robot type specs
|
||||
type_specs: Dict[str, RobotTypeSpec] = {}
|
||||
for t_id, t_data in bundle.robots.get("robot_types", {}).items():
|
||||
type_specs[t_id] = RobotTypeSpec.from_dict(t_id, t_data)
|
||||
|
||||
# Build robot fleet entities
|
||||
robots: List[Robot] = []
|
||||
for r_data in bundle.robots.get("fleet", []):
|
||||
robots.append(Robot.from_fleet_dict(r_data, type_specs))
|
||||
|
||||
return cls(model, robots)
|
||||
|
||||
def generate_usda_content(self) -> str:
|
||||
"""Construct valid ASCII OpenUSD 3D stage content representing the warehouse."""
|
||||
"""Construct valid ASCII OpenUSD 3D stage content representing the warehouse and AMRs."""
|
||||
dims = self.model.dimensions
|
||||
w = dims.width
|
||||
d = dims.depth
|
||||
@@ -150,7 +174,7 @@ class WarehouseUSDGenerator:
|
||||
spec = rack_specs.get(loc.zone, {"color": "(0.5, 0.5, 0.5)", "scale": (1.0, 0.5, 1.5)})
|
||||
col = spec["color"]
|
||||
sx, sy, sz = spec["scale"]
|
||||
rz = sz # base is at z=0, center is at z=sz
|
||||
rz = sz
|
||||
|
||||
lines.extend([
|
||||
f' def Xform "{loc_id}"',
|
||||
@@ -179,18 +203,17 @@ class WarehouseUSDGenerator:
|
||||
|
||||
for st_id, st in self.model.stations.items():
|
||||
pos = st.position
|
||||
# Distinguish station visuals
|
||||
if "inbound" in st.station_type.value:
|
||||
st_col = "(0.85, 0.25, 0.2)" # Inbound red/orange
|
||||
st_col = "(0.85, 0.25, 0.2)"
|
||||
st_dim = (1.5, 2.0, 0.15)
|
||||
elif "outbound" in st.station_type.value:
|
||||
st_col = "(0.9, 0.4, 0.1)" # Outbound amber
|
||||
st_col = "(0.9, 0.4, 0.1)"
|
||||
st_dim = (1.5, 2.0, 0.15)
|
||||
elif "picking" in st.station_type.value:
|
||||
st_col = "(0.2, 0.75, 0.85)" # Picking teal/cyan
|
||||
st_col = "(0.2, 0.75, 0.85)"
|
||||
st_dim = (2.0, 1.2, 0.4)
|
||||
else:
|
||||
st_col = "(0.25, 0.8, 0.35)" # Production feed green
|
||||
st_col = "(0.25, 0.8, 0.35)"
|
||||
st_dim = (1.8, 1.8, 0.25)
|
||||
|
||||
lines.extend([
|
||||
@@ -228,7 +251,7 @@ class WarehouseUSDGenerator:
|
||||
"",
|
||||
' def Cube "ChargePad"',
|
||||
" {",
|
||||
" color3f[] primvars:displayColor = [(0.15, 0.85, 0.95)]", # Electric cyan pad
|
||||
" color3f[] primvars:displayColor = [(0.15, 0.85, 0.95)]",
|
||||
" }",
|
||||
"",
|
||||
' def Cube "StationPedestal"',
|
||||
@@ -243,6 +266,68 @@ class WarehouseUSDGenerator:
|
||||
|
||||
lines.extend([
|
||||
" }",
|
||||
])
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Autonomous Mobile Robot (AMR) Fleet (Phase 2 Addition)
|
||||
# -------------------------------------------------------------------------
|
||||
if self.robots:
|
||||
lines.extend([
|
||||
"",
|
||||
" # -------------------------------------------------------------------------",
|
||||
" # Autonomous Mobile Robot (AMR) Fleet",
|
||||
" # -------------------------------------------------------------------------",
|
||||
' def Scope "Robots"',
|
||||
" {",
|
||||
])
|
||||
|
||||
for robot in self.robots:
|
||||
is_heavy = "heavy" in robot.robot_type
|
||||
pos = robot.position
|
||||
|
||||
if is_heavy:
|
||||
# Heavy AMR: Industrial Amber rugged pallet chassis (1.4m x 1.0m x 0.45m)
|
||||
chassis_col = "(0.92, 0.65, 0.08)"
|
||||
indicator_col = "(0.15, 0.85, 0.3)" # Emerald ready glow
|
||||
scale_tuple = (0.70, 0.50, 0.225)
|
||||
elev_z = 0.225
|
||||
else:
|
||||
# Light AMR: High-tech pearl white agile chassis (0.8m x 0.6m x 0.35m)
|
||||
chassis_col = "(0.88, 0.90, 0.95)"
|
||||
indicator_col = "(0.15, 0.75, 0.95)" # Electric cyan ready glow
|
||||
scale_tuple = (0.40, 0.30, 0.175)
|
||||
elev_z = 0.175
|
||||
|
||||
lines.extend([
|
||||
f' def Xform "{robot.robot_id}"',
|
||||
" {",
|
||||
f" double3 xformOp:translate = ({pos.x:.2f}, {pos.y:.2f}, {elev_z:.3f})",
|
||||
f" double3 xformOp:rotateZ = {robot.yaw_degrees:.1f}",
|
||||
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZ"]',
|
||||
"",
|
||||
' def Cube "Chassis"',
|
||||
" {",
|
||||
f" double3 xformOp:scale = ({scale_tuple[0]}, {scale_tuple[1]}, {scale_tuple[2]})",
|
||||
' uniform token[] xformOpOrder = ["xformOp:scale"]',
|
||||
f" color3f[] primvars:displayColor = [{chassis_col}]",
|
||||
" float[] primvars:displayRoughness = [0.25]",
|
||||
" }",
|
||||
"",
|
||||
' def Cube "StatusDome"',
|
||||
" {",
|
||||
f" double3 xformOp:translate = (0.0, 0.0, {scale_tuple[2] + 0.08:.3f})",
|
||||
f" double3 xformOp:scale = ({scale_tuple[0] * 0.4:.3f}, {scale_tuple[1] * 0.4:.3f}, 0.05)",
|
||||
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
|
||||
f" color3f[] primvars:displayColor = [{indicator_col}]",
|
||||
" }",
|
||||
" }",
|
||||
])
|
||||
|
||||
lines.extend([
|
||||
" }",
|
||||
])
|
||||
|
||||
lines.extend([
|
||||
"}",
|
||||
"",
|
||||
])
|
||||
|
||||
@@ -94,3 +94,38 @@ def temp_config_dir(tmp_path: Path) -> Path:
|
||||
json.dump(data, f)
|
||||
|
||||
return config_dir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_robot_types():
|
||||
"""Return dictionary of RobotTypeSpec instances."""
|
||||
from tests.fixtures.sample_models import create_sample_robot_types
|
||||
return create_sample_robot_types()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_light_robot():
|
||||
"""Return an initialized Light AMR instance."""
|
||||
from tests.fixtures.sample_models import create_sample_light_robot
|
||||
return create_sample_light_robot()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_heavy_robot():
|
||||
"""Return an initialized Heavy AMR instance."""
|
||||
from tests.fixtures.sample_models import create_sample_heavy_robot
|
||||
return create_sample_heavy_robot()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_tasks():
|
||||
"""Return a dictionary of sample tasks across zones."""
|
||||
from tests.fixtures.sample_models import create_sample_tasks
|
||||
return create_sample_tasks()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_inventory_catalog():
|
||||
"""Return an initialized InventoryCatalog instance."""
|
||||
from tests.fixtures.sample_models import create_sample_inventory_catalog
|
||||
return create_sample_inventory_catalog()
|
||||
|
||||
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
"""Test fixtures package."""
|
||||
|
||||
from tests.fixtures.sample_models import (
|
||||
create_sample_heavy_robot,
|
||||
create_sample_inventory_catalog,
|
||||
create_sample_light_robot,
|
||||
create_sample_robot_types,
|
||||
create_sample_tasks,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"create_sample_heavy_robot",
|
||||
"create_sample_inventory_catalog",
|
||||
"create_sample_light_robot",
|
||||
"create_sample_robot_types",
|
||||
"create_sample_tasks",
|
||||
]
|
||||
Vendored
+183
@@ -0,0 +1,183 @@
|
||||
"""Deterministic test fixtures and model factories for unit and scenario tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, List
|
||||
|
||||
from warehouse_twin.domain.inventory import InventoryCatalog, InventoryItem
|
||||
from warehouse_twin.domain.robot import Robot, RobotState, RobotTypeSpec
|
||||
from warehouse_twin.domain.task import Task, TaskStatus, TaskType
|
||||
from warehouse_twin.domain.warehouse import Position3D
|
||||
|
||||
|
||||
def create_sample_robot_types() -> Dict[str, RobotTypeSpec]:
|
||||
"""Return standard AMR type specifications."""
|
||||
light_spec = RobotTypeSpec(
|
||||
type_id="light_amr",
|
||||
name="Agile Lightweight AMR",
|
||||
description="Zone A fast parts and transit",
|
||||
payload_capacity_kg=150.0,
|
||||
max_speed_mps=1.8,
|
||||
acceleration_mps2=0.8,
|
||||
battery_capacity_kwh=3.0,
|
||||
power_consumption_kw={
|
||||
"idle": 0.05,
|
||||
"moving_empty": 0.35,
|
||||
"moving_loaded": 0.65,
|
||||
"handling": 0.15,
|
||||
},
|
||||
allowed_zones={"zone_a", "zone_c"}, # Prohibited from Zone B
|
||||
dimensions=(0.8, 0.6, 0.35),
|
||||
)
|
||||
|
||||
heavy_spec = RobotTypeSpec(
|
||||
type_id="heavy_amr",
|
||||
name="Heavy-Duty Pallet AMR",
|
||||
description="Zone B heavy parts and Zone C raw materials",
|
||||
payload_capacity_kg=1500.0,
|
||||
max_speed_mps=1.1,
|
||||
acceleration_mps2=0.4,
|
||||
battery_capacity_kwh=15.0,
|
||||
power_consumption_kw={
|
||||
"idle": 0.12,
|
||||
"moving_empty": 0.90,
|
||||
"moving_loaded": 2.20,
|
||||
"handling": 0.50,
|
||||
},
|
||||
allowed_zones={"zone_a", "zone_b", "zone_c"},
|
||||
dimensions=(1.4, 1.0, 0.45),
|
||||
)
|
||||
|
||||
return {"light_amr": light_spec, "heavy_amr": heavy_spec}
|
||||
|
||||
|
||||
def create_sample_light_robot(robot_id: str = "amr_light_01") -> Robot:
|
||||
"""Create a standard Light AMR for tests."""
|
||||
specs = create_sample_robot_types()
|
||||
spec = specs["light_amr"]
|
||||
return Robot(
|
||||
robot_id=robot_id,
|
||||
robot_type="light_amr",
|
||||
position=Position3D(2.0, 36.0, 0.0),
|
||||
maximum_speed=spec.max_speed_mps,
|
||||
payload_capacity=spec.payload_capacity_kg,
|
||||
battery_level=spec.battery_capacity_kwh,
|
||||
battery_capacity=spec.battery_capacity_kwh,
|
||||
energy_consumption=dict(spec.power_consumption_kw),
|
||||
allowed_zones=set(spec.allowed_zones),
|
||||
)
|
||||
|
||||
|
||||
def create_sample_heavy_robot(robot_id: str = "amr_heavy_01") -> Robot:
|
||||
"""Create a standard Heavy AMR for tests."""
|
||||
specs = create_sample_robot_types()
|
||||
spec = specs["heavy_amr"]
|
||||
return Robot(
|
||||
robot_id=robot_id,
|
||||
robot_type="heavy_amr",
|
||||
position=Position3D(6.0, 36.0, 0.0),
|
||||
maximum_speed=spec.max_speed_mps,
|
||||
payload_capacity=spec.payload_capacity_kg,
|
||||
battery_level=spec.battery_capacity_kwh,
|
||||
battery_capacity=spec.battery_capacity_kwh,
|
||||
energy_consumption=dict(spec.power_consumption_kw),
|
||||
allowed_zones=set(spec.allowed_zones),
|
||||
)
|
||||
|
||||
|
||||
def create_sample_tasks() -> Dict[str, Task]:
|
||||
"""Create a dictionary of representative tasks across all zones."""
|
||||
return {
|
||||
"light_order": Task(
|
||||
task_id="task_ord_001",
|
||||
task_type=TaskType.ORDER_PICK,
|
||||
source="rack_a_01",
|
||||
destination="picking_station_a1",
|
||||
priority=2,
|
||||
release_time=10.0,
|
||||
required_payload=12.5,
|
||||
item_id="filter_hydraulic_hf1",
|
||||
quantity=5,
|
||||
target_zone="zone_a",
|
||||
),
|
||||
"heavy_order": Task(
|
||||
task_id="task_ord_002",
|
||||
task_type=TaskType.ORDER_PICK,
|
||||
source="rack_b_01",
|
||||
destination="picking_station_b1",
|
||||
priority=2,
|
||||
release_time=25.0,
|
||||
required_payload=650.0,
|
||||
item_id="transmission_combine_ct8",
|
||||
quantity=1,
|
||||
target_zone="zone_b",
|
||||
),
|
||||
"production_feed": Task(
|
||||
task_id="task_feed_001",
|
||||
task_type=TaskType.PRODUCTION_LINE_FEED,
|
||||
source="rack_c_01",
|
||||
destination="production_dropoff_c1",
|
||||
priority=1,
|
||||
release_time=50.0,
|
||||
deadline=350.0,
|
||||
required_payload=1100.0,
|
||||
item_id="raw_steel_coil_sc5",
|
||||
quantity=1,
|
||||
target_zone="zone_c",
|
||||
),
|
||||
"replenishment": Task(
|
||||
task_id="task_replen_001",
|
||||
task_type=TaskType.REPLENISHMENT,
|
||||
source="dock_inbound_1",
|
||||
destination="rack_a_03",
|
||||
priority=3,
|
||||
release_time=100.0,
|
||||
required_payload=75.0,
|
||||
item_id="hardware_bolt_pack_m12",
|
||||
quantity=15,
|
||||
target_zone="zone_a",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def create_sample_inventory_catalog() -> InventoryCatalog:
|
||||
"""Create a deterministic catalog containing items from Zones A, B, and C."""
|
||||
items = {
|
||||
"filter_hydraulic_hf1": InventoryItem(
|
||||
item_id="filter_hydraulic_hf1",
|
||||
name="Hydraulic Oil Filter HF-1",
|
||||
category="Fast-moving Inventory",
|
||||
zone="zone_a",
|
||||
unit_weight_kg=2.5,
|
||||
initial_stock=200,
|
||||
current_stock=200,
|
||||
minimum_stock=50,
|
||||
replenishment_batch=100,
|
||||
storage_location="rack_a_01",
|
||||
),
|
||||
"transmission_combine_ct8": InventoryItem(
|
||||
item_id="transmission_combine_ct8",
|
||||
name="Heavy Combine Transmission Unit CT-8",
|
||||
category="Slow-moving and Specialized",
|
||||
zone="zone_b",
|
||||
unit_weight_kg=650.0,
|
||||
initial_stock=8,
|
||||
current_stock=8,
|
||||
minimum_stock=2,
|
||||
replenishment_batch=4,
|
||||
storage_location="rack_b_01",
|
||||
),
|
||||
"raw_steel_coil_sc5": InventoryItem(
|
||||
item_id="raw_steel_coil_sc5",
|
||||
name="Hot-Rolled Sheet Steel Coil SC-5",
|
||||
category="Raw Materials and Production Supply",
|
||||
zone="zone_c",
|
||||
unit_weight_kg=1100.0,
|
||||
initial_stock=10,
|
||||
current_stock=10,
|
||||
minimum_stock=3,
|
||||
replenishment_batch=5,
|
||||
storage_location="rack_c_01",
|
||||
),
|
||||
}
|
||||
return InventoryCatalog(items)
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Unit tests for simulation event schema and serialization."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.domain.events import SimulationEvent, SimulationEventType
|
||||
|
||||
|
||||
def test_simulation_event_serialization():
|
||||
"""Verify SimulationEvent to_dict and to_jsonl formatting."""
|
||||
evt = SimulationEvent(
|
||||
event_id="evt_001",
|
||||
simulation_time=124.5678,
|
||||
event_type=SimulationEventType.TASK_ASSIGNED,
|
||||
entity_id="amr_light_01",
|
||||
task_id="task_ord_001",
|
||||
metadata={"priority": 1, "battery_pct": 98.5},
|
||||
)
|
||||
|
||||
data = evt.to_dict()
|
||||
assert data["event_id"] == "evt_001"
|
||||
assert data["simulation_time"] == 124.568
|
||||
assert data["event_type"] == "TASK_ASSIGNED"
|
||||
assert data["entity_id"] == "amr_light_01"
|
||||
assert data["task_id"] == "task_ord_001"
|
||||
assert data["metadata"]["priority"] == 1
|
||||
|
||||
jsonl_str = evt.to_jsonl()
|
||||
reparsed = json.loads(jsonl_str)
|
||||
assert reparsed["event_type"] == "TASK_ASSIGNED"
|
||||
assert reparsed["metadata"]["battery_pct"] == 98.5
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Unit tests for inventory domain models, stock reservation, and catalog manager."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.config.loader import ConfigLoader
|
||||
from warehouse_twin.domain.inventory import (
|
||||
InsufficientStockError,
|
||||
InventoryCatalog,
|
||||
InventoryItem,
|
||||
)
|
||||
|
||||
|
||||
def test_inventory_item_reservation_lifecycle():
|
||||
"""Verify stock reservation, consumption, and release."""
|
||||
item = InventoryItem(
|
||||
item_id="filter_hf1",
|
||||
name="Oil Filter",
|
||||
category="Zone A Fast",
|
||||
zone="zone_a",
|
||||
unit_weight_kg=2.5,
|
||||
initial_stock=100,
|
||||
current_stock=100,
|
||||
minimum_stock=20,
|
||||
)
|
||||
|
||||
assert item.available_stock == 100
|
||||
assert item.needs_replenishment() is False
|
||||
|
||||
# Reserve 30 units
|
||||
item.reserve(30)
|
||||
assert item.reserved_stock == 30
|
||||
assert item.current_stock == 100
|
||||
assert item.available_stock == 70
|
||||
|
||||
# Consume 20 of the reserved units
|
||||
item.consume(20)
|
||||
assert item.reserved_stock == 10
|
||||
assert item.current_stock == 80
|
||||
assert item.available_stock == 70
|
||||
|
||||
# Release remaining 10 reserved units
|
||||
item.release_reservation(10)
|
||||
assert item.reserved_stock == 0
|
||||
assert item.available_stock == 80
|
||||
|
||||
|
||||
def test_insufficient_stock_errors():
|
||||
"""Verify InsufficientStockError when exceeding available or current quantities."""
|
||||
item = InventoryItem(
|
||||
item_id="item_scarce",
|
||||
name="Scarce Part",
|
||||
category="Specialized",
|
||||
zone="zone_b",
|
||||
unit_weight_kg=10.0,
|
||||
initial_stock=5,
|
||||
current_stock=5,
|
||||
minimum_stock=2,
|
||||
)
|
||||
|
||||
# Exceed reservation
|
||||
with pytest.raises(InsufficientStockError) as exc_info:
|
||||
item.reserve(10)
|
||||
assert "Only 5 available" in str(exc_info.value)
|
||||
|
||||
# Exceed consumption
|
||||
with pytest.raises(InsufficientStockError):
|
||||
item.consume(15)
|
||||
|
||||
|
||||
def test_replenishment_trigger_and_restocking():
|
||||
"""Verify needs_replenishment detection and stock restocking."""
|
||||
item = InventoryItem(
|
||||
item_id="belt_bd10",
|
||||
name="V-Belt",
|
||||
category="Zone A Fast",
|
||||
zone="zone_a",
|
||||
unit_weight_kg=1.0,
|
||||
initial_stock=50,
|
||||
current_stock=50,
|
||||
minimum_stock=15,
|
||||
replenishment_batch=30,
|
||||
)
|
||||
|
||||
assert item.needs_replenishment() is False
|
||||
|
||||
# Consume down to threshold
|
||||
item.reserve(35)
|
||||
item.consume(35)
|
||||
assert item.current_stock == 15
|
||||
assert item.needs_replenishment() is True
|
||||
|
||||
# Replenish with batch
|
||||
item.replenish(item.replenishment_batch)
|
||||
assert item.current_stock == 45
|
||||
assert item.needs_replenishment() is False
|
||||
|
||||
|
||||
def test_inventory_catalog_loading(project_config_dir: Path):
|
||||
"""Verify InventoryCatalog loads real project inventory configuration."""
|
||||
loader = ConfigLoader(project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
catalog = InventoryCatalog.from_config_dict(bundle.inventory)
|
||||
|
||||
assert catalog.total_sku_count() == 13
|
||||
|
||||
# Check Zone A items
|
||||
zone_a_items = catalog.get_items_by_zone("zone_a")
|
||||
assert len(zone_a_items) == 5
|
||||
assert any(i.item_id == "filter_hydraulic_hf1" for i in zone_a_items)
|
||||
assert any(i.item_id == "belt_drive_bd10" for i in zone_a_items)
|
||||
|
||||
# Check Zone B items
|
||||
zone_b_items = catalog.get_items_by_zone("zone_b")
|
||||
assert len(zone_b_items) == 4
|
||||
assert any(i.item_id == "transmission_combine_ct8" for i in zone_b_items)
|
||||
assert any(i.item_id == "structural_chassis_frame_sf3" for i in zone_b_items)
|
||||
|
||||
# Check Zone C items
|
||||
zone_c_items = catalog.get_items_by_zone("zone_c")
|
||||
assert len(zone_c_items) == 4
|
||||
assert any(i.item_id == "raw_steel_coil_sc5" for i in zone_c_items)
|
||||
assert any(i.item_id == "electronic_control_module_ecm9" for i in zone_c_items)
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Unit tests for robot domain models, state machine transitions, and compatibility rules."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.domain.robot import (
|
||||
IncompatibleRobotTaskError,
|
||||
InvalidStateTransitionError,
|
||||
Robot,
|
||||
RobotState,
|
||||
RobotTypeSpec,
|
||||
)
|
||||
from warehouse_twin.domain.task import Task, TaskStatus, TaskType
|
||||
from warehouse_twin.domain.warehouse import Position3D
|
||||
|
||||
|
||||
def test_robot_initialization_and_properties(sample_light_robot: Robot):
|
||||
"""Verify AMR initial attributes, battery percentage, and capacity ratings."""
|
||||
assert sample_light_robot.robot_id == "amr_light_01"
|
||||
assert sample_light_robot.robot_type == "light_amr"
|
||||
assert sample_light_robot.current_state == RobotState.IDLE
|
||||
assert sample_light_robot.battery_percent == pytest.approx(100.0)
|
||||
assert sample_light_robot.payload_capacity == 150.0
|
||||
assert sample_light_robot.maximum_speed == 1.8
|
||||
assert sample_light_robot.accumulated_distance == 0.0
|
||||
|
||||
|
||||
def test_robot_normal_cycle_state_transitions(sample_light_robot: Robot):
|
||||
"""Verify full operational lifecycle: IDLE -> DISPATCHED -> PICKING -> LOADED_TRANSIT -> DROPPING -> IDLE."""
|
||||
r = sample_light_robot
|
||||
sim_time = 0.0
|
||||
|
||||
# 1. IDLE -> DISPATCHED
|
||||
r.transition_to(RobotState.DISPATCHED, sim_time=10.0)
|
||||
assert r.current_state == RobotState.DISPATCHED
|
||||
assert r.idle_time == pytest.approx(10.0)
|
||||
|
||||
# 2. DISPATCHED -> PICKING
|
||||
r.transition_to(RobotState.PICKING, sim_time=25.0)
|
||||
assert r.current_state == RobotState.PICKING
|
||||
assert r.busy_time == pytest.approx(15.0)
|
||||
|
||||
# 3. PICKING -> LOADED_TRANSIT
|
||||
r.transition_to(RobotState.LOADED_TRANSIT, sim_time=35.0)
|
||||
assert r.current_state == RobotState.LOADED_TRANSIT
|
||||
assert r.busy_time == pytest.approx(25.0)
|
||||
|
||||
# 4. LOADED_TRANSIT -> DROPPING
|
||||
r.transition_to(RobotState.DROPPING, sim_time=50.0)
|
||||
assert r.current_state == RobotState.DROPPING
|
||||
assert r.busy_time == pytest.approx(40.0)
|
||||
|
||||
# 5. DROPPING -> IDLE
|
||||
r.transition_to(RobotState.IDLE, sim_time=60.0)
|
||||
assert r.current_state == RobotState.IDLE
|
||||
assert r.busy_time == pytest.approx(50.0)
|
||||
assert r.idle_time == pytest.approx(10.0)
|
||||
|
||||
|
||||
def test_robot_charging_state_transitions(sample_light_robot: Robot):
|
||||
"""Verify charging cycle: IDLE -> TRANSIT_TO_CHARGE -> CHARGING -> IDLE."""
|
||||
r = sample_light_robot
|
||||
|
||||
r.transition_to(RobotState.TRANSIT_TO_CHARGE, sim_time=100.0)
|
||||
assert r.current_state == RobotState.TRANSIT_TO_CHARGE
|
||||
assert r.idle_time == pytest.approx(100.0)
|
||||
|
||||
r.transition_to(RobotState.CHARGING, sim_time=120.0)
|
||||
assert r.current_state == RobotState.CHARGING
|
||||
|
||||
r.transition_to(RobotState.IDLE, sim_time=300.0)
|
||||
assert r.current_state == RobotState.IDLE
|
||||
assert r.charging_time == pytest.approx(180.0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid_target", [
|
||||
RobotState.DROPPING,
|
||||
RobotState.LOADED_TRANSIT,
|
||||
RobotState.PICKING,
|
||||
])
|
||||
def test_illegal_transitions_from_idle_rejected(sample_light_robot: Robot, invalid_target: RobotState):
|
||||
"""Ensure invalid transitions from IDLE immediately raise InvalidStateTransitionError."""
|
||||
with pytest.raises(InvalidStateTransitionError) as exc_info:
|
||||
sample_light_robot.transition_to(invalid_target, sim_time=1.0)
|
||||
assert f"Cannot transition from IDLE to {invalid_target.value}" in str(exc_info.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("from_state,to_state", [
|
||||
(RobotState.PICKING, RobotState.CHARGING),
|
||||
(RobotState.LOADED_TRANSIT, RobotState.IDLE),
|
||||
(RobotState.CHARGING, RobotState.LOADED_TRANSIT),
|
||||
(RobotState.DROPPING, RobotState.PICKING),
|
||||
])
|
||||
def test_various_illegal_transitions_rejected(sample_light_robot: Robot, from_state: RobotState, to_state: RobotState):
|
||||
"""Verify arbitrary illegal state combinations are rejected."""
|
||||
sample_light_robot.current_state = from_state
|
||||
with pytest.raises(InvalidStateTransitionError):
|
||||
sample_light_robot.transition_to(to_state, sim_time=5.0)
|
||||
|
||||
|
||||
def test_payload_capacity_compatibility(sample_light_robot: Robot, sample_heavy_robot: Robot, sample_tasks: dict):
|
||||
"""Verify payload rules: Light AMR rejects heavy parts; Heavy AMR accepts them."""
|
||||
light_bot = sample_light_robot # 150 kg rating
|
||||
heavy_bot = sample_heavy_robot # 1500 kg rating
|
||||
|
||||
light_task = sample_tasks["light_order"] # 12.5 kg
|
||||
heavy_task = sample_tasks["heavy_order"] # 650.0 kg
|
||||
feed_task = sample_tasks["production_feed"] # 1100.0 kg
|
||||
|
||||
# Light task (12.5 kg) is compatible with both
|
||||
assert light_bot.can_carry_payload(light_task.required_payload) is True
|
||||
assert heavy_bot.can_carry_payload(light_task.required_payload) is True
|
||||
|
||||
# Heavy task (650 kg) is rejected by light AMR, accepted by heavy AMR
|
||||
assert light_bot.can_carry_payload(heavy_task.required_payload) is False
|
||||
assert heavy_bot.can_carry_payload(heavy_task.required_payload) is True
|
||||
|
||||
with pytest.raises(IncompatibleRobotTaskError) as exc_info:
|
||||
light_bot.assign_task(heavy_task)
|
||||
assert "exceeds robot 'amr_light_01' capacity" in str(exc_info.value)
|
||||
|
||||
# Heavy bot can assign heavy task
|
||||
heavy_bot.assign_task(heavy_task)
|
||||
assert heavy_bot.current_task_id == heavy_task.task_id
|
||||
assert heavy_task.assigned_robot_id == heavy_bot.robot_id
|
||||
|
||||
|
||||
def test_zone_accessibility_compatibility(sample_light_robot: Robot, sample_tasks: dict):
|
||||
"""Verify operational rule: Light AMR is restricted from Zone B tasks."""
|
||||
light_bot = sample_light_robot
|
||||
heavy_task_in_zone_b = sample_tasks["heavy_order"] # target_zone='zone_b'
|
||||
|
||||
# Even if payload were reduced to 10 kg, zone_b should still block light AMR
|
||||
heavy_task_in_zone_b.required_payload = 10.0
|
||||
compatible, reason = light_bot.validate_task_compatibility(heavy_task_in_zone_b)
|
||||
|
||||
assert compatible is False
|
||||
assert "restricted from entering target zone 'zone_b'" in reason
|
||||
|
||||
with pytest.raises(IncompatibleRobotTaskError):
|
||||
light_bot.assign_task(heavy_task_in_zone_b)
|
||||
|
||||
|
||||
def test_busy_robot_assignment_rejected(sample_light_robot: Robot, sample_tasks: dict):
|
||||
"""Verify that busy robots cannot be assigned new tasks."""
|
||||
light_bot = sample_light_robot
|
||||
task = sample_tasks["light_order"]
|
||||
|
||||
light_bot.transition_to(RobotState.DISPATCHED, sim_time=10.0)
|
||||
compatible, reason = light_bot.validate_task_compatibility(task)
|
||||
|
||||
assert compatible is False
|
||||
assert "is currently busy in state DISPATCHED" in reason
|
||||
|
||||
with pytest.raises(IncompatibleRobotTaskError):
|
||||
light_bot.assign_task(task)
|
||||
|
||||
|
||||
def test_energy_consumption_and_charging(sample_light_robot: Robot):
|
||||
"""Verify energy deductions and charging calculations."""
|
||||
r = sample_light_robot
|
||||
initial = r.battery_level
|
||||
|
||||
# Consume energy moving empty for 360 seconds at 0.35 kW
|
||||
consumed = r.consume_energy(360.0, mode="moving_empty")
|
||||
expected_kwh = (0.35 * 360.0) / 3600.0
|
||||
assert consumed == pytest.approx(expected_kwh)
|
||||
assert r.battery_level == pytest.approx(initial - expected_kwh)
|
||||
|
||||
# Set battery level to 1.0 kWh to ensure headroom for charging test
|
||||
r.battery_level = 1.0
|
||||
added = r.charge_energy(60.0, charging_rate_kw=25.0)
|
||||
expected_charge = (25.0 * 60.0) / 3600.0 # 0.4167 kWh
|
||||
assert added == pytest.approx(expected_charge)
|
||||
assert r.battery_level == pytest.approx(1.0 + expected_charge)
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Unit tests for task domain models, lifecycle transitions, and deadlines."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.domain.robot import InvalidStateTransitionError
|
||||
from warehouse_twin.domain.task import Task, TaskStatus, TaskType
|
||||
|
||||
|
||||
def test_task_initialization():
|
||||
"""Verify task initialization, priorities, and default attributes."""
|
||||
task = Task(
|
||||
task_id="task_001",
|
||||
task_type=TaskType.ORDER_PICK,
|
||||
source="rack_a_01",
|
||||
destination="picking_station_a1",
|
||||
priority=1,
|
||||
release_time=100.0,
|
||||
deadline=400.0,
|
||||
required_payload=25.0,
|
||||
item_id="filter_hydraulic_hf1",
|
||||
quantity=10,
|
||||
)
|
||||
|
||||
assert task.task_id == "task_001"
|
||||
assert task.status == TaskStatus.PENDING
|
||||
assert task.priority == 1
|
||||
assert task.turnaround_time() is None
|
||||
assert task.execution_time() is None
|
||||
assert task.waiting_time(150.0) == pytest.approx(50.0)
|
||||
assert task.is_overdue(200.0) is False
|
||||
|
||||
|
||||
def test_task_normal_lifecycle_transitions():
|
||||
"""Verify PENDING -> ASSIGNED -> IN_PROGRESS -> COMPLETED."""
|
||||
task = Task(
|
||||
task_id="task_002",
|
||||
task_type=TaskType.ORDER_PICK,
|
||||
source="rack_a_02",
|
||||
destination="picking_station_a1",
|
||||
release_time=50.0,
|
||||
)
|
||||
|
||||
# 1. PENDING -> ASSIGNED
|
||||
task.transition_to(TaskStatus.ASSIGNED, sim_time=60.0)
|
||||
assert task.status == TaskStatus.ASSIGNED
|
||||
|
||||
# 2. ASSIGNED -> IN_PROGRESS
|
||||
task.transition_to(TaskStatus.IN_PROGRESS, sim_time=80.0)
|
||||
assert task.status == TaskStatus.IN_PROGRESS
|
||||
assert task.start_time == 80.0
|
||||
assert task.waiting_time() == pytest.approx(30.0)
|
||||
|
||||
# 3. IN_PROGRESS -> COMPLETED
|
||||
task.transition_to(TaskStatus.COMPLETED, sim_time=150.0)
|
||||
assert task.status == TaskStatus.COMPLETED
|
||||
assert task.completion_time == 150.0
|
||||
assert task.turnaround_time() == pytest.approx(100.0)
|
||||
assert task.execution_time() == pytest.approx(70.0)
|
||||
|
||||
|
||||
def test_task_cancellation_and_preemption():
|
||||
"""Verify preemption (ASSIGNED -> PENDING) and cancellation."""
|
||||
task = Task(
|
||||
task_id="task_003",
|
||||
task_type=TaskType.REPLENISHMENT,
|
||||
source="dock_inbound_1",
|
||||
destination="rack_c_01",
|
||||
release_time=0.0,
|
||||
)
|
||||
|
||||
# PENDING -> ASSIGNED
|
||||
task.transition_to(TaskStatus.ASSIGNED, sim_time=10.0)
|
||||
# Preemption: ASSIGNED -> PENDING
|
||||
task.transition_to(TaskStatus.PENDING, sim_time=20.0)
|
||||
assert task.status == TaskStatus.PENDING
|
||||
|
||||
# PENDING -> CANCELLED
|
||||
task.transition_to(TaskStatus.CANCELLED, sim_time=30.0)
|
||||
assert task.status == TaskStatus.CANCELLED
|
||||
assert task.completion_time == 30.0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid_from,invalid_to", [
|
||||
(TaskStatus.PENDING, TaskStatus.COMPLETED),
|
||||
(TaskStatus.PENDING, TaskStatus.IN_PROGRESS),
|
||||
(TaskStatus.COMPLETED, TaskStatus.IN_PROGRESS),
|
||||
(TaskStatus.CANCELLED, TaskStatus.PENDING),
|
||||
(TaskStatus.FAILED, TaskStatus.COMPLETED),
|
||||
])
|
||||
def test_illegal_task_transitions_rejected(invalid_from: TaskStatus, invalid_to: TaskStatus):
|
||||
"""Ensure invalid task lifecycle jumps raise InvalidStateTransitionError."""
|
||||
task = Task(
|
||||
task_id="task_invalid",
|
||||
task_type=TaskType.ORDER_PICK,
|
||||
source="s",
|
||||
destination="d",
|
||||
)
|
||||
task.status = invalid_from
|
||||
with pytest.raises(InvalidStateTransitionError):
|
||||
task.transition_to(invalid_to, sim_time=10.0)
|
||||
|
||||
|
||||
def test_deadline_and_overdue_tracking():
|
||||
"""Verify strict deadline tracking for production line feed tasks."""
|
||||
task = Task(
|
||||
task_id="feed_critical",
|
||||
task_type=TaskType.PRODUCTION_LINE_FEED,
|
||||
source="rack_c_01",
|
||||
destination="production_dropoff_c1",
|
||||
release_time=100.0,
|
||||
deadline=300.0, # 200s window
|
||||
)
|
||||
|
||||
assert task.is_overdue(250.0) is False
|
||||
assert task.is_overdue(301.0) is True
|
||||
|
||||
# Completed on time
|
||||
task.transition_to(TaskStatus.ASSIGNED, 110.0)
|
||||
task.transition_to(TaskStatus.IN_PROGRESS, 120.0)
|
||||
task.transition_to(TaskStatus.COMPLETED, 280.0)
|
||||
assert task.is_overdue(500.0) is False # Finished at 280 <= 300, so not overdue
|
||||
@@ -251,3 +251,26 @@ def test_export_usda_scene(project_config_dir: Path, tmp_path: Path):
|
||||
assert 'def Xform "picking_station_a1"' in content
|
||||
assert 'def Xform "charge_bay_1"' in content
|
||||
assert 'def Xform "rack_a_01"' in content
|
||||
|
||||
|
||||
def test_export_usda_with_robots(project_config_dir: Path, tmp_path: Path):
|
||||
"""Verify OpenUSD scene generation includes AMR fleet entities when provided."""
|
||||
from warehouse_twin.interfaces.usd_generator import WarehouseUSDGenerator
|
||||
|
||||
loader = ConfigLoader(project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
|
||||
generator = WarehouseUSDGenerator.from_config_bundle(bundle)
|
||||
usda_path = tmp_path / "test_warehouse_phase2.usda"
|
||||
saved = generator.export_usda(usda_path)
|
||||
|
||||
assert saved.exists()
|
||||
content = saved.read_text(encoding="utf-8")
|
||||
|
||||
assert 'def Scope "Robots"' in content
|
||||
assert 'def Xform "amr_light_01"' in content
|
||||
assert 'def Xform "amr_light_02"' in content
|
||||
assert 'def Xform "amr_heavy_01"' in content
|
||||
assert 'def Xform "amr_heavy_02"' in content
|
||||
assert 'def Cube "StatusDome"' in content
|
||||
|
||||
|
||||
Reference in New Issue
Block a user