Module contents
Lesson 17 of 27Advanced 100 min

Local and global sensitivity analysis

Explore parameter importance through local sensitivities, Morris screening, Sobol variance decomposition, polynomial chaos and active subspaces.

After this lesson you can

  • Calculate normalized local sensitivities of an ODE model by direct sensitivity equations or automatic differentiation.
  • Apply Morris screening to distinguish negligible, linear and nonlinear or interacting parameters.
  • Define Sobol indices through ANOVA and implement Saltelli and Jansen estimators with bootstrap intervals.
  • Obtain Sobol indices analytically from polynomial-chaos coefficients.
  • Discover an active subspace from gradients and construct a low-dimensional surrogate.

Before you start

Which parameter matters?

In a twenty-parameter epidemiological model, perhaps only three can be measured. The answer depends on the output, range and input distribution. Local sensitivity ∂Q/∂θi\partial Q/\partial\theta_i measures changes near a nominal point. If QQ and θi\theta_i are nonzero, θiQ−1∂Q/∂θi\theta_i Q^{-1}\partial Q/\partial\theta_i is a dimensionless elasticity. At zero another scale is needed, such as the range width. A small local value does not establish that the parameter is irrelevant over the entire domain.

For y˙=f(y,θ,t)\dot y=f(y,\theta,t), direct sensitivities si=∂y/∂θis_i=\partial y/\partial\theta_i satisfy

s˙i=fysi+fθi,si(0)=∂y0/∂θi.\dot s_i=f_y s_i+f_{\theta_i},\qquad s_i(0)=\partial y_0/\partial\theta_i.

There is one vector equation per parameter. An adjoint is often convenient with many parameters and few scalar outputs; automatic differentiation and finite differences are other routes. Differences require studying step size. Differentiating the continuous model and then discretizing is not automatically equivalent to differentiating any discrete implementation.

Morris screening

The Morris method evaluates trajectories on a grid: each step changes one coordinate. For parameter ii, the elementary effect is (Q(x+Δei)−Q(x))/Δ(Q(x+\Delta e_i)-Q(x))/\Delta, including the displacement sign. Mean absolute effect μi∗\mu_i^* detects large effects even if their sign changes, and its deviation σi\sigma_i indicates that the effect varies among trajectories. A large σ\sigma may arise from nonlinearity, interaction or both; it does not separate them alone.

InteractiveMorris trajectories

A trajectory changes one coordinate per step; the oblique projection may overlap points.

  • x1
  • x2
  • x3

Horizontal axis μ*, vertical axis σ. Deviation combines nonlinearity and interaction and does not distinguish them alone.

10
μ* per parameter1.433 / 1.400 / 0.010
σ per parameter0.446 / 0.263 / 0.000
A projected trajectory is shown and its effects are accumulated with preceding ones.

Morris is screening dependent on ranges and design, not an exact variance allocation. A coordinate with small μ∗\mu^* deserves an additional check before being fixed.

Decomposing variance

For independent inputs and Q∈L2Q\in L^2, the ANOVA decomposition defines Q∅=EQQ_\varnothing=\mathbb EQ and recursively Qu=E[Q∣Xu]−∑v⊊uQvQ_u=\mathbb E[Q\mid X_u]-\sum_{v\subsetneq u}Q_v. Terms are orthogonal and

Q=Q∅+∑∅≠uQu,V=Var⁡(Q)=∑u≠∅Vu.Q=Q_\varnothing+\sum_{\varnothing\ne u}Q_u,\qquad V=\operatorname{Var}(Q)=\sum_{u\ne\varnothing}V_u.

Sobol indices are Si=V{i}/VS_i=V_{\{i\}}/V and STi=∑u∋iVu/VS_{T_i}=\sum_{u\ni i}V_u/V. The first measures the isolated effect, while the total includes all interactions. With correlated inputs this orthogonal decomposition and its standard interpretation no longer apply directly.

For example, for f(X1,X2)=X1+X1X2f(X_1,X_2)=X_1+X_1X_2 with both inputs uniform on [0,1][0,1], Ef=3/4\mathbb Ef=3/4 and V=31/144V=31/144. Conditioning on X1X_1 gives E[f∣X1]=3X1/2\mathbb E[f\mid X_1]=3X_1/2, whose variance is 27/14427/144; conditioning on X2X_2 gives (1+X2)/2(1+X_2)/2, with variance 3/1443/144. Residual interaction contributes 1/1441/144. Thus S1=27/31S_1=27/31, S2=3/31S_2=3/31, ST1=28/31S_{T_1}=28/31 and ST2=4/31S_{T_2}=4/31. First-order indices need not sum to one when interactions exist.

The Ishigami function f=sin⁡x1+asin⁡2x2+bx34sin⁡x1f=\sin x_1+a\sin^2x_2+b x_3^4\sin x_1 illustrates the danger of fixing x3x_3: S3=0S_3=0, although ST3S_{T_3} can be large. Inputs are independent uniform on [−π,π][-\pi,\pi].

InteractiveIshigami anatomy

Surface in the (x₁,x₃) plane at x₂=π/4, shown in oblique projection. Three slices of that surface appear below.

  • x₃ = 0
  • x₃ = π/2
  • x₃ = π
x1 S=0.314 ST=0.558
x2 S=0.442 ST=0.442
x3 S=0.000 ST=0.244

The bar represents the total index; S values show first order. x₃ has zero first order but participates in the interaction with x₁.

7.0
0.10
Interaction 1 and 30.2437
Total variance13.845
Surface and three slices at x₂=π/4; index bars are calculated analytically.

Estimating with coupled samples

The Saltelli and Jansen estimators take independent matrices A,BA,B with NN rows and form AB(i)A_B^{(i)} by replacing column ii of AA with that of BB. A shared realization in the other columns allows estimation of

S^i=N−1∑k(f(Bk)−fˉ)(f(AB,k(i))−f(Ak))V^,S^Ti=∑k(f(Ak)−f(AB,k(i)))22NV^.\widehat S_i=\frac{N^{-1}\sum_k (f(B_k)-\bar f)(f(A_{B,k}^{(i)})-f(A_k))}{\widehat V}, \qquad \widehat S_{T_i}=\frac{\sum_k(f(A_k)-f(A_{B,k}^{(i)}))^2}{2N\widehat V}.

The first numerator estimates ViV_i: BB and AB(i)A_B^{(i)} share only XiX_i, while AA and BB are independent. The second estimates V−V−iV-V_{-i}. N(d+2)N(d+2) evaluations are needed, except for reuse. Finite estimators can be negative or greater than one; do not clip them without disclosure. Independent randomized Sobol replicates estimate between-replicate variability. Paired-row bootstrap is natural for IID rows; applied to dependent QMC points here it is a descriptive diagnostic, not a guaranteed interval. See the SALib documentation.

Subtracting the mean in the first-order estimator does not change its limit, but prevents a large output constant from amplifying finite-estimate noise. Comparing implementations requires agreeing on which matrix is mixed, how variance is calculated and how outputs are normalized; small differences can arise from these conventions rather than a different population index.

From PCE and gradients to indices

In an orthonormal polynomial basis for independent inputs, each nonconstant coefficient belongs to the interaction given by the indices of variables that appear. Indices from PCE sum cν2c_\nu^2 of terms using only ii for SiS_i, and of all terms using ii for STiS_{T_i}; divide by ∑ν≠0cν2\sum_{\nu\ne0}c_\nu^2. These are surrogate indices: validate it first. Sudret develops this connection.

An active subspace diagonalizes C=E[∇Q∇QT]C=\mathbb E[\nabla Q\nabla Q^\mathsf T] under the input distribution. Leading eigenvectors are directions of average variation; each input’s scale changes CC. A spectral gap suggests approximating QQ by a function of a few projections, but does not guarantee a good surrogate at every point.

InteractiveThe hidden ridge
  • 300 evaluations
1
2
3
4
5
6
7
8
9
10

Eigenvalues of C=mean(∇f∇fᵀ): this exact ridge example has rank one. A gap observed in finite data does not guarantee exact reduction for another model.

Horizontal axis
Largest eigenvalue fraction100.00 %
Leading eigenvalue2.1114
Exact rank-one synthetic example; switch between the active direction and an original coordinate.

Lab: Ishigami and SEIR

The library implements Morris, Saltelli/Jansen, bootstrap, PCE and a normalized SEIR with RK4 and direct sensitivity equations. Independent inputs are uniform over ranges stated in code. SEIR has transmission, incubation, recovery, immunity loss and vaccination rates, initial conditions E0,I0E_0,I_0 and final time TT: eight parameters. The output is fraction R(T)R(T), which includes vaccinated individuals, not a forecast or real mortality rate. Time is rescaled to [0,1][0,1] and gradients to uniform coordinates [0,1]8[0,1]^8.

With S+E+I+R=1S+E+I+R=1, equations in physical time are

S˙=−βSI+ωR−vS,E˙=βSI−σE,I˙=σE−γI,R˙=γI−ωR+vS.\begin{aligned} \dot S&=-\beta SI+\omega R-vS,&\dot E&=\beta SI-\sigma E,\\ \dot I&=\sigma E-\gamma I,&\dot R&=\gamma I-\omega R+vS. \end{aligned}

Daily rates range over β∈[0.2,0.6]\beta\in[0.2,0.6], σ∈[0.12,0.35]\sigma\in[0.12,0.35], γ∈[0.08,0.22]\gamma\in[0.08,0.22], ω∈[0,0.04]\omega\in[0,0.04] and v∈[0,0.02]v\in[0,0.02]. Fractions E0,I0E_0,I_0 range over [0.002,0.01][0.002,0.01] and TT ranges from 20 to 60 days; S(0)=1−E0−I0S(0)=1-E_0-I_0 and R(0)=0R(0)=0. The lab assumes independence across those eight ranges. They have not been calibrated to a specific epidemic.

Run the library and then the cells in order. Ishigami has exact first-order indices approximately (0.3139,0.4424,0)(0.3139,0.4424,0) and totals (0.5576,0.4424,0.2437)(0.5576,0.4424,0.2437) for a=7,b=0.1a=7,b=0.1.

[ ]Sensitivity methods from scratchBrowser
"""Sensibilidad local y global: Ishigami y SEIR."""
import numpy as np
from scipy.stats import qmc
from numpy.polynomial.legendre import legvander

def ishigami(x,a=7.,b=.1):
    x=np.asarray(x);return np.sin(x[:,0])+a*np.sin(x[:,1])**2+b*x[:,2]**4*np.sin(x[:,0])

def ishigami_exact(a=7.,b=.1):
    v1=(1+b*np.pi**4/5)**2/2;v2=a*a/8;v13=8*b*b*np.pi**8/225;v=v1+v2+v13
    return np.array([v1,v2,0.])/v,np.array([v1+v13,v2,v13])/v

def sobol_indices(f,d,N,sampler):
    """A, B son columnas disjuntas de una muestra (N,2d) uniforme en [0,1]."""
    u=np.asarray(sampler(N,2*d))
    if u.shape!=(N,2*d):raise ValueError('sampler debe devolver (N,2d)')
    A=u[:,:d];B=u[:,d:];ya=f(A);yb=f(B);mix=[]
    for j in range(d):
        ab=A.copy();ab[:,j]=B[:,j];mix.append(f(ab))
    mix=np.stack(mix,axis=1);mean=np.mean(np.r_[ya,yb]);v=np.var(np.r_[ya,yb],ddof=1)
    if v<=0:raise ValueError('varianza nula')
    first=np.mean((yb[:,None]-mean)*(mix-ya[:,None]),axis=0)/v
    total=np.mean((ya[:,None]-mix)**2,axis=0)/(2*v)
    return first,total,(ya,yb,mix)

def bootstrap_sobol(raw,nboot=200,seed=4):
    """Remuestreo de filas emparejadas; para QMC es solo diagnóstico descriptivo."""
    a,b,m=raw;n=len(a);rng=np.random.default_rng(seed);first=[];total=[]
    for _ in range(nboot):
        ix=rng.integers(0,n,n);aa=a[ix];bb=b[ix];mm=m[ix];mean=np.mean(np.r_[aa,bb]);v=np.var(np.r_[aa,bb],ddof=1)
        first.append(np.mean((bb[:,None]-mean)*(mm-aa[:,None]),axis=0)/v)
        total.append(np.mean((aa[:,None]-mm)**2,axis=0)/(2*v))
    return np.quantile(first,[.025,.975],axis=0),np.quantile(total,[.025,.975],axis=0)

def morris(f,d,trajectories=100,seed=17,levels=4):
    if levels<4 or levels%2:raise ValueError('niveles pares >=4')
    rng=np.random.default_rng(seed);delta=levels/(2*(levels-1));paths=[];orders=[];directions=[]
    starts=np.arange(levels//2)/(levels-1)
    for _ in range(trajectories):
        signs=rng.choice([-1,1],d);start=rng.choice(starts,d);x=np.where(signs>0,start,1-start)
        path=[x.copy()];order=rng.permutation(d)
        for j in order:
            x=x.copy();x[j]+=signs[j]*delta;path.append(x.copy())
        paths.append(path);orders.append(order);directions.append(signs)
    paths=np.array(paths);values=np.asarray(f(paths.reshape(-1,d))).reshape(trajectories,d+1);e=np.zeros((trajectories,d))
    for k in range(trajectories):
        for step,j in enumerate(orders[k]):e[k,j]=(values[k,step+1]-values[k,step])/(directions[k][j]*delta)
    return np.mean(np.abs(e),axis=0),np.std(e,axis=0,ddof=1),paths,e

LOW=np.array([.2,.12,.08,.0,.0,.002,.002,20.])
HIGH=np.array([.6,.35,.22,.04,.02,.01,.01,60.])
def seir(u,steps=100,with_grad=False):
    """SEIR normalizado: parámetros sobre [0,1]^8; salida R(T), RK4."""
    u=np.asarray(u,dtype=float);p=LOW+(HIGH-LOW)*u
    beta,sigma,gamma,omega,v,e0,i0,T=p.T;n=len(u)
    y=np.column_stack((1-e0-i0,e0,i0,np.zeros(n)))
    sens=np.zeros((n,4,8));sens[:,0,5]=-1;sens[:,1,5]=1;sens[:,0,6]=-1;sens[:,2,6]=1
    def rhs(y,s):
        S,E,I,R=y.T;inc=beta*S*I
        F=np.stack((-inc+omega*R-v*S,inc-sigma*E,sigma*E-gamma*I,gamma*I-omega*R+v*S),axis=1)
        if not with_grad:return T[:,None]*F,None
        J=np.zeros((n,4,4));J[:,0,0]=-beta*I-v;J[:,0,2]=-beta*S;J[:,0,3]=omega
        J[:,1,0]=beta*I;J[:,1,1]=-sigma;J[:,1,2]=beta*S
        J[:,2,1]=sigma;J[:,2,2]=-gamma;J[:,3,0]=v;J[:,3,2]=gamma;J[:,3,3]=-omega
        D=np.zeros((n,4,8));D[:,0,0]=-S*I;D[:,1,0]=S*I;D[:,1,1]=-E;D[:,2,1]=E
        D[:,2,2]=-I;D[:,3,2]=I;D[:,0,3]=R;D[:,3,3]=-R;D[:,0,4]=-S;D[:,3,4]=S
        ds=T[:,None,None]*(np.einsum('nij,njk->nik',J,s)+D);ds[:,:,7]+=F
        return T[:,None]*F,ds
    h=1/steps
    for _ in range(steps):
        k1,g1=rhs(y,sens)
        k2,g2=rhs(y+h*k1/2,sens+h*g1/2 if with_grad else sens)
        k3,g3=rhs(y+h*k2/2,sens+h*g2/2 if with_grad else sens)
        k4,g4=rhs(y+h*k3,sens+h*g3 if with_grad else sens)
        y+=h*(k1+2*k2+2*k3+k4)/6
        if with_grad:sens+=h*(g1+2*g2+2*g3+g4)/6
    if with_grad:return y[:,3],sens[:,3,:]*(HIGH-LOW)[None,:]
    return y[:,3]

def pce_sobol(coeff,indices):
    idx=np.asarray(indices);c=np.asarray(coeff);var=np.sum(c[1:]**2)
    if var<=0:raise ValueError('varianza nula')
    first=np.array([sum(c[(idx[:,j]>0)&(np.count_nonzero(idx,axis=1)==1)]**2)/var for j in range(idx.shape[1])])
    total=np.array([sum(c[idx[:,j]>0]**2)/var for j in range(idx.shape[1])])
    return first,total

def pce_ishigami(degree=6,n=2048,seed=19):
    import itertools
    indices=[a for a in itertools.product(range(degree+1),repeat=3) if sum(a)<=degree]
    def basis(u):
        x=2*u-1;v=[legvander(x[:,j],degree)*np.sqrt(2*np.arange(degree+1)+1) for j in range(3)]
        return np.column_stack([v[0][:,a]*v[1][:,b]*v[2][:,c] for a,b,c in indices])
    rng=np.random.default_rng(seed);train=rng.random((n,3));y=ishigami(np.pi*(2*train-1))
    X=basis(train);coef=np.linalg.lstsq(X,y,rcond=None)[0]
    test=rng.random((1000,3));truth=ishigami(np.pi*(2*test-1));pred=basis(test)@coef
    return pce_sobol(coef,indices),np.sqrt(np.mean((pred-truth)**2)),np.linalg.cond(X)
print('sensibilidad lista')
[ ]Ishigami and SobolBrowser
def sampler(n,d):
    if n<1 or n&(n-1):raise ValueError('N debe ser potencia de dos')
    return qmc.Sobol(d,scramble=True,seed=42).random_base2(int(np.log2(n)))
f=lambda u:ishigami(np.pi*(2*u-1))
s,st,raw=sobol_indices(f,3,8192,sampler)
ci1,cit=bootstrap_sobol(raw)
print('exactos S, ST',ishigami_exact())
print('estimados S',s,'ST',st)
print('bootstrap descriptivo QMC S',ci1,'ST',cit)
print('evaluaciones',(3+2)*8192)
(pfirst,ptotal),rmse,cond=pce_ishigami()
print('PCE S',pfirst,'ST',ptotal,'RMSE independiente',rmse,'condición',cond)

The degree-six PCE is approximate and its RMSE is not zero. The bootstrap resamples paired rows to preserve A,B,AB(i)A,B,A_B^{(i)}; it does not make the QMC net IID.

To measure QMC variability, repeat the estimate with eight independent scramblings of 1024 points. Standard error across replicates refers to the mean of the eight estimates; with so few replicates it remains uncertain.

[ ]Independent QMC replicatesBrowser
rep=[]
for seed in range(8):
    sample=lambda n,d:qmc.Sobol(d,scramble=True,seed=seed).random_base2(int(np.log2(n)))
    s,st,_=sobol_indices(f,3,1024,sample)
    rep.append(np.r_[s,st])
rep=np.array(rep)
print('media de réplicas S y ST',rep.mean(axis=0))
print('SE entre réplicas de la media',rep.std(axis=0,ddof=1)/np.sqrt(len(rep)))
[ ]SEIR: screening and indicesBrowser
mu,sigma,_,_=morris(seir,8,100)
s,st,raw=sobol_indices(seir,8,1024,sampler)
ci1,cit=bootstrap_sobol(raw)
print('orden: beta, sigma, gamma, omega, vacunación, E0, I0, T')
print('Morris mu*',mu,'sigma',sigma)
print('Sobol S',s,'ST',st)
print('bootstrap descriptivo QMC ST',cit)
print('evaluaciones Morris',100*9,'Sobol',1024*10)
[ ]SEIR: gradients and subspaceBrowser
u=np.full((1,8),.5);y,g=seir(u,with_grad=True)
fd=[]
for j in range(8):
    a=u.copy();b=u.copy();a[:,j]+=1e-5;b[:,j]-=1e-5
    fd.append(float((seir(a)-seir(b))[0]/2e-5))
print('salida nominal',y,'gradiente normalizado',g)
nominal=(LOW+HIGH)/2
print('elasticidades nominales',g*nominal/(HIGH-LOW)/y[:,None])
print('máxima discrepancia con diferencias',np.max(abs(g-np.array(fd))))
print('refinamiento RK4 de 100 a 200 pasos',abs(seir(u,100)-seir(u,200)))
rng=np.random.default_rng(5);u=rng.random((400,8));y,g=seir(u,with_grad=True)
C=g[:300].T@g[:300]/300;val,vec=np.linalg.eigh(C);order=np.argsort(val)[::-1]
val=val[order];w=vec[:,order[0]];t=(u-.5)@w
coef=np.polyfit(t[:300],y[:300],5);prediction=np.polyval(coef,t[300:])
print('autovalores',val,'fracción principal',val[0]/val.sum())
print('RMSE independiente del sustituto unidimensional',np.sqrt(np.mean((prediction-y[300:])**2)))

The ridge fit uses 300 gradients and 100 test points; a leading fraction near 0.8 does not imply one-dimensional accuracy. The choice of output and ranges changes both sensitivities and the active direction.

The next comparison uses the same SALib matrices A,BA,B for Ishigami and the same custom trajectories for Morris on SEIR. SALib and our formula use slightly different sample-variance conventions: finite indices need not match bit for bit. Morris results do match for these trajectories.

[ ]Comparison with SALibBrowser
from SALib.sample import sobol as salib_sample
from SALib.analyze import sobol as salib_sobol, morris as salib_morris
problem={'num_vars':3,'names':['x1','x2','x3'],'bounds':[[-np.pi,np.pi]]*3}
N=1024
X=salib_sample.sample(problem,N,calc_second_order=False,seed=42)
Y=ishigami(X)
result=salib_sobol.analyze(problem,Y,calc_second_order=False,num_resamples=50,seed=3)
A=X[0::5];B=X[4::5]
ours=sobol_indices(lambda u:ishigami(np.pi*(2*u-1)),3,N,
                   lambda n,d:(np.c_[A,B]+np.pi)/(2*np.pi))
print('Ishigami SALib S',result['S1'],'ST',result['ST'])
print('Ishigami propios, mismas A y B',ours[0],ours[1])
print('máxima diferencia índices',max(np.max(abs(result['S1']-ours[0])),
                                      np.max(abs(result['ST']-ours[1]))))
problem8={'num_vars':8,'names':['beta','sigma','gamma','omega','v','E0','I0','T'],
          'bounds':[[0,1]]*8}
mu,sig,paths,_=morris(seir,8,100)
X=paths.reshape(-1,8);Y=seir(X)
result=salib_morris.analyze(problem8,X,Y,num_levels=4,num_resamples=50,seed=3)
print('Morris SALib mu*',result['mu_star'])
print('máxima diferencia Morris mu*, sigma',
      np.max(abs(mu-result['mu_star'])),np.max(abs(sig-result['sigma'])))

Exercises

ProofANOVA orthogonality
Prove: Justify the decomposition and variance allocation for independent inputs.
0
Define recursively Qᵤ=E[Q|Xᵤ]−Σᵥ⊊ᵤ Qᵥ.

Step 1 of 3. What mean does Qᵤ have when integrating any of its variables?

NumericFirst order
For f=x₁+x₁x₂ with independent uniform inputs on [0,1], what is S₁? Give at least four decimal places.
NumericTotal effect
For the same function, what is ST₂? Give at least four decimal places.
QuizSmall first order
If a parameter has small Sᵢ and large STᵢ, what is a prudent decision?
CodeSaltelli and Jansen
Implement sobol_indices(f,d,N,sampler): sampler(N,2*d) returns uniform rows; the first d columns are A and the rest B. Return arrays S and ST using the lesson's estimators. f takes matrices and returns a vector.
import numpy as np
def sobol_indices(f,d,N,sampler):
  pass
Shift+Enter to run
Key idea
Local sensitivity studies a neighborhood; Morris screens ranges, Sobol allocates variance under independence and active subspaces seek directions of average change.