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 @@
# #
############################################
from pymoo.algorithms.moo.nsga2 import NSGA2
from pymoo.algorithms.moo.nsga3 import NSGA3
from pymoo.algorithms.soo.nonconvex.cmaes import CMAES
from scipy.optimize import differential_evolution, minimize as scipy_minimize
import importlib
import pkgutil
from pymoo.algorithms import moo
def initialize_algorithm(library, algorithm_name, pop_size):
if library == 'pymoo':
if algorithm_name == 'NSGA2':
return NSGA2(pop_size=pop_size)
elif algorithm_name == 'NSGA3':
return NSGA3(pop_size=pop_size)
elif algorithm_name == 'CMAES':
return CMAES(pop_size=pop_size)
else:
raise ValueError(f"Unsupported algorithm: {algorithm_name}")
elif library == 'scipy':
if algorithm_name == 'de':
return differential_evolution
elif algorithm_name == 'minimize':
return scipy_minimize
else:
raise ValueError(f"Unsupported algorithm: {algorithm_name}")
def initialize_algorithm(algorithm_name, pop_size=None):
# Dynamically import all modules in pymoo.algorithms.moo
algorithm_modules = {}
for _, module_name, _ in pkgutil.iter_modules(moo.__path__):
module = importlib.import_module(f"pymoo.algorithms.moo.{module_name}")
for attribute_name in dir(module):
attribute = getattr(module, attribute_name)
if isinstance(attribute, type): # Check if it's a class
algorithm_modules[attribute_name.lower()] = attribute
# Check if the algorithm name is in the imported modules
if algorithm_name.lower() not in algorithm_modules:
raise ValueError(f"Algorithm {algorithm_name} is not supported.")
algorithm_class = algorithm_modules[algorithm_name.lower()]
if pop_size:
algorithm = algorithm_class(pop_size=pop_size)
else:
raise ValueError(f"Unsupported optimization library: {library}")
\ No newline at end of file
algorithm = algorithm_class()
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