示例#1
0
文件: general.py 项目: pfluegdk/SGpp
def project(grid, dims):
    """
    Project all grid points to the given dimensions

    @param grid: Grid sparse grid
    @param dims: list dimensions to which the grid points are projected
    """
    gs = grid.getStorage()

    # create a new empty grid
    dim = len(dims)
    gps = [None] * gs.getSize()

    # run over all grid points in grid and
    # project them to the dimensions dims
    for i in range(gs.getSize()):
        gp = gs.getPoint(i)
        ngp = HashGridPoint(dim)
        # copy level index to new grid point
        for k, d in enumerate(dims):
            ngp.set(k, gp.getLevel(d), gp.getIndex(d))
        # insert it to the new grid
        gps[i] = ngp

    # compute new basis
    ngrid = createGrid(grid, len(dims))
    basis = getBasis(ngrid)
    return gps, basis
示例#2
0
文件: general.py 项目: pfluegdk/SGpp
def extend_grid_1d(grid, *args, **kws):
    gs = grid.getStorage()
    accLevel = gs.getMaxLevel()
    dim = gs.getDimension()

    # create dim+1 dimensional grid of level 0
    new_grid = createGrid(grid, dim + 1, *args, **kws)

    # create 1 dimensional reference grid of level accLevel
    ref_grid = createGrid(grid, 1)
    ref_grid.getGenerator().regular(accLevel)  # == full grid in dim = 1
    ref_gs = ref_grid.getStorage()

    # create cross product between the 1d and the dimd-grid
    for i in range(gs.getSize()):
        gp = gs.getPoint(i)
        new_gp = HashGridPoint(dim + 1)

        # copy level index vectors from old grid to the new one
        for d in range(gs.getDimension()):
            new_gp.set(d, gp.getLevel(d), gp.getIndex(d))

        # get the indices in the missing dimension
        for j in range(ref_gs.getSize()):
            ref_gp = ref_gs.getPoint(j)
            new_gp.set(dim, ref_gp.getLevel(0), ref_gp.getIndex(0))
            insertPoint(new_grid, new_gp)

    return new_grid
示例#3
0
    def findIntersectionsOfOverlappingSuppportsForOneGridPoint(
            self, gpi, gpsj, overlap, grid):
        numDims = gpi.getDimension()
        gs = grid.getStorage()

        # find all possible intersections of grid points
        comparisonCosts = 0
        for j, gpj in list(gpsj.items()):
            if not isHierarchicalAncestor(gpi, gpj):
                comparisonCosts += 1
                if haveOverlappingSupport(gpi, gpj):
                    levelOuter, indexOuter = self.findOuterIntersection(
                        gpi, gpj)
                    if (levelOuter, indexOuter) not in overlap:
                        gpOuterIntersection = HashGridPoint(self.numDims)
                        for idim in range(self.numDims):
                            gpOuterIntersection.set(idim, levelOuter[idim],
                                                    indexOuter[idim])

                        # TODO: this might not be correct
                        # -> it does work for a few test cases but this might
                        #    be a coincidence
#                         if not gs.isContaining(gpOuterIntersection):
                        overlap[levelOuter,
                                indexOuter] = gpi, gpj, gpOuterIntersection

        return comparisonCosts
示例#4
0
    def transformToReferenceGrid(self, globalGrid):
        # 1. set the root node of the local grid
        localRoot = {'level': self.level, 'index': self.index}

        # 2. shift and scale the global grid to the local one
        localGrid = {}

        locallevels = np.ndarray(self.numDims, dtype="int")
        localindices = np.ndarray(self.numDims, dtype="int")

        for levelsGlobal, indicesGlobal in list(globalGrid.keys()):
            gpdd = HashGridPoint(self.numDims)
            for idim in range(self.numDims):
                lg, ig = levelsGlobal[idim], indicesGlobal[idim]
                llroot, ilroot = localRoot['level'][idim], localRoot['index'][
                    idim]

                # compute level and index of local grid
                # 1 -> level index of global root node, always the same
                locallevels[idim] = int(lg + (llroot - 1))
                localindices[idim] = int(ig + (ilroot - 1) * 2**(lg - 1))
                gpdd.set(idim, locallevels[idim], localindices[idim])

            localGrid[(tuple(locallevels), tuple(localindices))] = gpdd

        return localGrid
示例#5
0
    def copy(localFullGrid):
        numDims = localFullGrid.numDims
        gp = HashGridPoint(numDims)
        for idim in range(numDims):
            gp.set(idim, localFullGrid.level[idim], localFullGrid.index[idim])

        fullGrid = LocalFullGrid(localFullGrid.grid, gp,
                                 np.array(localFullGrid.fullGridLevels))

        return fullGrid
示例#6
0
    def computeCandidates(self, sortedOverlap, localFullGridLevels, grid,
                          alpha):
        # create full grid locally
        gs = grid.getStorage()
        maxLevel = gs.getMaxLevel()
        ans = {}
        costs = 0

        while len(sortedOverlap) > 0:
            numLocalGridPoints, levels, indices, (ranges, gpi,
                                                  gpj) = sortedOverlap.pop()

            # do not consider intersection if it is already part of the local grid
            # -> TODO: if an intersection is already part of some other local grid
            #          then there exists an ancestor in the list of intersections.
            #          Check first if there are ancestors available and if yes,
            #          remove the successor node from the intersection list
            if (levels, indices) not in ans:
                globalGrid = self.computeAnisotropicFullGrid(
                    levels, indices, localFullGridLevels[levels, indices])
                costs += len(globalGrid)
                assert numLocalGridPoints == len(globalGrid)

                # 1. set the root node of the local grid
                localRoot = {'level': levels, 'index': indices}

                # 2. shift and scale the global grid to the local one
                localGrid = {}
                levels = [None] * self.numDims
                indices = [None] * self.numDims
                for levelsGlobal, indicesGlobal in list(globalGrid.keys()):
                    gpdd = HashGridPoint(self.numDims)
                    for idim in range(self.numDims):
                        lg, ig = levelsGlobal[idim], indicesGlobal[idim]
                        llroot, ilroot = localRoot['level'][idim], localRoot[
                            'index'][idim]

                        # compute level and index of local grid
                        # 1 -> level index of global root node, always the same
                        levels[idim] = int(lg + (llroot - 1))
                        indices[idim] = int(ig + (ilroot - 1) * 2**(lg - 1))
                        gpdd.set(idim, levels[idim], indices[idim])

                    if not gs.isContaining(gpdd):
                        localGrid[(tuple(levels), tuple(indices))] = gpdd

                if self.plot and self.numDims == 2:
                    self.plotDebug(grid, alpha, localGrid, gpi, gpj, ans)

                assert len(localGrid) > 0
                oldSize = len(ans)
                ans.update(localGrid)
                assert len(ans) > oldSize

        return list(ans.values()), costs
示例#7
0
def parent(grid, gp, d):
    # get parent
    level = gp.getLevel(d) - 1
    index = gp.getIndex(d) / 2 + ((gp.getIndex(d) + 1) / 2) % 2

    if isValid1d(grid, level, index):
        # create parent
        ans = HashGridPoint(gp)
        ans.set(d, level, index)
        return ans

    return None
示例#8
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
示例#9
0
def getBoundsOfSupport(gs, level, index, gridType=GridType_Linear):
    if level > 0:
        if gridType in bsplineGridTypes:
            # this is just an approximation of the real boundaries
            gp = HashGridPoint(1)
            gp.set(0, level, index)
            xcenter = gs.getCoordinate(gp, 0)
            gp.getLeftBoundaryPoint(0)
            xleft = gs.getCoordinate(gp, 0)
            gp.set(0, level, index)
            gp.getRightBoundaryPoint(0)
            xright = gs.getCoordinate(gp, 0)
            return (max(0.0, xcenter - level * (xcenter - xleft)),
                    min(1.0, xcenter + level * (xright - xcenter)))
        else:
            gp = HashGridPoint(1)
            gp.set(0, level, index)
            gp.getLeftBoundaryPoint(0)
            xleft = gs.getCoordinate(gp, 0)
            gp.set(0, level, index)
            gp.getRightBoundaryPoint(0)
            xright = gs.getCoordinate(gp, 0)
            return xleft, xright
    else:
        return 0., 1.
示例#10
0
    def getLocalMaxLevel(self, dup, levels, indices, grid):
        gp = HashGridPoint(self.numDims)
        for idim, (level, index) in enumerate(zip(levels, indices)):
            gp.set(idim, level, index)

        # up in direction d to the root node
        gp.set(dup, 1, 1)
        # down as far as possible in direction d + 1 mod D
        ddown = (dup + 1) % self.numDims

        # search for children
        # as long as the corresponding grid point exist in the grid
        children = self.getMaxLevelOfChildrenUpToMaxLevel(gp, grid, ddown)
        maxLevel = int(max(1, np.max(children)))

        return maxLevel, ddown
示例#11
0
def hasChildren(grid, gp):
    gs = grid.getStorage()
    d = 0
    gpn = HashGridPoint(gp)
    while d < gs.getDimension():
        # load level index
        level, index = gp.getLevel(d), gp.getIndex(d)
        # check left child in d
        gp.getLeftChild(d)
        if gs.isContaining(gpn):
            return True

        # check right child in d
        gp.set(d, level, index)
        gp.getRightChild(d)
        if gs.isContaining(gpn):
            return True

        gpn.set(d, level, index)
        d += 1

    return False
示例#12
0
文件: general.py 项目: pfluegdk/SGpp
def projectList(gps, dims):
    """
    Project all grid points to the given dimensions

    @param gps: list of grid points
    @param dims: list dimensions to which the grid points are projected
    """
    # create a new empty grid
    dim = len(dims)
    projected_gps = [None] * len(gps)

    # run over all grid points in grid and
    # project them to the dimensions dims
    for i, gp in enumerate(gps):
        projected_gp = HashGridPoint(dim)
        # copy level index to new grid point
        for k, d in enumerate(dims):
            projected_gp.set(k, gp.getLevel(d), gp.getIndex(d))
        # insert it to the list of projected grid points
        projected_gps[i] = projected_gp

    return projected_gps
示例#13
0
    def getLocalMaxLevel(self, dup, levels, indices, grid):
        gp = HashGridPoint(self.numDims)
        for idim, (level, index) in enumerate(zip(levels, indices)):
            gp.set(idim, level, index)

        # up in direction d to the root node
        diffLevels = np.zeros(self.numDims)
        for idim in range(self.numDims):
            # search for children
            # as long as the corresponding grid point exist in the grid
            gp.set(idim, 1, 1)
            if self.verbose:
                print(" %i: root (%i) = %s" %
                      (dup, idim,
                       (tuple(getLevel(gp)), tuple(getIndex(gp)),
                        tuple([gp.getCoord(i) for i in range(self.numDims)]))))

            currentgp = HashGridPoint(gp)
            diffLevels[idim] = self.getMaxLevelOfChildrenUpToMaxLevel(
                currentgp, grid, idim)

        return diffLevels
示例#14
0
def __doMarginalize(grid, alpha, linearForm, dd, measure=None):
    gs = grid.getStorage()

    dim = gs.getDimension()

    if dim < 2:
        raise AttributeError("The grid has to be at least of dimension 2")

    if dd >= dim:
        raise AttributeError("The grid has only %i dimensions, so I can't \
                             integrate over %i" % (dim, dd))

    # create new grid
    n_dim = dim - 1
    n_grid = createGrid(grid, n_dim)
    n_gs = n_grid.getStorage()

    # insert grid points
    n_gp = HashGridPoint(n_dim)
    for i in range(gs.getSize()):
        gp = gs.getPoint(i)
        for d in range(dim):
            if d == dd:
                # omit marginalization direction
                continue
            elif d < dd:
                n_gp.set(d, gp.getLevel(d), gp.getIndex(d))
            else:
                n_gp.set(d - 1, gp.getLevel(d), gp.getIndex(d))

        # insert grid point
        if not n_gs.isContaining(n_gp):
            n_gs.insert(n_gp)

    n_gs.recalcLeafProperty()

    # create coefficient vector
    n_alpha = np.zeros(n_gs.getSize())

    basis = getBasis(grid)
    # set function values for n_alpha
    for i in range(gs.getSize()):
        gp = gs.getPoint(i)

        for d in range(dim):
            if d == dd:
                dd_level = gp.getLevel(d)
                dd_index = gp.getIndex(d)
            elif d < dd:
                n_gp.set(d, gp.getLevel(d), gp.getIndex(d))
            else:
                n_gp.set(d - 1, gp.getLevel(d), gp.getIndex(d))

        if not n_gs.isContaining(n_gp):
            raise Exception("This should not happen!")

        # compute the integral of the given basis
        if measure is None:
            q, err = getIntegral(grid, dd_level, dd_index), 0.
        else:
            dist, trans = measure[0][dd], measure[1][dd]
            linearForm.setDistributionAndTransformation([dist], [trans])
            gpdd = HashGridPoint(1)
            gpdd.set(0, dd_level, dd_index)
            q, err = linearForm.computeLinearFormByList(gs, [gpdd], basis)
            q = q[0] * trans.vol()
            err *= trans.vol()

        # search for the corresponding index
        j = n_gs.getSequenceNumber(n_gp)
        n_alpha[j] += alpha[i] * q

    return n_grid, n_alpha, err
示例#15
0
    def getLocalFullGridLevel(self, levels, indices, grid, gpk=None, gpl=None):
        localMaxLevels = np.zeros(self.numDims,
                                  dtype="int")  # + self.maxLevel - levels + 1
        if False and self.numDims == 2 and self.plot:
            levelouter, indexouter = self.findOuterIntersection(gpk, gpl)
            levelinner, indexinner = self.findInnerIntersection(gpk, gpl)
            fig = plt.figure()
            plotGrid2d(grid)
            if gpk is not None:
                plt.plot(gpk.getCoord(0), gpk.getCoord(1), "v", color="orange")
            if gpl is not None:
                plt.plot(gpl.getCoord(0), gpl.getCoord(1), "v", color="orange")
            plt.plot(2**-levelinner[0] * indexinner[0],
                     2**-levelinner[1] * indexinner[1],
                     "o ",
                     color="yellow")
            plt.plot(2**-levelouter[0] * indexouter[0],
                     2**-levelouter[1] * indexouter[1],
                     "o ",
                     color="yellow")
            plt.xlim(0, 1)
            plt.ylim(0, 1)
            fig.show()

        gpInnerIntersection = HashGridPoint(self.numDims)
        gpi = HashGridPoint(self.numDims)
        gpj = HashGridPoint(self.numDims)
        gs = grid.getStorage()

        for idim, jdim in combinations(list(range(self.numDims)), 2):
            # find neighbors in direction idim
            iright, ileft = getGridPointsOnBoundary(levels[idim],
                                                    indices[idim])
            # find neighbors in direction idim
            jright, jleft = getGridPointsOnBoundary(levels[jdim],
                                                    indices[jdim])

            for left, right in product((iright, ileft), (jright, jleft)):
                if left is not None and right is not None:
                    (llevel, lindex), (rlevel, rindex) = left, right
                    for i in range(self.numDims):
                        # compute intersection i
                        if i == idim:
                            gpi.set(i, int(llevel), int(lindex))
                        else:
                            gpi.set(i, levels[i], indices[i])

                        # compute intersection j
                        if i == jdim:
                            gpj.set(i, int(rlevel), int(rindex))
                        else:
                            gpj.set(i, levels[i], indices[i])

                    # compute inner intersection
                    levelInner, indexInner = self.findInnerIntersection(
                        gpi, gpj)
                    for i in range(self.numDims):
                        gpInnerIntersection.set(i, levelInner[i],
                                                indexInner[i])

                    if gs.isContaining(gpj):
                        localMaxLevels[idim] = max(
                            localMaxLevels[idim],
                            self.getMaxLevelOfChildrenUpToMaxLevel(
                                gpj, grid, idim))
                    if gs.isContaining(gpi):
                        localMaxLevels[jdim] = max(
                            localMaxLevels[jdim],
                            self.getMaxLevelOfChildrenUpToMaxLevel(
                                gpi, grid, jdim))
                    if gs.isContaining(gpInnerIntersection):
                        xdim = np.array([
                            i for i in range(self.numDims)
                            if i != idim and i != jdim
                        ],
                                        dtype="int")
                        for i in xdim:
                            localMaxLevels[i] = max(
                                localMaxLevels[i],
                                self.getMaxLevelOfChildrenUpToMaxLevel(
                                    gpInnerIntersection, grid, i))

                    # plot result
                    if False and self.plot:
                        levelouter, indexouter = self.findOuterIntersection(
                            gpi, gpj)
                        fig = plt.figure()
                        plotGrid2d(grid)

                        plt.plot(gpi.getCoord(0),
                                 gpi.getCoord(1),
                                 "v",
                                 color="orange")
                        plt.plot(gpj.getCoord(0),
                                 gpj.getCoord(1),
                                 "v",
                                 color="orange")
                        plt.plot(gpInnerIntersection.getCoord(0),
                                 gpInnerIntersection.getCoord(1),
                                 "v ",
                                 color="red")
                        plt.plot(2**-levelouter[0] * indexouter[0],
                                 2**-levelouter[1] * indexouter[1],
                                 "o ",
                                 color="yellow")
                        plt.xlim(0, 1)
                        plt.ylim(0, 1)
                        plt.title(localMaxLevels)
                        fig.show()

        if False and self.plot:
            plt.show()

        return localMaxLevels + 1