feat(phase-0): initialize project foundation, packaging, logging, configs, and tests
This commit is contained in:
@@ -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"
|
||||
@@ -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())
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Configuration package for Warehouse Digital Twin."""
|
||||
|
||||
from warehouse_twin.config.loader import ConfigBundle, ConfigLoader, ConfigurationError
|
||||
|
||||
__all__ = ["ConfigBundle", "ConfigLoader", "ConfigurationError"]
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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")
|
||||
@@ -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())
|
||||
Reference in New Issue
Block a user