World System Orchestration¶
This document details the architecture of the WorldSystem orchestrator and the world_system_builder module that configures it. It also provides a guide for extending the simulation by adding new sectors.
WorldSystem - The Central Orchestrator¶
Purpose: The WorldSystem class (proxima_model/world_system/world_system.py) is a Mesa Model subclass and the heart of the simulation. It owns the shared EventBus and the per-sector instances, runs the main per-step power/metrics/policy pipeline, and hands off to the EvaluationEngine and PolicyEngine.
Core Responsibilities:
Sector Initialization:
_initialize_sectors()iteratesconfig["agents_config"]and callsSectorFactory.create_sector(sector_name, self, sector_config, self.event_bus)for each entry, storing the result inself.sectors[sector_name]. A sector that fails to construct is logged and skipped (not fatal to the rest of the simulation).Event Bus:
WorldSystemcreates a singleEventBusinstance and passes it to every sector at construction time.WorldSystemitself never publishes or subscribes — the bus exists purely so sectors can communicate directly (e.g. manufacturing publishingresource_allocatedevents to whichever sector made aResourceRequest; seeworld_system_defs.EventTypefor the full list of event names in use).Simulation Loop (
stepmethod): Defines the exact order of operations for each simulation step (below).Power Allocation: Delegates the actual power-generation and distribution logic to the
EnergySector, but is responsible for collecting demand from every other sector first and feeding the allocations back.Coordination: Acts as the intermediary between the sectors, the
EvaluationEngine, and thePolicyEngine.
Simulation Step Lifecycle¶
WorldSystem.step() executes the following sequence every simulation step:
Identify power consumers (
_get_power_consumers): Every sector inself.sectorsexcept"energy"(excluded by name) that exposes aget_power_demandmethod.Aggregate power demand: Calls
get_power_demand()on each power consumer and clamps the result to>= 0, producing a{sector_name: demand}dict.Ordering is load-bearing here: this happens before
step()is called on any sector this timestep. Some sectors — notablyManufacturingSector— decide task/robot assignment for the step insideget_power_demand()rather than insidestep(), precisely so the demand number they report reflects the assignment about to execute, not the previous step’s. Ifget_power_demand()were called afterstep(), or assignment were deferred tostep(), the power allocation for a step would always be one step stale. Seedocumentation/sectors/manufacturing_sector.mdsection B for the sector-side half of this contract.Allocate power: Passes the full demand dict to
energy_sector.allocate_power(sector_demands)(a no-op{}if no energy sector was configured). Internallyallocate_power:Re-clamps/snapshots the demands and sums them into
total_demand.Calls the energy sector’s own
step(total_demand)— this is the energy sector’sstep()method; it runs generation/charge-discharge logic and returnsavailable_power. This is the only place the energy sector’sstep()runs — it is excluded from the generic per-sector step loop below.If
available_powercoverstotal_demand, every sector gets exactly what it asked for.Otherwise splits
available_poweracross sectors proportionally to demand (default), or via an equal/max-min-fair split ifallocation_mode == AllocationMode.EQUAL.Returns a
{sector_name: allocated_power}dict.
Step all consuming sectors: Calls
sector.step(allocated_power)on each power consumer identified in step 1, passing its share from step 3.Collect metrics (
_collect_sector_metrics): Callsget_metrics()on every sector inself.sectors(includingenergythis time), not just the power consumers.Assemble model metrics:
self.model_metrics = {"environment": {"step": self.steps}, **sector_metrics}.Evaluate performance: Passes
sector_metricsanddust_decay_per_steptoself.evaluation_engine.evaluate(...). The resultingperformance_metricsandscoresare merged intoself.model_metrics["performance"].Apply policies: Passes the complete
EvaluationResulttoself.policy.apply_policies(evaluation_result), which applies effects (e.g. throttling) that sectors read back on their next step.
world_system_builder - The Configuration Builder¶
Purpose: proxima_model/world_system/world_system_builder.py translates raw database documents (world system, experiment, environment, component templates, goals) into the plain configuration dict that WorldSystem.__init__ consumes directly — no further transformation happens between the builder’s output and the sectors’ configs.
Entry point — build_world_system_config(world_system_id, experiment_id, db, resume_state=True):
Loads the
world_systems,experiments, andenvironmentsdocuments, plus everycomponent_templatesdocument (keyed by_id).Builds the base dict with keys
sim_time,hours_per_step,p_need(hardcoded2.0),agents_config,environment_name,metrics,resources, anddust_decay_per_step— these are read back byWorldSystem.__init__asself.config.get("hours_per_step", 1)→self.time_scale,self.config.get("goals", {}),self.config.get("metrics", []), andself.config.get("dust_decay_per_step", 0.0).For each sector, instantiates that sector’s builder with
component_templates, calls.build(...)on the matching slice ofactive_components[0](the function assumes a single component-group dict), and stores the result underconfig["agents_config"][sector_name]. Ifresume_stateis true andworld_system["latest_state"]["sectors"][sector_name]exists, that persisted state dict is attached to the sector’s config aslatest_stateso the sector can resume mid-run instead of starting fresh.Finally builds
config["goals"]viaGoalsSystemBuilder.
Sector builders (all subclass ComponentBuilder except GoalsSystemBuilder):
Builder |
Produces ( |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ComponentBuilder (base class): Provides _get_template(template_id) (logs and returns None on a miss) and _merge_config(component, template), which layers template["config"], then template["default_config"], then the component instance’s own config (instance values win), and wraps the result in a ComponentConfig dataclass.
Dataclasses defined but only partially used:
ComponentConfigandPerformanceGoalare actively constructed and consumed (PerformanceGoal.to_dict()feedsGoalsSystemBuilder’s output).WorldSystemConfigis defined with the “proper” field names (e.g.time_scale) but is never instantiated anywhere in the codebase —build_world_system_configassembles and returns a plaindict(usinghours_per_step, nottime_scale) instead. See the TODO below.
Example — a manufacturing config as emitted into agents_config:
{
"sector_name": "manufacturing",
"initial_stocks": { "H2O_kg": 5.0, "He3_kg": 10.0 },
"isru_robots": [
{
"template_id": "comp_isru_robot",
"subtype": "standard",
"config": { "ice_extraction_power_kWh": 5.0, "isru_modes": ["ICE_EXTRACTION", "HE3_EXTRACTION"] },
"quantity": 4,
"metric_contributions": [
{ "metric_id": "IND-DUST-COV", "contribution_type": "predefined", "contribution_value": 0.01 }
]
}
],
"latest_state": { "...": "only present when resume_state=True and a prior run persisted state" }
}
How to Add a New Sector¶
Adding a new sector to the simulation involves four main steps:
Step 1: Create the Sector Class¶
Create a new Python file for your sector (e.g., new_sector.py) under proxima_model/sphere_engine/. The class must implement the following methods to integrate with WorldSystem:
# /proxima_model/sphere_engine/new_sector.py
class NewSector:
def __init__(self, model, config, event_bus):
self.model = model
self.config = config
self.event_bus = event_bus
# ... your initialization logic ...
def get_power_demand(self) -> float:
# Called on every sector BEFORE any sector's step() for this timestep.
# If your sector needs to decide "what will I do this step" before it
# can report an accurate number (like ManufacturingSector's task
# assignment), do that planning here rather than in step().
return 100.0
def step(self, allocated_power: float):
# Execute the sector's logic for one step, using allocated_power
# (<= what get_power_demand() asked for) to gate what can be done.
pass
def get_metrics(self) -> dict:
# Called on every sector (including energy) after all sectors have stepped.
return {
"metric_contributions": {
"IND-DUST-COV": 0.5
}
}
Step 2: Create the Sector Builder¶
In world_system_builder.py, create a new builder class for your sector, subclassing ComponentBuilder if it needs template merging.
# /proxima_model/world_system/world_system_builder.py
# ... existing code ...
class NewSectorBuilder(ComponentBuilder):
def build(self, components: List[Dict[str, Any]]) -> Dict[str, Any]:
config = {"sector_name": "new_sector", "some_parameter": "default"}
# ... your logic to process components and build the config dict ...
logger.info("✅ Configured new sector")
return config
Step 3: Register the Sector in SectorFactory¶
In proxima_model/sphere_engine/sector_factory.py, import your new sector class and add a branch to the if/elif chain in SectorFactory.create_sector (there is no registry dict — dispatch is a hardcoded string match on the lower-cased sector_type):
# /proxima_model/sphere_engine/sector_factory.py
from .new_sector import NewSector # <-- IMPORT
class SectorFactory:
@staticmethod
def create_sector(sector_type: str, model, config, event_bus) -> Any:
sector_type = sector_type.lower().strip()
...
elif sector_type == "new_sector": # <-- ADD BRANCH
return NewSector(model, config, event_bus)
...
WorldSystem._initialize_sectors() will pick it up automatically as long as config["agents_config"] contains a "new_sector" key — no changes to world_system.py are needed.
Step 4: Integrate the Builder¶
In world_system_builder.py, in build_world_system_config, instantiate and run your new builder before the goals section is built:
# /proxima_model/world_system/world_system_builder.py
# ... existing code ...
def build_world_system_config(...):
# ... existing builder calls ...
construction_builder = ConstructionSectorBuilder(component_templates)
config["agents_config"]["construction"] = construction_builder.build(components_dict.get("construction", []))
# Add your new builder here
new_sector_builder = NewSectorBuilder(component_templates)
config["agents_config"]["new_sector"] = new_sector_builder.build(components_dict.get("new_sector", []))
# Build goals configuration
goals_builder = GoalsSystemBuilder(db)
# ... existing code ...
Finally, add a "new_sector": [...] entry under active_components[0] in your world system JSON/document to define its components; the builder will process it on the next run.
TODO: Potential Improvements¶
[ ] Resolve the
WorldSystemConfigdead code: It documents the “intended” config shape (includingtime_scale), butbuild_world_system_confignever instantiates it and instead returns a hand-built dict keyedhours_per_step. Either constructWorldSystemConfigand derive the dict from it (giving validation via__post_init__), or remove the dataclass to stop it drifting further from reality.[ ] Replace the energy-sector name check with a role/interface check:
_get_power_consumers()excludes the energy sector by comparingname != "energy"rather than checking for an explicit “is a power producer” capability. A world system that names its energy sector anything else, or a config with more than one producer-like sector, would silently misbehave.[ ] Make failed sector initialization more visible:
_initialize_sectors()only logs and continues ifSectorFactory.create_sectorraises, which means a misconfigured sector can silently vanish fromself.sectorsrather than failing the run loudly.