feat(phase-0): initialize project foundation, packaging, logging, configs, and tests
This commit is contained in:
@@ -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,
|
||||
)
|
||||
Reference in New Issue
Block a user