Пример #1
0
    def __discretize(self):
        """
        Discretize squared f to obtain a well suited grid for all
        further computations.
        """
        def f(p, val):
            q = self.__T.unitToProbabilistic(p)
            return val**2 * self.__U.pdf(q)

        grid, _, _ = discretize(self.__grid,
                                self.__alpha,
                                f,
                                refnums=4,
                                deg=1,
                                epsilon=1e-6)

        # hierarchize without pdf
        gs = grid.getStorage()
        nodalValues = DataVector(gs.size())
        p = DataVector(gs.dim())
        for i in xrange(gs.size()):
            gs.get(i).getCoords(p)
            nodalValues[i] = evalSGFunction(self.__grid, self.__alpha, p)

        self.__alpha = hierarchize(grid, nodalValues)
        self.__grid = grid

        err = checkInterpolation(self.__grid, self.__alpha, nodalValues)
        if err is True:
            import pdb
            pdb.set_trace()
Пример #2
0
    def testEval(self):
        grid = Grid.createLinearGrid(1)
        grid.getGenerator().regular(3)
        gs = grid.getStorage()

        # prepare surplus vector
        nodalValues = DataVector(gs.getSize())
        nodalValues.setAll(0.0)

        # interpolation on nodal basis
        p = DataVector(gs.getDimension())
        for i in range(gs.getSize()):
            gs.getCoordinates(gs.getPoint(i), p)
            nodalValues[i] = f(p[0])
            # nodalValues[i] = f(p[0], p[1])

        # hierarchization
        alpha = hierarchize(grid, nodalValues)

        # eval the sparse grid function
        x = np.linspace(0, 1, 1000)
        y = [f(xi) for xi in x]
        y1 = [evalSGFunction(grid, alpha, np.array([xi])) for xi in x]
        y2 = evalSGFunctionMulti(grid, alpha, np.array([x]).T)

        assert np.all(y1 - y2 <= 1e-13)
Пример #3
0
    def __discretize(self):
        """
        Discretize squared f to obtain a well suited grid for all
        further computations.
        """
        def f(p, val):
            q = self.__T.unitToProbabilistic(p)
            return val ** 2 * self.__U.pdf(q)
        grid, _, _ = discretize(self.__grid, self.__alpha, f,
                                refnums=4, deg=1, epsilon=1e-6)

        # hierarchize without pdf
        gs = grid.getStorage()
        nodalValues = DataVector(gs.size())
        p = DataVector(gs.dim())
        for i in xrange(gs.size()):
            gs.get(i).getCoords(p)
            nodalValues[i] = evalSGFunction(self.__grid, self.__alpha, p)

        self.__alpha = hierarchize(grid, nodalValues)
        self.__grid = grid

        err = checkInterpolation(self.__grid, self.__alpha, nodalValues)
        if err is True:
            import pdb; pdb.set_trace()
Пример #4
0
def hierarchizeFun(fun):
    nodalValues = np.ndarray(grid.getSize())
    p = DataVector(gs.getDimension())
    for i in range(gs.getSize()):
        gs.getPoint(i).getStandardCoordinates(p)
        nodalValues[i] = fun(p.array())

    return hierarchize(grid, nodalValues)
Пример #5
0
    def computeHierarchicalCoefficients(self, grid, alpha, newGridPoints):
        newGs = grid.getStorage()
        nodalValues = dehierarchize(grid, alpha)

        for newGp in newGridPoints:
            # run over all grid points of current level
            i = newGs.seq(newGp)
            nodalValues[i] = 0.

        return hierarchize(grid, nodalValues)
Пример #6
0
    def makeCurrentNodalValuesPositive(self, grid, alpha, tol=-1e-14):
        nodalValues = dehierarchize(grid, alpha)
        neg = []
        for i, yi in enumerate(nodalValues):
            if yi < tol:
                nodalValues[i] = 0
                neg.append(i)
        if len(neg) > 0:
            alpha = hierarchize(grid, nodalValues)

        return alpha
Пример #7
0
    def computeHierarchicalCoefficients(self, grid, alpha, newGridPoints):
        # define the order of computing the interpolated values -> this
        # makes sure that all function values of the hierarchical ancestors
        # exist for the current value we are interpolating
        gs = grid.getStorage()
        nodalValues = np.ndarray(gs.getSize())
        p = DataVector(gs.getDimension())
        for i in range(gs.getSize()):
            gs.getPoint(i).getStandardCoordinates(p)
            nodalValues[i] = self.func(p.array())

        return hierarchize(grid, nodalValues)
    def makeCurrentGridPositive(self, grid, alpha):
        nodalValues = dehierarchize(grid, alpha)
        cnt = 0
        for i, yi in enumerate(nodalValues.array()):
            if yi < 0:
                nodalValues[i] = 0
                cnt += 1
        if cnt > 0:
            alpha = hierarchize(grid, nodalValues)
            if self.verbose:
                warnings.warn("negative function values encountered, this should not happen")

        return alpha
Пример #9
0
    def makeCurrentNodalValuesPositive(self, grid, alpha):
        nodalValues = dehierarchize(grid, alpha)
        cnt = 0
        for i, yi in enumerate(nodalValues):
            if yi < 0:
                nodalValues[i] = 0
                cnt += 1
        if cnt > 0:
            alpha = hierarchize(grid, nodalValues)
            if self.verbose:
                warnings.warn("negative function values at grid points encountered, this should not happen")

        return alpha
Пример #10
0
    def computeHierarchicalCoefficients(self, grid, alpha, newGridPoints):
        # define the order of computing the interpolated values -> this
        # makes sure that all function values of the hierarchical ancestors
        # exist for the current value we are interpolating
        gs = grid.getStorage()
        levelsum = gs.getMaxLevel() + gs.dim()
        maxlevelsum = gs.getMaxLevel() * gs.dim()

        # interpolate all missing values
        while levelsum <= maxlevelsum:
            filteredGridPoints = []
            for newGp in newGridPoints:
                if levelsum == newGp.getLevelSum():
                    filteredGridPoints.append(newGp)

            # compute coefficients for new grid points
            if len(filteredGridPoints) > 0:
                nodalValues = self.computeMean(grid, alpha, filteredGridPoints)

            levelsum += 1

        return hierarchize(grid, nodalValues)
Пример #11
0
    def computeHierarchicalCoefficients(self, grid, alpha, newGridPoints):
        # define the order of computing the interpolated values -> this
        # makes sure that all function values of the hierarchical ancestors
        # exist for the current value we are interpolating
        gs = grid.getStorage()
        levelsum = gs.getMaxLevel() + gs.dim()
        maxlevelsum = gs.getMaxLevel() * gs.dim()

        # interpolate all missing values
        while levelsum <= maxlevelsum:
            filteredGridPoints = []
            for newGp in newGridPoints:
                if levelsum == newGp.getLevelSum():
                    filteredGridPoints.append(newGp)

            # compute coefficients for new grid points
            if len(filteredGridPoints) > 0:
                nodalValues = self.computeMean(grid, alpha, filteredGridPoints)

            levelsum += 1

        return hierarchize(grid, nodalValues)
Пример #12
0
    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
Пример #13
0
plt.ylim(0, 1)
fig.show()

# get a sprse grid approximation
level = 6
grid = Grid.createLinearGrid(2)
grid.getGenerator().regular(level)
gs = grid.getStorage()

nodalValues = DataVector(grid.getSize())
p = DataVector(gs.getDimension())
for i in range(gs.getSize()):
    gs.getCoordinates(gs.getPoint(i), p)
    nodalValues[i] = dist.pdf(p.array())

alpha = hierarchize(grid, nodalValues)

# plot the result
fig = plt.figure()
plotSG2d(grid, alpha)
plt.title("plotSG: vol = %g" % (doQuadrature(grid, alpha)))
fig.show()

sgdeDist = SGDEdist(grid, alpha)

fig = plt.figure()
plotSGDE2d(sgdeDist)
plt.title("plotSGDE: vol = %g" % (doQuadrature(grid, alpha)))
fig.show()

fig = plt.figure()
Пример #14
0
    def doLearningIteration(self, points):
        """
        Interpolates the given points with the current grid
        @param points: interpolation points
        @return: Return hierarchical surpluses
        """
        gs = self.grid.getStorage()

        # assert that the number of dimensions of the data is the same
        # as the grids
        assert gs.dim() == points.getDim()

        nodalValues = DataVector(gs.size())
        nodalValues.setAll(0.0)

        # interpolation on nodal basis
        p = DataVector(gs.dim())
        cnt = 0
        for i in xrange(gs.size()):
            gp = gs.get(i)
            gp.getCoords(p)
            x = tuple(p.array())
            if x not in points:
                # # search for 2*d closest grid points
                # q = DataVector(gs.dim())
                # l = np.array([])
                # for j in xrange(gs.size()):
                #     gs.get(j).getCoords(q)
                #     q.sub(p)
                #     l = np.append(l, q.l2Norm())

                # n = min(gs.size(), gs.dim())

                # ixs = np.argsort(l)
                # # nodalValues[i] = np.mean(l[ixs[:n]])
                nodalValues[i] = 0.0
                print p, nodalValues[i]
                cnt += 1
            else:
                nodalValues[i] = float(points[x])

        if cnt > 0:
            print '%i/%i of the grid points have \
                   been set to 0' % (cnt, gs.size())
            pdb.set_trace()

        # hierarchization
        alpha = hierarchize(self.grid, nodalValues)

        # -----------------------------------------
        # check if interpolation property is given
#         fig, _ = plotNodal3d(A)
#         fig.show()
#         fig, _ = plotSGNodal3d(self.grid, alpha)
#         fig.show()
#         fig, _ = plotSG3d(self.grid, alpha)
#         fig.show()

        err, _ = checkInterpolation(self.grid, alpha, nodalValues, epsilon=1e-12)

        if len(err) > 0:
            print "interpolation property not met"
            pdb.set_trace()
        # -----------------------------------------

        return alpha
Пример #15
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
Пример #16
0
    def testBilinearForms(self):
        # define parameter set
        builder = ParameterBuilder().defineUncertainParameters()
        # builder.new().isCalled('x').withTNormalDistribution(0.5, 0.1, 0, 1)
        # builder.new().isCalled('y').withTNormalDistribution(0.5, 0.1, 0, 1)
        builder.new().isCalled('x').withUniformDistribution(0, 1)
        builder.new().isCalled('y').withUniformDistribution(0, 1)
        params = builder.andGetResult()

        U = params.getIndependentJointDistribution()
        T = params.getJointTransformation()

        def f(x):
            """
            Function to be interpolated
            """
            # return 2.
            # return float(np.sin(4 * x[0]) * np.cos(4 * x[1]))
            return np.prod([4 * xi * (1 - xi) for xi in x])

        # define sparse grid function
        grid = Grid.createLinearGrid(params.getStochasticDim())
        grid.getGenerator().regular(2)
        gs = grid.getStorage()

        nodalValues = DataVector(gs.getSize())
        p = DataVector(gs.getDimension())

        for i in range(gs.getSize()):
            gs.getCoordinates(gs.getPoint(i), p)
            nodalValues[i] = f(p.array())

        v = hierarchize(grid, nodalValues)
        res = DataVector(gs.getSize())

        # -------------------------------------------------------------------------------
        # compute admissible set
        admissibleSet = RefinableNodesSet()
        admissibleSet.create(grid)

        # -------------------------------------------------------------------------------
        # define the strategies
        s0 = UniformQuadratureStrategy()
        s1 = PiecewiseConstantQuadratureStrategy(params=params)
        s2 = BilinearGaussQuadratureStrategy(U=U.getDistributions(),
                                             T=T.getTransformations())
        s3 = SparseGridQuadratureStrategy(U=U.getDistributions())

        A = s0.computeBilinearForm(grid)
        C, _ = s2.computeBilinearForm(grid)
        D, _ = s3.computeBilinearForm(grid)

        # -------------------------------------------------------------------------------
        # compute bilinear form for lists of grid points
        gpsi, basisi = project(grid, [0, 1])
        gpsj, basisj = project(grid, [0, 1])

        C_list, _ = s2.computeBilinearFormByList(gs, gpsi, basisi, gpsj,
                                                 basisj)
        D_list, _ = s3.computeBilinearFormByList(gs, gpsi, basisi, gpsj,
                                                 basisj)

        assert np.all(np.abs(C_list - A) < 1e-13)
        assert np.all(np.abs(C_list - C) < 1e-13)
        assert np.all(np.abs(D_list - D) < 1e-13)
Пример #17
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
Пример #19
0
# -------------------------------------------------------
# define sparse grid function - control
# -------------------------------------------------------
grid_control = Grid.createLinearGrid(1)
grid_control.getGenerator().regular(4)
gsc = grid_control.getStorage()

nodalValues = DataVector(gsc.getSize())
p = DataVector(gsc.getDimension())

for i in range(gsc.getSize()):
    gsc.getCoordinates(gsc.getPoint(i), p)
    nodalValues[i] = f(p.array())

w = hierarchize(grid_control, nodalValues)

# -------------------------------------------------------
# define sparse grid function
# -------------------------------------------------------
grid = Grid.createLinearGrid(1)
grid.getGenerator().regular(2)
gs = grid.getStorage()

nodalValues = DataVector(gs.getSize())
p = DataVector(gs.getDimension())

for i in range(gs.getSize()):
    gs.getCoordinates(gs.getPoint(i), p)
    nodalValues[i] = f(p.array())
Пример #20
0
    def doLearningIteration(self, points):
        """
        Interpolates the given points with the current grid
        @param points: interpolation points
        @return: Return hierarchical surpluses
        """
        gs = self.grid.getStorage()

        # assert that the number of dimensions of the data is the same
        # as the grids
        assert gs.dim() == points.getDim()

        nodalValues = DataVector(gs.size())
        nodalValues.setAll(0.0)

        # interpolation on nodal basis
        p = DataVector(gs.dim())
        cnt = 0
        for i in xrange(gs.size()):
            gp = gs.get(i)
            gp.getCoords(p)
            x = tuple(p.array())
            if x not in points:
                # # search for 2*d closest grid points
                # q = DataVector(gs.dim())
                # l = np.array([])
                # for j in xrange(gs.size()):
                #     gs.get(j).getCoords(q)
                #     q.sub(p)
                #     l = np.append(l, q.l2Norm())

                # n = min(gs.size(), gs.dim())

                # ixs = np.argsort(l)
                # # nodalValues[i] = np.mean(l[ixs[:n]])
                nodalValues[i] = 0.0
                print p, nodalValues[i]
                cnt += 1
            else:
                nodalValues[i] = float(points[x])

        if cnt > 0:
            print '%i/%i of the grid points have \
                   been set to 0' % (cnt, gs.size())
            pdb.set_trace()

        # hierarchization
        alpha = hierarchize(self.grid, nodalValues)

        # -----------------------------------------
        # check if interpolation property is given
        #         fig, _ = plotNodal3d(A)
        #         fig.show()
        #         fig, _ = plotSGNodal3d(self.grid, alpha)
        #         fig.show()
        #         fig, _ = plotSG3d(self.grid, alpha)
        #         fig.show()

        err, _ = checkInterpolation(self.grid,
                                    alpha,
                                    nodalValues,
                                    epsilon=1e-12)

        if len(err) > 0:
            print "interpolation property not met"
            pdb.set_trace()
        # -----------------------------------------

        return alpha
Пример #21
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