From 4ea9e60851bec8f43537633a93b00276f528797e Mon Sep 17 00:00:00 2001
From: Zizhe Wang <zizhe.wang@tu-dresden.de>
Date: Fri, 7 Jun 2024 09:32:01 +0200
Subject: [PATCH] refactor import all algorithms from pymoo dynamically

---
 src/optimization_libraries.py | 45 ++++++++++++++++++-----------------
 1 file changed, 23 insertions(+), 22 deletions(-)

diff --git a/src/optimization_libraries.py b/src/optimization_libraries.py
index d3343c0..c7b10da 100644
--- a/src/optimization_libraries.py
+++ b/src/optimization_libraries.py
@@ -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
-- 
GitLab