Skip to content
Snippets Groups Projects
Commit 4ea9e608 authored by Zizhe Wang's avatar Zizhe Wang
Browse files

refactor import all algorithms from pymoo dynamically

parent 95c4b960
No related branches found
No related tags found
No related merge requests found
...@@ -7,27 +7,28 @@ ...@@ -7,27 +7,28 @@
# # # #
############################################ ############################################
from pymoo.algorithms.moo.nsga2 import NSGA2 import importlib
from pymoo.algorithms.moo.nsga3 import NSGA3 import pkgutil
from pymoo.algorithms.soo.nonconvex.cmaes import CMAES from pymoo.algorithms import moo
from scipy.optimize import differential_evolution, minimize as scipy_minimize
def initialize_algorithm(library, algorithm_name, pop_size): def initialize_algorithm(algorithm_name, pop_size=None):
if library == 'pymoo': # Dynamically import all modules in pymoo.algorithms.moo
if algorithm_name == 'NSGA2': algorithm_modules = {}
return NSGA2(pop_size=pop_size) for _, module_name, _ in pkgutil.iter_modules(moo.__path__):
elif algorithm_name == 'NSGA3': module = importlib.import_module(f"pymoo.algorithms.moo.{module_name}")
return NSGA3(pop_size=pop_size) for attribute_name in dir(module):
elif algorithm_name == 'CMAES': attribute = getattr(module, attribute_name)
return CMAES(pop_size=pop_size) if isinstance(attribute, type): # Check if it's a class
else: algorithm_modules[attribute_name.lower()] = attribute
raise ValueError(f"Unsupported algorithm: {algorithm_name}")
elif library == 'scipy': # Check if the algorithm name is in the imported modules
if algorithm_name == 'de': if algorithm_name.lower() not in algorithm_modules:
return differential_evolution raise ValueError(f"Algorithm {algorithm_name} is not supported.")
elif algorithm_name == 'minimize':
return scipy_minimize algorithm_class = algorithm_modules[algorithm_name.lower()]
else: if pop_size:
raise ValueError(f"Unsupported algorithm: {algorithm_name}") algorithm = algorithm_class(pop_size=pop_size)
else: else:
raise ValueError(f"Unsupported optimization library: {library}") algorithm = algorithm_class()
\ No newline at end of file
return algorithm
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment