Adaptive PCE

This notebook is an example of UncertainSCI’s functionality to adaptively determine the needed polynomial order of a given model and parameter set. This example is equivalent to demos/adapt_pce.py

from itertools import chain, combinations

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.animation as animation

from UncertainSCI.distributions import BetaDistribution
from UncertainSCI.model_examples import KLE_exponential_covariance_1d, \
                                        laplace_ode, laplace_grid_x
from UncertainSCI.indexing import TotalDegreeSet
from UncertainSCI.pce import PolynomialChaosExpansion
from UncertainSCI.utils.version import version_lessthan

# some features work better with this option
%matplotlib notebook

Adaptive PCE Setup

Three things must be specified:

  • The physical model

  • A parameter distribution

  • The initial expressivity of the PCE (polynomial space)

Define Forward model

The model in this example is a 1D laplacian ODE. See the laplace_ode_1d method or UncertainSCI/model_examples.py for details.

\[ -\frac{d}{dx} a(x,p) \cdot \frac{d}{dx} u(x,p) = f(x) \]

over \(x\) in \([-1,1]\), where \(a(x,p)\) is a parameterized diffusion model:

\[ a(x,p) = \bar{x} + \sum_{j=1}^d \lambda_j p_j \phi_j(x) \]

where \(d\) is the dimension, (\(\lambda_j\), \(\phi_j\)) are eigenpairs of the exponential covariance kernel,

\[ K(s,t) = e^{-|s-t|/a}. \]

The \(p_j\) are modeled as random variables.

# Number of parameters
dimension = 2

# Define diffusion coefficient
a = 1.
b = 1.  # Interval is [-b,b]
abar = lambda x: 1*np.ones(np.shape(x))
KLE = KLE_exponential_covariance_1d(dimension, a, b, abar)

diffusion = lambda x, p: KLE(x, p)

N = int(1e2)  # Number of spatial degrees of freedom of model
left = -1.
right = 1.
x = laplace_grid_x(left, right, N)

model = laplace_ode(left=left, right=right, N=N, diffusion=diffusion)

Parameter Distributions

We are using two model parameters with the same beta distribution for this example.

# Specifies 1D distribution on [0,1] (alpha=beta=1 ---> uniform)
alpha = 1.
beta = 1.
dist = BetaDistribution(alpha=alpha, beta=beta, dim=dimension)

Initial Expressivity of the PCE

This example uses a different setup than you might see in other examples. Other setups will be equivalent for many non-adaptive cases, but it is useful to operate with the index set in this example. Another important distinction that is necessary for the adaptive case is supplying the model as a lambda function to the PCE object.

# Expressivity setup
order = 0
index_set = TotalDegreeSet(dim=dimension, order=order)
starting_indices = index_set.get_indices()
# Building the PCE
pce = PolynomialChaosExpansion(index_set, dist)
pce.build(model=model)
Nstarting_samples = pce.samples.shape[0]
initial_accuracy = pce.accuracy_metrics.copy()
Directory data_set created
Precomputing data for Jacobi parameters (alpha,beta) = (0.000000, 0.000000)...
Done

Running Adaptive PCE

With the initial PCE setup, we can run adaptive method. This will attempt to find the best order to represent the uncertainty for the given model and parameter distributions. The method will add new samples as needed to minimize the residual error between iterations. This may take a few minutes to run from scratch.

# pce.adapt_robustness(max_new_samples=50)
residuals, loocvs, added_indices, added_samples = pce.adapt_expressivity(max_new_samples=100, add_rule=3)
Precomputing data for Jacobi parameters (alpha,beta) = (0.000000, 0.000000)...
Done
new indices:      1,   new samples:      4
old residual: 2.967e-01,  old loocv: 1.521e-01
new residual: 1.364e-02,  new loocv: 2.997e-02
Precomputing data for Jacobi parameters (alpha,beta) = (0.000000, 0.000000)...
Done
new indices:      1,   new samples:      4
old residual: 1.364e-02,  old loocv: 2.997e-02
new residual: 5.315e-03,  new loocv: 1.562e-02
Precomputing data for Jacobi parameters (alpha,beta) = (0.000000, 0.000000)...
Done
new indices:      1,   new samples:      4
old residual: 5.315e-03,  old loocv: 1.562e-02
new residual: 3.729e-03,  new loocv: 1.206e-02
Precomputing data for Jacobi parameters (alpha,beta) = (0.000000, 0.000000)...
Done
new indices:      1,   new samples:      4
old residual: 3.729e-03,  old loocv: 1.206e-02
new residual: 3.472e-03,  new loocv: 1.080e-02
new indices:      1,   new samples:      4
old residual: 3.472e-03,  old loocv: 1.080e-02
new residual: 3.569e-04,  new loocv: 3.384e-03
Precomputing data for Jacobi parameters (alpha,beta) = (0.000000, 0.000000)...
Done
new indices:      1,   new samples:      4
old residual: 3.569e-04,  old loocv: 3.384e-03
new residual: 4.332e-04,  new loocv: 3.560e-03
Precomputing data for Jacobi parameters (alpha,beta) = (0.000000, 0.000000)...
Done
new indices:      1,   new samples:      4
old residual: 4.332e-04,  old loocv: 3.560e-03
new residual: 4.499e-04,  new loocv: 3.393e-03
new indices:      1,   new samples:      4
old residual: 4.499e-04,  old loocv: 3.393e-03
new residual: 5.433e-05,  new loocv: 1.270e-03
Precomputing data for Jacobi parameters (alpha,beta) = (0.000000, 0.000000)...
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
Cell In[6], line 2
      1 # pce.adapt_robustness(max_new_samples=50)
----> 2 residuals, loocvs, added_indices, added_samples = pce.adapt_expressivity(max_new_samples=100, add_rule=3)

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/pce.py:395, in PolynomialChaosExpansion.adapt_expressivity(self, max_new_samples, **chase_bulk_options)
    393 while self.samples.shape[0] < max_new_samples + Mold:
    394     samples_left = max_new_samples + Mold - self.samples.shape[0]
--> 395     a, b = self.chase_bulk(max_new_samples=samples_left, **chase_bulk_options)
    396     indices.append(self.index_set.get_indices()[-a:, :])
    397     sample_count.append(b)

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/pce.py:503, in PolynomialChaosExpansion.chase_bulk(self, delta, max_new_samples, max_new_indices, add_rule, mult_rule, verbosity)
    500 Nsamples = samplefun(Nindices)
    502 self.weights = weights
--> 503 self.generate_samples(new_samples=Nsamples)
    505 # Resample model
    506 self.model_output = np.vstack((self.model_output,
    507                                np.zeros([Nsamples, self.model_output.shape[1]])))

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/pce.py:229, in PolynomialChaosExpansion.generate_samples(self, **kwargs)
    226     else:  # Add new_samples random samples
    227         x = self.map_to_standard_space(self.samples)
--> 229         x = self.distribution.polys.wafp_sampling_restart(
    230                 self.index_set.get_indices(), x, new_samples,
    231                 **self.sampling_options)
    233         self.samples = self.map_to_model_space(x)
    235 elif self.sampling.lower() == 'gq':

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/opolynd.py:258, in TensorialPolynomials.wafp_sampling_restart(self, indices, samples, Nnewsamples, weights, sampler, fast_sampler)
    255 for q in range(Nnewsamples):
    257     if sampler == 'idist':
--> 258         x = self.idist_mixture_sampling(Ncandidates, indices,
    259                                         weights=weights,
    260                                         fast_sampler=fast_sampler)
    261     else:
    262         raise ValueError('Unrecognized string "{0:s}" for input \
    263                           "sampler"'.format(sampler))

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/opolynd.py:164, in TensorialPolynomials.idist_mixture_sampling(self, M, Lambdas, weights, fast_sampler)
    161     else:
    162         idistinv = self.polys1d[qd].idistinv
--> 164     x[:, qd] = idistinv(np.random.random(M), Lambdas[:, qd])
    165 return x

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/families.py:429, in JacobiPolynomials.fidistinv(self, u, n)
    427 msg = 'Precomputing data for Jacobi parameters (alpha,beta) = ({0:1.6f}, {1:1.6f})...'
    428 print(msg.format(self.alpha, self.beta), end='', flush=True)
--> 429 data = self.fidistinv_jacobi_setup(nmax, data)
    430 with open(os.path.join(path, filename), 'wb') as f:
    431     pickle.dump(data, f)

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/families.py:397, in JacobiPolynomials.fidistinv_jacobi_setup(self, n, data)
    394     def idistinv(u):
    395         return self.idistinv(u, nn)
--> 397     data.append(fidistinv_setup_helper2(ug, idistinv, exponents, 10, self.alpha, self.beta))  # , E_n?
    399 return data

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/families.py:178, in fidistinv_setup_helper2(ug, idistinv, exponents, M, alpha, beta)
    176     xgrid[:, q] = 2 * bbeta.ppf(ugrid[:, q], beta+1, alpha+1) - 1
    177 else:
--> 178     xgrid[:, q] = idistinv(ugrid[:, q])
    180 temp = xgrid[:, q]
    182 # temp = temp(ugrid)
    183 # for ugrid near 0, then temp behaves like a certain rational function (1-ugrid)**???

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/families.py:395, in JacobiPolynomials.fidistinv_jacobi_setup.<locals>.idistinv(u)
    394 def idistinv(u):
--> 395     return self.idistinv(u, nn)

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/families.py:334, in JacobiPolynomials.idistinv(self, u, n)
    331         return self.idist(xx, n, M=M)
    333     ab = self.recurrence_driver(2*n + M+1)
--> 334     x = idistinv_driver(u, n, primitive, ab, supp)
    336 else:
    337     nmax = int(np.amax(n))

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/opoly1d.py:321, in idistinv_driver(u, n, primitive, ab, supp)
    319 x = np.zeros(u.size,)
    320 for j in range(u.size):
--> 321     x[j] = optimize.bisect(lambda xx: np.asarray(primitive(xx)).item() - u[j], intervals[j, 0], intervals[j, 1])
    323 return x

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/scipy/optimize/_zeros_py.py:607, in bisect(f, a, b, args, xtol, rtol, maxiter, full_output, disp)
    605     raise ValueError(f"rtol too small ({rtol:g} < {_rtol:g})")
    606 f = _wrap_nan_raise(f)
--> 607 r = _zeros._bisect(f, a, b, xtol, rtol, maxiter, args, full_output, disp)
    608 return results_c(full_output, r, "bisect")

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/scipy/optimize/_zeros_py.py:107, in _wrap_nan_raise.<locals>.f_raise(x, *args)
    106 def f_raise(x, *args):
--> 107     fx = f(x, *args)
    108     f_raise._function_calls += 1
    109     if np.isnan(fx):

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/opoly1d.py:321, in idistinv_driver.<locals>.<lambda>(xx)
    319 x = np.zeros(u.size,)
    320 for j in range(u.size):
--> 321     x[j] = optimize.bisect(lambda xx: np.asarray(primitive(xx)).item() - u[j], intervals[j, 0], intervals[j, 1])
    323 return x

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/families.py:331, in JacobiPolynomials.idistinv.<locals>.primitive(xx)
    330 def primitive(xx):
--> 331     return self.idist(xx, n, M=M)

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/families.py:312, in JacobiPolynomials.idist(self, x, n, M)
    310 F = np.zeros(x.size, )
    311 mrs_centroid = self.idist_medapprox(n)
--> 312 F[np.where(x <= mrs_centroid)] = jacobi_idist_driver(x[np.where(x <= mrs_centroid)], n, self.alpha, self.beta, M)
    313 F[np.where(x > mrs_centroid)] = 1 - jacobi_idist_driver(-x[np.where(x > mrs_centroid)], n, self.beta, self.alpha, M)
    315 return F

File ~/checkouts/readthedocs.org/user_builds/uncertainsci/envs/latest/lib/python3.12/site-packages/UncertainSCI/families.py:131, in jacobi_idist_driver(x, n, alpha, beta, M)
    128     u, w = gauss_quadrature_driver(ab, M)
    130     Ival = np.sum(w * (2 - 1/2 * (u+1) * (x[ind]+1))**Aa)
--> 131     F[ind] = np.exp(logfactor - alpha*np.log(2) - sp.betaln(beta+1, alpha+1) -
    132                     np.log(beta+1) + (beta+1) * np.log((x[ind]+1)/2)) * Ival
    134 return F

KeyboardInterrupt: 

Output Statistics

With the optimal polynomial order determined, computing the output statistics is as straightforward as other examples.

# # Postprocess PCE: mean, stdev, sensitivities, quantiles
mean = pce.mean()
stdev = pce.stdev()
# Set of subsets of [0, 1, ..., dimension-1] with at most 3 components
variable_interactions = list(chain.from_iterable(combinations(range(dimension), r) for r in range(1, 3+1)))
# "Total sensitivity" is a non-partitive relative sensitivity measure per
# parameter.
total_sensitivity = pce.total_sensitivity()
# "Global sensitivity" is a partitive relative sensitivity measure per set of
# parameters.
global_sensitivity = pce.global_sensitivity(variable_interactions)
# Quantile bands, similar to a box plot
# used for PCE and MC
Q = 3  # Number of quantile bands to plot
dq = 0.5/(Q+1)
q_lower = np.arange(dq, 0.5-1e-7, dq)[::-1]
q_upper = np.arange(0.5 + dq, 1.0-1e-7, dq)
quantile_levels = np.append(np.concatenate((q_lower, q_upper)), 0.5)

Monte Carlo Statistics

Here we compute the output statistics using Monte Carlo (MC) sampling to compare to the adaptive PCE method.

# # For comparison: Monte Carlo statistics
M = 1000  # Generate MC samples
p_phys = dist.MC_samples(M)
output = np.zeros([M, N])

for j in range(M):
    output[j, :] = model(p_phys[j, :])

MC_mean = np.mean(output, axis=0)
MC_stdev = np.std(output, axis=0)
if version_lessthan(np,'1.15'):
    from scipy.stats.mstats import mquantiles
    MC_quantiles = mquantiles(output, quantile_levels, axis=0)
else:
    MC_quantiles = np.quantile(output, quantile_levels, axis=0)
MC_median = MC_quantiles[-1, :]

Visualize Statistics

Similar to other examples, we will plot the uncertainty over the domain of the domain of the model. This example shows how users might do so more manually instead of using the built in plotting functions

Plotting Setup

To plot our output statistics we are going to compute the quantile bands that we will visualize

quantiles = pce.quantile(quantile_levels, M=int(2e3))
median = quantiles[-1, :]

Single Domain Plot Comparison

Plotting the mean and standard deviation for both PCE and MC. Each are plotted a different way to help differentiate them.

# # Visualization
V = 50  # Number of MC samples to visualize

# mean +/- stdev plot
plt.plot(x, output[:V, :].T, 'k', alpha=0.8, linewidth=0.2)
plt.plot(x, mean, 'b', label='PCE mean')
plt.fill_between(x, mean-stdev, mean+stdev, interpolate=True, facecolor='red',
                 alpha=0.5, label='PCE 1 stdev range')

plt.plot(x, MC_mean, 'b:', label='MC mean')
plt.plot(x, MC_mean+MC_stdev, 'r:', label='MC mean $\\pm$ stdev')
plt.plot(x, MC_mean-MC_stdev, 'r:')

plt.xlabel('x')
plt.title('Mean $\\pm$ standard deviation')

plt.legend(loc='lower right')

Side-by-Side Domain Plot Comparison

Here we plot similar data to the previous figure, but with two plots to allow the quantile bands to be shown for each method.

# quantile plot
plt.figure()


plt.subplot(121)
plt.plot(x, pce.model_output[:V, :].T, 'k', alpha=0.8, linewidth=0.2)
plt.plot(x, median, 'b', label='PCE median')

band_mass = 1/(2*(Q+1))

for ind in range(Q):
    alpha = (Q-ind) * 1/Q - (1/(2*Q))
    if ind == 0:
        plt.fill_between(x, quantiles[ind, :], quantiles[Q+ind, :],
                         interpolate=True, facecolor='red', alpha=alpha,
                         label='{0:1.2f} probability mass (each band)'.format(band_mass))
    else:
        plt.fill_between(x, quantiles[ind, :], quantiles[Q+ind, :],
                         interpolate=True, facecolor='red', alpha=alpha)

plt.title('PCE Median + quantile bands')
plt.xlabel('x')
plt.legend(loc='lower right')

plt.subplot(122)
plt.plot(x, output[:V, :].T, 'k', alpha=0.8, linewidth=0.2)
plt.plot(x, MC_median, 'b', label='MC median')

for ind in range(Q):
    alpha = (Q-ind) * 1/Q - (1/(2*Q))
    if ind == 0:
        plt.fill_between(x, MC_quantiles[ind, :], MC_quantiles[Q+ind, :],
                         interpolate=True, facecolor='red',
                         alpha=alpha,
                         label='{0:1.2f} probability mass (each band)'
                         .format(band_mass))
    else:
        plt.fill_between(x, MC_quantiles[ind, :], MC_quantiles[Q+ind, :],
                         interpolate=True, facecolor='red', alpha=alpha)

plt.title('MC Median + quantile bands')
plt.xlabel('x')
plt.legend(loc='lower right')

Parameter Sensitivity Estimated with PCE

The pie chart shows the global sensitivity of the model to each parameter averaged over the domain. Global sensitivities can help differentiate model sensitivity from a single parameter and parameter interactions.

# Sensitivity pie chart, averaged over all model degrees of freedom
average_global_SI = np.sum(global_sensitivity, axis=1)/N

labels = ['[' + ' '.join(str(elem) for elem in [i+1 for i in item]) +
          ']' for item in variable_interactions]
_, ax = plt.subplots()
ax.pie(average_global_SI*100, labels=labels, autopct='%1.1f%%',
       startangle=90)
ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
plt.title('Sensitivity due to variable interactions')

Regression Plots

The regression plots in this section help illustrate the choices of the adaptive PCE method.

# Index set plot
fig = plt.figure()

plt.subplot(121)

current_inds = plt.plot(starting_indices[:, 0], starting_indices[:, 1],
                        'k.', markersize=20, label='Current indices')[0]
rmargin = plt.plot([], [], 'bo', markersize=10, fillstyle='none',
                   label='Candidates')[0]
future_inds = plt.plot([], [], 'rx', markersize=15,
                       label='Chosen indices')[0]

plt.legend(frameon=False)

indices = pce.index_set.get_indices()
maxx, maxy = indices[:, 0].max(), indices[:, 1].max()
plt.axis([-0.5, maxx+1.5, -0.5, maxy+1.5])
plt.gca().set_yticks(range(maxy+2), minor=False)
plt.gca().set_xticks(range(maxx+2), minor=False)
plt.grid()
plt.xlabel('Degree in $p_1$')
plt.ylabel('Degree in $p_2$')

plt.subplot(122)
added_samples_plt = added_samples[:] # shallow copy
added_samples_plt.insert(0, Nstarting_samples)
Nsamples = np.cumsum(added_samples_plt)

plt.semilogy(Nsamples, residuals, 'k-', label='Residual')
plt.semilogy(Nsamples, loocvs, 'k--', label='LOOCV')
current_accuracy = plt.plot([], [], 'rx', markersize=15)[0]
plt.xlabel('Total model queries')
plt.legend(frameon=False)

def animation_init():
    return current_inds, future_inds, rmargin, current_accuracy

def animation_update(i):
    index_set = TotalDegreeSet(dim=dimension, order=order)
    for q in range(i):
        index_set.augment(added_indices[q])

    current_set = index_set.get_indices()
    reduced_margin = index_set.get_reduced_margin()

    current_inds.set_data(current_set[:, 0], current_set[:, 1])
    rmargin.set_data(reduced_margin[:, 0], reduced_margin[:, 1])
    future_inds.set_data(added_indices[i][:, 0], added_indices[i][:, 1])
    current_accuracy.set_data([Nsamples[i+1], Nsamples[i+1]],
                              [residuals[i+1], loocvs[i+1]])

    return current_inds, future_inds, rmargin, current_accuracy

ani = animation.FuncAnimation(fig, animation_update,
                              np.arange(0, len(added_indices)),
                              interval=500, blit=True,
                              init_func=animation_init, repeat=False)