Exemplo n.º 1
0
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)
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
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)
Exemplo n.º 4
0
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
Exemplo n.º 5
0
    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
Exemplo n.º 6
0
def computeBilinearForm(grid, U):
    """
    Compute bilinear form
    (A)_ij = \int phi_i phi_j dU(x)
    on measure U, which is in this case supposed to be a lebesgue measure.
    @param grid: Grid, sparse grid
    @param U: list of distributions, Lebeasgue measure
    @return: DataMatrix
    """
    gs = grid.getStorage()
    basis = getBasis(grid)
    # interpolate phi_i phi_j on sparse grid with piecewise polynomial SG
    # the product of two piecewise linear functions is a piecewise
    # polynomial one of degree 2.
    ngrid = Grid.createPolyBoundaryGrid(1, 2)
    # ngrid = Grid.createLinearBoundaryGrid(1)
    ngrid.getGenerator().regular(gs.getMaxLevel() + 1)
    ngs = ngrid.getStorage()
    nodalValues = DataVector(ngs.size())

    level = DataMatrix(gs.size(), gs.getDimension())
    index = DataMatrix(gs.size(), gs.getDimension())
    gs.getLevelIndexArraysForEval(level, index)

    A = DataMatrix(gs.size(), gs.size())
    s = np.ndarray(gs.getDimension(), dtype='float')

    # run over all rows
    for i in range(gs.size()):
        gpi = gs.getPoint(i)
        # run over all columns
        for j in range(i, gs.size()):
            # print "%i/%i" % (i * gs.size() + j + 1, gs.size() ** 2)
            gpj = gs.getPoint(j)
            # run over all dimensions
            for d in range(gs.getDimension()):
                # get level index
                lid, iid = level.get(i, d), index.get(i, d)
                ljd, ijd = level.get(j, d), index.get(j, d)

                # compute left and right boundary of the support of both
                # basis functions
                lb = max([((iid - 1) / lid), ((ijd - 1) / ljd)])
                ub = min([((iid + 1) / lid), ((ijd + 1) / ljd)])

                # same level, different index
                if lid == ljd and iid != ijd:
                    s[d] = 0.
                # the support does not overlap
                elif lid != ljd and lb >= ub:
                    s[d] = 0.
                else:
                    # ----------------------------------------------------
                    # do the 1d interpolation ...
                    lid, iid = gpi.getLevel(d), int(iid)
                    ljd, ijd = gpj.getLevel(d), int(ijd)
                    for k in range(ngs.size()):
                        x = ngs.getCoordinate(ngs.getPoint(k), 0)
                        nodalValues[k] = max(0, basis.eval(lid, iid, x)) * \
                            max(0, basis.eval(ljd, ijd, x))
                    # ... by hierarchization
                    v = hierarchize(ngrid, nodalValues)

                    def f(x, y):
                        return float(y * U[d].pdf(x[0]))

                    g, w, _ = discretize(ngrid, v, f, refnums=0)
                    # compute the integral of it
                    s[d] = doQuadrature(g, w)
                    # ----------------------------------------------------
            # store result in matrix
            A.set(i, j, float(np.prod(s)))
            A.set(j, i, A.get(i, j))

    return A
Exemplo n.º 7
0
    def computeBilinearFormEntry(self, gs, gpi, basisi, gpj, basisj, d):
        # if not, compute it
        ans = 1
        err = 0.

        # interpolating 1d sparse grid
        ngrid = Grid.createPolyBoundaryGrid(1, 2)
        ngrid.getGenerator().regular(2)
        ngs = ngrid.getStorage()
        nodalValues = DataVector(ngs.getSize())

        for d in range(gpi.getDimension()):
            # get level index
            lid, iid = gpi.getLevel(d), gpi.getIndex(d)
            ljd, ijd = gpj.getLevel(d), gpj.getIndex(d)

            # compute left and right boundary of the support of both
            # basis functions
            xlowi, xhighi = getBoundsOfSupport(gs, lid, iid)
            xlowj, xhighj = getBoundsOfSupport(gs, ljd, ijd)

            xlow = max(xlowi, xlowj)
            xhigh = min(xhighi, xhighj)

            # same level, different index
            if lid == ljd and iid != ijd and lid > 0:
                return 0., 0.
            # the support does not overlap
            elif lid != ljd and xlow >= xhigh:
                return 0., 0.
            else:
                # ----------------------------------------------------
                # do the 1d interpolation ...
                # define transformation function
                T = LinearTransformation(xlow, xhigh)
                for k in range(ngs.getSize()):
                    x = ngs.getCoordinate(ngs.getPoint(k), 0)
                    x = T.unitToProbabilistic(x)
                    nodalValues[k] = basisi.eval(lid, iid, x) * \
                        basisj.eval(ljd, ijd, x)
                # ... by hierarchization
                v = hierarchize(ngrid, nodalValues)

                # discretize the following function
                def f(x, y):
                    xp = T.unitToProbabilistic(x)
                    return float(y * self._U[d].pdf(xp))

                # sparse grid quadrature
                g, w, err1d = discretize(ngrid,
                                         v,
                                         f,
                                         refnums=0,
                                         level=5,
                                         useDiscreteL2Error=False)
                s = T.vol() * doQuadrature(g, w)
                #                     fig = plt.figure()
                #                     plotSG1d(ngrid, v)
                #                     x = np.linspace(xlow, ub, 100)
                #                     plt.plot(np.linspace(0, 1, 100), U[d].pdf(x))
                #                     fig.show()
                #                     fig = plt.figure()
                #                     plotSG1d(g, w)
                #                     x = np.linspace(0, 1, 100)
                #                     plt.plot(x,
                #                              [evalSGFunction(ngrid, v, DataVector([xi])) * U[d].pdf(T.unitToProbabilistic(xi)) for xi in x])
                #                     fig.show()
                #                     plt.show()
                # compute the integral of it
                # ----------------------------------------------------
                ans *= s
                err += err1d[1]

        return ans, err
Exemplo n.º 8
0
def computeBilinearForm(grid, U):
    """
    Compute bilinear form
    (A)_ij = \int phi_i phi_j dU(x)
    on measure U, which is in this case supposed to be a lebesgue measure.
    @param grid: Grid, sparse grid
    @param U: list of distributions, Lebeasgue measure
    @return: DataMatrix
    """
    gs = grid.getStorage()
    basis = getBasis(grid)
    # interpolate phi_i phi_j on sparse grid with piecewise polynomial SG
    # the product of two piecewise linear functions is a piecewise
    # polynomial one of degree 2.
    ngrid = Grid.createPolyBoundaryGrid(1, 2)
    # ngrid = Grid.createLinearBoundaryGrid(1)
    ngrid.createGridGenerator().regular(gs.getMaxLevel() + 1)
    ngs = ngrid.getStorage()
    nodalValues = DataVector(ngs.size())

    level = DataMatrix(gs.size(), gs.dim())
    index = DataMatrix(gs.size(), gs.dim())
    gs.getLevelIndexArraysForEval(level, index)

    A = DataMatrix(gs.size(), gs.size())
    s = np.ndarray(gs.dim(), dtype='float')

    # run over all rows
    for i in xrange(gs.size()):
        gpi = gs.get(i)
        # run over all columns
        for j in xrange(i, gs.size()):
            # print "%i/%i" % (i * gs.size() + j + 1, gs.size() ** 2)
            gpj = gs.get(j)
            # run over all dimensions
            for d in xrange(gs.dim()):
                # get level index
                lid, iid = level.get(i, d), index.get(i, d)
                ljd, ijd = level.get(j, d), index.get(j, d)

                # compute left and right boundary of the support of both
                # basis functions
                lb = max([(iid - 1) / lid, (ijd - 1) / ljd])
                ub = min([(iid + 1) / lid, (ijd + 1) / ljd])

                # same level, different index
                if lid == ljd and iid != ijd:
                    s[d] = 0.
                # the support does not overlap
                elif lid != ljd and lb >= ub:
                    s[d] = 0.
                else:
                    # ----------------------------------------------------
                    # do the 1d interpolation ...
                    lid, iid = gpi.getLevel(d), int(iid)
                    ljd, ijd = gpj.getLevel(d), int(ijd)
                    for k in xrange(ngs.size()):
                        x = ngs.get(k).getCoord(0)
                        nodalValues[k] = max(0, basis.eval(lid, iid, x)) * \
                            max(0, basis.eval(ljd, ijd, x))
                    # ... by hierarchization
                    v = hierarchize(ngrid, nodalValues)

                    def f(x, y):
                        return float(y * U[d].pdf(x[0]))

                    g, w, _ = discretize(ngrid, v, f, refnums=0)
                    # compute the integral of it
                    s[d] = doQuadrature(g, w)
                    # ----------------------------------------------------
            # store result in matrix
            A.set(i, j, float(np.prod(s)))
            A.set(j, i, A.get(i, j))

    return A
Exemplo n.º 9
0
def computeBF(grid, U, admissibleSet):
    """
    Compute bilinear form
    (A)_ij = \int phi_i phi_j dU(x)
    on measure U, which is in this case supposed to be a lebesgue measure.
    @param grid: Grid, sparse grid
    @param U: list of distributions, Lebeasgue measure
    @param admissibleSet: AdmissibleSet
    @return: DataMatrix
    """
    gs = grid.getStorage()
    basis = getBasis(grid)
    # interpolate phi_i phi_j on sparse grid with piecewise polynomial SG
    # the product of two piecewise linear functions is a piecewise
    # polynomial one of degree 2.
    ngrid = Grid.createPolyBoundaryGrid(1, 2)
    ngrid.getGenerator().regular(2)
    ngs = ngrid.getStorage()
    nodalValues = DataVector(ngs.size())

    A = DataMatrix(admissibleSet.getSize(), gs.size())
    b = DataVector(admissibleSet.getSize())
    s = np.ndarray(gs.getDimension(), dtype='float')

#     # pre compute basis evaluations
#     basis_eval = {}
#     for li in xrange(1, gs.getMaxLevel() + 1):
#         for i in xrange(1, 2 ** li + 1, 2):
#             # add value with it self
#             x = 2 ** -li * i
#             basis_eval[(li, i, li, i, x)] = basis.eval(li, i, x) * \
#                 basis.eval(li, i, x)
#
#             # left side
#             x = 2 ** -(li + 1) * (2 * i - 1)
#             basis_eval[(li, i, li, i, x)] = basis.eval(li, i, x) * \
#                 basis.eval(li, i, x)
#             # right side
#             x = 2 ** -(li + 1) * (2 * i + 1)
#             basis_eval[(li, i, li, i, x)] = basis.eval(li, i, x) * \
#                 basis.eval(li, i, x)
#
#             # add values for hierarchical lower nodes
#             for lj in xrange(li + 1, gs.getMaxLevel() + 1):
#                 a = 2 ** (lj - li)
#                 j = a * i - a + 1
#                 while j < a * i + a:
#                     # center
#                     x = 2 ** -lj * j
#                     basis_eval[(li, i, lj, j, x)] = basis.eval(li, i, x) * \
#                         basis.eval(lj, j, x)
#                     basis_eval[(lj, j, li, i, x)] = basis_eval[(li, i, lj, j, x)]
#                     # left side
#                     x = 2 ** -(lj + 1) * (2 * j - 1)
#                     basis_eval[(li, i, lj, j, x)] = basis.eval(li, i, x) * \
#                         basis.eval(lj, j, x)
#                     basis_eval[(lj, j, li, i, x)] = basis_eval[(li, i, lj, j, x)]
#                     # right side
#                     x = 2 ** -(lj + 1) * (2 * j + 1)
#                     basis_eval[(li, i, lj, j, x)] = basis.eval(li, i, x) * \
#                         basis.eval(lj, j, x)
#                     basis_eval[(lj, j, li, i, x)] = basis_eval[(li, i, lj, j, x)]
#                     j += 2
#
#     print len(basis_eval)

    # run over all rows
    for i, gpi in enumerate(admissibleSet.values()):
        # run over all columns
        for j in range(gs.size()):
            # print "%i/%i" % (i * gs.size() + j + 1, gs.size() ** 2)
            gpj = gs.getPoint(j)
            for d in range(gs.getDimension()):
                # get level index
                lid, iid = gpi.getLevel(d), gpi.getIndex(d)
                ljd, ijd = gpj.getLevel(d), gpj.getIndex(d)

                # compute left and right boundary of the support of both
                # basis functions
                lb = max([(iid - 1) * 2 ** -lid, (ijd - 1) * 2 ** -ljd])
                ub = min([(iid + 1) * 2 ** -lid, (ijd + 1) * 2 ** -ljd])

                # same level, different index
                if lid == ljd and iid != ijd:
                    s[d] = 0.
                # the support does not overlap
                elif lid != ljd and lb >= ub:
                    s[d] = 0.
                else:
                    # ----------------------------------------------------
                    # do the 1d interpolation ...
                    # define transformation function
                    T = LinearTransformation(lb, ub)
                    for k in range(ngs.size()):
                        x = ngs.getCoordinate(ngs.getPoint(k), 0)
                        x = T.unitToProbabilistic(x)
                        nodalValues[k] = basis.eval(lid, iid, x) * \
                            basis.eval(ljd, ijd, x)
                    # ... by hierarchization
                    v = hierarchize(ngrid, nodalValues)

                    # discretize the following function
                    def f(x, y):
                        xp = T.unitToProbabilistic(x)
                        return float(y * U[d].pdf(xp))

                    # sparse grid quadrature
                    g, w, _ = discretize(ngrid, v, f, refnums=0, level=5,
                                         useDiscreteL2Error=False)
                    s[d] = doQuadrature(g, w) * (ub - lb)
#                     fig = plt.figure()
#                     plotSG1d(ngrid, v)
#                     x = np.linspace(xlow, ub, 100)
#                     plt.plot(np.linspace(0, 1, 100), U[d].pdf(x))
#                     fig.show()
#                     fig = plt.figure()
#                     plotSG1d(g, w)
#                     x = np.linspace(0, 1, 100)
#                     plt.plot(x,
#                              [evalSGFunction(ngrid, v, DataVector([xi])) * U[d].pdf(T.unitToProbabilistic(xi)) for xi in x])
#                     fig.show()
#                     plt.show()
                    # compute the integral of it
                    # ----------------------------------------------------
            A.set(i, j, float(np.prod(s)))
            if gs.getSequenceNumber(gpi) == j:
                b[i] = A.get(i, j)
    return A, b
def computeBF(grid, U, admissibleSet):
    """
    Compute bilinear form
    (A)_ij = \int phi_i phi_j dU(x)
    on measure U, which is in this case supposed to be a lebesgue measure.
    @param grid: Grid, sparse grid
    @param U: list of distributions, Lebeasgue measure
    @param admissibleSet: AdmissibleSet
    @return: DataMatrix
    """
    gs = grid.getStorage()
    basis = getBasis(grid)
    # interpolate phi_i phi_j on sparse grid with piecewise polynomial SG
    # the product of two piecewise linear functions is a piecewise
    # polynomial one of degree 2.
    ngrid = Grid.createPolyBoundaryGrid(1, 2)
    ngrid.createGridGenerator().regular(2)
    ngs = ngrid.getStorage()
    nodalValues = DataVector(ngs.size())

    A = DataMatrix(admissibleSet.getSize(), gs.size())
    b = DataVector(admissibleSet.getSize())
    s = np.ndarray(gs.dim(), dtype='float')

#     # pre compute basis evaluations
#     basis_eval = {}
#     for li in xrange(1, gs.getMaxLevel() + 1):
#         for i in xrange(1, 2 ** li + 1, 2):
#             # add value with it self
#             x = 2 ** -li * i
#             basis_eval[(li, i, li, i, x)] = basis.eval(li, i, x) * \
#                 basis.eval(li, i, x)
#
#             # left side
#             x = 2 ** -(li + 1) * (2 * i - 1)
#             basis_eval[(li, i, li, i, x)] = basis.eval(li, i, x) * \
#                 basis.eval(li, i, x)
#             # right side
#             x = 2 ** -(li + 1) * (2 * i + 1)
#             basis_eval[(li, i, li, i, x)] = basis.eval(li, i, x) * \
#                 basis.eval(li, i, x)
#
#             # add values for hierarchical lower nodes
#             for lj in xrange(li + 1, gs.getMaxLevel() + 1):
#                 a = 2 ** (lj - li)
#                 j = a * i - a + 1
#                 while j < a * i + a:
#                     # center
#                     x = 2 ** -lj * j
#                     basis_eval[(li, i, lj, j, x)] = basis.eval(li, i, x) * \
#                         basis.eval(lj, j, x)
#                     basis_eval[(lj, j, li, i, x)] = basis_eval[(li, i, lj, j, x)]
#                     # left side
#                     x = 2 ** -(lj + 1) * (2 * j - 1)
#                     basis_eval[(li, i, lj, j, x)] = basis.eval(li, i, x) * \
#                         basis.eval(lj, j, x)
#                     basis_eval[(lj, j, li, i, x)] = basis_eval[(li, i, lj, j, x)]
#                     # right side
#                     x = 2 ** -(lj + 1) * (2 * j + 1)
#                     basis_eval[(li, i, lj, j, x)] = basis.eval(li, i, x) * \
#                         basis.eval(lj, j, x)
#                     basis_eval[(lj, j, li, i, x)] = basis_eval[(li, i, lj, j, x)]
#                     j += 2
#
#     print len(basis_eval)

    # run over all rows
    for i, gpi in enumerate(admissibleSet.values()):
        # run over all columns
        for j in xrange(gs.size()):
            # print "%i/%i" % (i * gs.size() + j + 1, gs.size() ** 2)
            gpj = gs.get(j)
            for d in xrange(gs.dim()):
                # get level index
                lid, iid = gpi.getLevel(d), gpi.getIndex(d)
                ljd, ijd = gpj.getLevel(d), gpj.getIndex(d)

                # compute left and right boundary of the support of both
                # basis functions
                lb = max([(iid - 1) * 2 ** -lid, (ijd - 1) * 2 ** -ljd])
                ub = min([(iid + 1) * 2 ** -lid, (ijd + 1) * 2 ** -ljd])

                # same level, different index
                if lid == ljd and iid != ijd:
                    s[d] = 0.
                # the support does not overlap
                elif lid != ljd and lb >= ub:
                    s[d] = 0.
                else:
                    # ----------------------------------------------------
                    # do the 1d interpolation ...
                    # define transformation function
                    T = LinearTransformation(lb, ub)
                    for k in xrange(ngs.size()):
                        x = ngs.get(k).getCoord(0)
                        x = T.unitToProbabilistic(x)
                        nodalValues[k] = basis.eval(lid, iid, x) * \
                            basis.eval(ljd, ijd, x)
                    # ... by hierarchization
                    v = hierarchize(ngrid, nodalValues)

                    # discretize the following function
                    def f(x, y):
                        xp = T.unitToProbabilistic(x)
                        return float(y * U[d].pdf(xp))

                    # sparse grid quadrature
                    g, w, _ = discretize(ngrid, v, f, refnums=0, level=5,
                                         useDiscreteL2Error=False)
                    s[d] = doQuadrature(g, w) * (ub - lb)
#                     fig = plt.figure()
#                     plotSG1d(ngrid, v)
#                     x = np.linspace(xlow, ub, 100)
#                     plt.plot(np.linspace(0, 1, 100), U[d].pdf(x))
#                     fig.show()
#                     fig = plt.figure()
#                     plotSG1d(g, w)
#                     x = np.linspace(0, 1, 100)
#                     plt.plot(x,
#                              [evalSGFunction(ngrid, v, DataVector([xi])) * U[d].pdf(T.unitToProbabilistic(xi)) for xi in x])
#                     fig.show()
#                     plt.show()
                    # compute the integral of it
                    # ----------------------------------------------------
            A.set(i, j, float(np.prod(s)))
            if gs.seq(gpi) == j:
                b[i] = A.get(i, j)
    return A, b
Exemplo n.º 11
0
# --------------------------------------
# function
# --------------------------------------
symx, symy = symbols('x, y')

h = sinus(symx) + symx
f = lambda x: sin(x) + x
# --------------------------------------
# sparse grid function
# --------------------------------------
dim = 1
level = 4
deg = 2

# create grid
grid = Grid.createPolyBoundaryGrid(dim, deg)

# grid = Grid.createLinearGrid(dim)
gridStorage = grid.getStorage()

# create regular grid
gridGen = grid.createGridGenerator()
gridGen.regular(level)

# create coefficient vector
alpha = DataVector(gridStorage.size())
alpha.setAll(0.0)

# set function values in alpha
for i in range(gridStorage.size()):
    gp = gridStorage.get(i)
    def computeBilinearFormEntry(self, gpi, basisi, gpj, basisj):
        # check if this entry already exists
        for key in [self.getKey(gpi, gpj), self.getKey(gpj, gpi)]:
            if key in self._map:
                return self._map[key]

        # if not, compute it
        ans = 1
        err = 0.

        # interpolating 1d sparse grid
        ngrid = Grid.createPolyBoundaryGrid(1, 2)
        ngrid.createGridGenerator().regular(2)
        ngs = ngrid.getStorage()
        nodalValues = DataVector(ngs.size())

        for d in xrange(gpi.dim()):
            # get level index
            lid, iid = gpi.getLevel(d), gpi.getIndex(d)
            ljd, ijd = gpj.getLevel(d), gpj.getIndex(d)

            # compute left and right boundary of the support of both
            # basis functions
            xlowi, xhighi = self.getBounds(lid, iid)
            xlowj, xhighj = self.getBounds(ljd, ijd)

            xlow = max(xlowi, xlowj)
            xhigh = min(xhighi, xhighj)

            # same level, different index
            if lid == ljd and iid != ijd and lid > 0:
                return 0., 0.
            # the support does not overlap
            elif lid != ljd and xlow >= xhigh:
                return 0., 0.
            else:
                # ----------------------------------------------------
                # do the 1d interpolation ...
                # define transformation function
                T = LinearTransformation(xlow, xhigh)
                for k in xrange(ngs.size()):
                    x = ngs.get(k).getCoord(0)
                    x = T.unitToProbabilistic(x)
                    nodalValues[k] = basisi.eval(lid, iid, x) * \
                        basisj.eval(ljd, ijd, x)
                # ... by hierarchization
                v = hierarchize(ngrid, nodalValues)

                # discretize the following function
                def f(x, y):
                    xp = T.unitToProbabilistic(x)
                    return float(y * self._U[d].pdf(xp))

                # sparse grid quadrature
                g, w, err1d = discretize(ngrid, v, f, refnums=0, level=5,
                                         useDiscreteL2Error=False)
                s = T.vol() * doQuadrature(g, w)
#                     fig = plt.figure()
#                     plotSG1d(ngrid, v)
#                     x = np.linspace(xlow, ub, 100)
#                     plt.plot(np.linspace(0, 1, 100), U[d].pdf(x))
#                     fig.show()
#                     fig = plt.figure()
#                     plotSG1d(g, w)
#                     x = np.linspace(0, 1, 100)
#                     plt.plot(x,
#                              [evalSGFunction(ngrid, v, DataVector([xi])) * U[d].pdf(T.unitToProbabilistic(xi)) for xi in x])
#                     fig.show()
#                     plt.show()
                # compute the integral of it
                # ----------------------------------------------------
                ans *= s
                err += err1d[1]

        return ans, err