The following example shows how to integrate in SG++, using both direct integration of a sparse grid function and the use of Monte Carlo integration.
As in the tutorial.py (Start Here) example, we deal with the function
\[
f\colon [0, 1]^2 \to \mathbb{R},\quad
f(x_0, x_1) := 16 (x_0 - 1) x_0 (x_1 - 1) x_1
\]
which we first interpolate. We then integrate the interpolant, then the function itself using 100000 Monte Carlo points, and we then compute the L2-error.
The function, which sgpp::base::OperationQuadratureMC takes, has one parameter, a sequence (C++ provides a tuple) with the coordinates of the grid point \(\in [0,1]^d\).
import pysgpp
res = 1.0
for i in range(len(x)):
res *= 4.0*x[i]*(1.0-x[i])
return res
res = 1.0
for i in range(len(x)):
res *= 2.0*min(x[i], 1.0-x[i])
return res
base::VectorFunction & g
Definition AugmentedLagrangian.cpp:76
base::ScalarFunction & f
Definition AugmentedLagrangian.cpp:75
Create a two-dimensional piecewise bi-linear grid of level 3
dim = 2
grid = pysgpp.Grid.createLinearGrid(dim)
gridStorage = grid.getStorage()
print("dimensionality: {}".format(dim))
level = 3
gridGen = grid.getGenerator()
gridGen.regular(level)
print("number of grid points: {}".format(gridStorage.getSize()))
Calculate the surplus vector alpha for the interpolant of \(
f(x)\). Since the function can be evaluated at any point. Hence. we simply evaluate it at the coordinates of the grid points to obtain the nodal values. Then we use hierarchization to obtain the surplus value.
alpha = pysgpp.DataVector(gridStorage.getSize())
for i in range(gridStorage.getSize()):
gp = gridStorage.getPoint(i)
p = tuple([gp.getStandardCoordinate(j) for j in range(dim)])
pysgpp.createOperationHierarchisation(grid).doHierarchisation(alpha)
Now we compute and compare the quadrature using four different methods available in SG++.
opQ = pysgpp.createOperationQuadrature(grid)
res = opQ.doQuadrature(alpha)
print("exact integral value: {}".format(res))
opMC = pysgpp.OperationQuadratureMC(grid, 100000)
res = opMC.doQuadrature(alpha)
print("Monte Carlo value: {:.6f}".format(res))
res = opMC.doQuadrature(alpha)
print("Monte Carlo value: {:.6f}".format(res))
res = opMC.doQuadratureFunc(f)
print("MC value (f): {:.6f}".format(res))
res = opMC.doQuadratureL2Error(f, alpha)
print("MC L2-error (f-u) {:.7f}".format(res))
res = opMC.doQuadratureFunc(g)
print( "MC value (g): {:.6f}".format(res))
res = opMC.doQuadratureL2Error(g, alpha)
print( "MC L2-error (g-u) {:.7f}".format(res))
This results in an output similar to:
dimensionality: 2
number of grid points: 17
exact integral value: 0.421875
Monte Carlo value: 0.421298
Monte Carlo value: 0.421971
MC value: 0.444917
MC L2-error: 0.0242639