Estimate a probability using Line Sampling

In this example, we estimate the probability that the output of a function exceeds a given threshold with the Line Sampling method.

import openturns as ot
import openturns.viewer as otv
import matplotlib.pyplot as plt

Define the limit state function and the random vector

dim = 2
g_twoBranch = ot.SymbolicFunction(
    ["x1", "x2"],
    [
        "min(4 + 0.1 * (x1 - x2)^2 - (x1 + x2) / sqrt(2), 4 + 0.1 * (x1 - x2)^2 + (x1 + x2) / sqrt(2))"
    ],
)
X = ot.RandomVector(ot.Normal(dim))

Define the event

Run FORM approximation

Run Line Sampling

The design point will define the initial important direction

Define the root solver

solver = ot.Brent(1e-3, 1e-3, 1e-3, 5)
rootStrategy = ot.MediumSafe(solver)

Create the algorithm

Save the important direction history, and especially all root points

Run the simulation

probabilityEstimate=8.191687e-03 varianceEstimate=1.672833e-07 standard deviation=4.09e-04 coefficient of variation=4.99e-02 confidenceLength(0.95)=1.60e-03 outerSampling=81 blockSize=1

Retrieve important directions

Retrieve root points and root values

def drawLines(algo, n=10):
    """Draw sampling lines and the corresponding roots."""
    rootPoints = algo.getRootPointsHistory()
    alphas = algo.getAlphaHistory()
    n = min(n, len(rootPoints))
    for i in range(n):
        # there can be several roots per sample
        n_roots = len(rootPoints[i])
        alpha = alphas[i]
        for j in range(n_roots):
            if i + j == 0:
                print(f"n_roots={n_roots}")
            dp = rootPoints[i][j]
            # project design point on the hyperplane orthogonal to alpha to get origin point
            uPoint = dp
            uDot = uPoint.dot(alpha)
            uPoint = uPoint - alpha * uDot
            # draw segment origin -> design point
            plt.plot(
                (uPoint[0], dp[0]),
                (uPoint[1], dp[1]),
                color="blue",
                linestyle="--",
                linewidth=0.75,
            )
            # draw origin
            plt.plot(uPoint[0], uPoint[1], "ro", markersize=3)
            # draw design point
            plt.plot(dp[0], dp[1], "bo", markersize=3, zorder=3)
def drawLSDesign(algo):
    """Draw sampling lines, roots, and the limit state function."""
    dmin = [-4.0] * 2
    dmax = [4.0] * 2
    graph1 = g_twoBranch.draw(dmin, dmax)
    contour_g = graph1.getDrawable(0).getImplementation()
    contour_g.setColorBarPosition("")
    contour_g.setColorMap("gray")
    graph1.setDrawable(0, contour_g)
    view1 = otv.View(graph1, square_axes=True)
    # now draw the the limit state on same figure
    graph2 = g_twoBranch.draw(dmin, dmax)
    contour_g = graph2.getDrawable(0).getImplementation()
    contour_g.setLevels([threshold])
    contour_g.setColor("red")
    graph2.setDrawable(0, contour_g)
    plt.axline([-1, 1], [1, -1], linestyle="dotted", color="gray")
    drawLines(algo)
    graph2.setTitle("Line Sampling")
    _ = otv.View(graph2, figure=view1.getFigure())

Plot the limit state, a few design points and their origin

drawLSDesign(algo)
Line Sampling
n_roots=2

Now we disable the opposite direction search to try to save function evaluations. This practice is incorrect in this case, however, as the algorithm misses half the probability of the event.

probabilityEstimate=4.095844e-03 varianceEstimate=4.182082e-08 standard deviation=2.05e-04 coefficient of variation=4.99e-02 confidenceLength(0.95)=8.02e-04 outerSampling=81 blockSize=1

We plot the limit state, a few design points and their origin. This time we see each origin sample point in the orthogonal hyperplane yields only one design point.

drawLSDesign(algo)
Line Sampling
n_roots=1

Now re-enable adaptive important direction search

probabilityEstimate=8.121158e-03 varianceEstimate=1.621451e-07 standard deviation=4.03e-04 coefficient of variation=4.96e-02 confidenceLength(0.95)=1.58e-03 outerSampling=79 blockSize=1

Inspect important directions (without duplicates from history)

unique_alphas = ot.Sample(0, dim)
for alpha in algo.getAlphaHistory():
    if len(unique_alphas) == 0 or alpha != unique_alphas[-1]:
        unique_alphas.add(alpha)
print("unique alphas:")
print(unique_alphas)
unique alphas:
0 : [  0.707107  0.707106 ]
1 : [ -0.343161 -0.939276 ]
2 : [ -0.631146 -0.775664 ]
3 : [  0.669986  0.742374 ]
4 : [ -0.687288 -0.726385 ]
5 : [  0.717459  0.6966   ]
6 : [ -0.716641 -0.697443 ]