From 1de5123017fb0dbbbafa83d569a5559d42767b52 Mon Sep 17 00:00:00 2001 From: oliverweissl Date: Tue, 1 Jul 2025 11:45:17 +0200 Subject: [PATCH] Use wrapper to ensure bounds --- pymoo/core/crossover.py | 9 +++++++++ pymoo/operators/crossover/sbx.py | 1 + 2 files changed, 10 insertions(+) diff --git a/pymoo/core/crossover.py b/pymoo/core/crossover.py index ad35e80ec..84917867e 100644 --- a/pymoo/core/crossover.py +++ b/pymoo/core/crossover.py @@ -74,4 +74,13 @@ def do(self, problem, pop, parents=None, **kwargs): def _do(self, problem, X, **kwargs): pass + @staticmethod + def safe_bounds_do(func): + @functools.wraps(func) + def wrapped_do(self, problem, X, **kwargs): + result = func(self, problem, X, **kwargs) + if np.any(result < (problem.xl or -np.inf)) or np.any(result > (problem.xu or np.inf)): + raise ValueError("The generated solution is out of bounds.") + return result + return wrapped_do diff --git a/pymoo/operators/crossover/sbx.py b/pymoo/operators/crossover/sbx.py index 1150246f3..a75efb2ab 100644 --- a/pymoo/operators/crossover/sbx.py +++ b/pymoo/operators/crossover/sbx.py @@ -110,6 +110,7 @@ def __init__(self, self.prob_exch = Real(prob_exch, bounds=(0.0, 1.0), strict=(0.0, 1.0)) self.prob_bin = Real(prob_bin, bounds=(0.0, 1.0), strict=(0.0, 1.0)) + @Crossover.safe_bounds_do def _do(self, problem, X, **kwargs): _, n_matings, _ = X.shape