def plotDebugIntersections(self, newGrid, overlappingGridPoints):
        # -----------------------------------------------------------------
        # plot result
        gs = newGrid.getStorage()
        for n, ((i, j), (gpi,
                         gpj)) in enumerate(overlappingGridPoints.items()):
            fig = plt.figure()
            for k in range(gs.getSize()):
                gp = gs.getPoint(k)
                x, y = gp.getStandardCoordinate(0), gp.getStandardCoordinate(1)
                if alpha[k] < 0.0:
                    plt.plot(x, y, "v ", color="red")
                else:
                    plt.plot(x, y, "^ ", color="white")

            # annotate the
            plt.annotate(
                str(i),
                (gpi.getStandardCoordinate(0), gpi.getStandardCoordinate(1)))
            plt.annotate(
                str(j),
                (gpj.getStandardCoordinate(0), gpj.getStandardCoordinate(1)))

            # draw support
            # get level index
            for gp, col in ((gpi, "b"), (gpj, "r")):
                l0, i0, l1, i1 = gp.getLevel(0), gp.getIndex(0), gp.getLevel(
                    1), gp.getIndex(1)
                xlim0, xlim1 = getBoundsOfSupport(l0, i0), getBoundsOfSupport(
                    l1, i1)
                diff0, diff1 = xlim0[1] - xlim0[0], xlim1[1] - xlim1[0]
                currentAxis = plt.gca()
                currentAxis.add_patch(
                    Rectangle((xlim0[0], xlim1[0]),
                              diff0,
                              diff1,
                              facecolor=col,
                              alpha=0.5))

            xlim = self.computeBoundsOfOverlappingPatch(gpi, gpj)
            currentAxis = plt.gca()
            currentAxis.add_patch(
                Rectangle((xlim[0, 0], xlim[1, 0]),
                          np.diff(xlim[0, :2]),
                          np.diff(xlim[1, :2]),
                          facecolor="gray",
                          alpha=0.9))

            gp = self.findIntersection(gpi, gpj)
            plt.plot(gp.getStandardCoordinate(0),
                     gp.getStandardCoordinate(1),
                     "o ",
                     color="black")

            plt.title("%i/%i" % (n + 1, len(overlappingGridPoints)))
            plt.xlim(0, 1)
            plt.ylim(0, 1)
            plt.show()
            plt.close(fig)
Exemple #2
0
    def findIntersectionsOfOverlappingSuppportsForOneGridPoint(
            self, i, gpi, gpsj, overlap, grid, alpha):
        numDims = gpi.getDimension()
        gs = grid.getStorage()
        gpintersection = HashGridPoint(self.numDims)

        # find all possible intersections of grid points
        comparisonCosts = fullGridCosts = 0
        for j, gpj in list(gpsj.items()):
            comparisonCosts += 1
            idim = 0
            ranges = []
            while idim < numDims:
                # get level index
                lid, iid = gpi.getLevel(idim), gpi.getIndex(idim)
                ljd, ijd = gpj.getLevel(idim), gpj.getIndex(idim)

                # check if they have overlapping support
                xlowi, xhighi = getBoundsOfSupport(lid, iid)
                xlowj, xhighj = getBoundsOfSupport(ljd, ijd)

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

                # different level but not ancestors
                if xlow >= xhigh:
                    break
                else:
                    ranges.append([xlow, xhigh])

                idim += 1

            # check whether the supports are overlapping
            # in all dimensions
            if idim == numDims:
                ancestors_gpj = [(0, gpj)] + getHierarchicalAncestors(
                    grid, gpj)
                for _, ancestor_gpj in ancestors_gpj:
                    fullGridCosts += 1
                    level, index = self.findIntersection(gpi, ancestor_gpj)
                    gpintersection = HashGridPoint(self.numDims)
                    for idim in range(self.numDims):
                        gpintersection.set(idim, level[idim], index[idim])

                    if not gs.isContaining(gpintersection):

                        if self.plot and self.numDims == 2:
                            self.plotDebug(grid, alpha, {1: gpintersection},
                                           gpi, gpj, overlap)

                        overlap[level, index] = gpintersection

        return comparisonCosts, fullGridCosts
Exemple #3
0
    def computeBilinearFormEntry(self, gs, gpi, basisi, gpj, basisj, d):
        # if not, compute it
        val = 1
        err = 0.

        # run over all dimensions
        d = 0
        while d < gpi.getDimension() and abs(val) > 1e-15:
            # 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:
                val = err = 0
            # the support does not overlap
            elif lid != ljd and xlow >= xhigh:
                val = err = 0
            else:
                # ----------------------------------------------------
                # use scipy for integration
                def f(p):
                    return basisi.eval(lid, iid, p) * \
                        basisj.eval(ljd, ijd, p)

                s, err1d = quad(f, xlow, xhigh, epsabs=1e-8)
                # ----------------------------------------------------
                val *= s
                err += err1d

            d += 1

        return val, err
Exemple #4
0
    def computeTrilinearFormEntry(self, gs, gpk, basisk, gpi, basisi, gpj,
                                  basisj, d):
        val = 1
        err = 0.

        # get level index
        lkd, ikd = gpk.getLevel(d), gpk.getIndex(d)
        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 all
        # three basis functions
        xlowk, xhighk = getBoundsOfSupport(gs, lkd, ikd, self._gridType)
        xlowi, xhighi = getBoundsOfSupport(gs, lid, iid, self._gridType)
        xlowj, xhighj = getBoundsOfSupport(gs, ljd, ijd, self._gridType)

        # compute overlapping support
        xlow = max(xlowk, xlowi, xlowj)
        xhigh = min(xhighk, xhighi, xhighj)

        # check if the overlapping support is larger than 0
        if xlow >= xhigh:
            val = err = 0
        else:
            # ----------------------------------------------------
            # use gauss-legendre-quadrature
            def f(p):
                return basisk.eval(lkd, ikd, p) * \
                    basisi.eval(lid, iid, p) * \
                    basisj.eval(ljd, ijd, p)

            if lid >= ljd and lid >= lkd:
                xcenter = gs.getCoordinate(gpi, d)
            elif ljd >= lid and ljd >= lkd:
                xcenter = gs.getCoordinate(gpj, d)
            else:
                xcenter = gs.getCoordinate(gpk, d)

            deg = 2
            if self._gridType in polyGridTypes:
                deg = lid + ljd + lkd

            sleft, err1dleft = self.quad(f, xlow, xcenter, deg=deg)
            sright, err1dright = self.quad(f, xcenter, xhigh, deg=deg)
            #             # -----------------------------------------
            #             # plot the basis
            #             import matplotlib.pyplot as plt
            #             import numpy as np
            #             x = np.linspace(xlow, xhigh, 100)
            #             b0 = [basisk.eval(lkd, ikd, xi) for xi in np.linspace(xlowk, xhighk, 100)]
            #             b1 = [basisi.eval(lid, iid, xi) for xi in np.linspace(xlowi, xhighi, 100)]
            #             b2 = [basisj.eval(ljd, ijd, xi) for xi in np.linspace(xlowj, xhighj, 100)]
            # #             pdf = [self._U[d].pdf(self._T[d].unitToProbabilistic(xi))
            # #                    for xi in x]
            #             res = [f(xi) for xi in x]
            #             numpy_quad = scipy.integrate.quad(f, xlow, xcenter)[0] + \
            #                 scipy.integrate.quad(f, xcenter, xhigh)[0]
            #
            #             fig = plt.figure()
            #             plt.plot(x, b0, label="basis 0")
            #             plt.plot(x, b1, label="basis 1")
            #             plt.plot(x, b2, label="basis 2")
            #             # plt.plot(x, pdf, label="pdf")
            #             plt.plot(x, res, label="product")
            #             plt.title("[%g, %g] -> (%i, %i), (%i, %i), (%i, %i), %g = %g" % (xlow, xhigh, lkd, ikd, lid, iid, ljd, ijd, sleft + sright, numpy_quad))
            #             plt.legend()
            #             plt.xlim(0, 1)
            #             plt.show()
            #             # fig.savefig("/home/franzefn/Desktop/tmp/trilinear/no_key_%i.png" % np.random.randint(10000))
            #             # ----------------------------------------------------
            val = sleft + sright
            err = err1dleft + err1dright

        return val, err
Exemple #5
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
Exemple #6
0
    def computeTrilinearFormEntry(self, gpk, basisk,
                                  gpi, basisi,
                                  gpj, basisj,
                                  d):
        val = 1
        err = 0.

        # get level index
        lkd, ikd = gpk.getLevel(d), gpk.getIndex(d)
        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 all
        # three basis functions
        xlowk, xhighk = getBoundsOfSupport(lkd, ikd)
        xlowi, xhighi = getBoundsOfSupport(lid, iid)
        xlowj, xhighj = getBoundsOfSupport(ljd, ijd)

        # compute overlapping support
        xlow = max(xlowk, xlowi, xlowj)
        xhigh = min(xhighk, xhighi, xhighj)

        # check if the overlapping support is larger than 0
        if xlow >= xhigh:
            val = err = 0
        else:
            # ----------------------------------------------------
            # use gauss-legendre-quadrature
            def f(p):
                return basisk.eval(lkd, ikd, p) * \
                    basisi.eval(lid, iid, p) * \
                    basisj.eval(ljd, ijd, p)

            sleft, err1dleft = self.quad(f, xlow, (xlow + xhigh) / 2,
                                         deg=2 * (gpi.getLevel(d) + 1) + 1)
            sright, err1dright = self.quad(f, (xlow + xhigh) / 2, xhigh,
                                           deg=2 * (gpi.getLevel(d) + 1) + 1)
#             # -----------------------------------------
#             # plot the basis
#             import matplotlib.pyplot as plt
#             import numpy as np
#             x = np.linspace(xlow, xhigh, 100)
#             b0 = [basisk.eval(lkd, ikd, xi) for xi in np.linspace(xlowk, xhighk, 100)]
#             b1 = [basisi.eval(lid, iid, xi) for xi in np.linspace(xlowi, xhighi, 100)]
#             b2 = [basisj.eval(ljd, ijd, xi) for xi in np.linspace(xlowj, xhighj, 100)]
# #             pdf = [self._U[d].pdf(self._T[d].unitToProbabilistic(xi))
# #                    for xi in x]
#             res = [f(xi) for xi in x]
# 
#             fig = plt.figure()
#             plt.plot(x, b0, label="basis 0")
#             plt.plot(x, b1, label="basis 1")
#             plt.plot(x, b2, label="basis 2")
#             # plt.plot(x, pdf, label="pdf")
#             plt.plot(x, res, label="product")
#             plt.title("[%g, %g] -> (%i, %i), (%i, %i), (%i, %i), %g" % (xlow, xhigh, lkd, ikd, lid, iid, ljd, ijd, sleft + sright))
#             plt.legend()
#             plt.xlim(0, 1)
#             plt.show()
#             # fig.savefig("/home/franzefn/Desktop/tmp/trilinear/no_key_%i.png" % np.random.randint(10000))
#             # ----------------------------------------------------
            val = val * (sleft + sright)
            err += val * (err1dleft + err1dright)

        return val, err