def createGrid(grid, dim, deg=1, addTruncatedBorder=False): # create new grid gridType = grid.getType() deg = max(deg, grid.getDegree()) # print( gridType, deg ) if deg > 1 and gridType in [GridType_Linear]: return Grid.createPolyGrid(dim, deg) if deg > 1 and gridType in [ GridType_LinearBoundary, GridType_LinearL0Boundary ]: return Grid.createPolyBoundaryGrid(dim, deg) elif deg > 1 and gridType in [GridType_LinearClenshawCurtis]: return Grid.createPolyClenshawCurtisGrid(dim, deg) elif deg > 1 and gridType in [GridType_LinearClenshawCurtisBoundary]: return Grid.createPolyClenshawCurtisBoundaryGrid(dim, deg) elif deg > 1 and gridType in [GridType_ModLinear]: return Grid.createModPolyGrid(dim, deg) elif deg > 1 and gridType in [GridType_ModLinearClenshawCurtis]: return Grid.createModPolyClenshawCurtisGrid(dim, deg) else: gridConfig = RegularGridConfiguration() gridConfig.type_ = gridType gridConfig.dim_ = dim gridConfig.maxDegree_ = deg return Grid.createGrid(gridConfig)
def createGrid(grid, dim, deg=1, addTruncatedBorder=False): # create new grid gridType = grid.getType() if gridType in [Poly, PolyBoundary]: deg = max(deg, grid.getDegree()) # print gridType, deg if deg > 1: if gridType in [LinearBoundary, PolyBoundary]: return Grid.createPolyBoundaryGrid(dim, deg) elif gridType == LinearL0Boundary: raise NotImplementedError( "there is no full boundary polynomial grid") elif gridType in [Linear, Poly]: return Grid.createPolyGrid(dim, deg) else: raise Exception('unknown grid type %s' % gridType) else: if gridType == Linear: return Grid.createLinearGrid(dim) elif gridType == LinearBoundary: return Grid.createLinearBoundaryGrid(dim) elif gridType == LinearL0Boundary: return Grid.createLinearBoundaryGrid(dim, 0) else: raise Exception('unknown grid type %s' % gridType)
def createGrid(grid, dim, deg=1, addTruncatedBorder=False): # create new grid gridType = grid.getType() if gridType in [Poly, PolyBoundary]: deg = max(deg, grid.getDegree()) # print gridType, deg if deg > 1: if gridType in [LinearBoundary, PolyBoundary]: return Grid.createPolyBoundaryGrid(dim, deg) elif gridType == LinearL0Boundary: raise NotImplementedError("there is no full boundary polynomial grid") elif gridType in [Linear, Poly]: return Grid.createPolyGrid(dim, deg) else: raise Exception('unknown grid type %s' % gridType) else: if gridType == Linear: return Grid.createLinearGrid(dim) elif gridType == LinearBoundary: return Grid.createLinearBoundaryGrid(dim) elif gridType == LinearL0Boundary: return Grid.createLinearBoundaryGrid(dim, 0) else: raise Exception('unknown grid type %s' % gridType)
def test_2DNormalDist_variance(self): # prepare data U = dists.J( [dists.Normal(2.0, .5, -1, 4), dists.Normal(1.0, .5, -1, 3)]) # U = dists.J([dists.Normal(0.5, .5, -1, 2), # dists.Normal(0.5, .4, -1, 2)]) # define linear transformation trans = JointTransformation() for a, b in U.getBounds(): trans.add(LinearTransformation(a, b)) # get a sparse grid approximation grid = Grid.createPolyGrid(U.getDim(), 10) grid.getGenerator().regular(5) gs = grid.getStorage() # now refine adaptively 5 times p = DataVector(gs.getDimension()) nodalValues = np.ndarray(gs.getSize()) # set function values in alpha for i in range(gs.getSize()): gs.getPoint(i).getStandardCoordinates(p) nodalValues[i] = U.pdf(trans.unitToProbabilistic(p.array())) # hierarchize alpha = hierarchize(grid, nodalValues) # # make positive # alpha_vec = DataVector(alpha) # createOperationMakePositive().makePositive(grid, alpha_vec) # alpha = alpha_vec.array() dist = SGDEdist(grid, alpha, bounds=U.getBounds()) fig = plt.figure() plotDensity2d(U) fig.show() fig = plt.figure() plotSG2d(dist.grid, dist.alpha, addContour=True, show_negative=True, show_grid_points=True) fig.show() print("2d: mean = %g ~ %g" % (U.mean(), dist.mean())) print("2d: var = %g ~ %g" % (U.var(), dist.var())) plt.show()
def test_1DNormalDist_variance(self): # prepare data U = dists.Normal(1, 2, -8, 8) # U = dists.Normal(0.5, .2, 0, 1) # define linear transformation trans = JointTransformation() a, b = U.getBounds() trans.add(LinearTransformation(a, b)) # get a sparse grid approximation grid = Grid.createPolyGrid(U.getDim(), 10) grid.getGenerator().regular(5) gs = grid.getStorage() # now refine adaptively 5 times p = DataVector(gs.getDimension()) nodalValues = np.ndarray(gs.getSize()) # set function values in alpha for i in range(gs.getSize()): gs.getPoint(i).getStandardCoordinates(p) nodalValues[i] = U.pdf(trans.unitToProbabilistic(p.array())) # hierarchize alpha = hierarchize(grid, nodalValues) dist = SGDEdist(grid, alpha, bounds=U.getBounds()) fig = plt.figure() plotDensity1d(U, alpha_value=0.1, mean_label="$\mathbb{E}", interval_label="$\alpha=0.1$") fig.show() fig = plt.figure() plotDensity1d(dist, alpha_value=0.1, mean_label="$\mathbb{E}", interval_label="$\alpha=0.1$") fig.show() print("1d: mean = %g ~ %g" % (U.mean(), dist.mean())) print("1d: var = %g ~ %g" % (U.var(), dist.var())) plt.show()
def discretizeProduct(grid1, alpha1, grid2, alpha2): """ Discretizes the product of two sparse grid functions: h(x) := f(x) * g(x) on a full grid with piecewise polynomial basis. Therefore a maximum number of grid points 10^6 is allowed. @param grid1: Grid, grid of f @param alpha1: DataVector, hierarchical coefficients of f @param grid2: Grid, grid of g @param alpha2: DataVector, hierarchical coefficients of g """ # make sure that the grids are either piece wise linear # or piecewise polynomial if grid1.getType() not in [GridType_Linear, GridType_Poly]: raise AttributeError("grid type '%s' not supported" % grid1.getType()) if grid2.getType() not in [GridType_Linear, GridType_Poly]: raise AttributeError("grid type '%s' not supported" % grid2.getType()) # get the degrees of the grid maxlevelGrid1 = grid1.getStorage().getMaxLevel() maxlevelGrid2 = grid2.getStorage().getMaxLevel() deg1 = min(getDegree(grid1), maxlevelGrid1 + 1) deg2 = min(getDegree(grid2), maxlevelGrid2 + 1) deg = deg1 + deg2 maxlevel = max(maxlevelGrid1 + deg2, maxlevelGrid2 + deg1) # check if maximum number of grid points is goint to be exceeded n = 2**((deg - 1) * grid1.getStorage().getDimension()) if n > 1e6: raise AttributeError( "Can not create a full grid of level %i and dimensionality %i. The number of grid points %i would exceed 10^6" % (deg - 1, grid1.getStorage().getDimension(), n)) # join the two grids joinedGrid = Grid.createPolyGrid(grid1.getStorage().getDimension(), deg) joinedGrid.getGenerator().full(maxlevel) # interpolate the product on the new grid joinedAlpha = interpolateProduct(grid1, alpha1, grid2, alpha2, joinedGrid) return joinedGrid, joinedAlpha
def discretizeProduct(grid1, alpha1, grid2, alpha2): """ Discretizes the product of two sparse grid functions: h(x) := f(x) * g(x) on a full grid with piecewise polynomial basis. Therefore a maximum number of grid points 10^6 is allowed. @param grid1: Grid, grid of f @param alpha1: DataVector, hierarchical coefficients of f @param grid2: Grid, grid of g @param alpha2: DataVector, hierarchical coefficients of g """ # make sure that the grids are either piece wise linear # or piecewise polynomial if grid1.getType() not in [Linear, Poly]: raise AttributeError("grid type '%s' not supported" % grid1.getType()) if grid2.getType() not in [Linear, Poly]: raise AttributeError("grid type '%s' not supported" % grid2.getType()) # get the degrees of the grid maxlevelGrid1 = grid1.getStorage().getMaxLevel() maxlevelGrid2 = grid2.getStorage().getMaxLevel() deg1 = min(getDegree(grid1), maxlevelGrid1 + 1) deg2 = min(getDegree(grid2), maxlevelGrid2 + 1) deg = deg1 + deg2 maxlevel = max(maxlevelGrid1 + deg2, maxlevelGrid2 + deg1) # check if maximum number of grid points is goint to be exceeded n = 2 ** ((deg - 1) * grid1.getStorage().dim()) if n > 1e6: raise AttributeError("Can not create a full grid of level %i and dimensionality %i. The number of grid points %i would exceed 10^6" % (deg - 1, grid1.getStorage().dim(), n)) # join the two grids joinedGrid = Grid.createPolyGrid(2, deg) joinedGrid.createGridGenerator().full(maxlevel) # interpolate the product on the new grid joinedAlpha = interpolateProduct(grid1, alpha1, grid2, alpha2, joinedGrid) return joinedGrid, joinedAlpha
def interpolate(f, level, dim, gridType=GridType_Linear, deg=2, trans=None): # create a two-dimensional piecewise bi-linear grid if gridType == GridType_PolyBoundary: grid = Grid.createPolyBoundaryGrid(dim, deg) elif gridType == GridType_Poly: grid = Grid.createPolyGrid(dim, deg) elif gridType == GridType_Linear: grid = Grid.createLinearGrid(dim) elif gridType == GridType_LinearBoundary: grid = Grid.createLinearBoundaryGrid(dim, 1) else: raise AttributeError gridStorage = grid.getStorage() # create regular grid grid.getGenerator().regular(level) # create coefficient vector alpha = DataVector(gridStorage.getSize()) alpha.setAll(0.0) # set function values in alpha x = DataVector(dim) for i in range(gridStorage.getSize()): gp = gridStorage.getPoint(i) gridStorage.getCoordinates(gp, x) p = x.array() if trans is not None: p = trans.unitToProbabilistic(p) if gridStorage.getDimension() == 1: p = p[0] alpha[i] = f(p) # hierarchize createOperationHierarchisation(grid).doHierarchisation(alpha) return grid, alpha
def interpolate(self, dim, level, deg=1): # discretize f if deg == 1: grid = Grid.createLinearGrid(dim) else: grid = Grid.createPolyGrid(dim, deg) grid.getGenerator().regular(level) gs = grid.getStorage() # prepare surplus vector nodalValues = np.zeros(gs.getSize()) # interpolation on nodal basis p = DataVector(gs.getDimension()) for i in range(gs.getSize()): gs.getCoordinates(gs.getPoint(i), p) nodalValues[i] = self.f(p.array()) # hierarchization alpha = hierarchize(grid, nodalValues) return grid, alpha
def setUpClass(cls): super(MonteCarloStrategyTest, cls).setUpClass() builder = ParameterBuilder() up = builder.defineUncertainParameters() up.new().isCalled('x1').withUniformDistribution(0, 1) up.new().isCalled('x2').withUniformDistribution(0, 1) cls.params = builder.andGetResult() cls.numDims = cls.params.getStochasticDim() cls.samples = np.random.random((10000, 1)) cls.grid = Grid.createPolyGrid(cls.numDims, 2) cls.grid.getGenerator().regular(1) gs = cls.grid.getStorage() # interpolate parabola nodalValues = np.zeros(gs.getSize()) x = DataVector(cls.numDims) for i in range(gs.getSize()): gs.getCoordinates(gs.getPoint(i), x) nodalValues[i] = 16 * (1 - x[0]) * (1 - x[1]) cls.alpha = hierarchize(cls.grid, nodalValues)
def createGrid(self): """ Creates the specified grid """ grid = None if self.__file is not None and os.path.exists(self.__file): gridFormatter = GridFormatter() grid = gridFormatter.deserializeFromFile(self.__file) else: if self.__grid is not None: self.__dim = self.__grid.getStorage().dim() if (self.__dim is None or self.level is None) and self.__grid is None: raise AttributeError("Not all attributes assigned to create\ grid") if self.__border is not None: if self.__border == BorderTypes.TRAPEZOIDBOUNDARY: if self.__deg > 1: grid = Grid.createPolyBoundaryGrid( self.__dim, self.__deg) else: grid = Grid.createLinearBoundaryGrid(self.__dim) elif self.__border == BorderTypes.COMPLETEBOUNDARY: if self.__deg > 1: raise NotImplementedError() else: grid = Grid.createLinearBoundaryGrid(self.__dim, 0) else: if self.__deg > 1: grid = Grid.createModPolyGrid(self.__dim, self.__deg) else: grid = Grid.createModLinearGrid(self.__dim) else: # no border points if self.__deg > 1: grid = Grid.createPolyGrid(self.__dim, self.__deg) else: grid = Grid.createLinearGrid(self.__dim) # generate the grid if self.level is not None: generator = grid.createGridGenerator() if not self.__full: generator.regular(self.level) else: generator.full(self.level) # if there is a grid specified, add all the missing points if self.__grid is not None: gs = grid.getStorage() copygs = self.__grid.getStorage() # insert grid points for i in xrange(copygs.size()): gp = copygs.get(i) # insert grid point if not gs.has_key(gp): gs.insert(HashGridIndex(gp)) if self.__border == BorderTypes.TRAPEZOIDBOUNDARY: insertTruncatedBorder(grid, gp) gs.recalcLeafProperty() return grid
# use, please see the copyright notice provided with SG++ or at # sgpp.sparsegrids.org import numpy as np import matplotlib.pyplot as plt from pysgpp import DataVector, Grid, createOperationHierarchisation, createOperationEval from pysgpp.extensions.datadriven.uq.operations import hierarchize from pysgpp.extensions.datadriven.uq.plot import plotFunction3d, plotSG3d from pysgpp.extensions.datadriven.uq.dists import Normal, J from pysgpp.extensions.datadriven.uq.operations.sparse_grid import evalSGFunction U = J([Normal.by_alpha(0.5, 0.05, 0.001), Normal.by_alpha(0.5, 0.05, 0.001)]) grid = Grid.createPolyGrid(2, 2) grid.getGenerator().regular(3) gs = grid.getStorage() nodalValues = np.ndarray(gs.getSize()) p = DataVector(2) for i in range(gs.getSize()): gs.getCoordinates(gs.getPoint(i), p) nodalValues[i] = U.pdf(p.array()) alpha = hierarchize(grid, nodalValues) fig, _, _ = plotFunction3d(U.pdf) fig.show()