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


Python numpy.diagflat方法代码示例

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


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

示例1: kernel_qchem_inter_rf_pos_neg

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def kernel_qchem_inter_rf_pos_neg(self, **kw):
    """ This is constructing the E_m-E_n and E_n-E_m matrices """
    h_rpa = diagflat(concatenate((ravel(self.FmE),-ravel(self.FmE))))
    print(h_rpa.shape)

    nf = self.nfermi[0]
    nv = self.norbs-self.vstart[0]
    vs = self.vstart[0]
    neh = nf*nv
    x = self.mo_coeff[0,0,:,:,0]
    pab2v = self.pb.get_ac_vertex_array()
    self.pmn2v = pmn2v = einsum('nb,pmb->pmn', x[:nf,:], einsum('ma,pab->pmb', x[vs:,:], pab2v))
    pmn2c = einsum('qp,pmn->qmn', self.hkernel_den, pmn2v)
    meri = einsum('pmn,pik->mnik', pmn2c, pmn2v).reshape((nf*nv,nf*nv))
    #print(meri.shape)
    #meri.fill(0.0)
    h_rpa[:neh, :neh] = h_rpa[:neh, :neh]+meri
    h_rpa[:neh, neh:] = h_rpa[:neh, neh:]+meri
    h_rpa[neh:, :neh] = h_rpa[neh:, :neh]-meri
    h_rpa[neh:, neh:] = h_rpa[neh:, neh:]-meri
    edif, s2z = np.linalg.eig(h_rpa)
    print(abs(h_rpa-h_rpa.transpose()).sum())
    print('edif', edif.real*27.2114)
    
    return 
开发者ID:pyscf,项目名称:pyscf,代码行数:27,代码来源:qchem_inter_rf.py

示例2: learn_embedding

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def learn_embedding(self):

        graph = self.g.G
        A = nx.to_numpy_matrix(graph)

        # self._beta = 0.0728

        # M_g = np.eye(graph.number_of_nodes()) - self._beta * A
        # M_l = self._beta * A

        M_g = np.eye(graph.number_of_nodes())
        M_l = np.dot(A, A)

        S = np.dot(np.linalg.inv(M_g), M_l)
        # s: \sigma_k
        u, s, vt = lg.svds(S, k=self._d // 2)
        sigma = np.diagflat(np.sqrt(s))
        X1 = np.dot(u, sigma)
        X2 = np.dot(vt.T, sigma)
        # self._X = X2
        self._X = np.concatenate((X1, X2), axis=1) 
开发者ID:thunlp,项目名称:OpenNE,代码行数:23,代码来源:hope.py

示例3: get_bounds_fit_matrix

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def get_bounds_fit_matrix(xmin, xmax, ymin, ymax, zmin, zmax):
    """Create a 4x4 transform matrix which maps the default bounding box ([-0.5, 0.5] in all dimensions) into
    a custom bounding box ([xmin, xmax, ymin, ymax, zmin, zmax]).

    It is used for fitting fields (VectorField, Surface, MachingCubes) into custom domains."""

    for name, value in locals().items():
        try:
            float(value)
        except (TypeError, ValueError):
            raise TypeError('%s: expected float, %s given' % (name, type(value).__name__))

    matrix = np.diagflat(np.array((xmax - xmin, ymax - ymin, zmax - zmin, 1.0), np.float32, order='C'))
    matrix[0:3, 3] = ((xmax + xmin) / 2.0, (ymax + ymin) / 2.0, (zmax + zmin) / 2.0)

    return matrix 
开发者ID:K3D-tools,项目名称:K3D-jupyter,代码行数:18,代码来源:transform.py

示例4: threeassetportfolio

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def threeassetportfolio(plength=5000, SRlist=[1.0, 1.0, 1.0], annual_vol=.15, clist=[.0,.0,.0], index_start=pd.datetime(2000,1,1)):

    (c1, c2, c3)=clist
    dindex=arbitrary_timeindex(plength, index_start)

    daily_vol=annual_vol/16.0
    means=[x*annual_vol/250.0 for x in SRlist]
    stds = np.diagflat([daily_vol]*3)
    corr=np.array([[1.0, c1, c2], [c1, 1.0, c3], [c2, c3, 1.0]])
 
    covs=np.dot(stds, np.dot(corr, stds))
    plength=len(dindex)

    m = np.random.multivariate_normal(means, covs, plength).T

    portreturns=pd.DataFrame(dict(one=m[0], two=m[1], three=m[2]), dindex)
    portreturns=portreturns[['one', 'two', 'three']]
    
    return portreturns 
开发者ID:robcarver17,项目名称:systematictradingexamples,代码行数:21,代码来源:commonrandom.py

示例5: diag_hamiltonian

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def diag_hamiltonian(self, subsystem, evals=None):
        """Returns a `qutip.Qobj` which has the eigenenergies of the object `subsystem` on the diagonal.

        Parameters
        ----------
        subsystem: object derived from `QuantumSystem`
            Subsystem for which the Hamiltonian is to be provided.
        evals: ndarray, optional
            Eigenenergies can be provided as `evals`; otherwise, they are calculated.

        Returns
        -------
        qutip.Qobj operator
        """
        evals_count = subsystem.truncated_dim
        if evals is None:
            evals = subsystem.eigenvals(evals_count=evals_count)
        diag_qt_op = qt.Qobj(inpt=np.diagflat(evals[0:evals_count]))
        return self.identity_wrap(diag_qt_op, subsystem) 
开发者ID:scqubits,项目名称:scqubits,代码行数:21,代码来源:hilbert_space.py

示例6: number

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def number(dimension, prefactor=None):
    """Number operator matrix of size dimension x dimension in sparse matrix representation. An additional prefactor
    can be directly included in the generation of the matrix by supplying 'prefactor'.

    Parameters
    ----------
    dimension: int
    prefactor: float or complex, optional
        prefactor multiplying the number operator matrix


    Returns
    -------
    ndarray
        number operator matrix, size dimension x dimension
    """
    diag_elements = np.arange(dimension)
    if prefactor:
        diag_elements *= prefactor
    return np.diagflat(diag_elements) 
开发者ID:scqubits,项目名称:scqubits,代码行数:22,代码来源:operators.py

示例7: _bwd

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def _bwd(self, dLdy, X):
        """
        Actual computation of the gradient of the loss wrt. the input X.

        The Jacobian, J, of the softmax for input x = [x1, ..., xn] is:
            J[i, j] =
                softmax(x_i)  * (1 - softmax(x_j))  if i = j
                -softmax(x_i) * softmax(x_j)        if i != j
            where
                x_n is input example n (ie., the n'th row in X)
        """
        dX = []
        for dy, x in zip(dLdy, X):
            dxi = []
            for dyi, xi in zip(*np.atleast_2d(dy, x)):
                yi = self._fwd(xi.reshape(1, -1)).reshape(-1, 1)
                dyidxi = np.diagflat(yi) - yi @ yi.T  # jacobian wrt. input sample xi
                dxi.append(dyi @ dyidxi)
            dX.append(dxi)
        return np.array(dX).reshape(*X.shape) 
开发者ID:ddbourgin,项目名称:numpy-ml,代码行数:22,代码来源:layers.py

示例8: test_flip

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def test_flip():
    X = np.diagflat([-2, -1, 0, 1, 2])
    # eigenvalues -2, -1, 0, 1, 2; eigenvectors are I

    Xflip = FlipPSD().fit_transform(X)
    assert np.allclose(Xflip, np.diagflat([2, 1, 0, 1, 2]))

    Xflip2 = FlipPSD().fit(X).transform(X)
    assert np.allclose(Xflip2, np.diagflat([2, 1, 0, 1, 2]))

    Xflip3 = FlipPSD().fit(X).transform(X[:3, :])
    assert np.allclose(Xflip3, [[2,0,0,0,0], [0,1,0,0,0], [0,0,0,0,0]])

    assert_raises(TypeError, lambda: FlipPSD().fit(X[:2, :]))
    assert_raises(TypeError, lambda: FlipPSD().fit_transform(X[:2, :]))
    assert_raises(TypeError, lambda: FlipPSD().fit(X).transform(X[:, :2])) 
开发者ID:djsutherland,项目名称:skl-groups,代码行数:18,代码来源:test_transforms.py

示例9: test_shift

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def test_shift():
    X = np.diagflat([-2., -1, 0, 1, 2])
    # eigenvalues -2, -1, 0, 1, 2; eigenvectors are I

    Xshift = ShiftPSD().fit_transform(X)
    assert np.allclose(Xshift, np.diagflat([0, 1, 2, 3, 4]))

    Xshift2 = ShiftPSD().fit(X).transform(X)
    assert np.allclose(Xshift2, np.diagflat([0, 1, 2, 3, 4]))

    Xshift3 = ShiftPSD().fit(X).transform(X[:3, :])
    assert np.allclose(Xshift3, X[:3, :])

    Xshift4 = ShiftPSD(min_eig=2).fit_transform(X)
    assert np.allclose(Xshift4, np.diagflat([2, 3, 4, 5, 6]))

    assert_raises(TypeError, lambda: ShiftPSD().fit(X[:2, :]))
    assert_raises(TypeError, lambda: ShiftPSD().fit_transform(X[:2, :]))
    assert_raises(TypeError, lambda: ShiftPSD().fit(X).transform(X[:, :2])) 
开发者ID:djsutherland,项目名称:skl-groups,代码行数:21,代码来源:test_transforms.py

示例10: compute_shares_by_xi_jacobian

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def compute_shares_by_xi_jacobian(self, probabilities: Array, conditionals: Optional[Array]) -> Array:
        """Compute the Jacobian of shares with respect to xi (equivalently, to delta)."""
        diagonal_shares = np.diagflat(self.products.shares)
        weighted_probabilities = self.agents.weights * probabilities.T
        jacobian = diagonal_shares - probabilities @ weighted_probabilities

        if self.epsilon_scale != 1:
            jacobian /= self.epsilon_scale

        if self.H > 0:
            membership = self.get_membership_matrix()
            jacobian += self.rho / (1 - self.rho) * (
                diagonal_shares - membership * (conditionals @ weighted_probabilities)
            )

        return jacobian 
开发者ID:jeffgortmaker,项目名称:pyblp,代码行数:18,代码来源:market.py

示例11: get_matrix_elements

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def get_matrix_elements():

    # In[5]: np.diagflat([1, 2, 3, 4])[:3, :]

    matrix = np.diagflat([1.0, 2.0, 3.0, 4.0])[:3, :]

    # Now matrix is:
    # array([[1, 0, 0, 0],
    #        [0, 2, 0, 0],
    #        [0, 0, 3, 0]])

    mc_energies = [1.0, 2.0, 3.0, 4.0, 5.0]

    ebounds = [1.0, 2.5, 4.5, 5.0]

    return matrix, mc_energies, ebounds 
开发者ID:threeML,项目名称:threeML,代码行数:18,代码来源:test_response.py

示例12: getLap

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def getLap(self):
        # degree_mat = np.diagflat(np.sum(self.adj_mat, axis=1))
        # print('np.diagflat(np.sum(self.adj_mat, axis=1))')
        # deg_trans = np.diagflat(np.reciprocal(np.sqrt(np.sum(self.adj_mat, axis=1))))
        # print('np.diagflat(np.reciprocal(np.sqrt(np.sum(self.adj_mat, axis=1))))')
        # deg_trans = np.nan_to_num(deg_trans)
        # L = degree_mat-self.adj_mat
        # print('begin norm_lap_mat')
        # # eye = np.eye(self.node_size)
        #
        # norm_lap_mat = np.matmul(np.matmul(deg_trans, L), deg_trans)
        G = self.g.G.to_undirected()
        print('begin norm_lap_mat')
        norm_lap_mat = nx.normalized_laplacian_matrix(G)
        print('finish norm_lap_mat')
        return norm_lap_mat 
开发者ID:xiangyue9607,项目名称:BioNEV,代码行数:18,代码来源:lap.py

示例13: kernel_qchem_inter_rf

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def kernel_qchem_inter_rf(self, **kw):
    from pyscf.gw.gw import rpa_AB_matrices
    """ This is constructing A B matrices and diagonalizes the problem """

    nf = self.nfermi[0]
    nv = self.norbs-self.vstart[0]
    vs = self.vstart[0]
    
    x = self.mo_coeff[0,0,:,:,0]
    pab2v = self.pb.get_ac_vertex_array()
    self.pmn2v = pmn2v = einsum('nb,pmb->pmn', x[:nf,:], einsum('ma,pab->pmb', x[vs:,:], pab2v))
    pmn2c = einsum('qp,pmn->qmn', self.hkernel_den, pmn2v)
    meri = einsum('pmn,pik->mnik', pmn2c, pmn2v)
    #meri.fill(0.0)

    A = (diagflat( self.FmE ).reshape([nv,nf,nv,nf]) + meri).reshape([nv*nf,nv*nf])
    B = meri.reshape([nv*nf,nv*nf])

    assert np.allclose(A, A.transpose())
    assert np.allclose(B, B.transpose())

    AmB = A-B
    n = len(AmB)
    print(__name__)
    for i in range(n): print(i, AmB[i,i])
    
    ham_rpa = np.multiply(self.sqrt_FmE[:,None], np.multiply(A+B, self.sqrt_FmE))
    esq, self.s2z = np.linalg.eigh(ham_rpa)
    self.s2omega = np.sqrt(esq)
    print(self.s2omega*27.2114)

    self.s2z = self.s2z.T
    self.s2xpy = np.zeros_like(self.s2z)
    for s,(e2,z) in enumerate(zip(esq, self.s2z)):
      w = np.sqrt(e2)
      self.s2xpy[s] = np.multiply(self.sqrt_FmE, self.s2z[s])/np.sqrt(w)
      #print(e2, abs(np.dot(ham_rpa,z)-e2*z).sum())
    return self.s2omega,self.s2z 
开发者ID:pyscf,项目名称:pyscf,代码行数:40,代码来源:qchem_inter_rf.py

示例14: getLap

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def getLap(self):
        degree_mat = np.diagflat(np.sum(self.adj_mat, axis=1))
        deg_trans = np.diagflat(np.reciprocal(np.sqrt(np.sum(self.adj_mat, axis=1))))
        deg_trans = np.nan_to_num(deg_trans)
        L = degree_mat-self.adj_mat

        # eye = np.eye(self.node_size)
        norm_lap_mat = np.matmul(np.matmul(deg_trans, L), deg_trans)
        return norm_lap_mat 
开发者ID:thunlp,项目名称:OpenNE,代码行数:11,代码来源:lap.py

示例15: test_reduce_reorder

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diagflat [as 别名]
def test_reduce_reorder(self):
        # gh 10370, 11029 Some compilers reorder the call to npy_getfloatstatus
        # and put it before the call to an intrisic function that causes
        # invalid status to be set. Also make sure warnings are not emitted
        for n in (2, 4, 8, 16, 32):
            for dt in (np.float32, np.float16, np.complex64):
                for r in np.diagflat(np.array([np.nan] * n, dtype=dt)):
                    assert_equal(np.min(r), np.nan) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:10,代码来源:test_umath.py


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