From 7ef65ce65df495a1bf187ad91afa81575dafc9eb Mon Sep 17 00:00:00 2001 From: Warehouse Twin Dev Date: Mon, 19 Oct 2026 14:55:54 +0530 Subject: [PATCH] feat(phase-0): initialize project foundation, packaging, logging, configs, and tests --- .env.example | 20 +++ .gitignore | 81 +++++++++++ CHANGELOG.md | 27 ++++ IMPLEMENTATION_DETAILS.md | 103 ++++++++++++++ PROJECT_STATUS.md | 77 +++++++++++ README.md | 173 ++++++++++++++++++++++++ config/dispatch_policies.json | 39 ++++++ config/inventory.json | 142 ++++++++++++++++++++ config/robots.json | 75 +++++++++++ config/simulation.json | 29 ++++ config/warehouse.json | 128 ++++++++++++++++++ data/input/.gitkeep | 0 data/sample/.gitkeep | 0 docs/API_AND_DATA_CONTRACTS.md | 122 +++++++++++++++++ docs/ARCHITECTURE.md | 100 ++++++++++++++ docs/DECISIONS.md | 45 +++++++ docs/INSTALLATION.md | 76 +++++++++++ docs/TESTING.md | 47 +++++++ docs/USER_GUIDE.md | 66 +++++++++ docs/phases/phase_0_foundation.md | 161 ++++++++++++++++++++++ logs/.gitkeep | 0 omniverse/README.md | 43 ++++++ omniverse/assets/.gitkeep | 0 omniverse/scenes/.gitkeep | 0 pyproject.toml | 58 ++++++++ results/experiments/.gitkeep | 0 results/reports/.gitkeep | 0 results/trajectories/.gitkeep | 0 scripts/check_environment.sh | 63 +++++++++ scripts/run_tests.sh | 17 +++ src/warehouse_twin/__init__.py | 8 ++ src/warehouse_twin/cli.py | 152 +++++++++++++++++++++ src/warehouse_twin/config/__init__.py | 5 + src/warehouse_twin/config/loader.py | 186 ++++++++++++++++++++++++++ src/warehouse_twin/logging_config.py | 134 +++++++++++++++++++ src/warehouse_twin/main.py | 7 + tests/__init__.py | 1 + tests/conftest.py | 96 +++++++++++++ tests/unit/__init__.py | 1 + tests/unit/test_config_loader.py | 172 ++++++++++++++++++++++++ tests/unit/test_environment.py | 50 +++++++ tests/unit/test_logging.py | 103 ++++++++++++++ 42 files changed, 2607 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 IMPLEMENTATION_DETAILS.md create mode 100644 PROJECT_STATUS.md create mode 100644 README.md create mode 100644 config/dispatch_policies.json create mode 100644 config/inventory.json create mode 100644 config/robots.json create mode 100644 config/simulation.json create mode 100644 config/warehouse.json create mode 100644 data/input/.gitkeep create mode 100644 data/sample/.gitkeep create mode 100644 docs/API_AND_DATA_CONTRACTS.md create mode 100644 docs/ARCHITECTURE.md create mode 100644 docs/DECISIONS.md create mode 100644 docs/INSTALLATION.md create mode 100644 docs/TESTING.md create mode 100644 docs/USER_GUIDE.md create mode 100644 docs/phases/phase_0_foundation.md create mode 100644 logs/.gitkeep create mode 100644 omniverse/README.md create mode 100644 omniverse/assets/.gitkeep create mode 100644 omniverse/scenes/.gitkeep create mode 100644 pyproject.toml create mode 100644 results/experiments/.gitkeep create mode 100644 results/reports/.gitkeep create mode 100644 results/trajectories/.gitkeep create mode 100755 scripts/check_environment.sh create mode 100755 scripts/run_tests.sh create mode 100644 src/warehouse_twin/__init__.py create mode 100644 src/warehouse_twin/cli.py create mode 100644 src/warehouse_twin/config/__init__.py create mode 100644 src/warehouse_twin/config/loader.py create mode 100644 src/warehouse_twin/logging_config.py create mode 100644 src/warehouse_twin/main.py create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/unit/__init__.py create mode 100644 tests/unit/test_config_loader.py create mode 100644 tests/unit/test_environment.py create mode 100644 tests/unit/test_logging.py diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..eeaa0a0 --- /dev/null +++ b/.env.example @@ -0,0 +1,20 @@ +# Warehouse Robot Fleet Digital Twin Environment Configuration + +# Paths +WAREHOUSE_TWIN_CONFIG_DIR=config +WAREHOUSE_TWIN_LOG_DIR=logs +WAREHOUSE_TWIN_RESULTS_DIR=results + +# Relocation support for disk-constrained primary drives: +# Set this to an external mounted directory if the root filesystem is low on disk space. +# Example: WAREHOUSE_TWIN_SECONDARY_DRIVE=/media/external/warehouse_data +WAREHOUSE_TWIN_SECONDARY_DRIVE= + +# Logging Settings +WAREHOUSE_TWIN_LOG_LEVEL=INFO +WAREHOUSE_TWIN_LOG_MAX_BYTES=10485760 +WAREHOUSE_TWIN_LOG_BACKUP_COUNT=5 + +# NVIDIA Omniverse Kit Integration Paths +KIT_PATH=/home/dmhai/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/kit/kit +KIT_APP_PATH=/home/dmhai/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/apps/warehouse_twin.kit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a4ef443 --- /dev/null +++ b/.gitignore @@ -0,0 +1,81 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# Virtual environments +.venv/ +venv/ +ENV/ +env/ + +# Unit test / coverage +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Environment and secrets +.env +!.env.example + +# IDE and Editor +.idea/ +.vscode/* +!.vscode/settings.json +!.vscode/launch.json +*.swp +*.swo +*~ +.DS_Store + +# Application & Simulation Generated Logs (keep .gitkeep) +logs/*.log +logs/*.log.* +!logs/.gitkeep + +# Large Generated Results & Artifacts (keep .gitkeep) +results/experiments/* +!results/experiments/.gitkeep +results/reports/* +!results/reports/.gitkeep +results/trajectories/* +!results/trajectories/.gitkeep + +# Omniverse & Kit local caches and builds +_build/ +_compiler/ +_repo/ +*.usd.bak +.nvidia-omniverse/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..4bb40b6 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,27 @@ +# Changelog + +All notable changes to the Warehouse Robot Fleet Digital Twin will be documented in this file. + +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.1.0] - 2026-10-19 + +### Added - Phase 0: Environment and Project Foundation +- Initial project directory layout adhering strictly to master prompt specifications. +- Host environment inspection identifying Ubuntu 24.04.3 LTS, Python 3.12.3, NVIDIA RTX 5090 GPU (Driver 580.178.04), and 8.9 GB disk availability. +- Omniverse Kit inspection discovering installed Kit 110.4.0 and base app `warehouse_twin.kit` under `/home/dmhai/nvidia-omniverse/kit-app-template`. +- Python packaging configuration (`pyproject.toml`) with dependencies on `simpy` 4.1.2, `networkx` 3.7, and `pytest` 9.1.1. +- `.gitignore` and `.env.example` with secondary drive relocation parameters. +- Base configurations in `config/`: + - `warehouse.json`: 60m x 40m facility with Zones A, B, C, inbound docks, picking stations, production drop-offs, and charging bays. + - `robots.json`: Light AMR and Heavy AMR definitions with speed, payload, and energy models. + - `inventory.json`: Fast-moving, slow-moving, and production raw material item catalogs. + - `simulation.json`: Discrete-event parameters, arrival rates, and random seed. + - `dispatch_policies.json`: Dispatch policy definitions and traffic reservation settings. +- Structured rotating logging module (`warehouse_twin.logging_config`) managing `application.log`, `simulation.log`, and `errors.log`. +- Robust configuration loader (`warehouse_twin.config.loader`) with schema validation. +- Command-line interface (`warehouse_twin.cli`) supporting `validate-env` and `validate-config`. +- Automated shell verification scripts: `scripts/check_environment.sh` and `scripts/run_tests.sh`. +- Comprehensive unit test suite in `tests/unit/` (17 tests passing in 0.09s). +- Full documentation suite: `README.md`, `IMPLEMENTATION_DETAILS.md`, `PROJECT_STATUS.md`, `docs/ARCHITECTURE.md`, `docs/INSTALLATION.md`, `docs/USER_GUIDE.md`, `docs/API_AND_DATA_CONTRACTS.md`, `docs/TESTING.md`, `docs/DECISIONS.md`, `docs/phases/phase_0_foundation.md`, and `omniverse/README.md`. diff --git a/IMPLEMENTATION_DETAILS.md b/IMPLEMENTATION_DETAILS.md new file mode 100644 index 0000000..b7f3572 --- /dev/null +++ b/IMPLEMENTATION_DETAILS.md @@ -0,0 +1,103 @@ +# Implementation Details: Warehouse Robot Fleet Digital Twin + +## 1. System Architecture & Module Responsibilities + +The system is structured as a decoupled discrete-event simulation engine with an asynchronous 3D visualization and analytics pipeline. + +``` +warehouse-digital-twin/ +├── config/ # Declarative simulation and physical facility definitions +├── docs/ # Architectural, API, and phase reports +├── logs/ # Structured rotating application, simulation, and error logs +├── omniverse/ # NVIDIA Omniverse Kit 110.4 assets and visualizer extensions +├── results/ # Trajectories, experiment logs, and KPI reports +├── scripts/ # Automated verification and test execution scripts +├── src/warehouse_twin/ # Python package implementation +│ ├── config/ # Config parsing, validation, and bundle models +│ ├── domain/ # (Phase 1-2) Typed entity models, states, and event schemas +│ ├── simulation/ # (Phase 3) SimPy event loop and order generation +│ ├── routing/ # (Phase 4) NetworkX spatial graph and time-space reservations +│ ├── fleet/ # (Phase 4-5) Dispatcher, battery controller, charging manager +│ ├── analytics/ # (Phase 6) KPI calculators, reports, and congestion heatmaps +│ ├── storage/ # (Phase 6) JSONL event streaming and experiment stores +│ ├── interfaces/ # (Phase 6-7) Output serialization and trajectory generation +│ ├── logging_config.py # Multi-target rotating file and console logger +│ ├── cli.py # Command-line interface +│ └── main.py # Execution entry point +└── tests/ # Pytest unit, integration, and scenario tests +``` + +--- + +## 2. Important Classes, Functions, and Data Models + +### 2.1 Configuration Subsystem (`warehouse_twin.config`) +- **`ConfigLoader`**: + - `load_all() -> ConfigBundle`: Reads, parses, and validates the 5 configuration files (`warehouse.json`, `robots.json`, `inventory.json`, `simulation.json`, `dispatch_policies.json`). + - Validation routines: `validate_warehouse`, `validate_robots`, `validate_inventory`, `validate_simulation`, `validate_dispatch_policies`. + - Raises `ConfigurationError` with line, file, and field details upon syntax or semantic violations. +- **`ConfigBundle`**: Frozen dataclass containing parsed dictionaries and verified directory path. + +### 2.2 Logging Subsystem (`warehouse_twin.logging_config`) +- **`setup_logging(...) -> Path`**: + - Initializes root and simulation loggers with rotating file handlers. + - Generates `application.log` (DEBUG+), `simulation.log` (dedicated simulation event format), and `errors.log` (ERROR+). + - Enforces `max_bytes` (default 10 MB) and `backup_count` (default 5) to protect low-disk environments. +- **`get_logger(name: str) -> logging.Logger`**: Returns module-namespaced logger. +- **`get_simulation_logger() -> logging.Logger`**: Returns dedicated simulation event stream. + +### 2.3 CLI Interface (`warehouse_twin.cli`) +- **`check_environment() -> int`**: Tests Python version (>=3.10), checks disk space on `/` (warns if < 10 GB, fails if < 2 GB), checks core imports (`simpy`, `networkx`, `pytest`), verifies log directory writability, and detects Kit executable. +- **`validate_config(config_dir: Optional[str]) -> int`**: Invokes `ConfigLoader` and prints validation summaries. + +--- + +## 3. Coordinate System and Measurement Units + +The simulation and 3D visualizer strictly adopt standard industrial robotics conventions: + +- **Reference Frame**: Right-Handed Cartesian coordinate system. +- **Axes Orientation**: + - **X-axis**: Facility Width (East) in meters. + - **Y-axis**: Facility Depth (North) in meters. + - **Z-axis**: Facility Height (Up) in meters. Ground floor plane is at `Z = 0.0 m`. +- **Orientation / Heading**: Yaw angle $\theta$ measured in degrees counter-clockwise from the positive X-axis ($0^\circ = \text{East}$, $90^\circ = \text{North}$). +- **Kinematic Units**: + - Linear velocity: meters per second ($\text{m/s}$). + - Linear acceleration: meters per second squared ($\text{m/s}^2$). + - Mass / payload: kilograms ($\text{kg}$). + - Energy: kilowatt-hours ($\text{kWh}$). + - Power: kilowatts ($\text{kW}$). + - Time: seconds ($\text{s}$). + +--- + +## 4. Hardware, OS, and Dependency Findings + +| Component | Host Finding | Architectural Implication | +| :--- | :--- | :--- | +| **Operating System** | Ubuntu 24.04.3 LTS (Kernel 7.0.0-38) | Modern Linux with glibc 2.39; fully supported. | +| **Python Version** | Python 3.12.3 (`/usr/bin/python3`) | Virtual environment uses Python 3.12, identical to Kit's embedded Python. | +| **Primary Disk** | `/dev/nvme0n1p4` at 99% capacity (**8.9 GB free**) | **High Disk Constraint**: Isaac Sim cannot be installed. Rotating logs strictly capped at 10 MB. Relocation to secondary drive supported. | +| **GPU** | NVIDIA GeForce RTX 5090 (32,607 MiB VRAM) | Ample VRAM for real-time 3D visualization and ray-traced Kit rendering. | +| **NVIDIA Omniverse Kit** | Kit 110.4.0 at `kit-app-template` | Active app `warehouse_twin.kit`. Trajectory playback in Phase 7 will target Kit 110.4 extension APIs. | +| **SimPy** | Version 4.1.2 | Installed in `.venv`; supports microsecond discrete-event simulation. | +| **NetworkX** | Version 3.7 | Installed in `.venv`; supports spatial routing and shortest-path planning. | +| **Pytest** | Version 9.1.1 | Installed in `.venv`; test suite verified. | + +--- + +## 5. Testing and Validation Strategy + +The testing architecture adheres to the following principles: +- **Headless Execution**: All unit, integration, and scenario tests execute without display servers or GPU dependencies. +- **Isolated Fixtures**: Tests in `tests/conftest.py` use temporary directories (`tmp_path`) for configuration and logging validation to prevent workspace side-effects. +- **Fail-Fast Boundary Tests**: Explicit tests verify negative paths: malformed JSON, non-positive dimensions, missing zones, undefined robot types, and duplicate inventory item IDs. +- **Phase Gate**: Each phase must pass 100% of its test suite before advancing to the next phase. + +--- + +## 6. Current Limitations & Next Phase + +- **Current Limitations**: Phase 0 provides the foundational architecture, configuration validation, logging, CLI, and test runner. Domain classes (`Robot`, `Task`, `WarehouseGraph`) will be instantiated in Phases 1 and 2. +- **Phase 1 Target**: Implement the warehouse topological graph in `warehouse_twin.domain.warehouse` and `warehouse_twin.routing.graph_builder`, populate Zones A, B, and C nodes, validate station accessibility, and export graph connectivity metrics. diff --git a/PROJECT_STATUS.md b/PROJECT_STATUS.md new file mode 100644 index 0000000..969e966 --- /dev/null +++ b/PROJECT_STATUS.md @@ -0,0 +1,77 @@ +# Project Status: Warehouse Robot Fleet Digital Twin + +**Last Updated**: October 19, 2026 +**Current Phase**: **Phase 0: Environment and Project Foundation (COMPLETED)** +**Status**: Ready for User Review and Approval + +--- + +## 1. Phase Tracker + +| Phase | Description | Status | Test Coverage | +| :--- | :--- | :--- | :--- | +| **Phase 0** | **Environment and project foundation** | **COMPLETED** | **17 passed (100%)** | +| Phase 1 | Warehouse model | Planned (Pending Phase 0 approval) | - | +| Phase 2 | Robot and task models | Planned | - | +| Phase 3 | Discrete-event simulation | Planned | - | +| Phase 4 | Routing and fleet assignment | Planned | - | +| Phase 5 | Charging and operational constraints | Planned | - | +| Phase 6 | Analytics and experiment framework | Planned | - | +| Phase 7 | Omniverse USD visualization | Planned | - | +| Phase 8 | Operational dashboard | Planned | - | +| Phase 9 | Optimization and final demonstration | Planned | - | + +--- + +## 2. Completed Tasks (Phase 0) + +- [x] Host environment inspected: Ubuntu 24.04.3 LTS, Python 3.12.3, NVIDIA RTX 5090 (Driver 580.178.04), 8.9 GB free disk space. +- [x] NVIDIA Omniverse Kit inspected: Kit 110.4.0 running with `warehouse_twin.kit` at `/home/dmhai/nvidia-omniverse/kit-app-template`. +- [x] Verified virtual environment (`.venv`) configured with `simpy` 4.1.2, `networkx` 3.7, `pytest` 9.1.1, and `setuptools` 84.0.0. +- [x] Package metadata created in `pyproject.toml` and installed in editable mode (`warehouse-digital-twin` v0.1.0). +- [x] `.gitignore` and `.env.example` created with secondary disk relocation support. +- [x] Baseline configuration files created for all 5 domains in `config/`: + - `warehouse.json` (60x40m, Zones A, B, C, stations, chargers) + - `robots.json` (Light AMR, Heavy AMR, battery limits, fleet) + - `inventory.json` (Zone A fast, Zone B heavy, Zone C production raw items) + - `simulation.json` (3600s duration, seed 42, arrival rates) + - `dispatch_policies.json` (active policy, reservation settings) +- [x] Structured rotating logging implemented in `src/warehouse_twin/logging_config.py` with `application.log`, `simulation.log`, and `errors.log`. +- [x] Configuration loader with detailed schema and integrity validation implemented in `src/warehouse_twin/config/loader.py`. +- [x] CLI entry point implemented in `src/warehouse_twin/cli.py` (`warehouse-twin validate-env`, `warehouse-twin validate-config`). +- [x] Automated verification scripts created: `scripts/check_environment.sh`, `scripts/run_tests.sh`. +- [x] Unit test suite implemented in `tests/unit/`: + - `test_environment.py` (5 tests) + - `test_logging.py` (3 tests) + - `test_config_loader.py` (9 tests) +- [x] Comprehensive documentation delivered in `docs/` and `docs/phases/phase_0_foundation.md`. + +--- + +## 3. Test & Validation Summary + +- **Total Unit Tests Executed**: 17 +- **Passed**: 17 +- **Failed**: 0 +- **Skipped**: 0 +- **Execution Time**: 0.09s +- **CLI Verification**: Exit code 0, 0 failures, 1 warning (low disk space). +- **Configuration Verification**: Exit code 0, all 5 configuration files valid. + +--- + +## 4. Known Environment Constraints & Mitigations + +- **Constrained Primary Disk (`/dev/nvme0n1p4`)**: + - Capacity: 886 GB total, 832 GB used, **8.9 GB free (99% used)**. + - Mitigations: + - Rotating file logs capped at 10 MB each with 5 backups. + - Large generated outputs ignored in Git. + - `WAREHOUSE_TWIN_SECONDARY_DRIVE` environment variable supported to route logs and simulation output to an external mount if configured. + - NVIDIA Isaac Sim installation omitted as required. + +--- + +## 5. Next Recommended Action + +Obtain user approval for Phase 0 completion, then begin **Phase 1: Warehouse Model** (graph representation, Zone A/B/C nodes, docks, stations, connectivity validation, and export). diff --git a/README.md b/README.md new file mode 100644 index 0000000..f776403 --- /dev/null +++ b/README.md @@ -0,0 +1,173 @@ +# Warehouse Robot Fleet Digital Twin + +A modular, scalable discrete-event simulation and digital twin for Autonomous Mobile Robot (AMR) warehouse operations, featuring multi-zone inventory logistics, traffic congestion management, opportunity charging, and 3D visualization via NVIDIA Omniverse and OpenUSD. + +--- + +## 1. Project Overview & Objectives + +In modern automated distribution and manufacturing hubs, coordinating heterogeneous AMR fleets across mixed inventory velocities is a primary operational challenge. This project models, simulates, and optimizes fleet performance across three distinct operational zones: + +- **Zone A (Fast-moving inventory)**: Frequent order arrivals, high-speed agile robots, short transit paths, and peak-demand prioritization (Filters, Belts, Fasteners, Fluid Lines, Tractor Panels). +- **Zone B (Slow-moving & specialized inventory)**: Heavy-duty parts, payload constraints, wider aisle requirements, and extended handling times (Combine Transmissions, Structural Frames, Engine Pistons). +- **Zone C (Raw materials & production-line supply)**: Scheduled material feeds, production deadlines, stock-out tracking, and priority line delivery (Steel Coils, Control Modules, Coating Drums). + +The system decouples discrete-event simulation from 3D visualization, enabling deterministic headless simulation and KPI benchmarking, while supporting OpenUSD trajectory visualization in NVIDIA Omniverse Kit. + +--- + +## 2. Architecture Overview + +``` ++-----------------------------------------------------------------------------------+ +| CONFIG & SPECIFICATION LAYER | +| config/warehouse.json config/robots.json | +| config/inventory.json config/simulation.json | +| config/dispatch_policies.json | ++-----------------------------------------------------------------------------------+ + | + v ++-----------------------------------------------------------------------------------+ +| SIMULATION ENGINE (Headless & Deterministic) | +| - SimPy Discrete-Event Scheduler - Multi-Zone Order Generator | +| - NetworkX Graph & Path Planning - Dynamic Time-Space Traffic Resv. | +| - Pluggable Fleet Dispatching - Battery State & Opportunity Charging | ++-----------------------------------------------------------------------------------+ + | + v ++-----------------------------------------------------------------------------------+ +| OUTPUTS & STORAGE | +| logs/simulation.log results/trajectories/ results/experiments/ | ++-----------------------------------------------------------------------------------+ + | | + v v ++-----------------------------------------+ +-------------------------------------+ +| NVIDIA OMNIVERSE VISUALIZATION | | ANALYTICS & METRICS | +| Kit 110.4 + OpenUSD Scene Playback | | Throughput, Fleet Utilization, | +| Lightweight Robot Prims & Indicators | | Aisle Congestion & Latency KPIs | ++-----------------------------------------+ +-------------------------------------+ +``` + +--- + +## 3. Features Implemented & Roadmap + +### Currently Implemented (Phase 0) +- [x] Host environment and Omniverse Kit template inspection. +- [x] Decoupled project structure adhering to modular standards. +- [x] Standard Python packaging (`pyproject.toml`) and editable install. +- [x] Multi-target rotating file logging (`application.log`, `simulation.log`, `errors.log`). +- [x] Robust configuration loader and schema validator for all 5 domains. +- [x] Automated environment verification script (`scripts/check_environment.sh`). +- [x] CLI entry point with `validate-env` and `validate-config`. +- [x] Comprehensive unit test suite (17 passed in 0.09s). +- [x] Low-disk-space mitigation strategy (`WAREHOUSE_TWIN_SECONDARY_DRIVE`). + +### Planned Roadmap +- **Phase 1**: Warehouse topological graph, Zone A/B/C nodes, docks, and connectivity validation. +- **Phase 2**: AMR state machine, payload validation, and task models. +- **Phase 3**: SimPy discrete-event simulation engine and order generation. +- **Phase 4**: NetworkX shortest-path routing, fleet dispatching, and aisle reservations. +- **Phase 5**: Battery discharge/recharge dynamics, charging queues, and production deadlines. +- **Phase 6**: Analytics, KPI calculations, and congestion heatmaps. +- **Phase 7**: NVIDIA Omniverse USD 3D visualization and trajectory playback. +- **Phase 8**: Interactive operational dashboard. +- **Phase 9**: Optimization scenarios, fleet-size benchmarking, and final demonstration. + +--- + +## 4. Supported Environment + +- **Operating System**: Ubuntu 24.04.3 LTS (x86_64). +- **Python**: Python 3.12 (Host has 3.12.3; compatible with >= 3.10). +- **Core Dependencies**: `simpy` 4.1.2, `networkx` 3.7, `pytest` 9.1.1. +- **NVIDIA GPU**: NVIDIA GeForce RTX 5090 (Driver 580.178.04, CUDA 13.0). +- **NVIDIA Omniverse Kit**: Kit 110.4.0 (located at `/home/dmhai/nvidia-omniverse/kit-app-template`). +- **Isaac Sim**: **NOT required**. The core simulation operates completely independently of Isaac Sim. + +--- + +## 5. Installation & Setup + +1. **Clone or enter the project directory**: + ```bash + cd /home/dmhai/warehouse-digital-twin + ``` + +2. **Activate the virtual environment**: + ```bash + source .venv/bin/activate + ``` + +3. **Install the package in editable mode**: + ```bash + pip install -e . + ``` + +4. **Run environment verification**: + ```bash + ./scripts/check_environment.sh + ``` + +--- + +## 6. Configuration Instructions + +All parameters are externalized in `config/`: +- `config/warehouse.json`: Facility dimensions (60m x 40m), Zone A/B/C bounds, docks, stations, and charging bays. +- `config/robots.json`: Robot types (Light AMR, Heavy AMR), speeds, payloads, battery capacities, and fleet composition. +- `config/inventory.json`: Item catalogs for Zones A, B, and C with stock counts, weights, and replenishment parameters. +- `config/simulation.json`: Duration (3600s), tick resolution, random seed, and arrival rates. +- `config/dispatch_policies.json`: Dispatch policies, reservation parameters, and charging thresholds. + +--- + +## 7. Running Commands + +### Verify Environment +```bash +warehouse-twin validate-env +``` + +### Validate Configuration Files +```bash +warehouse-twin validate-config +``` + +### Run Automated Tests +```bash +./scripts/run_tests.sh +# Or directly with pytest: +pytest tests/ -v +``` + +--- + +## 8. Low-Disk-Space Protection + +The primary drive (`/`) has constrained free space (~8.9 GB free). To prevent disk exhaustion: +1. All application logs use rotating file handlers capped at 10 MB. +2. Large trajectory recordings and experiment results are ignored by `.gitignore`. +3. To redirect logs and results to an external or secondary drive, set: + ```bash + export WAREHOUSE_TWIN_SECONDARY_DRIVE="/path/to/external/storage" + ``` + +--- + +## 9. Omniverse Visualization (Phase 7 Preview) + +The visualizer connects via file-based trajectory playback: +- Simulation writes time-stamped Cartesian coordinates to `results/trajectories/`. +- Omniverse Kit 110.4 loads the warehouse USD stage (`omniverse/scenes/`) and moves robot prims along the scheduled trajectory. +- Run command (available in Phase 7): + ```bash + /home/dmhai/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/kit/kit /home/dmhai/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/apps/warehouse_twin.kit --ext-folder omniverse/extensions + ``` + +--- + +## 10. Current Implementation Phase + +**Current Phase**: **Phase 0: Environment and Project Foundation (Completed)**. +**Next Phase**: **Phase 1: Warehouse Model** (Awaiting user confirmation). diff --git a/config/dispatch_policies.json b/config/dispatch_policies.json new file mode 100644 index 0000000..fc67c91 --- /dev/null +++ b/config/dispatch_policies.json @@ -0,0 +1,39 @@ +{ + "active_policy": "priority_nearest_idle", + "available_policies": [ + "nearest_idle", + "priority_nearest_idle", + "balanced_utilization" + ], + "policy_settings": { + "priority_nearest_idle": { + "priority_weight": 0.6, + "distance_weight": 0.4, + "consider_battery_headroom": true, + "preemption_enabled": false + }, + "nearest_idle": { + "distance_weight": 1.0 + }, + "balanced_utilization": { + "utilization_weight": 0.5, + "distance_weight": 0.5 + } + }, + "traffic_reservation": { + "enabled": true, + "reservation_window_seconds": 10.0, + "intersection_exclusive_zone_radius_meters": 2.0, + "deadlock_timeout_seconds": 30.0, + "yield_rules": { + "loaded_yields_to_empty": false, + "lower_priority_yields_to_higher": true + } + }, + "charging_strategy": { + "policy": "threshold_opportunity", + "opportunistic_charging_threshold_percent": 60.0, + "mandatory_charging_threshold_percent": 25.0, + "min_charge_duration_seconds": 180.0 + } +} diff --git a/config/inventory.json b/config/inventory.json new file mode 100644 index 0000000..e9e8150 --- /dev/null +++ b/config/inventory.json @@ -0,0 +1,142 @@ +{ + "categories": { + "zone_a_fast_moving": { + "name": "Fast-moving Inventory", + "zone": "zone_a", + "default_priority": 1, + "items": [ + { + "item_id": "filter_hydraulic_hf1", + "name": "Hydraulic Oil Filter HF-1", + "unit_weight_kg": 2.5, + "initial_stock": 200, + "minimum_stock": 50, + "replenishment_batch": 100, + "storage_location": "rack_a_01" + }, + { + "item_id": "belt_drive_bd10", + "name": "V-Ribbed Drive Belt BD-10", + "unit_weight_kg": 1.2, + "initial_stock": 150, + "minimum_stock": 40, + "replenishment_batch": 80, + "storage_location": "rack_a_02" + }, + { + "item_id": "hardware_bolt_pack_m12", + "name": "M12 High-Tensile Fastener Pack", + "unit_weight_kg": 5.0, + "initial_stock": 300, + "minimum_stock": 75, + "replenishment_batch": 150, + "storage_location": "rack_a_03" + }, + { + "item_id": "fluid_line_assembly_fl4", + "name": "Reinforced Fluid Line Assembly FL-4", + "unit_weight_kg": 3.8, + "initial_stock": 120, + "minimum_stock": 30, + "replenishment_batch": 60, + "storage_location": "rack_a_04" + }, + { + "item_id": "tractor_hood_panel_th2", + "name": "Composite Tractor Hood Panel TH-2", + "unit_weight_kg": 22.0, + "initial_stock": 40, + "minimum_stock": 10, + "replenishment_batch": 20, + "storage_location": "rack_a_05" + } + ] + }, + "zone_b_slow_moving": { + "name": "Slow-moving and Specialized Inventory", + "zone": "zone_b", + "default_priority": 2, + "items": [ + { + "item_id": "transmission_combine_ct8", + "name": "Heavy Combine Transmission Unit CT-8", + "unit_weight_kg": 650.0, + "initial_stock": 8, + "minimum_stock": 2, + "replenishment_batch": 4, + "storage_location": "rack_b_01" + }, + { + "item_id": "structural_chassis_frame_sf3", + "name": "Welded Structural Chassis Frame SF-3", + "unit_weight_kg": 850.0, + "initial_stock": 6, + "minimum_stock": 2, + "replenishment_batch": 3, + "storage_location": "rack_b_02" + }, + { + "item_id": "engine_piston_set_ep6", + "name": "Precision Engine Piston Set EP-6", + "unit_weight_kg": 45.0, + "initial_stock": 25, + "minimum_stock": 8, + "replenishment_batch": 12, + "storage_location": "rack_b_03" + }, + { + "item_id": "specialized_planetary_hub_ph1", + "name": "Final Drive Planetary Hub PH-1", + "unit_weight_kg": 180.0, + "initial_stock": 15, + "minimum_stock": 4, + "replenishment_batch": 8, + "storage_location": "rack_b_04" + } + ] + }, + "zone_c_production_supply": { + "name": "Raw Materials and Production-Line Supply", + "zone": "zone_c", + "default_priority": 3, + "items": [ + { + "item_id": "raw_steel_coil_sc5", + "name": "Hot-Rolled Sheet Steel Coil SC-5", + "unit_weight_kg": 1100.0, + "initial_stock": 10, + "minimum_stock": 3, + "replenishment_batch": 5, + "storage_location": "rack_c_01" + }, + { + "item_id": "electronic_control_module_ecm9", + "name": "Main Electronic Control Module ECM-9", + "unit_weight_kg": 8.5, + "initial_stock": 50, + "minimum_stock": 15, + "replenishment_batch": 25, + "storage_location": "rack_c_02" + }, + { + "item_id": "finishing_coating_drum_fc2", + "name": "Corrosion-Resistant Finishing Coat Drum (200L)", + "unit_weight_kg": 220.0, + "initial_stock": 18, + "minimum_stock": 5, + "replenishment_batch": 10, + "storage_location": "rack_c_03" + }, + { + "item_id": "mfg_fastener_bulk_drum_fd1", + "name": "Bulk Manufacturing Rivet/Fastener Drum", + "unit_weight_kg": 350.0, + "initial_stock": 14, + "minimum_stock": 4, + "replenishment_batch": 8, + "storage_location": "rack_c_04" + } + ] + } + } +} diff --git a/config/robots.json b/config/robots.json new file mode 100644 index 0000000..157b21b --- /dev/null +++ b/config/robots.json @@ -0,0 +1,75 @@ +{ + "robot_types": { + "light_amr": { + "name": "Agile Lightweight AMR", + "description": "Optimized for Zone A fast-moving small parts and rapid 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_b", "zone_c"], + "dimensions": { + "length": 0.8, + "width": 0.6, + "height": 0.35 + } + }, + "heavy_amr": { + "name": "Heavy-Duty Pallet AMR", + "description": "Engineered for Zone B heavy mechanical assemblies 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": { + "length": 1.4, + "width": 1.0, + "height": 0.45 + } + } + }, + "fleet": [ + { + "robot_id": "amr_light_01", + "robot_type": "light_amr", + "initial_position": [2.0, 36.0, 0.0], + "initial_battery_percent": 100.0 + }, + { + "robot_id": "amr_light_02", + "robot_type": "light_amr", + "initial_position": [4.0, 36.0, 0.0], + "initial_battery_percent": 100.0 + }, + { + "robot_id": "amr_heavy_01", + "robot_type": "heavy_amr", + "initial_position": [6.0, 36.0, 0.0], + "initial_battery_percent": 100.0 + }, + { + "robot_id": "amr_heavy_02", + "robot_type": "heavy_amr", + "initial_position": [8.0, 36.0, 0.0], + "initial_battery_percent": 100.0 + } + ], + "battery_policy": { + "low_battery_threshold_percent": 25.0, + "critical_battery_threshold_percent": 15.0, + "recharge_target_percent": 85.0 + } +} diff --git a/config/simulation.json b/config/simulation.json new file mode 100644 index 0000000..22011d5 --- /dev/null +++ b/config/simulation.json @@ -0,0 +1,29 @@ +{ + "simulation": { + "duration_seconds": 3600.0, + "time_unit": "seconds", + "random_seed": 42, + "warmup_duration_seconds": 300.0, + "tick_resolution_seconds": 0.5 + }, + "workload": { + "zone_a_arrival_rate_per_hour": 60.0, + "zone_b_arrival_rate_per_hour": 15.0, + "zone_c_scheduled_feed_interval_seconds": 600.0, + "peak_demand_multiplier": 1.5, + "peak_start_second": 1200.0, + "peak_end_second": 2400.0 + }, + "operational_times": { + "pickup_time_seconds": 15.0, + "dropoff_time_seconds": 15.0, + "heavy_pickup_overhead_seconds": 30.0, + "line_feed_lead_time_seconds": 300.0 + }, + "outputs": { + "events_format": "jsonl", + "export_trajectories": true, + "trajectory_sample_interval_seconds": 1.0, + "summary_report": true + } +} diff --git a/config/warehouse.json b/config/warehouse.json new file mode 100644 index 0000000..55a7537 --- /dev/null +++ b/config/warehouse.json @@ -0,0 +1,128 @@ +{ + "coordinate_system": { + "type": "right_handed_cartesian", + "axes": { + "x": "width_east_meters", + "y": "depth_north_meters", + "z": "height_up_meters" + }, + "units": "meters" + }, + "dimensions": { + "width": 60.0, + "depth": 40.0, + "height": 8.0 + }, + "zones": { + "zone_a": { + "name": "Zone A: Fast-moving inventory", + "description": "High-throughput, frequent order arrivals, short routes (Filters, Belts, Hardware, Fluid lines, Tractor panels)", + "area": { + "x_min": 5.0, + "x_max": 25.0, + "y_min": 5.0, + "y_max": 35.0 + }, + "aisle_width": 2.5, + "max_robot_speed": 1.8 + }, + "zone_b": { + "name": "Zone B: Slow-moving and specialized inventory", + "description": "Heavy-duty parts, longer travel, restricted aisles (Combine transmissions, Structural frames, Engine pistons)", + "area": { + "x_min": 30.0, + "x_max": 45.0, + "y_min": 5.0, + "y_max": 35.0 + }, + "aisle_width": 3.5, + "max_robot_speed": 1.2 + }, + "zone_c": { + "name": "Zone C: Raw materials and production-line supply", + "description": "Scheduled deliveries, production deadlines, stock-out tracking (Steel coils, Control modules, Finishing materials)", + "area": { + "x_min": 48.0, + "x_max": 58.0, + "y_min": 5.0, + "y_max": 35.0 + }, + "aisle_width": 3.0, + "max_robot_speed": 1.0 + } + }, + "stations": [ + { + "station_id": "dock_inbound_1", + "type": "inbound_dock", + "position": [2.0, 10.0, 0.0], + "capacity": 2 + }, + { + "station_id": "dock_inbound_2", + "type": "inbound_dock", + "position": [2.0, 20.0, 0.0], + "capacity": 2 + }, + { + "station_id": "picking_station_a1", + "type": "picking_station", + "position": [25.0, 2.0, 0.0], + "capacity": 1 + }, + { + "station_id": "picking_station_b1", + "type": "picking_station", + "position": [40.0, 2.0, 0.0], + "capacity": 1 + }, + { + "station_id": "production_dropoff_c1", + "type": "production_feed", + "position": [55.0, 38.0, 0.0], + "capacity": 2 + }, + { + "station_id": "outbound_pack_1", + "type": "outbound_dock", + "position": [2.0, 30.0, 0.0], + "capacity": 2 + } + ], + "charging_stations": [ + { + "station_id": "charge_bay_1", + "position": [2.0, 36.0, 0.0], + "charging_rate_kw": 25.0, + "capacity": 1 + }, + { + "station_id": "charge_bay_2", + "position": [4.0, 36.0, 0.0], + "charging_rate_kw": 25.0, + "capacity": 1 + }, + { + "station_id": "charge_bay_3", + "position": [6.0, 36.0, 0.0], + "charging_rate_kw": 50.0, + "capacity": 1 + }, + { + "station_id": "charge_bay_4", + "position": [8.0, 36.0, 0.0], + "charging_rate_kw": 50.0, + "capacity": 1 + } + ], + "grid": { + "node_spacing": 2.0, + "one_way_edges": [], + "restricted_edges": [ + { + "zone": "zone_b", + "allowed_robot_types": ["heavy_amr"] + } + ] + } +} diff --git a/data/input/.gitkeep b/data/input/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/data/sample/.gitkeep b/data/sample/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docs/API_AND_DATA_CONTRACTS.md b/docs/API_AND_DATA_CONTRACTS.md new file mode 100644 index 0000000..601e8d3 --- /dev/null +++ b/docs/API_AND_DATA_CONTRACTS.md @@ -0,0 +1,122 @@ +# API and Data Contracts + +This document formalizes the data interchange models between the simulation engine, event logging, trajectory output, and the Omniverse visualizer. + +--- + +## 1. Domain Data Models + +### 1.1 Robot Model (`Robot`) +```json +{ + "robot_id": "amr_light_01", + "robot_type": "light_amr", + "position": [2.0, 36.0, 0.0], + "maximum_speed": 1.8, + "payload_capacity": 150.0, + "battery_level": 3.0, + "battery_capacity": 3.0, + "energy_consumption": { + "idle_kw": 0.05, + "moving_empty_kw": 0.35, + "moving_loaded_kw": 0.65, + "handling_kw": 0.15 + }, + "current_state": "IDLE", + "current_task_id": null, + "current_route": [], + "accumulated_distance": 0.0, + "busy_time": 0.0, + "idle_time": 0.0, + "charging_time": 0.0 +} +``` + +### 1.2 Robot State Enumeration +- `IDLE`: Stationed at node, awaiting assignment. +- `DISPATCHED`: En route to pickup station or warehouse storage rack. +- `PICKING`: Handling/loading cargo at source. +- `LOADED_TRANSIT`: En route to dropoff destination with payload. +- `DROPPING`: Unloading cargo at destination. +- `TRANSIT_TO_CHARGE`: Traveling to assigned charging station. +- `CHARGING`: Actively recharging at charging bay. +- `MAINTENANCE` / `ERROR`: Out of service. + +### 1.3 Task Model (`Task`) +```json +{ + "task_id": "task_ord_00101", + "task_type": "ORDER_PICK", + "source": "rack_a_01", + "destination": "picking_station_a1", + "priority": 1, + "release_time": 124.5, + "deadline": 424.5, + "required_payload": 25.0, + "status": "COMPLETED", + "assigned_robot_id": "amr_light_01", + "completion_time": 312.0 +} +``` + +### 1.4 Task Types +- `ORDER_PICK`: Fulfilling an outbound picking order (predominantly Zone A & B). +- `REPLENISHMENT`: Inbound dock to storage rack restocking. +- `PRODUCTION_LINE_FEED`: Time-critical material transfer to production line (Zone C). +- `CHARGING`: Internal battery maintenance dispatch. + +--- + +## 2. Simulation Event Record Schema + +Events recorded in `logs/simulation.log` and exported to `results/experiments/events.jsonl`: + +```json +{ + "event_id": "evt_000984", + "simulation_time": 128.5, + "event_type": "TASK_DISPATCHED", + "entity_id": "amr_light_01", + "task_id": "task_ord_00101", + "metadata": { + "source": "rack_a_01", + "destination": "picking_station_a1", + "route_length_m": 24.0, + "estimated_duration_s": 15.2, + "battery_soc_pct": 94.2 + } +} +``` + +--- + +## 3. Trajectory Export Schema (For Omniverse USD Playback) + +Saved under `results/trajectories/trajectory_.json`: + +```json +{ + "metadata": { + "simulation_run_id": "sim_20261019_144000", + "time_step_seconds": 0.5, + "coordinate_system": "right_handed_cartesian_meters_z_up", + "total_duration_seconds": 3600.0 + }, + "robots": { + "amr_light_01": [ + { + "t": 0.0, + "pos": [2.0, 36.0, 0.0], + "yaw_deg": 0.0, + "state": "IDLE" + }, + { + "t": 0.5, + "pos": [2.0, 35.1, 0.0], + "yaw_deg": 180.0, + "state": "DISPATCHED" + } + ] + } +} +``` diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..f116f36 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,100 @@ +# Warehouse Robot Fleet Digital Twin: Architecture + +## 1. Executive Overview + +The Warehouse Robot Fleet Digital Twin is a modular, event-driven simulation and 3D visualization platform engineered to model, analyze, and optimize autonomous mobile robot (AMR) fleet operations in multi-zone industrial facilities. + +The architecture strictly decouples: +1. **Core Simulation Engine**: Discrete-event logic, fleet dispatching, path reservation, battery dynamics, and inventory state. +2. **Data & Storage Layer**: Structured simulation event logs (JSONL/CSV), KPI aggregations, and trajectory records. +3. **Visualization & Digital Twin Layer**: NVIDIA Omniverse Kit, OpenUSD scene hierarchy, and trajectory playback. +4. **Analytics & Optimization Layer**: Reporting, congestion heatmaps, and scenario comparisons. + +This decoupling guarantees that the simulation runs headlessly and deterministically without requiring a GPU, display server, NVIDIA Isaac Sim, or Omniverse Kit. Visualization is an asynchronous consumer of simulation outputs. + +``` ++-----------------------------------------------------------------------------------+ +| CONFIG & INPUT LAYER | +| config/warehouse.json config/robots.json config/inventory.json config/... | ++-----------------------------------------------------------------------------------+ + | + v ++-----------------------------------------------------------------------------------+ +| DISCRETE-EVENT SIMULATION ENGINE | +| +------------------------+ +------------------------+ +---------------------+ | +| | SimPy Clock & | | NetworkX Routing | | Fleet Dispatch | | +| | Event Loop | | & Time-Space Resv. | | & Battery Mgr | | +| +------------------------+ +------------------------+ +---------------------+ | +| +------------------------+ +------------------------+ +---------------------+ | +| | Order & Replenish | | Zone A, B, C Logic | | AMR State Machine | | +| | Generators | | & Capacity Checks | | Controllers | | +| +------------------------+ +------------------------+ +---------------------+ | ++-----------------------------------------------------------------------------------+ + | + v ++-----------------------------------------------------------------------------------+ +| DATA OUTPUTS & STORAGE INTERFACE | +| logs/simulation.log results/trajectories/robot_paths.json | +| results/experiments/events.jsonl results/reports/kpis.json | ++-----------------------------------------------------------------------------------+ + | | + v v ++-----------------------------------------+ +-------------------------------------+ +| OMNIVERSE VISUALIZATION | | ANALYTICS & KPI | +| Kit 110.4 + OpenUSD Playback | | Throughput, Robot Utilization, | +| USD Prims / Live Kit Extension | | Aisle Congestion, Latency Heatmaps | ++-----------------------------------------+ +-------------------------------------+ +``` + +--- + +## 2. Decoupled Subsystems + +### 2.1 Domain Layer (`warehouse_twin.domain`) +Defines immutable data classes, domain models, and strict type-checked enums: +- **Robot**: ID, type, physical specs, payload limits, battery state, kinematics, state machine. +- **Task**: ID, category (order pick, restocking, production-feed), priority, release time, deadline, status. +- **Inventory**: SKU ID, category (Zone A fast, Zone B heavy, Zone C production raw), quantity, lot size, min stock. +- **Warehouse**: Dimensions, nodes, coordinate system, zone definitions, docks, charging bays. +- **Events**: Canonical simulation events emitted to storage and logging. + +### 2.2 Simulation Engine (`warehouse_twin.simulation`) +Built on `SimPy`: +- Event loop with microsecond-level discrete-event scheduling. +- Separate simulation clock (`sim_time`) independent of host execution wall-clock time. +- Deterministic random seed propagation (`random.Random` instances, no unseeded globals). +- Order generators parameterized by zone throughput and peak demand windows. + +### 2.3 Routing & Traffic Management (`warehouse_twin.routing`) +- Graph representation of warehouse floor using `NetworkX`. +- Spatio-temporal reservation table to prevent head-on collisions and deadlocks in narrow aisles. +- Kinematic path travel times calculated from acceleration, top speed, and turning constraints. + +### 2.4 Fleet Management (`warehouse_twin.fleet`) +- Task dispatcher with pluggable policies (`priority_nearest_idle`, `balanced_utilization`). +- Battery manager monitoring state of charge (SoC) and enforcing opportunity charging thresholds. +- Safe preemption and task reassignment if an AMR encounters an unexpected delay or low battery. + +### 2.5 Storage & Interfaces (`warehouse_twin.storage`, `warehouse_twin.interfaces`) +- Streamed JSONL event logs. +- Interpolated 3D trajectory generator producing time-indexed Cartesian coordinates `(x, y, z, yaw, state)`. + +### 2.6 Omniverse USD Visualization (`omniverse/`) +- Utilizes NVIDIA Omniverse Kit 110.4. +- Reads exported trajectory JSON and updates USD prim transforms on each Kit update tick (`omni.kit.app.get_app().get_update_event_stream()`). +- Clean teardown without dangling event subscriptions. + +--- + +## 3. Coordinate System & Measurement Units + +| Dimension | Unit | Description | +| :--- | :--- | :--- | +| **Coordinate System** | Right-Handed Cartesian | X = East (Width), Y = North (Depth), Z = Up (Height) | +| **Distance** | Meters (m) | Standard SI units for all node coordinates and dimensions | +| **Linear Velocity** | Meters per second (m/s) | Robot speed limits and travel rates | +| **Acceleration** | Meters per second² (m/s²) | Ramp-up and braking kinematics | +| **Mass / Payload** | Kilograms (kg) | Payload constraints and inventory weights | +| **Energy / Battery** | Kilowatt-hours (kWh) | Battery pack capacity and residual energy | +| **Power Rate** | Kilowatts (kW) | Consumption (idle, moving, lifting) and charging rate | +| **Time** | Seconds (s) | Discrete-event simulation clock | diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md new file mode 100644 index 0000000..cbcab36 --- /dev/null +++ b/docs/DECISIONS.md @@ -0,0 +1,45 @@ +# Architecture Decision Records (ADRs) + +## ADR-001: Separation of Discrete-Event Simulation from 3D Visualization +- **Status**: Accepted +- **Context**: Omniverse Kit and USD are powerful visualization engines, but coupling simulation logic directly into Kit extension update loops slows testing, complicates continuous integration, and ties discrete event timing to render frame rates. +- **Decision**: Keep the discrete-event simulation engine in pure standard Python. The simulation will export time-indexed trajectories (JSON) and event logs. Omniverse Kit will consume these trajectories in Phase 7 as an asynchronous visualizer. +- **Consequences**: Fast test execution (headless in < 1s), zero GPU requirement for algorithmic development, clear data interchange boundaries. + +--- + +## ADR-002: Discrete-Event Engine with SimPy & NetworkX +- **Status**: Accepted +- **Context**: Need a lightweight, deterministic framework for managing asynchronous robot events (orders, traveling, picking, battery discharge, recharging). +- **Decision**: Use `SimPy` for the event-scheduling loop and `NetworkX` for graph-based warehouse topology and shortest-path calculation. +- **Consequences**: Highly deterministic runs via seeded random streams; no heavy external robotics simulator dependencies during core fleet logic development. + +--- + +## ADR-003: Standalone Operation Without Isaac Sim Dependency +- **Status**: Accepted +- **Context**: Isaac Sim requires substantial disk space (~30-50+ GB) and the host root drive `/dev/nvme0n1p4` is constrained with only ~8.9 GB free. +- **Decision**: Do not require Isaac Sim. Rely on discrete-event kinematics for robot movement. Ensure data models (coordinates, states, speeds) conform to standard robotics conventions so Isaac Sim can be integrated in the future without architectural redesign. +- **Consequences**: Enables immediate development on the user's host without risking disk exhaustion. + +--- + +## ADR-004: Low-Disk-Space Mitigation and Secondary Drive Relocation +- **Status**: Accepted +- **Context**: The root filesystem is at 99% capacity (~8.9 GB free). Simulation logs and trajectory files could exhaust space if unconstrained. +- **Decision**: + 1. Enforce size-capped rotating log handlers (`RotatingFileHandler` with 10MB limits and 5 backups). + 2. Implement an optional `WAREHOUSE_TWIN_SECONDARY_DRIVE` environment variable. When set, all large outputs (`logs/`, `results/`) are redirected to the specified secondary path. + 3. Include disk space warnings in `check_environment.sh` and CLI `validate-env`. +- **Consequences**: Prevents host crash due to accidental root drive fill-up. + +--- + +## ADR-005: Structured Logging with Rotating Handlers +- **Status**: Accepted +- **Context**: Need separate logging streams for diagnostic debugging versus simulation event auditing, with automatic size limits. +- **Decision**: Provide three dedicated streams: + 1. `application.log`: Component lifecycle, config loading, and diagnostic info. + 2. `simulation.log`: High-resolution simulation events with timestamp and entity tracking. + 3. `errors.log`: Error and critical level events with full stack traces. +- **Consequences**: Clean separation of operational concerns, easy debugging, bounded disk usage. diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md new file mode 100644 index 0000000..60125d8 --- /dev/null +++ b/docs/INSTALLATION.md @@ -0,0 +1,76 @@ +# Installation and Setup Guide + +## 1. Prerequisites + +- **Operating System**: Ubuntu Linux 22.04 LTS or 24.04 LTS (Tested on Ubuntu 24.04.3 LTS). +- **Python**: Version 3.10, 3.11, or 3.12 (Host has Python 3.12.3). +- **GPU** (For 3D visualization only): NVIDIA RTX GPU with modern driver (Tested on NVIDIA RTX 5090 with driver 580.178.04). +- **Disk Space**: At least 500 MB free for simulation, virtual environment, and initial outputs. (Host currently has ~8.9 GB free on `/dev/nvme0n1p4`). +- **NVIDIA Isaac Sim**: **NOT required**. The simulation engine is completely standalone. + +--- + +## 2. Setting Up the Virtual Environment + +From the project root: + +```bash +cd /home/dmhai/warehouse-digital-twin + +# Create virtual environment if not already present +python3 -m venv .venv + +# Activate virtual environment +source .venv/bin/activate + +# Upgrade pip and install package in editable mode +pip install --upgrade pip +pip install -e . +``` + +--- + +## 3. Verifying the Setup + +Run the automated environment check script: + +```bash +./scripts/check_environment.sh +``` + +Or invoke the Python CLI directly: + +```bash +warehouse-twin validate-env +warehouse-twin validate-config +``` + +--- + +## 4. Running the Automated Tests + +Execute the unit test suite: + +```bash +./scripts/run_tests.sh +``` + +Or using pytest with options: + +```bash +pytest tests/ -v +``` + +--- + +## 5. Storage Relocation (For Disk-Constrained Systems) + +If your system drive `/` is low on disk space (e.g., < 2 GB), configure environment variables in `.env` or in your shell to redirect generated logs and simulation results to an external or secondary drive: + +```bash +export WAREHOUSE_TWIN_SECONDARY_DRIVE="/media/external/warehouse_data" +``` + +When set, the simulation will automatically place logs and output results under: +- `$WAREHOUSE_TWIN_SECONDARY_DRIVE/logs/` +- `$WAREHOUSE_TWIN_SECONDARY_DRIVE/results/` diff --git a/docs/TESTING.md b/docs/TESTING.md new file mode 100644 index 0000000..8e5f79e --- /dev/null +++ b/docs/TESTING.md @@ -0,0 +1,47 @@ +# Testing Strategy and Test Suites + +## 1. Testing Philosophy + +The test suite validates correctness, repeatability, schema integrity, and boundary conditions at each phase. + +Core principles: +- **Zero Isaac Sim / Omniverse dependency**: Unit and simulation tests run cleanly in headless environments without graphical displays or NVIDIA Kit runtime. +- **Fast execution**: Unit tests execute in under 1 second to encourage continuous verification during development. +- **Deterministic fixtures**: Temporary fixtures isolate filesystem effects and ensure tests do not pollute real logs or results. + +--- + +## 2. Test Structure + +``` +tests/ +├── __init__.py +├── conftest.py # Shared fixtures (temp config, mock objects) +├── unit/ +│ ├── __init__.py +│ ├── test_environment.py # System dependencies, Python version, disk checks +│ ├── test_logging.py # Log file creation, severity routing, log rotation +│ └── test_config_loader.py # JSON schema checks, missing keys, validations +├── integration/ # Multi-component integration tests (Phase 3+) +├── scenarios/ # Scenario workloads: normal, peak, line outages (Phase 6+) +└── fixtures/ # Static deterministic datasets +``` + +--- + +## 3. Running Tests + +### 3.1 All Tests +```bash +./scripts/run_tests.sh +``` + +### 3.2 Specific Test File +```bash +.venv/bin/pytest tests/unit/test_config_loader.py -v +``` + +### 3.3 With Coverage (when pytest-cov is installed) +```bash +.venv/bin/pytest tests/ --cov=warehouse_twin +``` diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md new file mode 100644 index 0000000..035f15a --- /dev/null +++ b/docs/USER_GUIDE.md @@ -0,0 +1,66 @@ +# User Guide: Warehouse Robot Fleet Digital Twin + +## 1. Quick Start + +Activate the project virtual environment before running commands: + +```bash +cd /home/dmhai/warehouse-digital-twin +source .venv/bin/activate +``` + +--- + +## 2. Command-Line Reference + +The main executable CLI is `warehouse-twin` (also accessible via `python -m warehouse_twin.main`). + +### 2.1 Validate Environment +Checks Python version, disk capacity, installed simulation libraries, log directory writability, and Omniverse Kit paths: + +```bash +warehouse-twin validate-env +``` + +### 2.2 Validate Configuration Files +Validates all 5 configuration files (`warehouse.json`, `robots.json`, `inventory.json`, `simulation.json`, `dispatch_policies.json`) against schema constraints: + +```bash +warehouse-twin validate-config +``` + +Specify a custom configuration directory: + +```bash +warehouse-twin validate-config --config-dir /path/to/custom/config +``` + +### 2.3 Check Version +Display installed package version: + +```bash +warehouse-twin --version +``` + +--- + +## 3. Configuring the Simulation + +All simulation behaviors are externalized in JSON configuration files located under `config/`: + +| File | Purpose | +| :--- | :--- | +| `config/warehouse.json` | Warehouse dimensions, zones (Zone A, B, C), stations, docks, and charging bays. | +| `config/robots.json` | Robot definitions (Light AMR, Heavy AMR), battery capacities, power consumption rates, initial fleet positions. | +| `config/inventory.json` | Catalog of items across Fast-moving, Slow-moving, and Production-supply zones, initial stock, and replenishment parameters. | +| `config/simulation.json` | Simulation duration, time resolution, random seed, and zone arrival rates. | +| `config/dispatch_policies.json` | Pluggable dispatch algorithms, reservation rules, and charging trigger thresholds. | + +--- + +## 4. Operational Logs + +Logs are automatically rotated and organized into three streams under `logs/`: +- `logs/application.log`: Application lifecycle, component configuration, and operational diagnostics. +- `logs/simulation.log`: High-resolution simulation events (order arrival, dispatch, pick, transit, delivery). +- `logs/errors.log`: Filtered log containing only ERROR and CRITICAL exceptions. diff --git a/docs/phases/phase_0_foundation.md b/docs/phases/phase_0_foundation.md new file mode 100644 index 0000000..0707480 --- /dev/null +++ b/docs/phases/phase_0_foundation.md @@ -0,0 +1,161 @@ +# Phase 0 Implementation Report: Environment and Foundation + +## 1. Phase Objective +Establish a clean, reproducible, and robust software foundation for the Warehouse Robot Fleet Digital Twin. This includes inspecting the host Ubuntu environment and Omniverse Kit installation, configuring the Python virtual environment and packaging, implementing structured and rotating logging, establishing configuration loading and schema validation, providing automated environment verification scripts, and delivering a unit test suite verifying the foundation. + +--- + +## 2. Requirements +- Inspect Ubuntu version, Python interpreter, available disk space, GPU details, and existing Omniverse Kit installation. +- Establish project directory structure strictly conforming to the master implementation blueprint. +- Implement standard Python packaging (`pyproject.toml`) with editable install support. +- Implement structured rotating logging with dedicated handlers for application diagnostics, simulation events, and errors. +- Implement configuration loading and validation for all 5 core configuration domains (`warehouse.json`, `robots.json`, `inventory.json`, `simulation.json`, `dispatch_policies.json`). +- Provide an automated environment validation script (`scripts/check_environment.sh`) and CLI (`warehouse-twin validate-env`). +- Implement unit tests covering environment checks, logging rotation, and configuration validation without requiring Isaac Sim or Omniverse Kit. + +--- + +## 3. Design Decisions +- **Decoupled Architecture**: Keep the discrete-event simulation engine in standard Python using `SimPy` and `NetworkX`, separate from Kit's rendering loop. +- **Disk Space Safeguards**: Given the 99% used root partition (~8.9 GB free), set strict 10 MB caps on rotating logs, exclude all large logs and results from git via `.gitignore`, and add support for the `WAREHOUSE_TWIN_SECONDARY_DRIVE` environment variable. +- **No Isaac Sim Dependency**: Develop the full fleet scheduling, kinematics, and routing models headlessly. +- **Kit 110.4 Compatibility**: Inspected the running Kit application at `/home/dmhai/nvidia-omniverse/kit-app-template` (Kit version 110.4.0) to ensure the eventual Phase 7 extension and USD trajectories seamlessly match Kit's extension mechanisms. + +--- + +## 4. Files Created or Modified + +| File | Description | +| :--- | :--- | +| `pyproject.toml` | PEP 517/621 packaging metadata, dependencies, scripts, pytest configuration. | +| `.gitignore` | Excludes venv, pycache, build artifacts, raw logs, and result files while preserving directories. | +| `.env.example` | Environment variable template including secondary drive relocation and Kit paths. | +| `config/warehouse.json` | 60x40m warehouse layout with Zones A, B, C, stations, and charging bays. | +| `config/robots.json` | Robot definitions (Light AMR, Heavy AMR), battery capacities, power models, initial fleet. | +| `config/inventory.json` | Item catalogs for Zones A, B, and C with stock levels, weights, and replenishment batches. | +| `config/simulation.json` | Discrete-event parameters: 3600s duration, seed 42, arrival rates, peak multipliers. | +| `config/dispatch_policies.json` | Dispatch policy settings, reservation window, and charging rules. | +| `src/warehouse_twin/__init__.py` | Package root with version `0.1.0`. | +| `src/warehouse_twin/logging_config.py` | Structured rotating logging with `application.log`, `simulation.log`, and `errors.log`. | +| `src/warehouse_twin/config/loader.py` | `ConfigLoader` and schema validators for all configuration files. | +| `src/warehouse_twin/config/__init__.py` | Exports `ConfigLoader`, `ConfigBundle`, and `ConfigurationError`. | +| `src/warehouse_twin/cli.py` | Command-line interface with `validate-env` and `validate-config`. | +| `src/warehouse_twin/main.py` | Main entry point for `python -m warehouse_twin.main`. | +| `scripts/check_environment.sh` | Shell script verifying system, disk, GPU, Kit, and Python packages. | +| `scripts/run_tests.sh` | Automated test runner script. | +| `tests/__init__.py` | Tests root package init. | +| `tests/conftest.py` | Pytest fixtures providing temporary test configs and paths. | +| `tests/unit/__init__.py` | Unit tests package init. | +| `tests/unit/test_environment.py` | Unit tests for Python version, package imports, and disk checks. | +| `tests/unit/test_logging.py` | Unit tests for log creation, severity routing, and file rotation. | +| `tests/unit/test_config_loader.py` | Unit tests for config loading, missing file errors, and validation checks. | +| `docs/ARCHITECTURE.md` | Comprehensive system architecture specification. | +| `docs/INSTALLATION.md` | Setup and environment guide. | +| `docs/USER_GUIDE.md` | CLI instructions and configuration documentation. | +| `docs/API_AND_DATA_CONTRACTS.md` | Data models and serialization schemas. | +| `docs/TESTING.md` | Test strategy and execution guide. | +| `docs/DECISIONS.md` | Architecture Decision Records (ADRs 001 - 005). | +| `omniverse/README.md` | Kit 110.4 integration strategy and trajectory playback design. | +| `README.md` | Master project documentation. | +| `IMPLEMENTATION_DETAILS.md` | Engineering implementation details across all modules. | +| `PROJECT_STATUS.md` | Phase tracking and task status. | +| `CHANGELOG.md` | Version change history. | + +--- + +## 5. Implementation Explanation + +### Environment Inspection Findings +- **Host OS**: Ubuntu 24.04.3 LTS (Kernel 7.0.0-38-generic). +- **Python**: System Python 3.12.3 at `/usr/bin/python3`. Virtual environment at `/home/dmhai/warehouse-digital-twin/.venv`. +- **Disk Space**: Primary NVMe drive `/dev/nvme0n1p4` mounted at `/` has 886 GB total, 832 GB used, and **8.9 GB free (99% full)**. No secondary drives are currently mounted. +- **GPU**: NVIDIA GeForce RTX 5090 (32,607 MiB VRAM), Driver 580.178.04, CUDA 13.0. +- **NVIDIA Omniverse Kit**: Located at `/home/dmhai/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/kit/kit` running Kit Version **110.4.0+feature.386251.187cf21b.gl** with app template `warehouse_twin.kit`. + +### Logging Subsystem +Configured using standard library `logging.handlers.RotatingFileHandler`. To prevent unbounded log growth on the disk-constrained drive, each log file defaults to a 10 MB limit with up to 5 backups. Handlers are segregated: +- Console: INFO level. +- `application.log`: DEBUG level, formatted with timestamp, level, module name, and line number. +- `simulation.log`: High-frequency simulation events with format `%(asctime)s [SIM_EVENT] %(message)s`. +- `errors.log`: Filtered strictly to ERROR and CRITICAL. + +### Configuration Subsystem +`ConfigLoader` parses the 5 project JSON files. It verifies spatial dimensions, coordinates, zone keys, robot attributes, fleet associations, inventory catalog records, and simulation execution limits. If any key is invalid or missing, it raises a specific `ConfigurationError` identifying the file, line, and attribute. + +--- + +## 6. Commands Executed and Outcomes + +1. **Environment inspection**: + `df -h && lsb_release -a && python3 --version && nvidia-smi` -> Verified Ubuntu 24.04, Python 3.12.3, RTX 5090, 8.9 GB free. +2. **Kit process inspection**: + `ps aux | grep kit` -> Found active Kit 110.4 process using app `warehouse_twin.kit`. +3. **Editable package installation**: + `.venv/bin/pip install -e .` -> Successfully built and installed `warehouse-digital-twin-0.1.0`. +4. **CLI verification**: + `.venv/bin/warehouse-twin --version` -> Output: `warehouse-twin 0.1.0`. + `.venv/bin/warehouse-twin validate-env` -> PASSED: 0 failures, 1 warning (low disk space). + `.venv/bin/warehouse-twin validate-config` -> PASSED: all 5 config files valid. +5. **Shell script execution**: + `./scripts/check_environment.sh` -> Completed successfully with zero exit code. +6. **Test execution**: + `./scripts/run_tests.sh` -> 17 passed in 0.09s. + +--- + +## 7. Tests and Their Results + +``` +============================== 17 passed in 0.09s ============================== +- tests/unit/test_config_loader.py: 9 passed + * test_load_real_project_configurations + * test_missing_config_file_raises_error + * test_invalid_json_syntax_raises_error + * test_missing_warehouse_zone_raises_error + * test_invalid_warehouse_dimensions_raises_error + * test_undefined_robot_type_raises_error + * test_duplicate_item_id_in_inventory_raises_error + * test_invalid_active_dispatch_policy_raises_error + * test_config_dir_env_var_override +- tests/unit/test_environment.py: 5 passed + * test_package_metadata + * test_python_version + * test_required_dependencies_importable + * test_check_environment_passes + * test_check_environment_detects_low_disk +- tests/unit/test_logging.py: 3 passed + * test_logging_directory_creation + * test_log_files_created_and_written + * test_log_file_rotation +``` + +--- + +## 8. Expected Outputs +- `logs/application.log`, `logs/simulation.log`, `logs/errors.log` created when logging is active. +- CLI exit code 0 when environment and configs are healthy. +- Fast unit test output completing in < 0.2s without requiring Isaac Sim or Kit. + +--- + +## 9. Known Issues & Risks +- **Primary Disk Space**: The `/` partition has only ~8.9 GB free (99% full). Mitigation is in place via rotating logs, gitignore, and the `WAREHOUSE_TWIN_SECONDARY_DRIVE` variable. Isaac Sim must NOT be installed. +- **Kit 110.4 Python environment**: Kit runs an embedded Python 3.12 interpreter. Discrete event simulation runs cleanly in the project `.venv` (Python 3.12.3), which matches Kit's Python version. + +--- + +## 10. Acceptance Criteria Checklist +- [x] The Python package can be imported. +- [x] Environment checks work. +- [x] Logging creates and rotates files. +- [x] Configuration loads successfully. +- [x] Tests run without requiring Isaac Sim. +- [x] Documentation reflects the actual environment. + +--- + +## 11. Next-Phase Dependencies +Phase 1 (Warehouse Model) depends on: +- Validated `config/warehouse.json` (completed). +- `NetworkX` graph builder to convert nodes, zones, and stations into a navigational graph with distance and restriction attributes. diff --git a/logs/.gitkeep b/logs/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/omniverse/README.md b/omniverse/README.md new file mode 100644 index 0000000..de8299c --- /dev/null +++ b/omniverse/README.md @@ -0,0 +1,43 @@ +# NVIDIA Omniverse Kit Integration: Warehouse Digital Twin + +## 1. Overview + +This directory contains assets, scene definitions, and integration documentation for the 3D visualization layer of the Warehouse Robot Fleet Digital Twin. + +The visualizer connects to the discrete-event simulation engine via decoupled data contracts: +1. **Simulation Phase (Headless)**: The simulation engine runs in Python (`SimPy`), computes fleet task allocation, schedules routes, and exports time-indexed trajectory recordings (`results/trajectories/trajectory_.json`). +2. **Visualization Phase (Omniverse Kit)**: NVIDIA Omniverse Kit loads the warehouse USD stage and plays back the AMR trajectories by updating prim transformation matrices along time steps. + +--- + +## 2. Inspected Environment Findings + +Inspection of the host system confirmed: +- **Kit Application Directory**: `/home/dmhai/nvidia-omniverse/kit-app-template` +- **Kit Kernel Version**: `110.4.0+feature.386251.187cf21b.gl` +- **Application Target**: `_build/linux-x86_64/release/apps/warehouse_twin.kit` +- **Kit Launch Executable**: `_build/linux-x86_64/release/kit/kit` +- **Embedded Python Version**: Python 3.12 (cp312) + +--- + +## 3. Directory Layout + +``` +omniverse/ +├── README.md # Integration guide and Kit version documentation +├── extensions/ # Verified Kit extension structure (Phase 7) +├── scenes/ # Generated warehouse OpenUSD scene files (.usda / .usd) +└── assets/ # Lightweight USD primitives for AMRs, racks, and stations +``` + +--- + +## 4. Phase 7 Visualization Architecture Preview + +In Phase 7, the visualizer extension will: +1. Load a parameterized USD stage representing the warehouse (Zones A, B, and C, picking stations, inbound docks, charging bays). +2. Instantiate lightweight AMR prims (`/World/Robots/amr_light_01`, etc.). +3. Subscribe to the Kit update loop via `omni.kit.app.get_app().get_update_event_stream()`. +4. Synchronize simulation playback time with Kit wall-clock frames and update robot translation `(x, y, z)` and orientation `yaw`. +5. Ensure clean teardown on extension shutdown or stage closing so no orphan subscriptions remain. diff --git a/omniverse/assets/.gitkeep b/omniverse/assets/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/omniverse/scenes/.gitkeep b/omniverse/scenes/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..33848ca --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,58 @@ +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "warehouse-digital-twin" +version = "0.1.0" +description = "A modular, discrete-event simulation and digital twin for warehouse AMR fleet operations with NVIDIA Omniverse integration" +readme = "README.md" +requires-python = ">=3.10" +license = { text = "Apache-2.0" } +authors = [ + { name = "Warehouse Twin Team", email = "dev@example.com" } +] +keywords = ["warehouse", "robotics", "digital-twin", "omniverse", "simpy", "amr"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Manufacturing", + "Intended Audience :: Science/Research", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Scientific/Engineering", +] + +dependencies = [ + "simpy>=4.1.0", + "networkx>=3.0", +] + +[project.optional-dependencies] +test = [ + "pytest>=8.0.0", +] +analytics = [ + "pandas>=2.0.0", + "matplotlib>=3.8.0", +] +dashboard = [ + "streamlit>=1.30.0", +] +dev = [ + "warehouse-digital-twin[test,analytics]", +] + +[project.scripts] +warehouse-twin = "warehouse_twin.cli:main" + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +python_files = ["test_*.py"] +python_functions = ["test_*"] +python_classes = ["Test*"] +addopts = "-v --strict-markers" diff --git a/results/experiments/.gitkeep b/results/experiments/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/results/reports/.gitkeep b/results/reports/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/results/trajectories/.gitkeep b/results/trajectories/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/scripts/check_environment.sh b/scripts/check_environment.sh new file mode 100755 index 0000000..df7e1b7 --- /dev/null +++ b/scripts/check_environment.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# Warehouse Robot Fleet Digital Twin - Environment Verification Script +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" + +echo "=== System Environment Inspection ===" +echo "Date: $(date)" +echo "Host: $(hostname)" +echo "OS: $(lsb_release -d 2>/dev/null | cut -f2 || uname -s)" +echo "Kernel: $(uname -r)" + +# Disk Space Check +echo "" +echo "=== Disk Space on Primary Drive ===" +df -h / + +# Virtual Environment Detection +VENV_DIR="${PROJECT_ROOT}/.venv" +if [ -d "$VENV_DIR" ]; then + echo "" + echo "=== Virtual Environment Found ===" + echo "Path: $VENV_DIR" + PYTHON_EXEC="${VENV_DIR}/bin/python" +else + echo "" + echo "=== Using System Python (Virtual environment not found at $VENV_DIR) ===" + PYTHON_EXEC="$(which python3)" +fi + +echo "Python Executable: $PYTHON_EXEC" +"$PYTHON_EXEC" --version + +# GPU Check +echo "" +echo "=== NVIDIA GPU Status ===" +if command -v nvidia-smi &> /dev/null; then + nvidia-smi --query-gpu=name,driver_version,memory.total,memory.free --format=csv,noheader +else + echo "nvidia-smi not found. Running in CPU-only mode." +fi + +# Omniverse Kit Check +echo "" +echo "=== NVIDIA Omniverse Kit Status ===" +KIT_DEFAULT="/home/dmhai/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/kit/kit" +KIT_EXEC="${KIT_PATH:-$KIT_DEFAULT}" +if [ -x "$KIT_EXEC" ]; then + echo "[OK] Found Omniverse Kit executable at: $KIT_EXEC" +else + echo "[INFO] Omniverse Kit executable not found at: $KIT_EXEC (Required only for Phase 7 visualization)" +fi + +# Run Python-level Environment Check +echo "" +echo "=== Running Python Verification ===" +cd "$PROJECT_ROOT" +"$PYTHON_EXEC" -m warehouse_twin.cli validate-env +"$PYTHON_EXEC" -m warehouse_twin.cli validate-config + +echo "" +echo "=== Environment Check Completed Successfully ===" diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh new file mode 100755 index 0000000..dd9ec85 --- /dev/null +++ b/scripts/run_tests.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Warehouse Robot Fleet Digital Twin - Run Tests Script +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" + +cd "$PROJECT_ROOT" + +if [ -f "${PROJECT_ROOT}/.venv/bin/pytest" ]; then + PYTEST_BIN="${PROJECT_ROOT}/.venv/bin/pytest" +else + PYTEST_BIN="pytest" +fi + +echo "Running test suite with: $PYTEST_BIN" +"$PYTEST_BIN" "$@" diff --git a/src/warehouse_twin/__init__.py b/src/warehouse_twin/__init__.py new file mode 100644 index 0000000..ee33de7 --- /dev/null +++ b/src/warehouse_twin/__init__.py @@ -0,0 +1,8 @@ +"""Warehouse Robot Fleet Digital Twin. + +A modular, scalable discrete-event simulation and digital twin for warehouse +AMR fleet management with NVIDIA Omniverse Kit and OpenUSD integration. +""" + +__version__ = "0.1.0" +__author__ = "Warehouse Twin Team" diff --git a/src/warehouse_twin/cli.py b/src/warehouse_twin/cli.py new file mode 100644 index 0000000..3ccb2bd --- /dev/null +++ b/src/warehouse_twin/cli.py @@ -0,0 +1,152 @@ +"""Command-line interface for Warehouse Robot Fleet Digital Twin.""" + +from __future__ import annotations + +import argparse +import os +import shutil +import sys +from pathlib import Path +from typing import Optional + +from warehouse_twin import __version__ +from warehouse_twin.config.loader import ConfigLoader, ConfigurationError +from warehouse_twin.logging_config import get_logger, setup_logging + + +def check_environment() -> int: + """Run programmatic environment checks and output structured status.""" + print("=" * 65) + print("Warehouse Robot Fleet Digital Twin - Environment Verification") + print("=" * 65) + + failures = 0 + warnings = 0 + + # 1. Python Version + py_major, py_minor, py_micro = sys.version_info[:3] + py_str = f"{py_major}.{py_minor}.{py_micro}" + if (py_major, py_minor) >= (3, 10): + print(f"[OK] Python version: {py_str} (>= 3.10 required)") + else: + print(f"[FAIL] Python version: {py_str} (< 3.10 is unsupported)") + failures += 1 + + # 2. Disk Space on Primary Drive + stat = shutil.disk_usage("/") + free_gb = stat.free / (1024**3) + total_gb = stat.total / (1024**3) + used_pct = ((stat.total - stat.free) / stat.total) * 100.0 + disk_msg = f"{free_gb:.2f} GB free of {total_gb:.2f} GB ({used_pct:.1f}% used)" + + if free_gb < 2.0: + print(f"[CRITICAL] Disk space: {disk_msg} (Less than 2 GB free!)") + failures += 1 + elif free_gb < 10.0: + print(f"[WARN] Disk space: {disk_msg} (Low disk space; relocation recommended)") + warnings += 1 + else: + print(f"[OK] Disk space: {disk_msg}") + + # 3. Core Simulation Dependencies + for pkg_name in ("simpy", "networkx", "pytest"): + try: + mod = __import__(pkg_name) + ver = getattr(mod, "__version__", "installed") + print(f"[OK] Module '{pkg_name}': version {ver}") + except ImportError: + print(f"[FAIL] Required module '{pkg_name}' is not installed") + failures += 1 + + # 4. Logging & Writable Directories + log_dir = setup_logging() + test_log_file = log_dir / ".write_test" + try: + test_log_file.write_text("test", encoding="utf-8") + test_log_file.unlink() + print(f"[OK] Log directory writable: {log_dir}") + except OSError as err: + print(f"[FAIL] Log directory is not writable ({log_dir}): {err}") + failures += 1 + + # 5. NVIDIA Omniverse Kit Check (Optional for Simulation, Required for Visualizer) + kit_env_path = os.environ.get( + "KIT_PATH", + "/home/dmhai/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/kit/kit" + ) + kit_path = Path(kit_env_path) + if kit_path.exists() and os.access(kit_path, os.X_OK): + print(f"[OK] NVIDIA Omniverse Kit found at: {kit_path}") + else: + print(f"[INFO] Omniverse Kit not detected at default path ({kit_path}). Phase 7 will require Kit.") + + print("-" * 65) + if failures > 0: + print(f"VERIFICATION FAILED: {failures} critical failure(s), {warnings} warning(s).") + return 1 + print(f"VERIFICATION PASSED: 0 failures, {warnings} warning(s). Environment ready.") + print("=" * 65) + return 0 + + +def validate_config(config_dir: Optional[str] = None) -> int: + """Validate all simulation configuration JSON files.""" + setup_logging() + logger = get_logger("cli") + try: + loader = ConfigLoader(config_dir) + print(f"Loading and validating configurations from: {loader.config_dir}") + bundle = loader.load_all() + + print(f"[OK] warehouse.json: {len(bundle.warehouse.get('zones', {}))} zones, {len(bundle.warehouse.get('stations', []))} stations, {len(bundle.warehouse.get('charging_stations', []))} chargers") + print(f"[OK] robots.json: {len(bundle.robots.get('robot_types', {}))} robot types, {len(bundle.robots.get('fleet', []))} registered robots") + print(f"[OK] inventory.json: {len(bundle.inventory.get('categories', {}))} categories") + print(f"[OK] simulation.json: duration={bundle.simulation['simulation']['duration_seconds']}s, seed={bundle.simulation['simulation']['random_seed']}") + print(f"[OK] dispatch_policies.json: active='{bundle.dispatch_policies['active_policy']}'") + print("All configuration files validated successfully!") + return 0 + except ConfigurationError as err: + logger.error("Configuration validation failed: %s", err) + print(f"[FAIL] Configuration Error: {err}", file=sys.stderr) + return 1 + + +def main(argv: Optional[list[str]] = None) -> int: + """Main CLI entry point.""" + parser = argparse.ArgumentParser( + prog="warehouse-twin", + description="Warehouse Robot Fleet Digital Twin CLI", + ) + parser.add_argument( + "--version", + action="version", + version=f"%(prog)s {__version__}", + ) + + subparsers = parser.add_subparsers(dest="command", help="Available subcommands") + + # Subcommand: validate-env + subparsers.add_parser("validate-env", help="Check system environment, Python version, dependencies, and disk space") + + # Subcommand: validate-config + config_parser = subparsers.add_parser("validate-config", help="Validate simulation configuration files") + config_parser.add_argument( + "--config-dir", + type=str, + default=None, + help="Path to directory containing configuration JSON files", + ) + + args = parser.parse_args(argv) + + if args.command == "validate-env": + return check_environment() + elif args.command == "validate-config": + return validate_config(args.config_dir) + else: + parser.print_help() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/warehouse_twin/config/__init__.py b/src/warehouse_twin/config/__init__.py new file mode 100644 index 0000000..2cf3578 --- /dev/null +++ b/src/warehouse_twin/config/__init__.py @@ -0,0 +1,5 @@ +"""Configuration package for Warehouse Digital Twin.""" + +from warehouse_twin.config.loader import ConfigBundle, ConfigLoader, ConfigurationError + +__all__ = ["ConfigBundle", "ConfigLoader", "ConfigurationError"] diff --git a/src/warehouse_twin/config/loader.py b/src/warehouse_twin/config/loader.py new file mode 100644 index 0000000..e2f1816 --- /dev/null +++ b/src/warehouse_twin/config/loader.py @@ -0,0 +1,186 @@ +"""Configuration loading and validation for Warehouse Robot Fleet Digital Twin.""" + +from __future__ import annotations + +import json +import os +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, Optional + + +class ConfigurationError(Exception): + """Raised when configuration validation or loading fails.""" + pass + + +@dataclass(frozen=True) +class ConfigBundle: + """Container holding all validated configuration components.""" + warehouse: Dict[str, Any] + robots: Dict[str, Any] + inventory: Dict[str, Any] + simulation: Dict[str, Any] + dispatch_policies: Dict[str, Any] + config_dir: Path + + +class ConfigLoader: + """Loads and validates warehouse simulation configuration files.""" + + REQUIRED_FILES = ( + "warehouse.json", + "robots.json", + "inventory.json", + "simulation.json", + "dispatch_policies.json", + ) + + def __init__(self, config_dir: Optional[Path | str] = None) -> None: + """Initialize the ConfigLoader with a specific directory or default.""" + if config_dir is not None: + self.config_dir = Path(config_dir).resolve() + else: + env_dir = os.environ.get("WAREHOUSE_TWIN_CONFIG_DIR") + if env_dir: + self.config_dir = Path(env_dir).resolve() + else: + # Default to project root / config + self.config_dir = (Path(__file__).resolve().parents[3] / "config").resolve() + + def _load_json_file(self, filename: str) -> Dict[str, Any]: + """Load and parse a JSON file, returning helpful error messages on failure.""" + file_path = self.config_dir / filename + if not file_path.exists(): + raise ConfigurationError( + f"Missing required configuration file: '{filename}' at path: {file_path}" + ) + try: + with open(file_path, "r", encoding="utf-8") as f: + data = json.load(f) + if not isinstance(data, dict): + raise ConfigurationError( + f"Configuration file '{filename}' must contain a JSON object (top-level dict), got {type(data).__name__}." + ) + return data + except json.JSONDecodeError as err: + raise ConfigurationError( + f"Invalid JSON syntax in '{filename}' at line {err.lineno}, column {err.colno}: {err.msg}" + ) from err + except OSError as err: + raise ConfigurationError(f"Failed to read '{filename}': {err}") from err + + def validate_warehouse(self, data: Dict[str, Any]) -> None: + """Validate warehouse spatial dimensions and required zones.""" + if "dimensions" not in data: + raise ConfigurationError("warehouse.json missing required key: 'dimensions'") + dims = data["dimensions"] + for axis in ("width", "depth", "height"): + if axis not in dims or not isinstance(dims[axis], (int, float)) or dims[axis] <= 0: + raise ConfigurationError(f"warehouse.json 'dimensions.{axis}' must be a positive number.") + + if "zones" not in data or not isinstance(data["zones"], dict): + raise ConfigurationError("warehouse.json missing or invalid 'zones' dictionary.") + + # Ensure Zone A, Zone B, Zone C are defined + for zone_id in ("zone_a", "zone_b", "zone_c"): + if zone_id not in data["zones"]: + raise ConfigurationError(f"warehouse.json missing required zone specification: '{zone_id}'") + + if "stations" not in data or not isinstance(data["stations"], list): + raise ConfigurationError("warehouse.json missing 'stations' list.") + + if "charging_stations" not in data or not isinstance(data["charging_stations"], list): + raise ConfigurationError("warehouse.json missing 'charging_stations' list.") + + def validate_robots(self, data: Dict[str, Any]) -> None: + """Validate robot specifications and fleet registry.""" + if "robot_types" not in data or not isinstance(data["robot_types"], dict) or not data["robot_types"]: + raise ConfigurationError("robots.json must define at least one entry in 'robot_types'.") + + for type_id, spec in data["robot_types"].items(): + for key in ("payload_capacity_kg", "max_speed_mps", "battery_capacity_kwh"): + if key not in spec or not isinstance(spec[key], (int, float)) or spec[key] <= 0: + raise ConfigurationError( + f"robots.json robot type '{type_id}' must specify a positive '{key}'." + ) + + if "fleet" not in data or not isinstance(data["fleet"], list) or not data["fleet"]: + raise ConfigurationError("robots.json must define a non-empty 'fleet' list.") + + for robot in data["fleet"]: + if "robot_id" not in robot or not robot["robot_id"]: + raise ConfigurationError("robots.json fleet contains an entry missing 'robot_id'.") + robot_type = robot.get("robot_type") + if robot_type not in data["robot_types"]: + raise ConfigurationError( + f"Robot '{robot['robot_id']}' references undefined robot_type '{robot_type}'." + ) + + def validate_inventory(self, data: Dict[str, Any]) -> None: + """Validate inventory categories and item records.""" + if "categories" not in data or not isinstance(data["categories"], dict) or not data["categories"]: + raise ConfigurationError("inventory.json must specify 'categories'.") + + # Verify items exist across categories + total_items = 0 + item_ids = set() + for cat_id, cat_data in data["categories"].items(): + items = cat_data.get("items", []) + for item in items: + item_id = item.get("item_id") + if not item_id: + raise ConfigurationError(f"Inventory category '{cat_id}' has an item missing 'item_id'.") + if item_id in item_ids: + raise ConfigurationError(f"Duplicate item_id '{item_id}' detected in inventory.json.") + item_ids.add(item_id) + total_items += 1 + + if total_items == 0: + raise ConfigurationError("inventory.json must contain at least one item.") + + def validate_simulation(self, data: Dict[str, Any]) -> None: + """Validate discrete-event simulation settings.""" + sim = data.get("simulation") + if not sim or not isinstance(sim, dict): + raise ConfigurationError("simulation.json missing required 'simulation' section.") + if "duration_seconds" not in sim or sim["duration_seconds"] <= 0: + raise ConfigurationError("simulation.json 'duration_seconds' must be positive.") + if "random_seed" not in sim: + raise ConfigurationError("simulation.json missing 'random_seed'.") + + def validate_dispatch_policies(self, data: Dict[str, Any]) -> None: + """Validate dispatch policies and active policy selection.""" + if "active_policy" not in data: + raise ConfigurationError("dispatch_policies.json missing 'active_policy'.") + available = data.get("available_policies", []) + if data["active_policy"] not in available: + raise ConfigurationError( + f"Active policy '{data['active_policy']}' is not in available_policies: {available}" + ) + + def load_all(self) -> ConfigBundle: + """Load and validate all configuration files into a ConfigBundle.""" + if not self.config_dir.exists() or not self.config_dir.is_dir(): + raise ConfigurationError(f"Configuration directory does not exist: {self.config_dir}") + + warehouse = self._load_json_file("warehouse.json") + robots = self._load_json_file("robots.json") + inventory = self._load_json_file("inventory.json") + simulation = self._load_json_file("simulation.json") + dispatch = self._load_json_file("dispatch_policies.json") + + self.validate_warehouse(warehouse) + self.validate_robots(robots) + self.validate_inventory(inventory) + self.validate_simulation(simulation) + self.validate_dispatch_policies(dispatch) + + return ConfigBundle( + warehouse=warehouse, + robots=robots, + inventory=inventory, + simulation=simulation, + dispatch_policies=dispatch, + config_dir=self.config_dir, + ) diff --git a/src/warehouse_twin/logging_config.py b/src/warehouse_twin/logging_config.py new file mode 100644 index 0000000..b1b916e --- /dev/null +++ b/src/warehouse_twin/logging_config.py @@ -0,0 +1,134 @@ +"""Structured and rotating logging configuration for Warehouse Digital Twin.""" + +from __future__ import annotations + +import logging +import os +from logging.handlers import RotatingFileHandler +from pathlib import Path +from typing import Optional + +# Standard formatters +STANDARD_FORMAT = "%(asctime)s [%(levelname)s] [%(name)s] %(message)s" +DETAILED_FORMAT = "%(asctime)s [%(levelname)s] [%(name)s:%(lineno)d] %(message)s" +SIMULATION_EVENT_FORMAT = "%(asctime)s [SIM_EVENT] %(message)s" + +# Global tracking to avoid duplicate handlers +_LOGGING_INITIALIZED = False + + +def get_default_log_dir() -> Path: + """Determine the default log directory using env var or fallback.""" + env_dir = os.environ.get("WAREHOUSE_TWIN_LOG_DIR") + if env_dir: + return Path(env_dir).resolve() + # Secondary drive relocation support + secondary = os.environ.get("WAREHOUSE_TWIN_SECONDARY_DRIVE") + if secondary: + return (Path(secondary) / "logs").resolve() + return (Path(__file__).resolve().parents[2] / "logs").resolve() + + +def setup_logging( + log_dir: Optional[Path | str] = None, + console_level: int = logging.INFO, + file_level: int = logging.DEBUG, + max_bytes: int = 10 * 1024 * 1024, # 10 MB default + backup_count: int = 5, + force_reinit: bool = False, +) -> Path: + """Configure structured rotating loggers for application and simulation. + + Creates three dedicated rotating log files: + 1. application.log - general operational and component diagnostics + 2. simulation.log - dedicated simulation events and step logs + 3. errors.log - error and critical events with tracebacks + + Args: + log_dir: Directory where log files are stored. Defaults to `logs/`. + console_level: Minimum severity level for standard console output. + file_level: Minimum severity level for application.log. + max_bytes: Size threshold in bytes before rotating log files. + backup_count: Number of rotated backup files to preserve. + force_reinit: If True, clears existing handlers and reconfigures. + + Returns: + Resolved Path to the active log directory. + """ + global _LOGGING_INITIALIZED + if _LOGGING_INITIALIZED and not force_reinit: + return get_default_log_dir() + + resolved_log_dir = Path(log_dir).resolve() if log_dir else get_default_log_dir() + resolved_log_dir.mkdir(parents=True, exist_ok=True) + + root_logger = logging.getLogger() + if force_reinit: + for handler in list(root_logger.handlers): + root_logger.removeHandler(handler) + handler.close() + + root_logger.setLevel(min(console_level, file_level)) + + formatter = logging.Formatter(STANDARD_FORMAT) + detailed_formatter = logging.Formatter(DETAILED_FORMAT) + + # 1. Console Handler (stdout) + console_handler = logging.StreamHandler() + console_handler.setLevel(console_level) + console_handler.setFormatter(formatter) + console_handler.name = "warehouse_twin_console" + root_logger.addHandler(console_handler) + + # 2. Application Log (Rotating) + app_log_path = resolved_log_dir / "application.log" + app_file_handler = RotatingFileHandler( + filename=str(app_log_path), + maxBytes=max_bytes, + backupCount=backup_count, + encoding="utf-8", + ) + app_file_handler.setLevel(file_level) + app_file_handler.setFormatter(detailed_formatter) + app_file_handler.name = "warehouse_twin_app_file" + root_logger.addHandler(app_file_handler) + + # 3. Errors Log (Rotating, ERROR and above) + err_log_path = resolved_log_dir / "errors.log" + err_file_handler = RotatingFileHandler( + filename=str(err_log_path), + maxBytes=max_bytes, + backupCount=backup_count, + encoding="utf-8", + ) + err_file_handler.setLevel(logging.ERROR) + err_file_handler.setFormatter(detailed_formatter) + err_file_handler.name = "warehouse_twin_err_file" + root_logger.addHandler(err_file_handler) + + # 4. Simulation Event Dedicated Logger + sim_logger = logging.getLogger("warehouse_twin.simulation") + sim_log_path = resolved_log_dir / "simulation.log" + sim_file_handler = RotatingFileHandler( + filename=str(sim_log_path), + maxBytes=max_bytes, + backupCount=backup_count, + encoding="utf-8", + ) + sim_file_handler.setLevel(logging.DEBUG) + sim_file_handler.setFormatter(logging.Formatter(SIMULATION_EVENT_FORMAT)) + sim_file_handler.name = "warehouse_twin_sim_file" + sim_logger.addHandler(sim_file_handler) + + _LOGGING_INITIALIZED = True + return resolved_log_dir + + +def get_logger(name: str) -> logging.Logger: + """Retrieve a namespaced application logger.""" + return logging.getLogger(f"warehouse_twin.{name}" if not name.startswith("warehouse_twin") else name) + + +def get_simulation_logger() -> logging.Logger: + """Retrieve the dedicated simulation event logger.""" + return logging.getLogger("warehouse_twin.simulation") diff --git a/src/warehouse_twin/main.py b/src/warehouse_twin/main.py new file mode 100644 index 0000000..7dfd40a --- /dev/null +++ b/src/warehouse_twin/main.py @@ -0,0 +1,7 @@ +"""Main execution entry point for Warehouse Digital Twin.""" + +import sys +from warehouse_twin.cli import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..9c73f5c --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Test suite for Warehouse Robot Fleet Digital Twin.""" diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..5c28ac2 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,96 @@ +"""Shared pytest fixtures for Warehouse Digital Twin.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Dict +import pytest + + +@pytest.fixture +def project_root() -> Path: + """Return the absolute path to the project root directory.""" + return Path(__file__).resolve().parents[1] + + +@pytest.fixture +def project_config_dir(project_root: Path) -> Path: + """Return the path to the real project configuration directory.""" + return project_root / "config" + + +@pytest.fixture +def temp_config_dir(tmp_path: Path) -> Path: + """Create a temporary directory with valid configuration files for testing.""" + config_dir = tmp_path / "config" + config_dir.mkdir(parents=True, exist_ok=True) + + warehouse_data = { + "coordinate_system": {"type": "right_handed_cartesian", "units": "meters"}, + "dimensions": {"width": 60.0, "depth": 40.0, "height": 8.0}, + "zones": { + "zone_a": {"name": "Zone A"}, + "zone_b": {"name": "Zone B"}, + "zone_c": {"name": "Zone C"}, + }, + "stations": [{"station_id": "st_1", "type": "dock", "position": [1.0, 1.0, 0.0]}], + "charging_stations": [{"station_id": "ch_1", "position": [2.0, 2.0, 0.0], "capacity": 1}], + } + + robots_data = { + "robot_types": { + "light_amr": { + "payload_capacity_kg": 150.0, + "max_speed_mps": 1.8, + "battery_capacity_kwh": 3.0, + } + }, + "fleet": [ + { + "robot_id": "amr_1", + "robot_type": "light_amr", + "initial_position": [0.0, 0.0, 0.0], + } + ], + } + + inventory_data = { + "categories": { + "zone_a_items": { + "name": "Zone A Items", + "items": [ + { + "item_id": "item_1", + "name": "Filter HF-1", + "unit_weight_kg": 2.0, + "initial_stock": 100, + } + ], + } + } + } + + simulation_data = { + "simulation": { + "duration_seconds": 3600.0, + "random_seed": 42, + } + } + + dispatch_data = { + "active_policy": "nearest_idle", + "available_policies": ["nearest_idle", "priority_first"], + } + + for name, data in [ + ("warehouse.json", warehouse_data), + ("robots.json", robots_data), + ("inventory.json", inventory_data), + ("simulation.json", simulation_data), + ("dispatch_policies.json", dispatch_data), + ]: + with open(config_dir / name, "w", encoding="utf-8") as f: + json.dump(data, f) + + return config_dir diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000..ea3f8b9 --- /dev/null +++ b/tests/unit/__init__.py @@ -0,0 +1 @@ +"""Unit tests package.""" diff --git a/tests/unit/test_config_loader.py b/tests/unit/test_config_loader.py new file mode 100644 index 0000000..9820bb4 --- /dev/null +++ b/tests/unit/test_config_loader.py @@ -0,0 +1,172 @@ +"""Unit tests for configuration loader and schema validation.""" + +from __future__ import annotations + +import json +from pathlib import Path +import pytest + +from warehouse_twin.config.loader import ConfigLoader, ConfigurationError + + +def test_load_real_project_configurations(project_config_dir: Path): + """Verify that the real project configurations in config/ load and validate cleanly.""" + loader = ConfigLoader(config_dir=project_config_dir) + bundle = loader.load_all() + + # Warehouse checks + assert bundle.warehouse["dimensions"]["width"] == 60.0 + assert "zone_a" in bundle.warehouse["zones"] + assert "zone_b" in bundle.warehouse["zones"] + assert "zone_c" in bundle.warehouse["zones"] + assert len(bundle.warehouse["stations"]) >= 4 + assert len(bundle.warehouse["charging_stations"]) >= 2 + + # Robot checks + assert "light_amr" in bundle.robots["robot_types"] + assert "heavy_amr" in bundle.robots["robot_types"] + assert len(bundle.robots["fleet"]) >= 4 + + # Inventory checks + assert len(bundle.inventory["categories"]) >= 3 + # Check specific items from prompt + all_items = [] + for cat in bundle.inventory["categories"].values(): + all_items.extend([i["item_id"] for i in cat.get("items", [])]) + assert any("filter" in i for i in all_items) + assert any("transmission" in i for i in all_items) + assert any("coil" in i for i in all_items) + + # Simulation checks + assert bundle.simulation["simulation"]["duration_seconds"] > 0 + assert bundle.simulation["simulation"]["random_seed"] == 42 + + # Dispatch checks + assert bundle.dispatch_policies["active_policy"] in bundle.dispatch_policies["available_policies"] + + +def test_missing_config_file_raises_error(tmp_path: Path): + """Ensure missing required configuration file raises a clear ConfigurationError.""" + empty_dir = tmp_path / "empty_cfg" + empty_dir.mkdir() + + loader = ConfigLoader(config_dir=empty_dir) + with pytest.raises(ConfigurationError) as exc_info: + loader.load_all() + + assert "Missing required configuration file" in str(exc_info.value) + + +def test_invalid_json_syntax_raises_error(temp_config_dir: Path): + """Ensure malformed JSON syntax raises ConfigurationError with line details.""" + broken_file = temp_config_dir / "warehouse.json" + broken_file.write_text("{ unquoted_bad_json: true, }", encoding="utf-8") + + loader = ConfigLoader(config_dir=temp_config_dir) + with pytest.raises(ConfigurationError) as exc_info: + loader.load_all() + + assert "Invalid JSON syntax" in str(exc_info.value) + + +def test_missing_warehouse_zone_raises_error(temp_config_dir: Path): + """Ensure omitting a mandatory zone (zone_a, zone_b, zone_c) fails validation.""" + wh_file = temp_config_dir / "warehouse.json" + with open(wh_file, "r", encoding="utf-8") as f: + data = json.load(f) + + # Delete zone_c + del data["zones"]["zone_c"] + with open(wh_file, "w", encoding="utf-8") as f: + json.dump(data, f) + + loader = ConfigLoader(config_dir=temp_config_dir) + with pytest.raises(ConfigurationError) as exc_info: + loader.load_all() + + assert "missing required zone specification: 'zone_c'" in str(exc_info.value) + + +def test_invalid_warehouse_dimensions_raises_error(temp_config_dir: Path): + """Ensure non-positive dimensions trigger validation failure.""" + wh_file = temp_config_dir / "warehouse.json" + with open(wh_file, "r", encoding="utf-8") as f: + data = json.load(f) + + data["dimensions"]["width"] = -10.0 + with open(wh_file, "w", encoding="utf-8") as f: + json.dump(data, f) + + loader = ConfigLoader(config_dir=temp_config_dir) + with pytest.raises(ConfigurationError) as exc_info: + loader.load_all() + + assert "must be a positive number" in str(exc_info.value) + + +def test_undefined_robot_type_raises_error(temp_config_dir: Path): + """Ensure fleet member referencing an unknown robot_type fails validation.""" + robots_file = temp_config_dir / "robots.json" + with open(robots_file, "r", encoding="utf-8") as f: + data = json.load(f) + + data["fleet"].append({ + "robot_id": "alien_bot_99", + "robot_type": "quantum_antigravity_bot", # Not in robot_types + "initial_position": [0, 0, 0] + }) + with open(robots_file, "w", encoding="utf-8") as f: + json.dump(data, f) + + loader = ConfigLoader(config_dir=temp_config_dir) + with pytest.raises(ConfigurationError) as exc_info: + loader.load_all() + + assert "references undefined robot_type 'quantum_antigravity_bot'" in str(exc_info.value) + + +def test_duplicate_item_id_in_inventory_raises_error(temp_config_dir: Path): + """Ensure duplicate item_id in inventory fails validation.""" + inv_file = temp_config_dir / "inventory.json" + with open(inv_file, "r", encoding="utf-8") as f: + data = json.load(f) + + # Add duplicate item_1 + data["categories"]["zone_a_items"]["items"].append({ + "item_id": "item_1", + "name": "Duplicate Item 1", + }) + with open(inv_file, "w", encoding="utf-8") as f: + json.dump(data, f) + + loader = ConfigLoader(config_dir=temp_config_dir) + with pytest.raises(ConfigurationError) as exc_info: + loader.load_all() + + assert "Duplicate item_id 'item_1' detected" in str(exc_info.value) + + +def test_invalid_active_dispatch_policy_raises_error(temp_config_dir: Path): + """Ensure active policy not present in available_policies raises error.""" + disp_file = temp_config_dir / "dispatch_policies.json" + with open(disp_file, "r", encoding="utf-8") as f: + data = json.load(f) + + data["active_policy"] = "non_existent_policy" + with open(disp_file, "w", encoding="utf-8") as f: + json.dump(data, f) + + loader = ConfigLoader(config_dir=temp_config_dir) + with pytest.raises(ConfigurationError) as exc_info: + loader.load_all() + + assert "is not in available_policies" in str(exc_info.value) + + +def test_config_dir_env_var_override(temp_config_dir: Path, monkeypatch): + """Verify that WAREHOUSE_TWIN_CONFIG_DIR env var is respected.""" + monkeypatch.setenv("WAREHOUSE_TWIN_CONFIG_DIR", str(temp_config_dir)) + loader = ConfigLoader() # No explicit config_dir passed + assert loader.config_dir == temp_config_dir.resolve() + bundle = loader.load_all() + assert bundle is not None diff --git a/tests/unit/test_environment.py b/tests/unit/test_environment.py new file mode 100644 index 0000000..92feac8 --- /dev/null +++ b/tests/unit/test_environment.py @@ -0,0 +1,50 @@ +"""Unit tests for environment validation and system requirements.""" + +from __future__ import annotations + +import sys +from unittest.mock import MagicMock, patch +import pytest + +from warehouse_twin import __version__ +from warehouse_twin.cli import check_environment + + +def test_package_metadata(): + """Verify that package version and name are properly defined.""" + assert __version__ == "0.1.0" + + +def test_python_version(): + """Ensure runtime Python meets the minimum requirement of >= 3.10.""" + major, minor = sys.version_info[:2] + assert (major, minor) >= (3, 10), f"Python version {major}.{minor} is below minimum 3.10" + + +def test_required_dependencies_importable(): + """Verify that core simulation dependencies can be imported successfully.""" + import simpy + import networkx + import pytest as pt + + assert simpy.__version__ is not None + assert networkx.__version__ is not None + assert pt.__version__ is not None + + +def test_check_environment_passes(): + """Verify that the check_environment CLI routine executes and passes.""" + exit_code = check_environment() + assert exit_code == 0 + + +def test_check_environment_detects_low_disk(monkeypatch): + """Verify that critical low disk space (<2GB) generates a failure return code.""" + # Mock shutil.disk_usage to return 1 GB free + fake_usage = MagicMock() + fake_usage.free = 1 * (1024**3) # 1 GB + fake_usage.total = 100 * (1024**3) + + with patch("shutil.disk_usage", return_value=fake_usage): + exit_code = check_environment() + assert exit_code == 1, "check_environment should fail when disk space is below 2 GB" diff --git a/tests/unit/test_logging.py b/tests/unit/test_logging.py new file mode 100644 index 0000000..c8c57e2 --- /dev/null +++ b/tests/unit/test_logging.py @@ -0,0 +1,103 @@ +"""Unit tests for structured and rotating logging configuration.""" + +from __future__ import annotations + +import logging +from pathlib import Path +import pytest + +from warehouse_twin.logging_config import ( + get_logger, + get_simulation_logger, + setup_logging, +) + + +def test_logging_directory_creation(tmp_path: Path): + """Verify that setup_logging automatically creates the requested log directory.""" + test_log_dir = tmp_path / "custom_logs" + assert not test_log_dir.exists() + + setup_logging(log_dir=test_log_dir, force_reinit=True) + assert test_log_dir.exists() + assert test_log_dir.is_dir() + + +def test_log_files_created_and_written(tmp_path: Path): + """Verify application.log, simulation.log, and errors.log creation and message routing.""" + test_log_dir = tmp_path / "test_logs" + setup_logging( + log_dir=test_log_dir, + console_level=logging.WARNING, + file_level=logging.DEBUG, + force_reinit=True, + ) + + app_logger = get_logger("test_module") + sim_logger = get_simulation_logger() + + # Emit various levels of logs + app_logger.debug("Test debug message") + app_logger.info("Test info message") + app_logger.error("Test error message occurred") + + sim_logger.info("Simulation order released: ORD-1001") + + # Flush all handlers + for handler in logging.getLogger().handlers: + handler.flush() + for handler in sim_logger.handlers: + handler.flush() + + app_log = test_log_dir / "application.log" + err_log = test_log_dir / "errors.log" + sim_log = test_log_dir / "simulation.log" + + assert app_log.exists(), "application.log was not created" + assert err_log.exists(), "errors.log was not created" + assert sim_log.exists(), "simulation.log was not created" + + app_content = app_log.read_text(encoding="utf-8") + err_content = err_log.read_text(encoding="utf-8") + sim_content = sim_log.read_text(encoding="utf-8") + + # application.log should contain debug, info, and error + assert "Test debug message" in app_content + assert "Test info message" in app_content + assert "Test error message occurred" in app_content + + # errors.log must ONLY contain the error, not debug or info + assert "Test error message occurred" in err_content + assert "Test info message" not in err_content + assert "Test debug message" not in err_content + + # simulation.log must contain the simulation event + assert "ORD-1001" in sim_content + + +def test_log_file_rotation(tmp_path: Path): + """Verify that log files rotate when exceeding the configured max_bytes.""" + test_log_dir = tmp_path / "rotating_logs" + # Set a very small max_bytes threshold (250 bytes) with 3 backups + setup_logging( + log_dir=test_log_dir, + file_level=logging.INFO, + max_bytes=250, + backup_count=3, + force_reinit=True, + ) + + logger = get_logger("rotator") + + # Write enough lines to exceed 250 bytes multiple times + for i in range(40): + logger.info(f"Writing log rotation payload line {i:03d} - padding to exceed byte limit") + + for handler in logging.getLogger().handlers: + handler.flush() + + app_log = test_log_dir / "application.log" + backup_1 = test_log_dir / "application.log.1" + + assert app_log.exists() + assert backup_1.exists(), "Expected rotated backup log file 'application.log.1' to exist"