|
| 1 | +import os |
| 2 | + |
| 3 | +from optimas.explorations import Exploration |
| 4 | +from optimas.generators import RandomSamplingGenerator |
| 5 | +from optimas.evaluators import FunctionEvaluator |
| 6 | +from optimas.core import VaryingParameter, Objective |
| 7 | + |
| 8 | + |
| 9 | +def eval_func(input_params, output_params): |
| 10 | + raise ValueError("Exception to break exploration") |
| 11 | + |
| 12 | + |
| 13 | +def test_exception_during_exploration_run(): |
| 14 | + """Test that the Exploration handles exceptions during the run correctly. |
| 15 | + |
| 16 | + When using `create_evaluation_dirs=True`, the current working directory |
| 17 | + will change during exploration and should be restored when `.run` finishes, |
| 18 | + even if an exception occurs. |
| 19 | + """ |
| 20 | + # Define variables and objectives. |
| 21 | + var1 = VaryingParameter("x0", -50.0, 5.0) |
| 22 | + var2 = VaryingParameter("x1", -5.0, 15.0) |
| 23 | + obj = Objective("f", minimize=False) |
| 24 | + |
| 25 | + # Create generator. |
| 26 | + gen = RandomSamplingGenerator( |
| 27 | + varying_parameters=[var1, var2], |
| 28 | + objectives=[obj], |
| 29 | + ) |
| 30 | + |
| 31 | + # Create function evaluator. |
| 32 | + ev = FunctionEvaluator( |
| 33 | + function=eval_func, create_evaluation_dirs=True |
| 34 | + ) |
| 35 | + |
| 36 | + # Create exploration. |
| 37 | + exploration = Exploration( |
| 38 | + generator=gen, |
| 39 | + evaluator=ev, |
| 40 | + max_evals=10, |
| 41 | + sim_workers=2, |
| 42 | + exploration_dir_path="./tests_output/test_function_evaluator", |
| 43 | + ) |
| 44 | + |
| 45 | + cwd = os.getcwd() |
| 46 | + |
| 47 | + # Run exploration without raising an exception. |
| 48 | + exploration.run() |
| 49 | + |
| 50 | + # Check that the cwd remains unchanged after a failed run. |
| 51 | + assert os.getcwd() == cwd |
| 52 | + |
| 53 | + |
| 54 | +if __name__ == "__main__": |
| 55 | + test_exception_during_exploration_run() |
0 commit comments