Algorithm Search⌘K

Algorithmcore

First-order reliability method

Also called Hasofer-Lind method, FORM, HL-RF algorithm.

Estimates a failure probability by finding the most probable failure point in standard normal space and linearizing the limit state there.

Time
O(K d C) worst
Space
O(d) extra
Where
C = the cost of one evaluation of the limit state function; K = the number of HL-RF iterations; d = the number of random inputs
Properties
deterministicnot exactnot intrusive
Origin
Abraham M. Hasofer, Niels C. Lind, Rudiger Rackwitz, Bernd Fiessler, Karl Breitung, 1974

The first-order reliability method (FORM) estimates the probability that a system fails, Pf=P[g(X)≤0]P_f = \mathbb{P}[g(X) \le 0], where gg is the limit state function of the random inputs XX. It maps XX to a vector uu of independent standard normal variables, finds the point u∗u^* of the limit state surface g=0g = 0 closest to the origin, and replaces the surface by its tangent plane there. The distance β=∥u∗∥\beta = \|u^*\| is the Hasofer-Lind reliability index, and Pf≈Φ(−β)P_f \approx \Phi(-\beta). The design point u∗u^* is the most probable failure point, because the standard normal density falls with the distance from the origin. FORM needs only a few dozen evaluations of gg and its gradient, no matter how small PfP_f is, which is why structural engineers use it for probabilities of 10−310^{-3} to 10−710^{-7}. The result is exact for a linear limit state of normal variables and an approximation otherwise; the second-order correction of Breitung uses the curvature of the surface.

In plain words

You want the chance that a load beats the strength of a part, when both are uncertain. First, rescale every uncertain quantity so that it becomes a standard bell curve variable; then all directions in this new space are alike, and the chance of a point falls off with its distance from the center. The border between safe and failed is a surface in this space. The failure point that is easiest to reach is the point of the border closest to the center. Find it by a simple iteration that steps toward the border along its slope. Its distance β\beta tells you the answer: if the border were flat, the chance of failure would be exactly the chance that a bell curve variable exceeds β\beta.

The problem

The inputs X=(X1,…,Xd)X = (X_1, \ldots, X_d) are independent with continuous marginal CDFs FkF_k. The map xk=Fk−1(Φ(uk))x_k = F_k^{-1}(\Phi(u_k)) sends a standard normal vector uu to XX, by inverse transform sampling; write x=T(u)x = T(u). The limit state function gg is differentiable, with failure for g(x)≤0g(x) \le 0. In standard normal space the limit state is G(u)=g(T(u))G(u) = g(T(u)). Find the design point

u∗=arg⁡min⁡{∥u∥:G(u)=0},u^* = \arg\min \{\|u\| : G(u) = 0\},

the reliability index β=±∥u∗∥\beta = \pm \|u^*\|, positive when the origin is safe (G(0)>0G(0) > 0), and the estimate Pf≈Φ(−β)P_f \approx \Phi(-\beta). Also return the unit normal α=−∇G(u∗)/∥∇G(u∗)∥\alpha = -\nabla G(u^*)/\|\nabla G(u^*)\|, whose squared entries αk2\alpha_k^2 measure the importance of each input.

The algorithm

  1. FORM(g, T, tol)
  2. 1u ← 0 ▷ the mean point
  3. 2repeat
  4. 3G ← g(T(u)); ∇G ← gradient of g(T(·)) at u
  5. 4u_new ← ((∇G^T u - G) / ‖∇G‖^2) ∇G ▷ HL-RF step
  6. 5until ‖u_new - u‖ ≤ tol · max(1, ‖u_new‖); u ← u_new
  7. 6β ← sign(G(0)) ‖u‖
  8. 7return β, P_f ≈ Φ(-β), u* = u, x* = T(u), α = -∇G / ‖∇G‖

Line L1 starts at the origin of standard normal space, which maps to the medians of the inputs. Line L3 evaluates the limit state and its gradient; the reference code uses central differences with step 10−610^{-6}, which costs 2d2d evaluations, while large models use an adjoint or automatic differentiation. Line L4 is the Hasofer-Lind-Rackwitz-Fiessler (HL-RF) step: it replaces GG by its linearization G(u)+∇GT(v−u)G(u) + \nabla G^{\mathsf T}(v - u) and jumps to the point of the plane {v:linearization=0}\{v : \text{linearization} = 0\} closest to the origin. For a linear GG this is the answer after one step. Line L5 stops when the step is small; the reference code raises an error after 100 iterations. Line L6 gives β\beta its sign, and line L7 evaluates Φ(−β)=12erfc⁡(β/2)\Phi(-\beta) = \frac{1}{2} \operatorname{erfc}(\beta / \sqrt{2}), which keeps full relative accuracy in the far tail, where 1−Φ(β)1 - \Phi(\beta) would lose all digits.

Example

Lognormal resistance against a normal load. Let g=R−Sg = R - S with ln⁡R∼N(ln⁡10,0.22)\ln R \sim N(\ln 10, 0.2^2) and S∼N(5,1.52)S \sim N(5, 1.5^2). The exact value is Pf=∫ϕS(s)FR(s) ds=1.289177×10−2P_f = \int \phi_S(s) F_R(s)\, ds = 1.289177 \times 10^{-2}, by a one dimensional integral. The HL-RF iterates are deterministic:

step u1u_1 (RR) u2u_2 (SS) ∥u∥\|u\| G(u)G(u)
1 -1.600000 1.200000 2.0000000 4.6×10−14.6 \times 10^{-1}
2 -1.527591 1.577766 2.1961060 7.7×10−47.7 \times 10^{-4}
3 -1.539187 1.566886 2.1964124 2.0×10−52.0 \times 10^{-5}
4 -1.537375 1.568675 2.1964203 4.8×10−74.8 \times 10^{-7}
6 -1.537614 1.568440 2.1964205 2.9×10−102.9 \times 10^{-10}

The first step is the exact answer for normal RR; the rest corrects for the lognormal shape. At the design point R=S=7.353R = S = 7.353, and α2=(0.490,0.510)\alpha^2 = (0.490, 0.510), so both inputs matter about equally. FORM gives Φ(−2.196420)=1.403×10−2\Phi(-2.196420) = 1.403 \times 10^{-2}, 8.8 percent too high, and Breitung's formula gives 1.305×10−21.305 \times 10^{-2}, 1.2 percent too high. A Monte Carlo estimate with the same 10 percent error would need about 8000 samples; FORM used 11 iterations of 5 evaluations each.

A curved limit state. Let G(u)=3−u1+k2u22G(u) = 3 - u_1 + \frac{k}{2} u_2^2 with standard normal uu. For every k≥0k \ge 0 the design point is (3,0)(3, 0) and β=3\beta = 3, so FORM always returns Φ(−3)=1.349898×10−3\Phi(-3) = 1.349898 \times 10^{-3}. The curvature of the surface at u∗u^* is kk. The exact values come from a one dimensional integral; they are deterministic.

kk exact PfP_f FORM error Breitung error
0 1.349898×10−31.349898 \times 10^{-3} 1.349898×10−31.349898 \times 10^{-3} 0 1.349898×10−31.349898 \times 10^{-3} 0
0.05 1.250308×10−31.250308 \times 10^{-3} 1.349898×10−31.349898 \times 10^{-3} +8.0% 1.258786×10−31.258786 \times 10^{-3} +0.7%
0.1 1.168962×10−31.168962 \times 10^{-3} 1.349898×10−31.349898 \times 10^{-3} +15.5% 1.183939×10−31.183939 \times 10^{-3} +1.3%
0.2 1.043599×10−31.043599 \times 10^{-3} 1.349898×10−31.349898 \times 10^{-3} +29.4% 1.067188×10−31.067188 \times 10^{-3} +2.3%
0.5 8.208174×10−48.208174 \times 10^{-4} 1.349898×10−31.349898 \times 10^{-3} +64.5% 8.537505×10−48.537505 \times 10^{-4} +4.0%

FORM cannot see the curvature, so its error grows with kk. Breitung's factor (1+3k)−1/2(1 + 3k)^{-1/2} removes most of it.

Correctness

Three statements are theorems; the proof file proves them. First, a fixed point of the HL-RF step with G(u)=0G(u) = 0 satisfies the optimality conditions of the design point problem: u=λ∇G(u)u = \lambda \nabla G(u), the KKT conditions of min⁡12∥u∥2\min \frac{1}{2}\|u\|^2 subject to G(u)=0G(u) = 0. Conversely, every regular point that satisfies them, with G=0G = 0, is a fixed point. Second, if G(u)=a0+aTuG(u) = a_0 + a^{\mathsf T} u is linear, then one step from any start lands on u∗=−a0a/∥a∥2u^* = -a_0 a / \|a\|^2, and Φ(−β)\Phi(-\beta) with β=a0/∥a∥\beta = a_0 / \|a\| is the exact failure probability, because aTu∼N(0,∥a∥2)a^{\mathsf T} u \sim N(0, \|a\|^2). Third, β\beta depends only on the failure set {G≤0}\{G \le 0\}, not on how gg is written: g=R−Sg = R - S, ln⁡R−ln⁡S\ln R - \ln S and R/S−1R/S - 1 give the same β\beta, which the tests check. This invariance is what Hasofer and Lind added over the earlier mean value indices.

Two statements are not theorems for general gg. The HL-RF iteration need not converge: for strongly curved surfaces it can cycle, as Liu and Der Kiureghian showed, and a step size control on a merit function fixes this. And Φ(−β)\Phi(-\beta) is only a first-order approximation. Breitung proved that Pf∼Φ(−β)∏i=1d−1(1+βκi)−1/2P_f \sim \Phi(-\beta) \prod_{i=1}^{d-1} (1 + \beta \kappa_i)^{-1/2} as β→∞\beta \to \infty with the products βκi\beta \kappa_i held fixed, which describes the error of FORM: it is small when βκi\beta \kappa_i is small. When the limit state has several design points of similar distance, FORM finds one of them and misses the others.

Proof: The HL-RF fixed points are the design point conditions, FORM is exact for a linear limit state, and the reliability index depends only on the failure setfull

We assume exact arithmetic and an exact gradient. The limit state in standard normal space is G(u)=g(T(u))G(u) = g(T(u)), continuously differentiable, and UU is a standard normal vector in Rd\mathbb{R}^d. The HL-RF map of line L4 is

H(u)=∇G(u)Tu−G(u)∥∇G(u)∥2 ∇G(u),∇G(u)≠0.H(u) = \frac{\nabla G(u)^{\mathsf T} u - G(u)}{\|\nabla G(u)\|^2}\, \nabla G(u), \qquad \nabla G(u) \neq 0.

A design point is a solution u∗u^* of min⁡∥u∥\min \|u\| subject to G(u)=0G(u) = 0. Put β=sign⁡(G(0))∥u∗∥\beta = \operatorname{sign}(G(0)) \|u^*\| and α=−∇G(u∗)/∥∇G(u∗)∥\alpha = -\nabla G(u^*) / \|\nabla G(u^*)\|.

Lemma 1 (the step is a projection). H(u)H(u) is the point of smallest norm on the hyperplane Pu={v:G(u)+∇G(u)T(v−u)=0}P_u = \{v : G(u) + \nabla G(u)^{\mathsf T} (v - u) = 0\}, where the linearization of GG at uu vanishes.

Proof. Write a=∇G(u)a = \nabla G(u) and c=aTu−G(u)c = a^{\mathsf T} u - G(u), so Pu={v:aTv=c}P_u = \{v : a^{\mathsf T} v = c\}. For v∈Puv \in P_u, the Cauchy-Schwarz inequality gives ∣c∣=∣aTv∣≤∥a∥∥v∥|c| = |a^{\mathsf T} v| \le \|a\| \|v\|, so ∥v∥≥∣c∣/∥a∥\|v\| \ge |c| / \|a\|. The point ca/∥a∥2=H(u)c a / \|a\|^2 = H(u) lies in PuP_u and has norm ∣c∣/∥a∥|c| / \|a\|. □\square

Lemma 2 (the design point conditions). Let u∗u^* be a design point with G(0)≠0G(0) \neq 0 and ∇G(u∗)≠0\nabla G(u^*) \neq 0. Then u∗=λ∇G(u∗)u^* = \lambda \nabla G(u^*) for a real λ\lambda, and u∗=βαu^* = \beta \alpha.

Proof. The gradient of the constraint is not zero, so the constraint is regular, and the first-order conditions for min⁡12∥u∥2\min \frac{1}{2}\|u\|^2 subject to G(u)=0G(u) = 0 (the KKT conditions with one equality constraint) give u∗−μ∇G(u∗)=0u^* - \mu \nabla G(u^*) = 0 for a multiplier μ\mu; put λ=μ\lambda = \mu. Now fix the sign. Since G(0)≠0G(0) \neq 0 and G(u∗)=0G(u^*) = 0, u∗≠0u^* \neq 0, so λ≠0\lambda \neq 0. For 0≤t<10 \le t < 1 the point tu∗t u^* has norm less than ∥u∗∥\|u^*\|, so G(tu∗)≠0G(t u^*) \neq 0 by minimality, and by continuity G(tu∗)G(t u^*) has the sign of G(0)G(0) on [0,1)[0, 1). Suppose G(0)>0G(0) > 0. Then G(tu∗)>0=G(u∗)G(t u^*) > 0 = G(u^*) for t<1t < 1, so the derivative ddtG(tu∗)\frac{d}{dt} G(t u^*) at t=1t = 1, which is ∇G(u∗)Tu∗=λ∥∇G(u∗)∥2\nabla G(u^*)^{\mathsf T} u^* = \lambda \|\nabla G(u^*)\|^2, is at most 0. So λ<0\lambda < 0, and u∗=λ∇G(u∗)=∣λ∣∥∇G(u∗)∥αu^* = \lambda \nabla G(u^*) = |\lambda| \|\nabla G(u^*)\| \alpha. Taking norms, ∣λ∣∥∇G(u∗)∥=∥u∗∥=β|\lambda| \|\nabla G(u^*)\| = \|u^*\| = \beta, so u∗=βαu^* = \beta \alpha. If G(0)<0G(0) < 0 the same argument gives λ>0\lambda > 0 and u∗=−∥u∗∥α=βαu^* = -\|u^*\| \alpha = \beta \alpha. □\square

Lemma 3 (fixed points). A point uu with ∇G(u)≠0\nabla G(u) \neq 0 is a fixed point of HH if and only if G(u)=0G(u) = 0 and u=λ∇G(u)u = \lambda \nabla G(u) for a real λ\lambda.

Proof. Write a=∇G(u)a = \nabla G(u). If H(u)=uH(u) = u, then u=λau = \lambda a with λ=(aTu−G(u))/∥a∥2\lambda = (a^{\mathsf T} u - G(u)) / \|a\|^2. Multiply the first equation by aTa^{\mathsf T}: aTu=λ∥a∥2=aTu−G(u)a^{\mathsf T} u = \lambda \|a\|^2 = a^{\mathsf T} u - G(u), so G(u)=0G(u) = 0. Conversely, if G(u)=0G(u) = 0 and u=λau = \lambda a, then (aTu−0)/∥a∥2=λ(a^{\mathsf T} u - 0) / \|a\|^2 = \lambda and H(u)=λa=uH(u) = \lambda a = u. □\square

So every design point is a fixed point of HL-RF (Lemmas 2 and 3), and every fixed point satisfies the first-order conditions of the design point problem. A fixed point need not be the global minimizer: it can be a local minimizer or a saddle point of ∥u∥\|u\| on the surface.

Lemma 4 (linear limit states). Let G(u)=a0+aTuG(u) = a_0 + a^{\mathsf T} u with a≠0a \neq 0. Then H(u)=−a0a/∥a∥2H(u) = -a_0 a / \|a\|^2 for every uu, this point is the design point, β=a0/∥a∥\beta = a_0 / \|a\|, and P[G(U)≤0]=Φ(−β)\mathbb{P}[G(U) \le 0] = \Phi(-\beta) exactly.

Proof. Here ∇G=a\nabla G = a and aTu−G(u)=−a0a^{\mathsf T} u - G(u) = -a_0, so H(u)=−a0a/∥a∥2H(u) = -a_0 a / \|a\|^2, the same point for every uu. The surface G=0G = 0 is the hyperplane PuP_u itself, so by Lemma 1 this point is the design point, and its norm is ∣a0∣/∥a∥|a_0| / \|a\|; with the sign of G(0)=a0G(0) = a_0, β=a0/∥a∥\beta = a_0 / \|a\|. The variable aTUa^{\mathsf T} U is normal with mean 0 and variance ∥a∥2\|a\|^2, so P[a0+aTU≤0]=P[Z≤−a0/∥a∥]=Φ(−β)\mathbb{P}[a_0 + a^{\mathsf T} U \le 0] = \mathbb{P}[Z \le -a_0 / \|a\|] = \Phi(-\beta) for a standard normal ZZ. □\square

Lemma 5 (invariance). Let GG and G~\tilde G have the same zero set, {G=0}={G~=0}\{G = 0\} = \{\tilde G = 0\}, and let G(0)G(0) and G~(0)\tilde G(0) have the same sign. Then they have the same design points and the same β\beta.

Proof. The design point problem uses only the set {G=0}\{G = 0\} and the sign of G(0)G(0). □\square

For example, with R,S>0R, S > 0 the functions R−SR - S, ln⁡R−ln⁡S\ln R - \ln S and R/S−1R / S - 1 all vanish exactly when R=SR = S, and all are positive exactly when R>SR > S, so they give the same β\beta. A mean value index, E[g]/sd⁡(g)\mathbb{E}[g] / \operatorname{sd}(g) of a linearization at the mean, does not have this property.

Theorem. FORM stops after at most max_iter iterations of the loop. If ∇G\nabla G is continuous and the iterates converge to a point uˉ\bar u with ∇G(uˉ)≠0\nabla G(\bar u) \neq 0, then G(uˉ)=0G(\bar u) = 0 and uˉ=λ∇G(uˉ)\bar u = \lambda \nabla G(\bar u), and if uˉ\bar u is a design point, the returned values satisfy uˉ=βα\bar u = \beta \alpha, with β\beta the Hasofer-Lind index. If GG is linear in uu, FORM returns the design point after its second iteration, and Φ(−β)\Phi(-\beta) is the exact failure probability.

Proof. Termination: the loop of lines L2 to L5 runs at most max_iter times; each pass either raises an error for a zero gradient, stops at line L5, or continues, and after max_iter passes the code raises an error. Each pass does a finite amount of work. Limit: HH is continuous where ∇G≠0\nabla G \neq 0, so uk+1=H(uk)u_{k+1} = H(u_k) and uk→uˉu_k \to \bar u give H(uˉ)=uˉH(\bar u) = \bar u. Lemma 3 gives the conditions, and Lemma 2 gives uˉ=βα\bar u = \beta \alpha when uˉ\bar u is a design point. Linear case: by Lemma 4 the first iterate is the design point and the second iterate equals the first, so the stopping test of line L5 holds at the second iteration, and the probability is exact by Lemma 4. ■\blacksquare

The theorem does not claim that the iterates converge. For a curved limit state, the HL-RF map can cycle or diverge, which Liu and Der Kiureghian showed; a line search on a merit function fixes this. The theorem also does not bound the error of Φ(−β)\Phi(-\beta) for a nonlinear limit state. The asymptotic formula of Breitung, which the page uses as a correction, is quoted and not proved here. With finite difference gradients, as in the reference code, the fixed point conditions hold only up to the difference error, which is why the stopping tolerance is 10−810^{-8} and not smaller.

Complexity

In the real RAM model, each HL-RF iteration costs one evaluation of gg and a gradient. With central differences the gradient costs 2d2d evaluations, so the total is O(KdC)O(K d C) for KK iterations; with an adjoint gradient it is O(KC)O(K C). The extra space is O(d)O(d). KK is typically 5 to 20 for smooth problems, and it does not depend on the size of PfP_f, while Monte Carlo integration needs about 1/(Pfε2)1/(P_f \varepsilon^2) samples for relative error ε\varepsilon. Breitung's correction adds a Hessian at the design point, O(d2)O(d^2) evaluations by differences, and an O(d3)O(d^3) determinant.

Properties

  • Deterministic. No sampling error; the error is the linearization error.
  • Cost independent of PfP_f. The work does not grow as the failure probability shrinks.
  • Exact for linear limit states (theorem). For GG linear in standard normal space, Φ(−β)\Phi(-\beta) is exact.
  • Invariant (theorem). β\beta depends only on the failure set.
  • Sensitivities for free. The entries αk2\alpha_k^2 sum to 1 and rank the inputs; ∂β/∂θ\partial \beta / \partial \theta for a parameter θ\theta follows from the gradient at u∗u^*.
  • Local. It sees the limit state only near one point.
  • Needs gradients. gg must be differentiable near the design point.

Variants and improvements

  • Second-order reliability method (SORM). Fit a quadratic at u∗u^* and use Breitung's formula, or the later exact or improved formulas for a paraboloid. The reference code computes the curvature matrix in the tangent plane from a finite difference Hessian.
  • Improved HL-RF. Use the HL-RF direction with a line search on a merit function, which makes the method converge for curved surfaces (Liu and Der Kiureghian).
  • General optimizers. The design point problem is a constrained minimization; sequential quadratic programming or a Newton method on the KKT system also work.
  • Dependent inputs. Use the Rosenblatt or Nataf transform instead of the separate map of each marginal.
  • Importance sampling at the design point. Sample from a normal law centered at u∗u^*; the importance sampling estimate corrects the FORM error at a modest cost.
  • System reliability. For several failure modes, find a design point for each and combine the linearized events with a multinormal integral.

When to use it

Use FORM when PfP_f is small, each evaluation of gg is expensive, gg is smooth with gradients available, and the failure domain has one dominant design point. It is the standard method of structural reliability and of reliability based design. Check its answer with Breitung's correction or with importance sampling around u∗u^*. Use subset simulation when the limit state is strongly nonlinear, has several design points, or has no usable gradient, and plain Monte Carlo when PfP_f is not small.

Pitfalls

  • Curvature. A curved limit state can make Φ(−β)\Phi(-\beta) wrong by a large factor, as the second table shows. Compute the SORM correction.
  • Several design points. A failure domain with two regions of similar distance is underestimated by half or more. Restart from different points, or use a sampling method.
  • Non-convergence. Plain HL-RF can oscillate. Monitor G(u)G(u) and ∥u∥\|u\|, and switch to a line search.
  • Noisy gradients. Finite differences of a model with solver noise give wrong directions. The stopping tolerance must be larger than the gradient noise; the reference code uses a relative 10−810^{-8} because its differences carry errors near 10−910^{-9}.
  • Tail arithmetic. Compute Φ(−β)\Phi(-\beta) with erfc, not as 1−Φ(β)1 - \Phi(\beta), which is 0 in double precision for β\beta above about 8.3.
  • Wrong transform. Dependent inputs mapped as if independent give a wrong β\beta. Use a transform that respects the joint law.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

first_order_reliability_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/first-order-reliability-method/. The authors are listed in prov/B2CCS2.jsonl.
"""First-order reliability method (FORM) by the HL-RF iteration, with Breitung's SORM correction.

The physical inputs X_1..X_d are independent with continuous marginal laws.
Each marginal is given by its inverse CDF, so x_k = F_k^(-1)(Phi(u_k)) maps a
standard normal vector u to X. Failure is g(x) <= 0. In the standard normal
space the limit state is G(u) = g(T(u)). The design point u* is the point of
G(u) = 0 closest to the origin, the reliability index is beta = +-||u*||
(positive when the origin is safe), and FORM gives P_f ~ Phi(-beta).
Gradients and the Hessian of G are central finite differences.
"""

import math
from statistics import NormalDist
from typing import Callable

Vector = list[float]
_STD = NormalDist()


def phi_cdf(t: float) -> float:
    """The standard normal CDF, by erfc, accurate in the far tail."""
    return 0.5 * math.erfc(-t / math.sqrt(2.0))


def normal_marginal(mean: float, sd: float) -> Callable[[float], float]:
    """x = mean + sd u: the map from u to a normal variable."""
    return lambda u: mean + sd * u


def lognormal_marginal(lam: float, zeta: float) -> Callable[[float], float]:
    """x = exp(lam + zeta u): the map from u to a lognormal variable with log-mean lam and log-sd zeta."""
    return lambda u: math.exp(lam + zeta * u)


def uniform_marginal(a: float, b: float) -> Callable[[float], float]:
    """x = a + (b - a) Phi(u): the map from u to a uniform variable on [a, b]."""
    return lambda u: a + (b - a) * phi_cdf(u)


def from_inverse_cdf(ppf: Callable[[float], float]) -> Callable[[float], float]:
    """The map u -> F^(-1)(Phi(u)) for a marginal given by its inverse CDF."""
    return lambda u: ppf(_STD.cdf(u))


def gradient(fun: Callable[[Vector], float], u: Vector, h: float = 1e-6) -> Vector:
    """Central difference gradient."""
    out = []
    for k in range(len(u)):
        up, dn = list(u), list(u)
        up[k] += h
        dn[k] -= h
        out.append((fun(up) - fun(dn)) / (2.0 * h))
    return out


def hessian(fun: Callable[[Vector], float], u: Vector, h: float = 1e-4) -> list[list[float]]:
    """Central difference Hessian."""
    d = len(u)
    hes = [[0.0] * d for _ in range(d)]
    for i in range(d):
        for j in range(i, d):
            vals = []
            for si, sj in ((1, 1), (1, -1), (-1, 1), (-1, -1)):
                v = list(u)
                v[i] += si * h
                v[j] += sj * h
                vals.append(fun(v))
            hes[i][j] = hes[j][i] = (vals[0] - vals[1] - vals[2] + vals[3]) / (4.0 * h * h)
    return hes


def det(a: list[list[float]]) -> float:
    """Determinant by Gaussian elimination with partial pivoting."""
    m = [list(r) for r in a]
    n = len(m)
    out = 1.0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0.0:
            return 0.0
        if p != c:
            m[c], m[p] = m[p], m[c]
            out = -out
        out *= m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for k in range(c, n):
                m[r][k] -= f * m[c][k]
    return out


def form(g: Callable[[Vector], float], marginals: list[Callable[[float], float]], tol: float = 1e-8, max_iter: int = 100) -> dict:
    """HL-RF iteration for the design point; returns beta, the FORM P_f, u*, x*, alpha and the step count."""
    def big_g(u: Vector) -> float:
        return g([t(v) for t, v in zip(marginals, u)])

    d = len(marginals)
    u = [0.0] * d  # @line L1
    g0 = big_g(u)
    steps = 0
    for steps in range(1, max_iter + 1):  # @line L2
        val = big_g(u)
        grad = gradient(big_g, u)  # @line L3
        n2 = sum(t * t for t in grad)
        if n2 == 0.0:
            raise ValueError("zero gradient of the limit state")
        lam = (sum(a * b for a, b in zip(grad, u)) - val) / n2
        new = [lam * t for t in grad]  # @line L4
        done = math.sqrt(sum((a - b) ** 2 for a, b in zip(new, u))) <= tol * max(1.0, math.sqrt(sum(t * t for t in new)))
        u = new
        if done:  # @line L5
            break
    else:
        raise RuntimeError("HL-RF did not converge")
    grad = gradient(big_g, u)
    norm = math.sqrt(sum(t * t for t in grad))
    alpha = [-t / norm for t in grad]
    beta = math.copysign(math.sqrt(sum(t * t for t in u)), g0)  # @line L6
    return {"beta": beta, "pf": phi_cdf(-beta), "u": u, "x": [t(v) for t, v in zip(marginals, u)], "alpha": alpha, "steps": steps, "G": big_g}  # @line L7


def breitung(result: dict) -> float:
    """Breitung's SORM: P_f ~ Phi(-beta) / sqrt(det(I + beta K)), K the curvature matrix in the tangent plane."""
    u, alpha, beta, big_g = result["u"], result["alpha"], result["beta"], result["G"]
    d = len(u)
    if d == 1:
        return result["pf"]
    norm = math.sqrt(sum(t * t for t in gradient(big_g, u)))
    hes = hessian(big_g, u)
    basis: list[Vector] = []
    for k in range(d):  # an orthonormal basis of the plane orthogonal to alpha, by Gram-Schmidt
        v = [1.0 if i == k else 0.0 for i in range(d)]
        for w in [alpha] + basis:
            c = sum(a * b for a, b in zip(v, w))
            v = [a - c * b for a, b in zip(v, w)]
        n = math.sqrt(sum(t * t for t in v))
        if n > 1e-8 and len(basis) < d - 1:
            basis.append([t / n for t in v])
    curv = [[sum(basis[i][p] * hes[p][q] * basis[j][q] for p in range(d) for q in range(d)) / norm for j in range(d - 1)] for i in range(d - 1)]
    mat = [[(1.0 if i == j else 0.0) + beta * curv[i][j] for j in range(d - 1)] for i in range(d - 1)]
    dt = det(mat)
    if dt <= 0.0:
        raise ValueError("Breitung's formula needs 1 + beta kappa > 0 for every curvature")
    return phi_cdf(-beta) / math.sqrt(dt)
test_first_order_reliability_method.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/first-order-reliability-method/. The authors are listed in prov/B2CCS2.jsonl.
import math
import random
from statistics import NormalDist

import pytest

from first_order_reliability_method import (
    breitung,
    form,
    gradient,
    lognormal_marginal,
    normal_marginal,
    phi_cdf,
    uniform_marginal,
)

STD = [normal_marginal(0.0, 1.0)]


def trap(f, a, b, n=20000):
    h = (b - a) / n
    return h * (0.5 * f(a) + 0.5 * f(b) + sum(f(a + i * h) for i in range(1, n)))


def pdf(t):
    return math.exp(-0.5 * t * t) / math.sqrt(2 * math.pi)


def test_phi_matches_reference_values():
    assert abs(phi_cdf(-3.0) - 0.0013498980316301) < 1e-15
    nd = NormalDist()
    for t in (-2.5, -1.0, 0.0, 0.7, 2.0):
        assert abs(phi_cdf(t) - nd.cdf(t)) < 1e-14


def test_linear_limit_state_is_exact():
    rng = random.Random(1)
    for _ in range(5):
        a = [rng.uniform(-2, 2) for _ in range(4)]
        a0 = rng.uniform(1, 4)
        res = form(lambda u: a0 + sum(x * y for x, y in zip(a, u)), STD * 4)
        na = math.sqrt(sum(t * t for t in a))
        assert abs(res["beta"] - a0 / na) < 1e-8
        assert res["steps"] <= 3
        assert max(abs(ui + a0 * ai / na**2) for ui, ai in zip(res["u"], a)) < 1e-8
        assert abs(res["pf"] - phi_cdf(-a0 / na)) < 1e-12


def test_normal_resistance_minus_normal_load():
    res = form(lambda x: x[0] - x[1], [normal_marginal(10.0, 1.0), normal_marginal(6.0, 1.5)])
    assert abs(res["beta"] - 4.0 / math.sqrt(1.0 + 2.25)) < 1e-8


def test_design_point_satisfies_the_optimality_conditions():
    res = form(lambda x: x[0] - x[1], [lognormal_marginal(math.log(10.0), 0.2), normal_marginal(5.0, 1.5)])
    u, alpha, beta = res["u"], res["alpha"], res["beta"]
    assert abs(res["G"](u)) < 1e-9
    assert max(abs(ui - beta * ai) for ui, ai in zip(u, alpha)) < 1e-7
    grad = gradient(res["G"], u)
    assert abs(grad[0] * u[1] - grad[1] * u[0]) < 1e-7


def test_formulation_invariance():
    marg = [lognormal_marginal(math.log(10.0), 0.2), normal_marginal(5.0, 1.5)]
    b1 = form(lambda x: x[0] - x[1], marg)["beta"]
    b2 = form(lambda x: math.log(x[0]) - math.log(x[1]), marg)["beta"]
    b3 = form(lambda x: x[0] / x[1] - 1.0, marg)["beta"]
    assert abs(b1 - b2) < 1e-7 and abs(b1 - b3) < 1e-7


def test_lognormal_resistance_against_exact_integral():
    lam, zeta = math.log(10.0), 0.2
    res = form(lambda x: x[0] - x[1], [lognormal_marginal(lam, zeta), normal_marginal(5.0, 1.5)])
    exact = trap(lambda s: pdf((s - 5.0) / 1.5) / 1.5 * phi_cdf((math.log(s) - lam) / zeta), 0.01, 20.0)
    assert abs(exact - 1.289177e-2) < 1e-7
    assert abs(res["beta"] - 2.1964205) < 1e-6
    assert 0.05 < res["pf"] / exact - 1.0 < 0.12
    assert abs(breitung(res) / exact - 1.0) < 0.02


def test_parabolic_limit_state_and_breitung():
    for k in (0.05, 0.1, 0.2, 0.5):
        res = form(lambda u: 3.0 - u[0] + 0.5 * k * u[1] ** 2, STD * 2)
        exact = trap(lambda t: pdf(t) * phi_cdf(-(3.0 + 0.5 * k * t * t)), -12.0, 12.0, 4000)
        assert abs(res["beta"] - 3.0) < 1e-8
        assert abs(res["pf"] - phi_cdf(-3.0)) < 1e-12
        assert res["pf"] > exact
        sorm = breitung(res)
        assert abs(sorm - phi_cdf(-3.0) / math.sqrt(1.0 + 3.0 * k)) < 1e-7
        assert abs(sorm - exact) < abs(res["pf"] - exact)


def test_origin_in_failure_domain_gives_negative_beta():
    res = form(lambda u: -1.0 - u[0], STD * 2)
    assert abs(res["beta"] + 1.0) < 1e-8
    assert abs(res["pf"] - phi_cdf(1.0)) < 1e-9


def test_uniform_marginal_map():
    t = uniform_marginal(2.0, 5.0)
    assert abs(t(0.0) - 3.5) < 1e-15
    assert abs(t(1.0) - (2.0 + 3.0 * phi_cdf(1.0))) < 1e-15


def test_zero_gradient_is_rejected():
    with pytest.raises(ValueError):
        form(lambda u: 1.0 + u[0] ** 2, STD)

History

Early reliability indices used the mean and standard deviation of gg and changed when gg was written in another form. Hasofer and Lind fixed this in 1974 by measuring the distance to the limit state surface in the space of standardized variables, which made the index depend only on the failure set. Rackwitz and Fiessler extended the method to non-normal inputs in 1978, with an equivalent normal transform and the iteration now called HL-RF. Breitung derived the asymptotic second-order formula in 1984. Liu and Der Kiureghian compared optimization algorithms for the design point in 1991 and gave a modified HL-RF method that converges where the plain one cycles. Ditlevsen and Madsen collected the theory in their 1996 book.

References

  1. Abraham M. Hasofer and Niels C. Lind, Exact and invariant second-moment code format, Journal of the Engineering Mechanics Division (ASCE) 100(1), 1974, 111-121, the reliability index as the distance from the origin to the limit state surface in the space of standardized variables, and its invariance under reformulation of the limit state
  2. Karl Breitung, Asymptotic approximations for multinormal integrals, Journal of Engineering Mechanics 110(3), 1984, 357-366, the asymptotic formula Phi(-beta) times the product of (1 + beta kappa_i)^(-1/2) over the principal curvatures at the design point
  3. Pei-Ling Liu and Armen Der Kiureghian, Optimization algorithms for structural reliability, Structural Safety 9(3), 1991, 161-177, the comparison of algorithms for the design point problem, the failure of plain HL-RF to converge in some cases, and the modified HL-RF method with a merit function
  4. Ove Ditlevsen and Henrik O. Madsen, Structural Reliability Methods, Wiley, 1996, Chapter 5 (the geometric reliability index of Hasofer and Lind) and the later chapters on non-normal inputs and second-order corrections

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example