.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_numerical_methods/optimization/plot_optimization_failure_penalty.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_numerical_methods_optimization_plot_optimization_failure_penalty.py: Optimize a failure-prone model with a failure penalty ===================================================== .. GENERATED FROM PYTHON SOURCE LINES 7-15 In this example we optimize a model which may fail to evaluate, e.g. a simulation which raises an exception outside its validity domain. This failure penalty handles simulations that raise exceptions, such as RuntimeError. It cannot recover from process-level crashes (segmentation fault, abort, ...). Without precaution the optimizer stops on the first failure. The :class:`~openturns.experimental.ExceptionPenalizedEvaluation` and :class:`~openturns.experimental.ExceptionPenalizedProblem` classes replace failures by a large failure-penalty value so the optimizer can proceed. .. GENERATED FROM PYTHON SOURCE LINES 17-24 .. code-block:: Python import math import openturns as ot import openturns.experimental as otexp import openturns.viewer as otv .. GENERATED FROM PYTHON SOURCE LINES 25-34 Define a failure-prone model ----------------------------- We minimize a quadratic function with optimum at :math:`(1, 1)`, but the model raises an exception inside the disk :math:`(x_1 - 0.5)^2 + (x_2 - 0.5)^2 < 0.375^2`, e.g. as if a solver failed to converge there. This failing region sits in the middle of the search space, so any space-filling search cannot avoid stepping into it. .. GENERATED FROM PYTHON SOURCE LINES 37-45 .. code-block:: Python def failing_py(x): if (x[0] - 0.5) ** 2 + (x[1] - 0.5) ** 2 < 0.375**2: raise RuntimeError("simulation fails inside the failing region") return [(x[0] - 1.0) ** 2 + (x[1] - 1.0) ** 2] model = ot.PythonFunction(2, 1, failing_py) .. GENERATED FROM PYTHON SOURCE LINES 46-47 The model works on feasible points: .. GENERATED FROM PYTHON SOURCE LINES 47-49 .. code-block:: Python print(model([1.0, 1.0])) .. rst-class:: sphx-glr-script-out .. code-block:: none [0] .. GENERATED FROM PYTHON SOURCE LINES 50-51 but it throws inside the failing region: .. GENERATED FROM PYTHON SOURCE LINES 51-56 .. code-block:: Python try: model([0.5, 0.5]) except RuntimeError as ex: print(f"evaluation failed: {ex}") .. rst-class:: sphx-glr-script-out .. code-block:: none evaluation failed: simulation fails inside the failing region .. GENERATED FROM PYTHON SOURCE LINES 57-61 Wrap the problem with a failure penalty --------------------------------------- We define the optimization problem on :math:`[-2, 2]^2`: .. GENERATED FROM PYTHON SOURCE LINES 63-67 .. code-block:: Python problem = ot.OptimizationProblem(model) problem.setMinimization(True) problem.setBounds(ot.Interval([-2.0] * 2, [2.0] * 2)) .. GENERATED FROM PYTHON SOURCE LINES 68-69 Starting from a failing point, a classical solver stops at the first failure: .. GENERATED FROM PYTHON SOURCE LINES 71-78 .. code-block:: Python algo = ot.Cobyla(problem) algo.setStartingPoint([0.5, 0.5]) try: algo.run() except TypeError as ex: print(f"optimization failed: {ex}") .. rst-class:: sphx-glr-script-out .. code-block:: none optimization failed: InvalidArgumentException : No feasible point found during optimization .. GENERATED FROM PYTHON SOURCE LINES 79-87 The :class:`~openturns.experimental.ExceptionPenalizedProblem` class wraps the problem and replaces its objective by a failure-penalty function: a failed evaluation returns a large positive value for minimization (a large negative value for maximization). Bounds, constraints and minimization flags are preserved. Note that the failure-penalty functions are flat where the model fails, so gradient-based solvers may stall there: use derivative-free solvers (e.g. :class:`~openturns.Cobyla`, :class:`~openturns.Pagmo`). .. GENERATED FROM PYTHON SOURCE LINES 89-91 .. code-block:: Python penalizedProblem = otexp.ExceptionPenalizedProblem(problem, 1.0e6) .. GENERATED FROM PYTHON SOURCE LINES 92-93 The failure-penalty objective agrees with the model on feasible points: .. GENERATED FROM PYTHON SOURCE LINES 93-95 .. code-block:: Python print(penalizedProblem.getObjective()([1.0, 1.0])) .. rst-class:: sphx-glr-script-out .. code-block:: none [0] .. GENERATED FROM PYTHON SOURCE LINES 96-97 and returns the failure-penalty value on failures: .. GENERATED FROM PYTHON SOURCE LINES 97-99 .. code-block:: Python print(penalizedProblem.getObjective()([0.5, 0.5])) .. rst-class:: sphx-glr-script-out .. code-block:: none [1e+06] .. GENERATED FROM PYTHON SOURCE LINES 100-102 Batch evaluations mix both cases, which is useful for population-based solvers such as :class:`~openturns.Pagmo`: .. GENERATED FROM PYTHON SOURCE LINES 102-104 .. code-block:: Python print(penalizedProblem.getObjective()(ot.Sample([[0.5, 0.5], [1.0, 1.0]]))) .. rst-class:: sphx-glr-script-out .. code-block:: none [ y0 ] 0 : [ 1e+06 ] 1 : [ 0 ] .. GENERATED FROM PYTHON SOURCE LINES 105-107 The low-level :class:`~openturns.experimental.ExceptionPenalizedEvaluation` class offers the same mechanism on a single evaluation: .. GENERATED FROM PYTHON SOURCE LINES 107-110 .. code-block:: Python penalizedEvaluation = otexp.ExceptionPenalizedEvaluation(model.getEvaluation(), 1.0e6) print(ot.Function(penalizedEvaluation)([0.5, 0.5])) .. rst-class:: sphx-glr-script-out .. code-block:: none [1e+06] .. GENERATED FROM PYTHON SOURCE LINES 111-118 Solve the problem with failure penalty -------------------------------------- We use a global evolutionary solver: its initial population lies in :math:`[-2, 0]^2`, far from the optimum, so the search must travel across the failing disk to reach :math:`(1, 1)`. Without a failure penalty the search stops at the first failure: .. GENERATED FROM PYTHON SOURCE LINES 120-133 .. code-block:: Python ot.RandomGenerator.SetSeed(0) pop0 = ot.JointDistribution([ot.Uniform(-2.0, 0.0)] * 2).getSample(30) algo = ot.Pagmo(problem, "de", pop0) algo.setMaximumIterationNumber(10) try: algo.run() except RuntimeError as ex: print(f"optimization failed: {ex}") crashedResult = algo.getResult() failedInputSample = crashedResult.getInputSample() print(f"evaluations before failure: {failedInputSample.getSize()}") print("best f before failure:", model(failedInputSample).getMin()) .. rst-class:: sphx-glr-script-out .. code-block:: none optimization failed: simulation fails inside the failing region evaluations before failure: 142 best f before failure: [0.0563574] .. GENERATED FROM PYTHON SOURCE LINES 134-136 With a failure penalty the failed evaluations are replaced by the failure-penalty value and the search proceeds across the failing region: .. GENERATED FROM PYTHON SOURCE LINES 138-145 .. code-block:: Python algo = ot.Pagmo(penalizedProblem, "de", pop0) algo.setMaximumIterationNumber(10) algo.run() result = algo.getResult() print("x*=", result.getOptimalPoint()) print("f(x*)=", result.getOptimalValue()) .. rst-class:: sphx-glr-script-out .. code-block:: none x*= [0.991077,1.01556] f(x*)= [0.000321737] .. GENERATED FROM PYTHON SOURCE LINES 146-149 The search stepped into the failing region on its way to the optimum: these evaluations were replaced by the failure-penalty value instead of stopping the optimization: .. GENERATED FROM PYTHON SOURCE LINES 149-154 .. code-block:: Python inputSample = result.getInputSample() outputSample = penalizedProblem.getObjective()(inputSample) nFailed = sum(1 for i in range(outputSample.getSize()) if outputSample[i, 0] >= 1.0e6) print(f"failed evaluations: {nFailed} / {outputSample.getSize()}") .. rst-class:: sphx-glr-script-out .. code-block:: none failed evaluations: 22 / 330 .. GENERATED FROM PYTHON SOURCE LINES 155-157 Despite these failures the optimizer recovered the minimum :math:`(1, 1)` with value :math:`0`. .. GENERATED FROM PYTHON SOURCE LINES 159-161 Graphical comparison --------------------- .. GENERATED FROM PYTHON SOURCE LINES 163-166 Draw the failure-penalty objective isovalues with each search path. We use the failure-penalty objective (and not the raw model) as it can be evaluated everywhere, including in the failing region. .. GENERATED FROM PYTHON SOURCE LINES 166-189 .. code-block:: Python penalizedFunction = penalizedProblem.getObjective() # Outline of the failing disk, drawn in red on both graphs: angles = [2.0 * math.pi * i / 100 for i in range(101)] disk = ot.Curve( [[0.5 + 0.375 * math.cos(t), 0.5 + 0.375 * math.sin(t)] for t in angles] ) disk.setColor("red") disk.setLegend("failing region") graph = penalizedFunction.draw([-2.0] * 2, [2.0] * 2, [100] * 2) graph.setTitle("Search path without failure penalty (failed)") graph.getDrawable(0).setLevels([0.5, 1.0, 2.0, 4.0, 8.0]) graph.add(disk) failedCloud = ot.Cloud(failedInputSample) failedCloud.setColor("orange") failedCloud.setLegend("evaluations") graph.add(failedCloud) popCloud = ot.Cloud(pop0) popCloud.setColor("green") popCloud.setLegend("initial population") graph.add(popCloud) graph.setLegendPosition("lower right") view = otv.View(graph) .. image-sg:: /auto_numerical_methods/optimization/images/sphx_glr_plot_optimization_failure_penalty_001.svg :alt: Search path without failure penalty (failed) :srcset: /auto_numerical_methods/optimization/images/sphx_glr_plot_optimization_failure_penalty_001.svg :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 190-224 .. code-block:: Python graph = penalizedFunction.draw([-2.0] * 2, [2.0] * 2, [100] * 2) graph.setTitle("Search path with failure penalty") graph.getDrawable(0).setLevels([0.5, 1.0, 2.0, 4.0, 8.0]) graph.add(disk) okSample = ot.Sample( [inputSample[i] for i in range(inputSample.getSize()) if outputSample[i, 0] < 1.0e6] ) failedPenalizedSample = ot.Sample( [ inputSample[i] for i in range(inputSample.getSize()) if outputSample[i, 0] >= 1.0e6 ] ) cloud = ot.Cloud(okSample) cloud.setColor("blue") cloud.setLegend("evaluations") graph.add(cloud) popCloud = ot.Cloud(pop0) popCloud.setColor("green") popCloud.setLegend("initial population") graph.add(popCloud) failedCloud = ot.Cloud(failedPenalizedSample) failedCloud.setColor("red") failedCloud.setLegend("failed evaluations") graph.add(failedCloud) optimum = ot.Cloud(ot.Sample([result.getOptimalPoint()])) optimum.setColor("orange") optimum.setPointStyle("bullet") optimum.setLegend("optimum") graph.add(optimum) graph.setLegendPosition("lower right") view = otv.View(graph) .. image-sg:: /auto_numerical_methods/optimization/images/sphx_glr_plot_optimization_failure_penalty_002.svg :alt: Search path with failure penalty :srcset: /auto_numerical_methods/optimization/images/sphx_glr_plot_optimization_failure_penalty_002.svg :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 225-230 The plateau at :math:`10^6` corresponds to the failing disk, outlined in red. The search without failure penalty stopped at its edge, while the search with failure penalty crossed it: the red dots inside the disk are failed evaluations which were replaced by the failure-penalty value on the way to the minimum (blue dots, orange optimum). .. GENERATED FROM PYTHON SOURCE LINES 232-235 .. code-block:: Python graph = result.drawOptimalValueHistory() view = otv.View(graph) .. image-sg:: /auto_numerical_methods/optimization/images/sphx_glr_plot_optimization_failure_penalty_003.svg :alt: Optimal value history :srcset: /auto_numerical_methods/optimization/images/sphx_glr_plot_optimization_failure_penalty_003.svg :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 236-237 Display all figures .. GENERATED FROM PYTHON SOURCE LINES 237-238 .. code-block:: Python otv.View.ShowAll() .. _sphx_glr_download_auto_numerical_methods_optimization_plot_optimization_failure_penalty.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_optimization_failure_penalty.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_optimization_failure_penalty.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_optimization_failure_penalty.zip `