当前位置: 首页>>代码示例>>Python>>正文


Python DataVector.setAll方法代码示例

本文整理汇总了Python中pysgpp.DataVector.setAll方法的典型用法代码示例。如果您正苦于以下问题:Python DataVector.setAll方法的具体用法?Python DataVector.setAll怎么用?Python DataVector.setAll使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pysgpp.DataVector的用法示例。


在下文中一共展示了DataVector.setAll方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: currentDiagHess

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
    def currentDiagHess(self, params):
        #return np.ones(params.shape)
#         if hasattr(self, 'H'):
#             return self.H
#         op_l2_dot = createOperationLTwoDotProduct(self.grid)
#         self.H = np.empty((self.grid.getSize(), self.grid.getSize()))
#         u = DataVector(self.grid.getSize())
#         u.setAll(0.0)
#         result = DataVector(self.grid.getSize())
#         for grid_idx in xrange(self.grid.getSize()):
#             u[grid_idx] = 1.0
#             op_l2_dot.mult(u, result)
#             self.H[grid_idx,:] = result.array()
#             u[grid_idx] = 0.0
#         self.H = np.diag(self.H).reshape(1,-1)
#         return self.H
        #import ipdb; ipdb.set_trace()
        size = self._lastseen.shape[0]
        data_matrix = DataMatrix(self._lastseen[:,:self.dim])
        mult_eval = createOperationMultipleEval(self.grid, data_matrix);
        params_DV = DataVector(self.grid.getSize())
        params_DV.setAll(0.)
        results_DV = DataVector(size)
        self.H = np.zeros(self.grid.getSize())
        for i in xrange(self.grid.getSize()):
            params_DV[i] = 1.0
            mult_eval.mult(params_DV, results_DV);
            self.H[i] = results_DV.l2Norm()**2
            params_DV[i] = 0.0
        self.H = self.H.reshape(1,-1)/size
        #import ipdb; ipdb.set_trace() 
        return self.H
开发者ID:mlocs,项目名称:ipython-nb,代码行数:34,代码来源:wrappers.py

示例2: mean

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
    def mean(self, grid, alpha, U, T):
        r"""
        Extraction of the expectation the given sparse grid function
        interpolating the product of function value and pdf.

        \int\limits_{[0, 1]^d} f_N(x) * pdf(x) dx
        """
        # extract correct pdf for moment estimation
        vol, W = self._extractPDFforMomentEstimation(U, T)
        D = T.getTransformations()
        # compute the integral of the product
        gs = grid.getStorage()
        acc = DataVector(gs.size())
        acc.setAll(1.)
        tmp = DataVector(gs.size())
        err = 0
        # run over all dimensions
        for i, dims in enumerate(W.getTupleIndices()):
            dist = W[i]
            trans = D[i]

            # get the objects needed for integration the current dimensions
            gpsi, basisi = project(grid, dims)

            if isinstance(dist, SGDEdist):
                # if the distribution is given as a sparse grid function we
                # need to compute the bilinear form of the grids
                # accumulate objects needed for computing the bilinear form
                gpsj, basisj = project(dist.grid, range(len(dims)))

                # compute the bilinear form
                bf = BilinearGaussQuadratureStrategy()
                A, erri = bf.computeBilinearFormByList(gpsi, basisi,
                                                       gpsj, basisj)
                # weight it with the coefficient of the density function
                self.mult(A, dist.alpha, tmp)
            else:
                # the distribution is given analytically, handle them
                # analytically in the integration of the basis functions
                if isinstance(dist, Dist) and len(dims) > 1:
                    raise AttributeError('analytic quadrature not supported for multivariate distributions')
                if isinstance(dist, Dist):
                    dist = [dist]
                    trans = [trans]

                lf = LinearGaussQuadratureStrategy(dist, trans)
                tmp, erri = lf.computeLinearFormByList(gpsi, basisi)

            # print error stats
            # print "%s: %g -> %g" % (str(dims), err, err + D[i].vol() * erri)
            # import ipdb; ipdb.set_trace()

            # accumulate the error
            err += D[i].vol() * erri

            # accumulate the result
            acc.componentwise_mult(tmp)

        moment = alpha.dotProduct(acc)
        return vol * moment, err
开发者ID:ABAtanasov,项目名称:Sparse-Grids,代码行数:62,代码来源:AnalyticEstimationStrategy.py

示例3: computeTrilinearFormByRow

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
 def computeTrilinearFormByRow(self,
                               gpsk, basisk,
                               gpi, basisi,
                               gpj, basisj):
     """
     Compute the trilinear form of two grid point with a list
     of grid points
     @param gpk: list of HashGridIndex
     @param basisk: SG++ Basis for grid indices k
     @param gpi: HashGridIndex
     @param basisi: SG++ Basis for grid indices i
     @param gpj: HashGridIndex
     @param basisj: SG++ Basis for grid indices j
     @return DataVector
     """
     b = DataVector(len(gpsk))
     b.setAll(1.0)
     err = 0.
     # run over all entries
     for k, gpk in enumerate(gpsk):
         # run over all dimensions
         for d in xrange(gpi.dim()):
             # compute trilinear form for one entry
             value, erri = self.getTrilinearFormEntry(gpk, basisk,
                                                      gpi, basisi,
                                                      gpj, basisj,
                                                      d)
             b[k] *= value
             err += erri
     return b, err
开发者ID:ABAtanasov,项目名称:Sparse-Grids,代码行数:32,代码来源:TrilinearQuadratureStrategy.py

示例4: testOperationB

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
 def testOperationB(self):
     from pysgpp import Grid, DataVector, DataMatrix
     factory = Grid.createLinearBoundaryGrid(1)
     gen = factory.createGridGenerator()
     gen.regular(2)
     
     alpha = DataVector(factory.getStorage().size())
     p = DataMatrix(1,1)
     beta = DataVector(1)
     
     
     alpha.setAll(0.0)
     p.set(0,0,0.25)
     beta[0] = 1.0
     
     opb = factory.createOperationB()
     opb.mult(beta, p, alpha)
     
     self.failUnlessAlmostEqual(alpha[0], 0.75)
     self.failUnlessAlmostEqual(alpha[1], 0.25)
     self.failUnlessAlmostEqual(alpha[2], 0.5)
     self.failUnlessAlmostEqual(alpha[3], 1.0)
     self.failUnlessAlmostEqual(alpha[4], 0.0)
     
     alpha.setAll(0.0)
     alpha[2] = 1.0
     
     p.set(0,0, 0.25)
     
     beta[0] = 0.0
     
     opb.multTranspose(alpha, p, beta)
     self.failUnlessAlmostEqual(beta[0], 0.5)
开发者ID:samhelmholtz,项目名称:skinny-dip,代码行数:35,代码来源:test_GridFactory.py

示例5: generateLaplaceMatrix

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
def generateLaplaceMatrix(factory, level, verbose=False):
    from pysgpp import DataVector
    storage = factory.getStorage()
    
    gen = factory.createGridGenerator()
    gen.regular(level)
    
    laplace = factory.createOperationLaplace()
    
    # create vector
    alpha = DataVector(storage.size())
    erg = DataVector(storage.size())

    # create stiffness matrix
    m = DataVector(storage.size(), storage.size())
    m.setAll(0)
    for i in xrange(storage.size()):
        # apply unit vectors
        alpha.setAll(0)
        alpha[i] = 1
        laplace.mult(alpha, erg)
        if verbose:
            print erg, erg.sum()
        m.setColumn(i, erg)

    return m
开发者ID:samhelmholtz,项目名称:skinny-dip,代码行数:28,代码来源:test_laplace.py

示例6: var

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
    def var(self, grid, alpha, U, T, mean):
        r"""
        Estimate the expectation value using Monte-Carlo.

        \frac{1}{N}\sum\limits_{i = 1}^N (f_N(x_i) - E(f))^2

        where x_i \in \Gamma
        """
        # init
        _, W = self._extractPDFforMomentEstimation(U, T)
        moments = np.zeros(self.__npaths)
        vecMean = DataVector(self.__n)
        vecMean.setAll(mean)
        for i in xrange(self.__npaths):
            samples = self.__getSamples(W, T, self.__n)
            res = evalSGFunctionMulti(grid, alpha, samples)
            res.sub(vecMean)
            res.sqr()

            # compute the moment
            moments[i] = res.sum() / (len(res) - 1.)

        # error statistics
        err = np.Inf

        # calculate moment
        return np.sum(moments) / self.__npaths, err
开发者ID:ABAtanasov,项目名称:Sparse-Grids,代码行数:29,代码来源:MonteCarloStrategy.py

示例7: testOperationTest_test

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
    def testOperationTest_test(self):
        from pysgpp import Grid, DataVector, DataMatrix

        factory = Grid.createLinearBoundaryGrid(1)
        gen = factory.createGridGenerator()
        gen.regular(1)
        
        alpha = DataVector(factory.getStorage().size())        
        
        data = DataMatrix(1,1)
        data.setAll(0.25)
        classes = DataVector(1)
        classes.setAll(1.0)

        testOP = factory.createOperationTest()

        alpha[0] = 0.0
        alpha[1] = 0.0
        alpha[2] = 1.0
        
        c = testOP.test(alpha, data, classes)
        self.failUnless(c > 0.0)
        
        alpha[0] = 0.0
        alpha[1] = 0.0
        alpha[2] = -1.0
        c = testOP.test(alpha, data, classes)
        self.failUnless(c == 0.0)
开发者ID:samhelmholtz,项目名称:skinny-dip,代码行数:30,代码来源:test_GridFactory.py

示例8: __computeRanking

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
    def __computeRanking(self, v, w, A, b):
        """
        Compute ranking for variance estimation

        \argmax_{i \in \A} | w (2 Av + wb) |

        @param v: DataVector, coefficients of known grid points
        @param w: DataVector, estimated coefficients of unknown grid points
        @param A: DataMatrix, stiffness matrix
        @param b: DataVector, squared expectation value contribution
        @return: numpy array, contains the ranking for the given samples
        """
        # update the ranking
        av = DataVector(A.getNrows())
        av.setAll(0.0)
        # = Av
        for i in xrange(A.getNrows()):
            for j in xrange(A.getNcols()):
                av[i] += A.get(i, j) * v[j]
        av.mult(2.)  # 2 * Av
        b.componentwise_mult(w)  # w * b
        av.add(b)  # 2 * Av + w * b
        w.componentwise_mult(av)  # = w * (2 * Av + w * b)
        w.abs()  # = | w * (2 * Av + w * b) |

        return w.array()
开发者ID:ABAtanasov,项目名称:Sparse-Grids,代码行数:28,代码来源:RefinementStrategy.py

示例9: estimate

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
    def estimate(self, vol, grid, alpha, f, U, T):
        r"""
        Extraction of the expectation the given sparse grid function
        interpolating the product of function value and pdf.

        \int\limits_{[0, 1]^d} f(x) * pdf(x) dx
        """
        # first: discretize f
        fgrid, falpha, discError = discretize(grid, alpha, f, self.__epsilon,
                                              self.__refnums, self.__pointsNum,
                                              self.level, self.__deg, True)
        # extract correct pdf for moment estimation
        vol, W, pdfError = self.__extractDiscretePDFforMomentEstimation(U, T)
        D = T.getTransformations()

        # compute the integral of the product
        gs = fgrid.getStorage()
        acc = DataVector(gs.size())
        acc.setAll(1.)
        tmp = DataVector(gs.size())
        for i, dims in enumerate(W.getTupleIndices()):
            sgdeDist = W[i]
            # accumulate objects needed for computing the bilinear form
            gpsi, basisi = project(fgrid, dims)
            gpsj, basisj = project(sgdeDist.grid, range(len(dims)))
            A = self.__computeMassMatrix(gpsi, basisi, gpsj, basisj, W, D)
            # A = ScipyQuadratureStrategy(W, D).computeBilinearForm(fgrid)
            self.mult(A, sgdeDist.alpha, tmp)
            acc.componentwise_mult(tmp)

        moment = falpha.dotProduct(acc)
        return vol * moment, discError[1] + pdfError
开发者ID:ABAtanasov,项目名称:Sparse-Grids,代码行数:34,代码来源:DiscreteIntegralStrategy.py

示例10: computeMoments

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
    def computeMoments(self, ts=None):
        names = ['time',
                 'iteration',
                 'grid_size',
                 'mean',
                 'meanDiscretizationError',
                 'var',
                 'varDiscretizationError']
        # parameters
        ts = self.__samples.keys()
        nrows = len(ts)
        ncols = len(names)
        data = DataMatrix(nrows, ncols)
        v = DataVector(ncols)

        row = 0
        for t in ts:
            v.setAll(0.0)
            v[0] = t
            v[1] = 0
            v[2] = len(self.__samples[t].values())
            v[3], v[4] = self.mean(ts=[t])
            v[5], v[6] = self.var(ts=[t])

            # write results to matrix
            data.setRow(row, v)
            row += 1

        return {'data': data,
                'names': names}
开发者ID:ABAtanasov,项目名称:Sparse-Grids,代码行数:32,代码来源:MCAnalysis.py

示例11: naive_calc_single

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
    def naive_calc_single(self, index):

        numData = self.trainData.getNrows()
        numCoeff = self.grid.getSize()
        seq = self.grid.getStorage().seq(index)
        num = 0
        denom = 0

        tmp = DataVector(numCoeff)
        self.multEval.multTranspose(self.errors, tmp) 

        num = tmp.__getitem__(seq)
        num **= 2

        alpha = DataVector(numCoeff)
        alpha.setAll(0.0)
        alpha.__setitem__(seq, 1.0)

        col = DataVector(numData)
        self.multEval.mult(alpha, col)

        col.sqr()

        denom = col.sum()

        if denom == 0:
            # print "Denominator is zero"
            value = 0
        else:
            value = num/denom 

        return value
开发者ID:ABAtanasov,项目名称:Sparse-Grids,代码行数:34,代码来源:automatic.py

示例12: setUp

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
 def setUp(self):
     self.grid = Grid.createLinearGrid(2)  # a simple 2D grid
     self.grid.createGridGenerator().regular(3)  # max level 3 => 17 points
     self.HashGridStorage = self.grid.getStorage()
     alpha = DataVector(self.grid.getSize())
     alpha.setAll(1.0)
     for i in [9, 10, 11, 12]:
         alpha[i] = 0.0
     coarseningFunctor = SurplusCoarseningFunctor(alpha, 4, 0.5)
     self.grid.createGridGenerator().coarsen(coarseningFunctor, alpha)
开发者ID:ABAtanasov,项目名称:Sparse-Grids,代码行数:12,代码来源:test_HashRefinementInconsistent.py

示例13: setUp

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
 def setUp(self):
     self.size = 42
     self.dim = 5
     self.container = DataContainer(size=self.size,dim=self.dim)
     values = self.container.getValues()
     points = self.container.getPoints()
     self.vectors = []
     for row in xrange(0,self.size):
         vector = DataVector(self.dim)
         vector.setAll(row)
         self.vectors.append(vector)
         points.setRow(row,vector)
         values[row] =row
开发者ID:ABAtanasov,项目名称:Sparse-Grids,代码行数:15,代码来源:test_DataContainer.py

示例14: test_InconsistentRefinement1Point

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
 def test_InconsistentRefinement1Point(self):
     """Dimensionally adaptive refinement using surplus coefficients as local
     error indicator and inconsistent hash refinement.
     
     """
     # point ((3,7), (1,1)) (middle most right) gets larger surplus coefficient
     alpha = DataVector(self.grid.getSize())
     alpha.setAll(1.0)
     alpha[12] = 2.0
     
     functor = SurplusRefinementFunctor(alpha, 1, 0.0)
     refinement = HashRefinementInconsistent()
     refinement.free_refine(self.HashGridStorage, functor)
     
     self.assertEqual(self.grid.getSize(), 17)
开发者ID:ABAtanasov,项目名称:Sparse-Grids,代码行数:17,代码来源:test_HashRefinementInconsistent.py

示例15: writeSensitivityValues

# 需要导入模块: from pysgpp import DataVector [as 别名]
# 或者: from pysgpp.DataVector import setAll [as 别名]
    def writeSensitivityValues(self, filename):

        def keymap(key):
            names = self.getLearner().getParameters().activeParams().getNames()
            ans = [names[i] for i in key]
            return ",".join(ans)

        # parameters
        ts = self.__knowledge.getAvailableTimeSteps()
        gs = self.__knowledge.getGrid(self._qoi).getStorage()

        n = len(ts)
        n1 = gs.dim()
        n2 = 2 ** n1 - 1
        data = DataMatrix(n, n1 + n2 + 1)
        names = ['time'] + [None] * (n1 + n2)

        for k, t in enumerate(ts):
            # estimated anova decomposition
            anova = self.getAnovaDecomposition(t=t)
            me = anova.getSobolIndices()

            if len(me) != n2:
                import ipdb; ipdb.set_trace()
            n2 = len(me)
            te = anova.getTotalEffects()
            n1 = len(te)

            v = DataVector(n1 + n2 + 1)
            v.setAll(0.0)
            v[0] = t

            for i, key in enumerate(anova.getSortedPermutations(te.keys())):
                v[i + 1] = te[key]
                if k == 0:
                    names[i + 1] = '"$T_{' + keymap(key) + '}$"'

            for i, key in enumerate(anova.getSortedPermutations(me.keys())):
                v[n1 + i + 1] = me[key]

                if k == 0:
                    names[n1 + 1 + i] = '"$S_{' + keymap(key) + '}$"'

            data.setRow(k, v)

        writeDataARFF({'filename': filename + ".sa.stats.arff",
                       'data': data,
                       'names': names})
开发者ID:ABAtanasov,项目名称:Sparse-Grids,代码行数:50,代码来源:ASGCAnalysis.py


注:本文中的pysgpp.DataVector.setAll方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。