In this example, we use the combigrid module for dimensional adaptivity.
First, we import the required modules.
import pysgpp
import numpy as np
import sys
try:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from pysgpp.extensions.combigrid.plotDeltas3d import plotDeltas3D
doPlot = True
except ImportError:
doPlot = False
def plotFunction(opEval, surpluses, X):
if not doPlot:
return
xx0 = np.linspace(0, 1, 65)
xx1 = np.linspace(0, 1, 65)
XX0, XX1 = np.meshgrid(xx0, xx1)
XX = pysgpp.DataMatrix(np.column_stack([XX0.flatten(), XX1.flatten()]))
YY = pysgpp.DataVector(0)
opEval.multiEval(surpluses, XX, YY)
YY = np.reshape(np.array([YY[k] for k in range(YY.getSize())]), XX0.shape)
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(projection="3d")
ax.plot_surface(XX0, XX1, YY)
ax.plot(X[:, 0], X[:, 1],
"k.", zs=
f(X[:, 0], X[:, 1]), ms=10)
dim = 2
n = 4
p = 3
hasBoundary = True
def f(XX0, XX1):
return np.sin(7*XX0-3)*np.cos(5*XX1-5)
pysgpp.Printer.getInstance().setVerbosity(-1)
basis1d = pysgpp.SBsplineBase(p)
basis = pysgpp.HeterogeneousBasis(dim, basis1d)
combiGrid = pysgpp.CombinationGrid.fromRegularSparse(
dim, n, basis, hasBoundary)
gridStorage = pysgpp.HashGridStorage(dim)
combiGrid.combinePoints(gridStorage)
X = np.array([[gridStorage.getPoint(k).getStandardCoordinate(d) for d in range(dim)]
for k in range(gridStorage.getSize())])
fX = pysgpp.DataVector(
f(X[:, 0], X[:, 1]))
values = pysgpp.DataVectorVector()
combiGrid.distributeValuesToFullGrids(gridStorage, fX, values)
surpluses = pysgpp.DataVectorVector(values)
opPole = pysgpp.OperationPoleVector()
pysgpp.OperationPoleHierarchisationGeneral.fromHeterogenerousBasis(
basis, opPole)
opHier = pysgpp.OperationUPCombinationGrid(combiGrid, opPole)
opHier.apply(surpluses)
x = [0.12, 0.34]
xDv = pysgpp.DataVector(x)
print(
"Value of test function at {}: {:.6g}".format(np.array(x),
f(*x)))
opEval = pysgpp.OperationEvalCombinationGrid(combiGrid)
y = opEval.eval(surpluses, xDv)
print("Value of combined sparse grid interpolant at {}: {:.6g}".format(np.array(x), y))
plotFunction(opEval, surpluses, X)
weightedRelevanceCalculator = pysgpp.WeightedRelevanceCalculator()
relevance = weightedRelevanceCalculator.calculate(
pysgpp.LevelVector([4, 5, 5]), 0.8)
averagingPriorityEstimator = pysgpp.AveragingPriorityEstimator()
priority = averagingPriorityEstimator.estimatePriority(pysgpp.LevelVector([5, 5, 5]),
pysgpp.map_levelvector_real({
pysgpp.LevelVector([5, 4, 5]): 0.8,
pysgpp.LevelVector([4, 5, 5]): 0.8
}))
subgridValuesAtX = pysgpp.DoubleVector(len(combiGrid.getFullGrids()), 0.)
for fullGridIndex in range(len(combiGrid.getFullGrids())):
fullGrid = combiGrid.getFullGrids()[fullGridIndex]
l = fullGrid.getLevel()
print("Level of selected full grid with index {}: {}".format(
fullGridIndex, np.array(l)))
opEval = pysgpp.OperationEvalFullGrid(fullGrid)
y = opEval.eval(surpluses[fullGridIndex], xDv)
print("Value of full grid interpolant at {}: {:.6g}".format(np.array(x), y))
subgridValuesAtX[fullGridIndex] = y
adaptiveCombinationGridGenerator = pysgpp.AdaptiveCombinationGridGenerator.fromCombinationGrid(
combiGrid, subgridValuesAtX)
adaptiveCombinationGridGenerator.adaptAllKnown()
oldSet = adaptiveCombinationGridGenerator.getOldSet()
adaptiveCombinationGridGenerator.getCurrentResult()
levels = pysgpp.LevelVectorVector()
for fullGridIndex in range(len(combiGrid.getFullGrids())):
fullGrid = combiGrid.getFullGrids()[fullGridIndex]
l = fullGrid.getLevel()
levels.push_back(l)
adaptiveCombinationGridGenerator.getDeltas(levels)
activeSet = adaptiveCombinationGridGenerator.getActiveSet()
priorities = adaptiveCombinationGridGenerator.getPriorities()
queue = adaptiveCombinationGridGenerator.getPriorityQueue()
newValue = {}
for qu in queue:
q = pysgpp.LevelVector(qu)
fullGrid = pysgpp.FullGrid(q, basis)
gridRange = pysgpp.IndexVectorRange(fullGrid)
value = pysgpp.DataVector(fullGrid.getNumberOfIndexVectors())
rangeIterator = gridRange.begin()
while rangeIterator != gridRange.end():
z = pysgpp.DataVector(dim)
rangeIterator.getStandardCoordinates(z)
value[rangeIterator.getSequenceNumber()] =
f(z[0], z[1])
try:
rangeIterator.__next__()
except StopIteration:
break
newValue[tuple(q)] = value
surplus = pysgpp.DataVector(value)
opHier = pysgpp.OperationUPFullGrid(fullGrid, opPole)
opHier.apply(surplus)
opEval = pysgpp.OperationEvalFullGrid(fullGrid)
y = opEval.eval(surplus, xDv)
print("Value of full grid interpolant at {}: {:.6g}".format(np.array(x), y))
adaptiveCombinationGridGenerator.setQoIInformation(q, y)
relevances = adaptiveCombinationGridGenerator.getRelevanceOfActiveSet()
priorities, relevances
adaptiveCombinationGridGenerator.adaptAllKnown()
currentSet = adaptiveCombinationGridGenerator.getOldSet()
adaptiveCombinationGridGenerator.getCurrentResult()
newCombiGrid = adaptiveCombinationGridGenerator.getCombinationGrid(basis)
numberNewLevels = len(newCombiGrid.getFullGrids())
newLevels = pysgpp.LevelVectorVector()
for fullGridIndex in range(numberNewLevels):
fullGrid = newCombiGrid.getFullGrids()[fullGridIndex]
l = fullGrid.getLevel()
newLevels.push_back(l)
newCoefficients = pysgpp.getStandardCoefficientsFromLevelSet(newLevels)
newValues = pysgpp.DataVectorVector()
newValues.reserve(numberNewLevels)
for newLevel in newLevels:
if newLevel in levels:
i = 0
while levels[i] != newLevel and i < numberNewLevels:
i = i+1
newValues.push_back(values[i])
else:
newValues.push_back(newValue[newLevel])
newSurpluses = pysgpp.DataVectorVector(newValues)
newOpHier = pysgpp.OperationUPCombinationGrid(newCombiGrid, opPole)
newOpHier.apply(newSurpluses)
opEval = pysgpp.OperationEvalCombinationGrid(newCombiGrid)
y = opEval.eval(newSurpluses, xDv)
print("Value of combined sparse grid interpolant at {}: {:.6g}".format(np.array(x), y))
if doPlot:
plotDeltas3D(adaptiveCombinationGridGenerator, ['l_0', 'l_1'])
base::ScalarFunction & f
Definition AugmentedLagrangian.cpp:75