Optimization Module
Optimization algorithm and reinforcement learning integration interfaces.
Optimization Interface
Base interfaces for simulation-optimization.
- class simcraft.optimization.base.ObjectiveType[source]
Bases:
EnumTypes of optimization objectives.
- MINIMIZE = 1
- MAXIMIZE = 2
- class simcraft.optimization.base.Parameter[source]
Bases:
objectA simulation parameter for optimization.
- class simcraft.optimization.base.SimulationObjective[source]
Bases:
objectAn objective function for optimization.
- direction
Minimize or maximize
- Type:
- direction: ObjectiveType = 1
- __init__(name, direction=ObjectiveType.MINIMIZE, weight=1.0, target=None)
- Parameters:
name (str)
direction (ObjectiveType)
weight (float)
target (float | None)
- Return type:
None
- class simcraft.optimization.base.EvaluationResult[source]
Bases:
objectResult of a simulation evaluation.
- __init__(parameters, objectives, constraints=<factory>, simulation_time=0.0, replications=1, metadata=<factory>)
- class simcraft.optimization.base.OptimizationInterface[source]
Bases:
ABCAbstract interface for simulation-optimization integration.
Subclass this to create an optimizable simulation model.
Examples
>>> class MyOptModel(OptimizationInterface): ... def get_parameters(self): ... return [Parameter("capacity", 1, 10, is_integer=True)] ... ... def get_objectives(self): ... return [SimulationObjective("cost", ObjectiveType.MINIMIZE)] ... ... def evaluate(self, params): ... sim = MySimulation(capacity=params["capacity"]) ... sim.run(until=100) ... return {"cost": sim.total_cost}
- abstractmethod get_parameters()[source]
Get list of optimization parameters.
- Returns:
Optimization parameters
- Return type:
List[Parameter]
- abstractmethod get_objectives()[source]
Get list of optimization objectives.
- Returns:
Optimization objectives
- Return type:
List[SimulationObjective]
- abstractmethod evaluate(parameters, replications=1)[source]
Evaluate objective(s) for given parameters.
- get_constraints()[source]
Get constraint functions.
- Returns:
Constraint functions returning True if satisfied
- Return type:
List[Callable]
- evaluate_full(parameters, replications=1)[source]
Full evaluation with constraints.
- Parameters:
- Returns:
Complete evaluation result
- Return type:
- class simcraft.optimization.base.SimulationExperiment[source]
Bases:
objectManages simulation experiments for optimization.
Handles parameter sampling, replication, and result collection.
- Parameters:
interface (OptimizationInterface) – Optimization interface
- __init__(interface)[source]
Initialize experiment.
- Parameters:
interface (OptimizationInterface)
- Return type:
None
- property results: List[EvaluationResult]
Get all evaluation results.
- property best_result: EvaluationResult | None
Get best result found.
- run_evaluation(parameters, replications=1)[source]
Run a single evaluation.
- Parameters:
- Returns:
Evaluation result
- Return type:
- run_grid_search(levels, replications=1)[source]
Run full factorial grid search.
- Parameters:
- Returns:
All results
- Return type:
List[EvaluationResult]
- run_random_search(n_evaluations, replications=1, seed=None)[source]
Run random search.
- Parameters:
- Returns:
All results
- Return type:
List[EvaluationResult]
Reinforcement Learning Interface
Gym-compatible environment wrapper for RL integration.
- class simcraft.optimization.rl_interface.ActionSpace[source]
Bases:
objectDefinition of action space.
- low
Lower bounds for continuous
- Type:
Optional[np.ndarray]
- high
Upper bounds for continuous
- Type:
Optional[np.ndarray]
- class simcraft.optimization.rl_interface.StateSpace[source]
Bases:
objectDefinition of state space.
- low
Lower bounds (for bounded spaces)
- Type:
Optional[np.ndarray]
- high
Upper bounds (for bounded spaces)
- Type:
Optional[np.ndarray]
- dtype
alias of
float32
- class simcraft.optimization.rl_interface.Transition[source]
Bases:
objectA single RL transition.
- action
Action taken
- Type:
Action
- reward
Reward received
- Type:
Reward
- info
Additional information
- Type:
Dict
- class simcraft.optimization.rl_interface.RLInterface[source]
Bases:
ABCAbstract interface for RL-simulation integration.
Subclass this to make a simulation model compatible with reinforcement learning agents.
Examples
>>> class PortRLInterface(RLInterface): ... def __init__(self, sim): ... self.sim = sim ... ... def get_state(self): ... return np.array([ ... self.sim.queue_length, ... self.sim.utilization, ... ]) ... ... def get_action_space(self): ... return ActionSpace.discrete(4) # 4 berths ... ... def apply_action(self, action): ... self.sim.allocate_berth(action) ... ... def get_reward(self): ... return -self.sim.waiting_time
- abstractmethod get_state()[source]
Get current state observation.
- Returns:
Current state
- Return type:
- abstractmethod get_action_space()[source]
Get action space definition.
- Returns:
Action space
- Return type:
- abstractmethod get_state_space()[source]
Get state space definition.
- Returns:
State space
- Return type:
- abstractmethod apply_action(action)[source]
Apply an action to the simulation.
- Parameters:
action (Action) – Action to apply
- Return type:
None
- abstractmethod get_reward()[source]
Get reward for current state/action.
- Returns:
Reward value
- Return type:
Reward
- class simcraft.optimization.rl_interface.RLEnvironment[source]
Bases:
objectGym-compatible wrapper for simulation-based RL.
Wraps an RLInterface to provide a standard RL environment API.
- Parameters:
interface (RLInterface) – RL interface implementation
simulation (Simulation) – Simulation instance
max_steps (int) – Maximum steps per episode
Examples
>>> env = RLEnvironment(interface, sim, max_steps=1000) >>> state = env.reset() >>> for _ in range(100): ... action = agent.select_action(state) ... state, reward, done, info = env.step(action) ... if done: ... break
- __init__(interface, simulation, max_steps=10000)[source]
Initialize environment.
- Parameters:
interface (RLInterface)
simulation (Simulation)
max_steps (int)
- Return type:
None
- property action_space: ActionSpace
Get action space.
- property observation_space: StateSpace
Get observation (state) space.
- class simcraft.optimization.rl_interface.DecisionPoint[source]
Bases:
objectRepresents a decision point in the simulation.
Used for event-driven RL where actions are taken at specific simulation events.
- Parameters:
name (str) – Decision point name
state_fn (Callable) – Function returning current state
action_space (ActionSpace) – Available actions
apply_fn (Callable) – Function to apply action
reward_fn (Callable) – Function returning reward
- property action_space: ActionSpace
Get action space.
- class simcraft.optimization.rl_interface.ReplayBuffer[source]
Bases:
objectExperience replay buffer for RL training.
Stores transitions and supports random sampling for off-policy algorithms.
- Parameters:
capacity (int) – Maximum buffer size
- push(transition)[source]
Add transition to buffer.
- Parameters:
transition (Transition) – Transition to add
- Return type:
None
- sample(batch_size)[source]
Sample random batch of transitions.
- Parameters:
batch_size (int) – Number of transitions to sample
- Returns:
Sampled transitions
- Return type:
List[Transition]
- class simcraft.optimization.rl_interface.MultiAgentInterface[source]
Bases:
objectInterface for multi-agent reinforcement learning.
Supports multiple agents with potentially different action spaces and rewards.
- Parameters:
n_agents (int) – Number of agents
Examples
>>> interface = MultiAgentInterface(n_agents=3) >>> interface.add_agent("berth_allocator", berth_space, berth_reward) >>> interface.add_agent("agv_dispatcher", agv_space, agv_reward)
- __init__(n_agents=1)[source]
Initialize multi-agent interface.
- Parameters:
n_agents (int)
- Return type:
None
- add_agent(name, action_space, reward_fn, state_fn=None, apply_fn=None)[source]
Add an agent.
- Parameters:
name (str) – Agent name
action_space (ActionSpace) – Agent’s action space
reward_fn (Callable) – Agent’s reward function
state_fn (Optional[Callable]) – Agent’s state function (uses shared if None)
apply_fn (Optional[Callable]) – Action application function
- Return type:
None
Set shared state function for all agents.
- get_agent(name)[source]
Get agent by name.
- Parameters:
name (str)
- Return type:
DecisionPoint | None