Algorithm Search⌘K

Algorithmadvanced

Fourier amplitude sensitivity test

Varies all inputs along a curve with distinct frequencies and reads each input's share of variance from the Fourier spectrum of the output.

Time
O(d R n (F + d + n)) worst
Space
O(d n) extra
Where
F = the cost of one model run; R = the number n_r of curves per input; d = the number of inputs; n = the number n_s of points per curve
Properties
randomizednot exactnot iterativerandomized
Origin
R. I. Cukier, C. M. Fortuin, Kurt E. Shuler, A. G. Petschek, J. H. Schaibly, Andrea Saltelli, Stefano Tarantola, Karen Chan, 1973

The Fourier amplitude sensitivity test (FAST) estimates the Sobol indices of a model by moving all inputs together along one periodic curve through the input space, each input at its own integer frequency. The output along the curve is a periodic signal, and the discrete Fourier transform of that signal splits its variance by frequency: the power at the frequency of an input and its first few harmonics is the variance due to that input alone. The extended form (eFAST) gives one input a high frequency and all others low ones, so that the same spectrum also gives the total index. The cost is d nr nsd\, n_r\, n_s model runs for dd inputs, and the method is exact only for models whose spectrum fits in the bands it reads.

In plain words

Turn every knob of a model back and forth at the same time, each knob at its own speed. One knob turns fast, and the others turn slowly. Record the output over one full cycle.

If the output wiggles at the fast speed, the fast knob is causing it. If the output only drifts slowly, the slow knobs are causing it. A frequency analysis of the recording tells how much of the output's spread sits at the fast speed and how much sits at the slow speeds. The share at the fast speed is what the fast knob does alone. The share at the slow speeds is what the other knobs do without it, so everything else belongs to the fast knob, alone or together with others.

Do this once for each knob, and each time make that knob the fast one.

The problem

The input is a model y=f(x)y = f(x) with dd independent inputs, each uniform on [0,1][0, 1] after a transformation, and a budget of model runs. The output is an estimate of the first order and total Sobol indices

Si=Var(E[y∣xi])Var(y),STi=1−Var(E[y∣x∼i])Var(y),S_i = \frac{\mathrm{Var}(\mathbb{E}[y \mid x_i])}{\mathrm{Var}(y)}, \qquad S_{Ti} = 1 - \frac{\mathrm{Var}(\mathbb{E}[y \mid x_{\sim i}])}{\mathrm{Var}(y)},

where x∼ix_{\sim i} is all inputs except xix_i. Inputs with other laws are handled by the inverse transform xi↦Fi−1(xi)x_i \mapsto F_i^{-1}(x_i) of inverse transform sampling.

The algorithm

For input ii, the curve is

xk(s)=12+1πarcsin⁡(sin⁡(ωks+φk)),s∈(−π,π),x_k(s) = \frac{1}{2} + \frac{1}{\pi}\arcsin\big(\sin(\omega_k s + \varphi_k)\big), \qquad s \in (-\pi, \pi),

with ωi=ωmax⁡\omega_i = \omega_{\max} and low frequencies ωk≤ωmax⁡/(2M)\omega_k \le \omega_{\max}/(2M) for k≠ik \ne i. Each xk(s)x_k(s) is a triangle wave, and it is uniform on [0,1][0, 1] when ss is uniform. MM is the number of harmonics read, usually 4, and ns≥2Mωmax⁡+1n_s \ge 2M\omega_{\max} + 1 is odd. The power at frequency pp is Λp=(Ap2+Bp2)/2\Lambda_p = (A_p^2 + B_p^2)/2, where ApA_p and BpB_p are the cosine and sine coefficients of the samples.

  1. EFAST(f, d, ω_max, M, n_r, n_s)
  2. 1for i = 1..d do ▷ input i is the fast one
  3. 2ω ← ω_max for input i, and d - 1 low frequencies, spread over 1..⌊ω_max / (2M)⌋, for the others
  4. 3repeat n_r times, with new phases φ_k uniform on [0, 2π):
  5. 4x^(j) ← the curve at s_j = π(2j - n_s - 1) / n_s, j = 1..n_s
  6. 5y_j ← f(x^(j)) for j = 1..n_s
  7. 6Λ_p ← (A_p^2 + B_p^2) / 2 for p = 1..(n_s - 1) / 2
  8. 7D ← Σ_p Λ_p ▷ the variance of the y_j
  9. 8D_i ← Σ_{q=1..M} Λ_(q ω_max) ▷ the harmonics of input i
  10. 9D_~i ← Σ_{p=1..⌊ω_max/2⌋} Λ_p ▷ the band of the other inputs
  11. 10S_i, S_Ti ← the averages over the n_r curves of D_i / D and 1 - D_~i / D
  12. return S, S_T and the run count d n_r n_s

Line L5 is the only step that runs the model. Lines L6 to L9 read the spectrum: the first order part at the multiples of ωmax⁡\omega_{\max} up to Mωmax⁡M\omega_{\max}, and the part of the other inputs in the low band. Line L10 averages over the random phases. The classic FAST of Cukier and coauthors uses one curve for all inputs, with a set of frequencies chosen so that their low harmonics do not collide, and reads only the first order indices.

Example

By hand. Let f=u1+2u2+u1u2f = u_1 + 2u_2 + u_1u_2 with uk=2xk−1u_k = 2x_k - 1 uniform on [−1,1][-1, 1]. Its Hoeffding-Sobol terms are u1u_1, 2u22u_2 and u1u2u_1u_2 with variances 1/31/3, 4/34/3 and 1/91/9, so D=16/9D = 16/9, S1=3/16S_1 = 3/16, S2=3/4S_2 = 3/4, ST1=1/4S_{T1} = 1/4 and ST2=13/16S_{T2} = 13/16. With ωmax⁡=64\omega_{\max} = 64, M=4M = 4, ns=513n_s = 513 and one curve per input, the frequencies are (64,1)(64, 1) for input 1 and (1,64)(1, 64) for input 2. A run with random.Random(1) gives, as a measurement:

index exact eFAST
S1S_1 0.1875 0.1856
S2S_2 0.75 0.7535
ST1S_{T1} 0.25 0.2457
ST2S_{T2} 0.8125 0.8084

The cost is 2⋅513=10262 \cdot 513 = 1026 runs. The small errors are not sampling noise: u1u_1 along the curve is a triangle wave, whose harmonics decay like 1/q21/q^2 and go on above q=Mq = M, so some power falls outside the bands of lines L8 and L9 or aliases above ns/2n_s/2.

The Ishigami function. With f(x)=sin⁡x1+7sin⁡2x2+0.1 x34sin⁡x1f(x) = \sin x_1 + 7\sin^2 x_2 + 0.1\, x_3^4 \sin x_1 on [−π,π]3[-\pi, \pi]^3, the same parameters, the low frequencies 1 and 8, and random.Random(1), eFAST gives, as a measurement:

input SiS_i exact SiS_i eFAST STiS_{Ti} exact STiS_{Ti} eFAST
x1x_1 0.3139 0.3126 0.5576 0.5365
x2x_2 0.4424 0.4437 0.4424 0.4890
x3x_3 0 0.0221 0.2437 0.2433

The run count is 3⋅513=15393 \cdot 513 = 1539. The first order indices are close, and the gap ST3−S3S_{T3} - S_3 shows the interaction of x3x_3 with x1x_1. The total indices carry a band bias of a few hundredths, which more phases do not remove.

Correctness

The proof file shows four facts. Each xk(s)x_k(s) is uniform on [0,1][0, 1]. For odd nsn_s, the sum of line L7 is exactly the sample variance of the yjy_j (the discrete Parseval theorem). Along the curve, the main effect fi(xi(s))f_i(x_i(s)) depends on ss only through ωmax⁡s\omega_{\max}s, so all its power is at the multiples of ωmax⁡\omega_{\max}. And cos⁡(2πmxk(s))=±cos⁡(2m(ωks+φk))\cos(2\pi m x_k(s)) = \pm\cos(2m(\omega_k s + \varphi_k)) is a pure harmonic. From these, the theorem: if MM is even and ff is an additive sum of cosines cos⁡(2πmxk)\cos(2\pi m x_k) with 2m≤M2m \le M, and the frequencies 2mωk2m\omega_k are distinct, then eFAST returns the exact SiS_i and STiS_{Ti} from one curve. For a general model, three errors remain: the power of fif_i above Mωmax⁡M\omega_{\max} (truncation), the power of interaction terms that falls on the harmonics of line L8 or in the band of line L9 (interference), and aliasing of frequencies above ns/2n_s/2. The method is consistent only in the band-limited sense of the theorem, and it gives no error bar.

Proof: The search curve has uniform marginals, the spectrum splits the variance, and eFAST is exact for band-limited modelsfull

We assume exact arithmetic. The inputs are independent and uniform on [0,1][0, 1]; other laws are reached by a map of each component. For input ii, the algorithm uses the frequency ωi=ωmax⁡\omega_i = \omega_{\max} for xix_i and integer frequencies ωk≤ωmax⁡/(2M)\omega_k \le \omega_{\max}/(2M) for the other inputs, random phases φk\varphi_k, and the curve

xk(s)=12+1πarcsin⁡(sin⁡(ωks+φk)),k=1,…,d.x_k(s) = \frac{1}{2} + \frac{1}{\pi} \arcsin\big(\sin(\omega_k s + \varphi_k)\big), \qquad k = 1, \ldots, d.

It evaluates y(s)=f(x(s))y(s) = f(x(s)) at the nn points sj=π(2j−n−1)/ns_j = \pi(2j - n - 1)/n, j=1,…,nj = 1, \ldots, n, with nn odd and n≥2Mωmax⁡+1n \ge 2M\omega_{\max} + 1. The power at the frequency pp is Λp=(Ap2+Bp2)/2\Lambda_p = (A_p^2 + B_p^2)/2 with Ap=2n∑jy(sj)cos⁡(psj)A_p = \frac{2}{n}\sum_j y(s_j) \cos(p s_j) and Bp=2n∑jy(sj)sin⁡(psj)B_p = \frac{2}{n}\sum_j y(s_j) \sin(p s_j). With H=(n−1)/2H = (n - 1)/2, line L7 sets D^=∑p=1HΛp\widehat{D} = \sum_{p=1}^{H} \Lambda_p, line L8 sets D^i=∑q=1MΛqωmax⁡\widehat{D}_i = \sum_{q=1}^{M} \Lambda_{q \omega_{\max}}, and line L9 sets D^∼i=∑p=1ωmax⁡/2Λp\widehat{D}_{\sim i} = \sum_{p=1}^{\omega_{\max}/2} \Lambda_p. The estimates are S^i=D^i/D^\widehat{S}_i = \widehat{D}_i / \widehat{D} and S^Ti=1−D^∼i/D^\widehat{S}_{Ti} = 1 - \widehat{D}_{\sim i} / \widehat{D}.

Lemma 1 (uniform marginals). If ss is uniform on (−π,π)(-\pi, \pi), each xk(s)x_k(s) is uniform on [0,1][0, 1], for every integer ωk≥1\omega_k \ge 1 and every phase.

Proof. The angle θ=ωks+φk\theta = \omega_k s + \varphi_k modulo 2π2\pi is uniform on one period, because ωks\omega_k s covers ωk\omega_k full periods at constant speed. The map t(θ)=arcsin⁡(sin⁡θ)t(\theta) = \arcsin(\sin \theta) is the triangle wave: t=θt = \theta on [−π/2,π/2][-\pi/2, \pi/2] and t=π−θt = \pi - \theta on [π/2,3π/2][\pi/2, 3\pi/2]. On each half period it is a bijection onto [−π/2,π/2][-\pi/2, \pi/2] with slope ±1\pm 1, so tt is uniform on [−π/2,π/2][-\pi/2, \pi/2], and xk=1/2+t/πx_k = 1/2 + t/\pi is uniform on [0,1][0, 1]. □\square

Lemma 2 (discrete Parseval). For odd nn, D^\widehat{D} is the population variance 1n∑j(y(sj)−yˉ)2\frac{1}{n}\sum_j (y(s_j) - \bar{y})^2 of the nn values.

Proof. With sj=−π+π(2j−1)/ns_j = -\pi + \pi(2j - 1)/n, ∑j=1neipsj=e−iπp(1−1/n)∑j=0n−1e2πipj/n\sum_{j=1}^{n} e^{\mathrm{i} p s_j} = e^{-\mathrm{i}\pi p (1 - 1/n)} \sum_{j=0}^{n-1} e^{2\pi \mathrm{i} p j / n}, which is zero unless pp is a multiple of nn. For p,q∈{0,…,H}p, q \in \{0, \ldots, H\}, the numbers p±qp \pm q are multiples of nn only when p=qp = q (or p=q=0p = q = 0), so the nn functions 1,cos⁡(ps),sin⁡(ps)1, \cos(p s), \sin(p s), 1≤p≤H1 \le p \le H, are orthogonal on the points, with the squared norms n,n/2,n/2n, n/2, n/2. They are nn orthogonal vectors in Rn\mathbb{R}^n, so they are a basis, and y(sj)=yˉ+∑p=1H(Apcos⁡psj+Bpsin⁡psj)y(s_j) = \bar{y} + \sum_{p=1}^{H} (A_p \cos p s_j + B_p \sin p s_j). Then 1n∑j(yj−yˉ)2=∑p(Ap2+Bp2)/2\frac{1}{n}\sum_j (y_j - \bar{y})^2 = \sum_p (A_p^2 + B_p^2)/2. □\square

So line L7 needs no second pass over the data, and the Parseval theorem of the discrete Fourier transform is the reason why the spectrum splits the variance.

Lemma 3 (cosine inputs are pure harmonics). For an integer m≥1m \ge 1, cos⁡(2πm xk(s))=(−1)mcos⁡(2m(ωks+φk))\cos(2\pi m\, x_k(s)) = (-1)^m \cos\big(2m(\omega_k s + \varphi_k)\big).

Proof. With xk=1/2+t/πx_k = 1/2 + t/\pi, 2πmxk=πm+2mt2\pi m x_k = \pi m + 2m t, so cos⁡(2πmxk)=(−1)mcos⁡(2mt)\cos(2\pi m x_k) = (-1)^m \cos(2mt). On the half period where t=θt = \theta this is (−1)mcos⁡(2mθ)(-1)^m \cos(2m\theta). On the other one t=π−θt = \pi - \theta and cos⁡(2mπ−2mθ)=cos⁡(2mθ)\cos(2m\pi - 2m\theta) = \cos(2m\theta). □\square

Lemma 4 (the main effect along the curve). Let fi(xi)=E[f∣xi]−E[f]f_i(x_i) = \mathbb{E}[f \mid x_i] - \mathbb{E}[f] be the first order term of the Hoeffding-Sobol decomposition. Along the curve, fi(xi(s))f_i(x_i(s)) is a function of ωmax⁡s\omega_{\max} s alone, so its Fourier series has only the frequencies qωmax⁡q\omega_{\max}, and, for ss uniform on (−π,π)(-\pi, \pi), its total power is Vi=Var(fi)V_i = \mathrm{Var}(f_i).

Proof. xi(s)x_i(s) depends on ss only through ωmax⁡s\omega_{\max} s, so fi(xi(s))f_i(x_i(s)) has the period 2π/ωmax⁡2\pi/\omega_{\max}, and a function with this period has Fourier modes only at multiples of ωmax⁡\omega_{\max}. By Lemma 1, the mean square of fi(xi(s))f_i(x_i(s)) over ss is E[fi(xi)2]=Vi\mathbb{E}[f_i(x_i)^2] = V_i, and its mean is zero. The total power is the mean square, by the Parseval theorem for Fourier series. □\square

Theorem (exact for band-limited models). Let MM be even and

f(x)=c0+∑k=1d∑m=1M/2ak,mcos⁡(2πmxk).f(x) = c_0 + \sum_{k=1}^{d} \sum_{m=1}^{M/2} a_{k, m} \cos(2\pi m x_k).

Assume that the numbers 2mωk2m\omega_k, k≠ik \ne i, 1≤m≤M/21 \le m \le M/2, are distinct. Then S^i=S^Ti=Si=STi\widehat{S}_i = \widehat{S}_{Ti} = S_i = S_{Ti} exactly, for every choice of phases.

Proof. By Lemma 3, along the curve y(s)=c0+∑k∑m(−1)mak,mcos⁡(2mωks+2mφk)y(s) = c_0 + \sum_k \sum_m (-1)^m a_{k, m} \cos(2m\omega_k s + 2m\varphi_k). The terms of input ii sit at the frequencies 2mωmax⁡2m\omega_{\max}, 2m≤M2m \le M, which are among the harmonics qωmax⁡q\omega_{\max}, q≤Mq \le M, of line L8. The terms of the other inputs sit at 2mωk≤Mωmax⁡/(2M)=ωmax⁡/22m\omega_k \le M \omega_{\max}/(2M) = \omega_{\max}/2, so they are inside the band of line L9 and below ωmax⁡\omega_{\max}. All the frequencies are at most Mωmax⁡≤HM\omega_{\max} \le H. By the distinctness assumption and Lemma 2, each term contributes exactly its own power ak,m2/2a_{k, m}^2/2 to one Λp\Lambda_p. So D^i=∑mai,m2/2\widehat{D}_i = \sum_m a_{i, m}^2/2, D^∼i=∑k≠i∑mak,m2/2\widehat{D}_{\sim i} = \sum_{k \ne i}\sum_m a_{k, m}^2/2 and D^=D^i+D^∼i\widehat{D} = \widehat{D}_i + \widehat{D}_{\sim i}. By Lemma 1 and the orthogonality of cos⁡(2πmx)\cos(2\pi m x) on [0,1][0, 1], these are the exact variance ViV_i of the terms of input ii, the exact variance of the other terms and the exact total variance. The model is additive, so Si=STi=Vi/DS_i = S_{Ti} = V_i / D, and the estimates are equal to it. ■\blacksquare

The general case. For a model that is not band-limited, three errors appear, and none of them goes to zero as the number nrn_r of random phases grows.

  • Truncation. Lemma 4 puts all of ViV_i at the harmonics qωmax⁡q\omega_{\max}, but line L8 keeps only q≤Mq \le M. The power at q>Mq > M is lost from D^i\widehat{D}_i and aliases into other frequencies. For a smooth fif_i the lost part decays fast in MM.
  • Interference. The harmonics of the low frequencies of the other inputs, and their sums and differences, can land on a frequency qωmax⁡q\omega_{\max} and change D^i\widehat{D}_i in either direction. With the cut ωk≤ωmax⁡/(2M)\omega_k \le \omega_{\max}/(2M), the first MM harmonics of each other input stay below ωmax⁡/2\omega_{\max}/2; higher harmonics and combinations of several inputs can still reach ωmax⁡\omega_{\max}.
  • The band of the other inputs. Line L9 assumes that all power of the terms without xix_i is at frequencies up to ωmax⁡/2\omega_{\max}/2 and that all terms with xix_i are above it. A term with xix_i has frequencies qωmax⁡±(combinations of the ωk)q\omega_{\max} \pm (\text{combinations of the } \omega_k), which are above ωmax⁡/2\omega_{\max}/2 if the combinations are small. Power of the other inputs above ωmax⁡/2\omega_{\max}/2 counts as part of the total effect of xix_i, so S^Ti\widehat{S}_{Ti} tends to be too large in that case.

The random phases average the interference over different curves. They do not remove the band errors, which come from the frequencies themselves. So eFAST is a consistent method only in the band-limited sense of the theorem. For a general model it has a bias that depends on ωmax⁡\omega_{\max}, MM and the frequency choice, and it gives no error bar.

What is not proved. The code places the low frequencies evenly in 1,…,⌊ωmax⁡/(2M)⌋1, \ldots, \lfloor \omega_{\max}/(2M) \rfloor. This choice is a heuristic, as is the choice M=4M = 4. If two other inputs get the same frequency, which happens when there are more than ωmax⁡/(2M)\omega_{\max}/(2M) of them, their terms share a frequency and add with phases that depend on the curve, so the variance along one curve can differ from DD, and both estimates of input ii change with it.

Complexity

The method makes d nr nsd\, n_r\, n_s model runs, with ns≥2Mωmax⁡+1n_s \ge 2M\omega_{\max} + 1, for example 3⋅513=15393 \cdot 513 = 1539 for the Ishigami example. Building one point costs O(d)O(d), and the spectrum of line L6 by direct sums costs O(ns2)O(n_s^2) per curve, so the total time is O(d nr ns(F+d+ns))O(d\, n_r\, n_s(F + d + n_s)) in the real RAM model. A fast Fourier transform reduces the spectrum to O(nslog⁡ns)O(n_s \log n_s), but the model runs dominate in practice. The extra space is O(d ns)O(d\, n_s) for the points of one curve. The run count does not depend on the number of interactions, and it is comparable to the N(d+2)N(d + 2) runs of the Saltelli sampling scheme for NN close to nsn_s.

Properties

  • First order and total indices from one spectrum. eFAST reads SiS_i and STiS_{Ti} from the same nsn_s runs of curve ii.
  • Deterministic sampling. The points are on a curve, not random; only the phases are random.
  • Exact for band-limited additive models, as in the theorem of the proof file.
  • Biased for general models. The truncation and interference errors are systematic; averaging over phases reduces only the part that changes with the phases.
  • Inputs must be independent. The variance split uses the Hoeffding-Sobol decomposition, which needs independent inputs.

Variants and improvements

  • Classic FAST. Cukier and coauthors (1973) use one curve with incommensurate, or in practice integer and interference-free, frequencies for all dd inputs and read only the first order indices. The needed ωmax⁡\omega_{\max} grows fast with dd, which limits classic FAST to a few tens of inputs.
  • Extended FAST. Saltelli, Tarantola and Chan (1999) give each input its own curve with one high frequency, read the total index from the low band, and repeat with random phases.
  • Random balance designs. One curve with the same frequency for all inputs, with the points permuted independently for each input; the first order indices of all inputs come from nsn_s runs in total.
  • Other curves. The curve of Cukier and coauthors was xk=Gk(sin⁡ωks)x_k = G_k(\sin \omega_k s) with a transformation GkG_k chosen for the input law; the triangle wave of eFAST makes the marginals exactly uniform.

When to use it

Use eFAST when the model has a few to a few tens of independent inputs, runs are cheap enough for a few thousand evaluations, and the first order and total indices are both needed. The Saltelli sampling scheme has error bars by the central limit theorem and no band bias, so it is the safer choice when an error estimate matters. With many inputs, screen first with the Morris method. With a smooth model, a polynomial chaos expansion gives all Sobol indices from its coefficients.

Pitfalls

  • Low frequencies too close. If the low frequencies of the other inputs are small and close, the curve covers their subcube badly and their interference changes with the phases. For the Ishigami function with low frequencies 1 and 2, S2S_2 came out between 0.35 and 0.40 depending on the phases, against 0.4424, a measurement; spreading them to 1 and 8 in line L2 fixed it.
  • An even number of points. With nsn_s even, the frequency ns/2n_s/2 has only a cosine term, and the sum of line L7 is no longer the sample variance. Keep nsn_s odd.
  • Too few points. If ns<2Mωmax⁡+1n_s < 2M\omega_{\max} + 1, the harmonics qωmax⁡q\omega_{\max} alias onto lower frequencies, and line L8 reads the wrong power.
  • Too few harmonics. A main effect with strong harmonics above Mωmax⁡M\omega_{\max} loses that power from DiD_i, so SiS_i is too low. Raise MM and ωmax⁡\omega_{\max} together.
  • Reading the error as noise. The gaps in the examples are biases from the bands, not sampling error. More phases (nrn_r) do not reduce them; only a larger ωmax⁡\omega_{\max} and MM with more points do.

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.

efast.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fourier-amplitude-sensitivity-test/. The authors are listed in prov/VVPHQA.jsonl.
"""The Fourier amplitude sensitivity test in its extended form (eFAST, Saltelli, Tarantola and Chan 1999).

For each input i, all inputs move along one search curve in the unit cube,

    x_j(s) = 1/2 + arcsin(sin(omega_j s + phi_j)) / pi,   s in (-pi, pi),

with a high frequency omega_i for input i and low frequencies for the others.
Each x_j(s) is uniform on [0, 1] when s is uniform. The output y(s) = f(x(s))
is periodic in s, and its Fourier spectrum splits the variance: the power at
the harmonics q omega_i, q = 1..M, is the first order part D_i, and the power at
the frequencies up to omega_i / 2 belongs to the complementary inputs, so that
1 - D_(~i) / D is the total index. The phases phi_j are random, and the run is
repeated n_r times (resampling) to reduce the error from the curve.

The classic FAST of Cukier et al. 1973 uses one curve with a frequency set
for all inputs at once and gives the first order indices only.

The cost is d n_r n_s model runs, with n_s >= 2 M omega_max + 1 points per curve.
"""

import math
import random
from typing import Callable, Sequence

Model = Callable[[Sequence[float]], float]


def frequencies(d: int, i: int, omega_max: int, m: int) -> list[int]:
    """omega_i = omega_max, and the other inputs get frequencies in 1..floor(omega_max / (2 M)).

    If there is room, the d - 1 low frequencies are spread evenly over that range,
    else they cycle through it. Spread frequencies make the curve fill more of the
    subcube of the other inputs.
    """
    top = omega_max // (2 * m)
    if top < 1:
        raise ValueError("omega_max must be at least 2 M")
    rest = d - 1
    if rest == 1:
        low = [1]
    elif top >= rest:
        low = [1 + (top - 1) * k // (rest - 1) for k in range(rest)]
    else:
        low = [1 + k % top for k in range(rest)]
    out = list(low)
    out.insert(i, omega_max)
    return out


def search_points(omegas: Sequence[int], phases: Sequence[float], n_s: int) -> list[list[float]]:
    """The n_s points of the curve at s_k = pi (2k - n_s - 1) / n_s, k = 1..n_s, in the unit cube."""
    pts = []
    for k in range(1, n_s + 1):
        s = math.pi * (2 * k - n_s - 1) / n_s
        pts.append([0.5 + math.asin(math.sin(w * s + ph)) / math.pi for w, ph in zip(omegas, phases)])
    return pts


def spectrum(y: Sequence[float], n_s: int) -> list[float]:
    """The power Lambda_p = (A_p^2 + B_p^2) / 2 for p = 0..(n_s - 1) / 2 (Lambda_0 is unused).

    For odd n_s, the sum of Lambda_p over p >= 1 is the population variance of y (discrete Parseval).
    """
    half = (n_s - 1) // 2
    s = [math.pi * (2 * k - n_s - 1) / n_s for k in range(1, n_s + 1)]
    out = [0.0]
    for p in range(1, half + 1):
        a = 2.0 / n_s * sum(yk * math.cos(p * sk) for yk, sk in zip(y, s))
        b = 2.0 / n_s * sum(yk * math.sin(p * sk) for yk, sk in zip(y, s))
        out.append(0.5 * (a * a + b * b))
    return out


def efast(f: Model, d: int, omega_max: int, m: int, n_r: int, rng: random.Random, n_s: int = 0) -> dict:
    """First order and total indices of the d inputs of f on the unit cube [0, 1]^d."""
    if n_s == 0:
        n_s = 2 * m * omega_max + 1
    if n_s < 2 * m * omega_max + 1 or n_s % 2 == 0:
        raise ValueError("n_s must be odd and at least 2 M omega_max + 1")
    s_first, s_total, runs = [], [], 0
    for i in range(d):  # @line L1
        first = total = 0.0
        omegas = frequencies(d, i, omega_max, m)  # @line L2
        for _ in range(n_r):  # @line L3
            phases = [2 * math.pi * rng.random() for _ in range(d)]
            pts = search_points(omegas, phases, n_s)  # @line L4
            y = [f(x) for x in pts]  # @line L5
            runs += n_s
            lam = spectrum(y, n_s)  # @line L6
            var = sum(lam[1:])  # @line L7
            d_i = sum(lam[q * omega_max] for q in range(1, m + 1))  # @line L8
            d_rest = sum(lam[1 : omega_max // 2 + 1])  # @line L9
            first += d_i / var
            total += 1.0 - d_rest / var
        s_first.append(first / n_r)  # @line L10
        s_total.append(total / n_r)
    return {"S": s_first, "ST": s_total, "runs": runs, "n_s": n_s}
fourier_amplitude_sensitivity_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fourier-amplitude-sensitivity-test/. The authors are listed in prov/VVPHQA.jsonl.
"""Entry point named after the slug. The code lives in efast.py, because tools treat
a file whose name ends in _test.py as a test file and skip its line markers."""

from efast import efast, frequencies, search_points, spectrum

__all__ = ["efast", "frequencies", "search_points", "spectrum"]
test_fourier_amplitude_sensitivity_test.py 70 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fourier-amplitude-sensitivity-test/. The authors are listed in prov/VVPHQA.jsonl.
import math
import random

import pytest

from fourier_amplitude_sensitivity_test import efast, frequencies, search_points, spectrum


def ishigami_unit(u):
    x = [-math.pi + 2 * math.pi * v for v in u]
    return math.sin(x[0]) + 7 * math.sin(x[1]) ** 2 + 0.1 * x[2] ** 4 * math.sin(x[0])


ISHIGAMI_S = [0.3139, 0.4424, 0.0]
ISHIGAMI_ST = [0.5576, 0.4424, 0.2437]


def test_frequencies_put_the_high_one_at_input_i():
    assert frequencies(3, 1, 64, 4) == [1, 64, 8]
    assert frequencies(5, 0, 64, 4) == [64, 1, 3, 5, 8]
    with pytest.raises(ValueError):
        frequencies(3, 0, 7, 4)


def test_search_curve_has_uniform_marginals():
    pts = search_points([1, 11, 4], [0.3, 1.1, 2.0], 2001)
    for j in range(3):
        col = sorted(p[j] for p in pts)
        assert all(0.0 <= v <= 1.0 for v in col)
        assert abs(sum(col) / len(col) - 0.5) < 0.01
        assert abs(col[len(col) // 4] - 0.25) < 0.01


def test_spectrum_power_sums_to_the_variance():
    rng = random.Random(3)
    n_s = 257
    y = [rng.random() for _ in range(n_s)]
    m = sum(y) / n_s
    assert abs(sum(spectrum(y, n_s)[1:]) - sum((v - m) ** 2 for v in y) / n_s) < 1e-12


def test_cosine_model_is_exact():
    # cos(2 pi x_j) along the curve is a pure harmonic at 2 omega_j, so no power leaks
    c = [1.0, 2.0, 0.0, 3.0]
    f = lambda x: sum(cj * math.cos(2 * math.pi * xj) for cj, xj in zip(c, x))  # noqa: E731
    res = efast(f, 4, 32, 4, 2, random.Random(11))
    assert res["runs"] == 4 * 2 * res["n_s"]
    total = sum(cj * cj for cj in c)
    for i in range(4):
        assert abs(res["S"][i] - c[i] ** 2 / total) < 1e-9
        assert abs(res["ST"][i] - c[i] ** 2 / total) < 1e-9


def test_ishigami_first_order_and_total_indices():
    res = efast(ishigami_unit, 3, 64, 4, 1, random.Random(1))
    assert res["runs"] == 3 * 513
    for i in range(3):
        assert abs(res["S"][i] - ISHIGAMI_S[i]) < 0.03
        assert abs(res["ST"][i] - ISHIGAMI_ST[i]) < 0.06
    # x3 acts only through its interaction with x1
    assert res["ST"][2] - res["S"][2] > 0.15


def test_even_or_short_curves_are_rejected():
    with pytest.raises(ValueError):
        efast(ishigami_unit, 3, 16, 4, 1, random.Random(0), n_s=128)
    with pytest.raises(ValueError):
        efast(ishigami_unit, 3, 16, 4, 1, random.Random(0), n_s=101)

History

Cukier, Fortuin, Shuler, Petschek and Schaibly proposed FAST in 1973 in the Journal of Chemical Physics, to measure how uncertain rate constants change the concentrations of coupled chemical reactions. Schaibly and Shuler and later Cukier, Levine and Shuler developed the frequency choices and the theory in the 1970s. Saltelli, Tarantola and Chan (1999) showed how to get the total index from the low band and introduced the triangle wave curve and the random phases, which is the extended FAST in common use.

References

  1. R. I. Cukier, C. M. Fortuin, K. E. Shuler, A. G. Petschek and J. H. Schaibly, Study of the sensitivity of coupled reaction systems to uncertainties in rate coefficients. I Theory, Journal of Chemical Physics 59(8), 1973, 3873-3878, the search curve with incommensurate frequencies and the partial variances from the Fourier coefficients at the harmonics of each frequency
  2. A. Saltelli, S. Tarantola and K. P.-S. Chan, A quantitative model-independent method for global sensitivity analysis of model output, Technometrics 41(1), 1999, 39-56, the extended FAST, the search curve 1/2 + arcsin(sin(omega s + phi))/pi, the total index from the low frequency band, the frequency rules and the resampling with random phases
  3. Andrea Saltelli, Marco Ratto, Terry Andres, Francesca Campolongo, Jessica Cariboni, Debora Gatelli, Michaela Saisana and Stefano Tarantola, Global Sensitivity Analysis, The Primer, Wiley, 2008, Chapter 4 (FAST and the extended FAST among the variance-based methods)

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