The Random-Key Optimizer (RKO) is a high-performance, parallel metaheuristic framework designed for combinatorial optimization problems. By mapping discrete, high-dimensional search spaces onto a continuous unit hypercube
RKO orchestrates up to 8 parallel metaheuristic workers using Python's native multiprocessing. Workers cooperate in real time by feeding and pulling elite solutions from a thread-safe, shared Solution Pool, accelerating convergence and improving optimization robustness.
- 8 Concurrent Metaheuristics: Run BRKGA, Multi-Start, SA, VNS, ILS, LNS, PSO, and GA concurrently.
- Online hyperparameters tuning via Q-learning
- Collaborative Search: Thread-safe
SolutionPoolsharing elite solutions to pull workers out of local minima. - Automatic Result Structuring: Automatically groups execution runs, creating a dedicated timestamped folder (
results_{instance}_{timestamp}/) containing:results.txt: Scientific summary containing aggregated averages, standard deviations, lists of costs, and computational times for academic reporting.logs.txt: Chronological trace of improvements (NEW BEST), optimized and clean for parser engines.run_x.png: Convergence trajectory plot generated automatically for each trial.
pip install rkofromrkoimportRKOrko_solver=RKO(
env=my_environment,
best_possible=None, # early-stop thresholdlogger="dual", # logger strategy or custom LogStrategy instancelog_filepath="./results/results.txt"# Base directory for structured outputs
)final_cost, final_solution, time_to_best=rko_solver.solve(
time_total=30, # Total time limit in secondsbrkga=1, # Number of parallel BRKGA instancesms=1, # Number of parallel Multi-Start instancessa=1, # Number of parallel SA instancesvns=1, # Number of parallel VNS instancesils=1, # Number of parallel ILS instanceslns=1, # Number of parallel LNS instancespso=1, # Number of parallel PSO instancesga=1, # Number of parallel GA instancesrestart=1.0, # Fraction of total time for each restart cycleruns=10, # Number of independent trialsplot=True# Enable automatic convergence plotting (generates .png charts)
)The RKO logging subsystem is built on the Strategy Pattern, allowing developers to customize logging behavior by passing a subclass of LogStrategy directly to the logger parameter in the RKO constructor.
"dual"(TerminalLogger with filepath): Prints logs to stdout and saves structured records to the dynamic results directory."terminal"(TerminalLogger): Outputs logs exclusively to stdout."file"(FileLogger): Saves logs exclusively to the specified disk path.
You can inherit from LogStrategy to route logs to databases, dashboards, or external analytical tools:
fromrko.LogStrategyimportLogStrategyclassDatabaseLogger(LogStrategy):
def__init__(self, db_connection):
self.db=db_connectiondeflog(self, *args, **kwargs):
msg=" ".join(str(arg) forarginargs)
# Custom logic to write to databaseself.db.insert_log(msg)To adapt RKO to your problem, subclass RKOEnvAbstract and implement decoder and cost.
,
importnumpyasnpclassRKOEnv():
def__init__(self):
# Required attributesself.tam_solution: int=50# Dimension of the random key vectorself.LS_type: str='Best'# Local Search strategy ('Best' or 'First')self.dict_best: dict= {} # Shared best dictionaryself.instance_name: str="kp50.txt"# Name of your problem instance# Configurations for Metaheuristicsself.BRKGA_parameters= {'p': [1000, 2000], 'pe': [0.2, 0.15], 'pm': [0.05], 'rhoe': [0.7]}
self.SA_parameters= {'SAmax': [100], 'alphaSA': [0.99, 0.9], 'betaMin': [0.01], 'betaMax': [0.05], 'T0': [10000]}
self.ILS_parameters= {'betaMin': [0.1], 'betaMax': [0.2]}
self.VNS_parameters= {'kMax': [8,7,6,5], 'betaMin': [0.05]}
self.LNS_parameters= {'betaMin': [0.1], 'betaMax': [0.3], 'TO': [1000], 'alphaLNS': [0.99, 0.95, 0.9]}
self.PSO_parameters= {'PSize': [1000], 'c1': [2.05], 'c2': [2.05], 'w': [0.73]}
self.GA_parameters= {'sizePop': [1000], 'probCros': [0.98], 'probMut': [0.005]}
defdecoder(self, keys: np.ndarray):
"""Maps random keys [0, 1) into a problem-specific discrete representation."""passdefcost(self, solution, final_solution: bool=False) ->float:
"""Returns objective cost (RKO minimizes this; return negated value for maximization)."""passRKO provides a built-in diagnostic utility check_env to validate custom environments before runtime. It performs the following verification passes:
- Attribute & Type Verification: Verifies the presence and types of all core variables (
tam_solution,LS_type,dict_best,instance_name) and metaheuristic parameter dictionaries. - Functional Dry-Run: Invokes the custom
decoderandcostmethods using mock random keys to verify execution safety. - Mathematical Compliance: Checks that the returned cost is a scalar float and that the decoder successfully processes vectors of dimensions defined by
tam_solution. - Actionable Diagnostics: If a check fails, the utility prints detailed stack traces and configuration hints to assist the developer in resolving interface mismatches or bugs.
fromrko.Environmentimportcheck_envmy_env=MyProblemEnv()
ifcheck_env(my_env):
print("Environment successfully validated.")