Source code for llamda.utils

# Adapted from ReEvo: https://github.com/ai4co/reevo/blob/main/utils/utils.py
# Licensed under the MIT License (see THIRD-PARTY-LICENSES.txt)

import os
import inspect
import importlib.util
from typing import Callable


[docs] def file_to_string(filename: str | os.PathLike[str]) -> str: with open(filename, "r") as file: return file.read()
def _get_heuristic_name(module: object, possible_func_names: list[str]) -> str: """Get the name of the heuristic function from the module.""" for func_name in possible_func_names: if hasattr(module, func_name): if inspect.isfunction(getattr(module, func_name)): return func_name raise ValueError("No valid heuristic function found in the module.")
[docs] def load_heuristic_from_code( code_path: str, possible_func_names: list[str] ) -> Callable: """Dynamically load heuristic function from given code path.""" spec = importlib.util.spec_from_file_location("gpt", code_path) gpt = importlib.util.module_from_spec(spec) spec.loader.exec_module(gpt) return getattr(gpt, _get_heuristic_name(gpt, possible_func_names))