From 1fe500202e33c30771f9367e36f57971c0a6b053 Mon Sep 17 00:00:00 2001 From: Her0n24 Date: Sun, 8 Mar 2026 01:22:24 +0000 Subject: [PATCH] Genetic: handle empty optimization results --- WeatherRoutingTool/algorithms/genetic/__init__.py | 15 +++++++++++++++ tests/test_genetic_termination.py | 15 +++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 tests/test_genetic_termination.py diff --git a/WeatherRoutingTool/algorithms/genetic/__init__.py b/WeatherRoutingTool/algorithms/genetic/__init__.py index c514fb0a..04b24311 100644 --- a/WeatherRoutingTool/algorithms/genetic/__init__.py +++ b/WeatherRoutingTool/algorithms/genetic/__init__.py @@ -157,6 +157,21 @@ def terminate(self, res: Result, problem: RoutingProblem): super().terminate() + if res is None or res.F is None or res.X is None: + raise RuntimeError( + "Genetic optimization produced no feasible solution " + "(empty result: res.F/res.X is None). " + "This typically means all candidate routes violated constraints. " + "Try relaxing constraints (e.g., disable `water_depth` and/or `via_waypoints` temporarily), " + "reducing the bbox/time window, or verifying weather/depth inputs." + ) + + if np.size(res.F) == 0 or np.size(res.X) == 0: + raise RuntimeError( + "Genetic optimization produced no feasible solution (empty result array). " + "This typically means all candidate routes violated constraints." + ) + best_index = res.F.argmin() # ensure res.X is of shape (n_sol, n_var) best_route = np.atleast_2d(res.X)[best_index, 0] diff --git a/tests/test_genetic_termination.py b/tests/test_genetic_termination.py new file mode 100644 index 00000000..79a6f751 --- /dev/null +++ b/tests/test_genetic_termination.py @@ -0,0 +1,15 @@ +import pytest + +from WeatherRoutingTool.algorithms.genetic import Genetic + + +class _EmptyResult: + F = None + X = None + + +def test_genetic_terminate_raises_on_empty_result(): + genetic = Genetic.__new__(Genetic) + + with pytest.raises(RuntimeError, match=r"no feasible solution"): + genetic.terminate(_EmptyResult(), problem=None)