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
- 29Polynomial chaos expansionEffective dimension and ANOVA decompositionRandomized quasi-Monte CarloNon-intrusive polynomial chaosCompartmental models
- 03Variational equation and sensitivitiesAdjoint sensitivity method
- 09Forward-mode automatic differentiationReverse-mode automatic differentiation
- 05Nonparametric bootstrapBootstrap percentile and basic intervals
- 02Spectral theorem
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 measures changes near a nominal point. If and are nonzero, 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 , direct sensitivities satisfy
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 , the elementary effect is , including the displacement sign. Mean absolute effect detects large effects even if their sign changes, and its deviation indicates that the effect varies among trajectories. A large may arise from nonlinearity, interaction or both; it does not separate them alone.
Morris is screening dependent on ranges and design, not an exact variance allocation. A coordinate with small deserves an additional check before being fixed.
Decomposing variance
For independent inputs and , the ANOVA decomposition defines and recursively . Terms are orthogonal and
Sobol indices are and . 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 with both inputs uniform on , and . Conditioning on gives , whose variance is ; conditioning on gives , with variance . Residual interaction contributes . Thus , , and . First-order indices need not sum to one when interactions exist.
The Ishigami function illustrates the danger of fixing : , although can be large. Inputs are independent uniform on .
Estimating with coupled samples
The Saltelli and Jansen estimators take independent matrices with rows and form by replacing column of with that of . A shared realization in the other columns allows estimation of
The first numerator estimates : and share only , while and are independent. The second estimates . 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 of terms using only for , and of all terms using for ; divide by . These are surrogate indices: validate it first. Sudret develops this connection.
An active subspace diagonalizes under the input distribution. Leading eigenvectors are directions of average variation; each input’s scale changes . A spectral gap suggests approximating by a function of a few projections, but does not guarantee a good surrogate at every point.
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 and final time : eight parameters. The output is fraction , which includes vaccinated individuals, not a forecast or real mortality rate. Time is rescaled to and gradients to uniform coordinates .
With , equations in physical time are
Daily rates range over , , , and . Fractions range over and ranges from 20 to 60 days; and . 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 and totals for .
"""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')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 ; 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.
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)))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)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 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.
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
Step 1 of 3. What mean does Qᵤ have when integrating any of its variables?
import numpy as np
def sobol_indices(f,d,N,sampler):
pass