.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_reliability/reliability_analysis/plot_python_active_learning_reliability.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_reliability_reliability_analysis_plot_python_active_learning_reliability.py: Custom active learning criterion for reliability analysis ========================================================== This example shows how to define a custom active learning criterion in Python and use it with the :class:`~openturns.experimental.ActiveLearningReliabilityAlgorithm`. The criterion used here is the least improvement function (LIF) proposed by Sun et al. [sun2017]_. The reliability problem is the four-branch function already used in the :doc:`active learning gallery example `, defined here as a single symbolic limit-state function. Using the same model, input distribution and initial design of experiments makes it easy to compare the custom criterion with the built-in :class:`~openturns.experimental.ActiveLearningUFunction`. .. GENERATED FROM PYTHON SOURCE LINES 20-28 .. code-block:: Python import math import openturns as ot import openturns.experimental as otexp import openturns.viewer as otv ot.RandomGenerator.SetSeed(0) .. GENERATED FROM PYTHON SOURCE LINES 29-66 The four-branch reliability problem ----------------------------------- The four-branch function :math:`g : \mathbb{R}^2 \rightarrow \mathbb{R}` is defined by: .. math:: :nowrap: \begin{align*} g(\vect{x}) = \min \begin{pmatrix}3+0.1(x_1-x_2)^2-\frac{(x_1+x_2)}{\sqrt{2}}\\ 3+0.1(x_1-x_2)^2+\frac{(x_1+x_2)}{\sqrt{2}}\\ (x_1-x_2)+ \frac{6}{\sqrt{2}}\\ (x_2-x_1)+ \frac{6}{\sqrt{2}} \end{pmatrix} \end{align*} with the input random vector :math:`\vect{X} = (X_1, X_2)` which follows the 2-dimensional Normal distribution: .. math:: :nowrap: \begin{align*} \vect{X} \sim \mathcal{N}(\mu = [0, 0], \sigma = [1.5,1.5], corr = \mat{I}_2) \end{align*} The probability to estimate is defined by: .. math:: :nowrap: \begin{align*} p = \mathbb{P} ( g(\vect{X}) \leq 0 ) \end{align*} The four branches are assembled in a single symbolic function. This is both cheaper to evaluate than a Python callback and simpler than a union of four events: the failure event is simply :math:`g(\vect{X}) \leq 0`. .. GENERATED FROM PYTHON SOURCE LINES 69-80 .. code-block:: Python input_distribution = ot.Normal([0.0, 0.0], [1.5, 1.5]) input_dimension = input_distribution.getDimension() g = ot.SymbolicFunction( ["x1", "x2"], [ "min(3+0.1*(x1-x2)^2-(x1+x2)/sqrt(2)," "3+0.1*(x1-x2)^2+(x1+x2)/sqrt(2)," "(x1-x2)+6/sqrt(2),(x2-x1)+6/sqrt(2))" ], ) .. GENERATED FROM PYTHON SOURCE LINES 81-85 .. code-block:: Python X = ot.RandomVector(input_distribution) Y = ot.CompositeRandomVector(g, X) event = ot.ThresholdEvent(Y, ot.Less(), 0.0) .. GENERATED FROM PYTHON SOURCE LINES 86-92 Initial design of experiments and Gaussian process fitter --------------------------------------------------------- A latin hypercube sample of size 10 is used to fit the initial Gaussian process. The covariance model and the trend are the same as in the reference active learning example. .. GENERATED FROM PYTHON SOURCE LINES 94-102 .. code-block:: Python input_DoE = ot.LHSExperiment( ot.JointDistribution([ot.Uniform(-5.0, 5.0)] * input_dimension), 10 ).generate() output_DoE = g(input_DoE) covariance_model = ot.MaternModel(input_dimension) basis = ot.ConstantBasisFactory(input_dimension).build() fitter = ot.GaussianProcessFitter(input_DoE, output_DoE, covariance_model, basis) .. GENERATED FROM PYTHON SOURCE LINES 103-137 The least improvement function ------------------------------ The LIF criterion combines the probability of misclassifying the sign of the limit state with the probability density of the input vector: .. math:: \mathrm{LIF}(\vect{x}) = \Phi(-U(\vect{x})) \, f_X(\vect{x}), \qquad U(\vect{x}) = \frac{|\widehat{\model}(\vect{x}) - T|}{\hat{\sigma}(\vect{x})}, where :math:`\widehat{\model}(\vect{x})` and :math:`\hat{\sigma}(\vect{x})` are the conditional mean and standard deviation of the Gaussian process, :math:`T` is the event threshold and :math:`f_X` is the joint probability density function of the inputs. The first factor :math:`\Phi(-U(\vect{x}))` is the probability that the Gaussian process predicts the wrong side of the threshold. The second factor :math:`f_X(\vect{x})` favors points that are likely to be sampled. The point that maximizes the LIF is added to the design of experiments. The class below implements this criterion by subclassing :class:`~openturns.experimental.PythonActiveLearningReliabilityFunction`. Three methods are required: - ``computeAsScalar`` evaluates the criterion at a given point; - ``checkConvergenceLearning`` decides whether the enrichment can stop; - ``isMaximization`` gives the direction of the criterion. Here, the enrichment stops when the largest LIF value over the candidate sample falls below a small threshold. As LIF values are probability densities, this threshold is problem dependent; the value used below was calibrated on this example. The convergence of the active learning algorithm can also be monitored with its ``PROBABILITY_UNCERTAINTY`` criterion. .. GENERATED FROM PYTHON SOURCE LINES 140-164 .. code-block:: Python class LIFCriterion(otexp.PythonActiveLearningReliabilityFunction): def __init__(self, reliability_threshold, learning_threshold, distribution): super().__init__(reliability_threshold, learning_threshold) self._distribution = distribution def computeAsScalar(self, x): covariance = ot.GaussianProcessConditionalCovariance( self.getGaussianProcessRegression() ) mean = covariance.getConditionalMean(x)[0] variance = covariance.getConditionalMarginalVariance(x) if not variance > 0.0: return 0.0 u = abs(mean - self.getReliabilityThreshold()) / math.sqrt(variance) misclassification_probability = 0.5 * math.erfc(u / math.sqrt(2.0)) return misclassification_probability * self._distribution.computePDF(x) def checkConvergenceLearning(self, values): return values.getMax()[0] <= self.getLearningThreshold() def isMaximization(self): return True .. GENERATED FROM PYTHON SOURCE LINES 165-168 The Python object is wrapped into an :class:`~openturns.experimental.ActiveLearningReliabilityFunction` so that it can be passed to the active learning algorithm. .. GENERATED FROM PYTHON SOURCE LINES 168-173 .. code-block:: Python learning_threshold = 1.0e-3 lif_criterion = otexp.ActiveLearningReliabilityFunction( LIFCriterion(0.0, learning_threshold, input_distribution) ) .. GENERATED FROM PYTHON SOURCE LINES 174-179 Active learning with the custom criterion ----------------------------------------- The simulation algorithm is a Monte Carlo simulation. Its input sample is the candidate pool used by the criterion at each iteration. .. GENERATED FROM PYTHON SOURCE LINES 181-194 .. code-block:: Python monte_carlo = ot.ProbabilitySimulationAlgorithm(event, ot.MonteCarloExperiment()) monte_carlo.setMaximumCoefficientOfVariation(0.02) monte_carlo.setMaximumOuterSampling(2000) active_learning = otexp.ActiveLearningReliabilityAlgorithm( fitter, monte_carlo, lif_criterion ) active_learning.setMaximumIterations(80) active_learning.setConvergenceCriterion(active_learning.ACTIVE_LEARNING) ot.RandomGenerator.SetSeed(0) active_learning.run() result = active_learning.getResult() .. GENERATED FROM PYTHON SOURCE LINES 195-201 .. code-block:: Python print( f"LIF active learning probability estimate: {result.getProbabilityEstimate():.4f}" ) print(f"Number of limit state function calls: {result.getFunctionCallNumber()}") print(f"Converged: {result.getHasConverged()}") .. rst-class:: sphx-glr-script-out .. code-block:: none LIF active learning probability estimate: 0.0660 Number of limit state function calls: 36 Converged: True .. GENERATED FROM PYTHON SOURCE LINES 202-204 A direct Monte Carlo simulation with a large sample gives a reference value for this problem. .. GENERATED FROM PYTHON SOURCE LINES 206-212 .. code-block:: Python ot.RandomGenerator.SetSeed(12345) reference = ot.ProbabilitySimulationAlgorithm(event, ot.MonteCarloExperiment(100000)) reference.run() reference_probability = reference.getResult().getProbabilityEstimate() print(f"Reference Monte Carlo probability estimate: {reference_probability:.4f}") .. rst-class:: sphx-glr-script-out .. code-block:: none Reference Monte Carlo probability estimate: 0.0630 .. GENERATED FROM PYTHON SOURCE LINES 213-214 The probability estimate is also exposed at each enrichment iteration. .. GENERATED FROM PYTHON SOURCE LINES 214-220 .. code-block:: Python graph_history = ot.Graph("Probability history", "iteration", "probability estimate") graph_history.setGrid(True) probability_history = result.getProbabilityHistory() graph_history.add(ot.Curve(range(len(probability_history)), probability_history)) _ = otv.View(graph_history) .. image-sg:: /auto_reliability/reliability_analysis/images/sphx_glr_plot_python_active_learning_reliability_001.svg :alt: Probability history :srcset: /auto_reliability/reliability_analysis/images/sphx_glr_plot_python_active_learning_reliability_001.svg :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 221-226 Visualization of the final metamodel ------------------------------------ The final Gaussian process is accurate near the limit state, where the enrichment points have been added. .. GENERATED FROM PYTHON SOURCE LINES 228-244 .. code-block:: Python metamodel = result.getGprResult().getMetaModel() final_input_DoE = result.getGprResult().getInputSample() graph = ot.Graph("Final Gaussian process metamodel", "x1", "x2") graph.setAxes(True) graph.setGrid(True) graph.setLegendPosition("upper right") graph.add( metamodel.draw( [-5.0] * input_dimension, [5.0] * input_dimension, [100] * input_dimension ) ) graph.add(ot.Cloud(final_input_DoE, "enriched DoE")) graph.add(ot.Cloud(input_DoE, "initial DoE")) _ = otv.View(graph) # sphinx_gallery_thumbnail_number = 2 .. image-sg:: /auto_reliability/reliability_analysis/images/sphx_glr_plot_python_active_learning_reliability_002.svg :alt: Final Gaussian process metamodel :srcset: /auto_reliability/reliability_analysis/images/sphx_glr_plot_python_active_learning_reliability_002.svg :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 245-248 The enriched design of experiments concentrates around the four branches of the limit state, where the misclassification probability is the largest, while the density factor avoids spending points in low-probability regions. .. GENERATED FROM PYTHON SOURCE LINES 248-249 .. code-block:: Python otv.View.ShowAll() .. _sphx_glr_download_auto_reliability_reliability_analysis_plot_python_active_learning_reliability.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_python_active_learning_reliability.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_python_active_learning_reliability.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_python_active_learning_reliability.zip `