python类kron()的实例源码

QuantumComputer.py 文件源码 项目:QuantumComputing 作者: corbett 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def apply_gate(self,gate,on_qubit_name):
        on_qubit=self.qubits.get_quantum_register_containing(on_qubit_name)
        if len(on_qubit.get_noop()) > 0:
            print "NOTE this qubit has been measured previously, there should be no more gates allowed but we are reverting that measurement for consistency with IBM's language"
            on_qubit.set_state(on_qubit.get_noop())
            on_qubit.set_noop([])
        if not on_qubit.is_entangled():
            if on_qubit.get_num_qubits()!=1:
                raise Exception("This qubit is not marked as entangled but it has an entangled state")
            on_qubit.set_state(gate*on_qubit.get_state())
        else:
            if not on_qubit.get_num_qubits()>1:
                raise Exception("This qubit is marked as entangled but it does not have an entangled state")
            n_entangled=len(on_qubit.get_entangled())
            apply_gate_to_qubit_idx=[qb.name for qb in on_qubit.get_entangled()].index(on_qubit_name)
            if apply_gate_to_qubit_idx==0:
                entangled_gate=gate
            else:
                entangled_gate=Gate.eye
            for i in range(1,n_entangled):
                if apply_gate_to_qubit_idx==i:
                    entangled_gate=np.kron(entangled_gate,gate)
                else:
                    entangled_gate=np.kron(entangled_gate,Gate.eye)
            on_qubit.set_state(entangled_gate*on_qubit.get_state())
UXO_TEM_Widget.py 文件源码 项目:em_examples 作者: geoscixyz 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def defineSensorLoc(self,XYZ):
        #############################################
        # DEFINE TRANSMITTER AND RECEIVER LOCATIONS
        #
        # XYZ: N X 3 array containing transmitter center locations
        # **NOTE** for this sensor, we know where the receivers are relative to transmitters
        self.TxLoc = XYZ

        dx,dy = np.meshgrid([-0.8,-0.4,0.,0.4,0.8],[-0.8,-0.4,0.,0.4,0.8])
        dx = mkvc(dx)
        dy = mkvc(dy)

        N = np.shape(XYZ)[0]

        X = np.kron(XYZ[:,0],np.ones((25))) + np.kron(np.ones((N)),dx)
        Y = np.kron(XYZ[:,1],np.ones((25))) + np.kron(np.ones((N)),dy)
        Z = np.kron(XYZ[:,2],np.ones((25)))

        self.RxLoc = np.c_[X,Y,Z]

        self.TxID = np.kron(np.arange(1,np.shape(XYZ)[0]+1),np.ones((25)))
        self.RxComp = np.kron(3*np.ones(np.shape(XYZ)[0]),np.ones((25)))
UXO_TEM_Widget.py 文件源码 项目:em_examples 作者: geoscixyz 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def defineSensorLoc(self,XYZ):
        #############################################
        # DEFINE TRANSMITTER AND RECEIVER LOCATIONS
        #
        # XYZ: N X 3 array containing transmitter center locations
        # **NOTE** for this sensor, we know where the receivers are relative to transmitters
        self.TxLoc = XYZ

        dx = np.kron([-0.18,0.,0.,0.,0.18],np.ones(3))
        dy = np.kron([0.,-0.18,0.,0.18,0.],np.ones(3))

        N = np.shape(XYZ)[0]

        X = np.kron(XYZ[:,0],np.ones((15))) + np.kron(np.ones((N)),dx)
        Y = np.kron(XYZ[:,1],np.ones((15))) + np.kron(np.ones((N)),dy)
        Z = np.kron(XYZ[:,2],np.ones((15)))

        self.RxLoc = np.c_[X,Y,Z]

        self.TxID = np.kron(np.arange(1,np.shape(XYZ)[0]+1),np.ones((15)))
        self.RxComp = np.kron(np.kron(np.ones(np.shape(XYZ)[0]),np.ones((5))),np.r_[1,2,3])
toa_calc_d_from_xy.py 文件源码 项目:lps-anchor-pos-estimator 作者: bitcraze 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def toa_calc_d_from_xy(x, y):
    dimx = x.shape
    x_dim = dimx[0]
    m = dimx[1]

    dimy = y.shape
    y_dim = dimy[0]
    n = dimy[1]

    if x_dim > y_dim:
        y[(y_dim + 1):x_dim, ] = np.zeros(x_dim - y_dim, n)
    elif y_dim > x_dim:
        x[(x_dim + 1):y_dim, ] = np.zeros(y_dim - x_dim, n)

    d = sqrt(
        ((np.kron(np.ones(1, n), x) - np.kron(y, np.ones(1, m))) ** 2).sum(
            axis=0))
    d = np.asarray(d)
    d = np.reshape(d, (m, n), order='F')

    return d
CylMesh.py 文件源码 项目:discretize 作者: simpeg 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def edgeCurl(self):
        """The edgeCurl property."""
        if self.nCy > 1:
            raise NotImplementedError('Edge curl not yet implemented for '
                                      'nCy > 1')
        if getattr(self, '_edgeCurl', None) is None:
            # 1D Difference matricies
            dr = sp.spdiags((np.ones((self.nCx+1, 1))*[-1, 1]).T, [-1, 0],
                            self.nCx, self.nCx, format="csr")
            dz = sp.spdiags((np.ones((self.nCz+1, 1))*[-1, 1]).T, [0, 1],
                            self.nCz, self.nCz+1, format="csr")

            # 2D Difference matricies
            Dr = sp.kron(sp.identity(self.nNz), dr)
            Dz = -sp.kron(dz, sp.identity(self.nCx))

            A = self.area
            E = self.edge
            # Edge curl operator
            self._edgeCurl = (utils.sdiag(1/A)*sp.vstack((Dz, Dr)) *
                              utils.sdiag(E))
        return self._edgeCurl
CylMesh.py 文件源码 项目:discretize 作者: simpeg 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def aveE2CC(self):
        "Construct the averaging operator on cell edges to cell centers."
        if getattr(self, '_aveE2CC', None) is None:
            # The number of cell centers in each direction
            n = self.vnC
            if self.isSymmetric:
                avR = utils.av(n[0])[:, 1:]
                avR[0, 0] = 1.
                self._aveE2CC = sp.kron(utils.av(n[2]), avR, format="csr")
            else:
                raise NotImplementedError('wrapping in the averaging is not '
                                          'yet implemented')
                # self._aveE2CC = (1./3)*sp.hstack((utils.kron3(utils.av(n[2]),
                #                                               utils.av(n[1]),
                #                                               utils.speye(n[0])),
                #                                   utils.kron3(utils.av(n[2]),
                #                                               utils.speye(n[1]),
                #                                               utils.av(n[0])),
                #                                   utils.kron3(utils.speye(n[2]),
                #                                               utils.av(n[1]),
                #                                               utils.av(n[0]))),
                #                                  format="csr")
        return self._aveE2CC
learningAlg.py 文件源码 项目:MinimaxFilter 作者: jihunhamm 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def f(W,G,y,hparams):
        # f = -1/N*sum_t log(exp(w(yt)'gt)/sum_k exp(wk'gt)) + l*||W||
        # = -1/N*sum_t [w(yt)'*gt - log(sum_k exp(wk'gt))] + l*||W||
        # = -1/N*sum(sum(W(:,y).*G,1),2) + 1/N*sum(log(sumexpWG),2) + l*sum(sum(W.^2));

        #K,l = hparams
        K = hparams['K']
        l = hparams['l']
        d,N = G.shape
        W = W.reshape((d,K))

        WG = np.dot(W.T,G) # K x N
        WG -= np.kron(np.ones((K,1)),WG.max(axis=0).reshape(1,N))
        #WG_max = WG.max(axis=0).reshape((1,N))
        #expWG = np.exp(WG-np.kron(np.ones((K,1)),WG_max)) # K x N
        expWG = np.exp(WG) # K x N
        sumexpWG = expWG.sum(axis=0) # N x 1
        WyG = WG[y,range(N)]
        #WyG -= WG_max

        fval = -1.0/N*(WyG).sum() \
            + 1.0/N*np.log(sumexpWG).sum() \
            + l*(W**2).sum()#(axis=(0,1))

        return fval
learningAlg.py 文件源码 项目:MinimaxFilter 作者: jihunhamm 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def dfdv(W,G,y,hparams):
        # df/dwk = -1/N*sum(x(:,y==k),2) + 1/N*sum_t exp(wk'xt)*xt/(sum_k exp(wk'xt))] + l*2*wk
        K = hparams['K']
        l = hparams['l']
        d,N = G.shape
        shapeW = W.shape
        W = W.reshape((d,K))

        WG = np.dot(W.T,G) # K x N
        WG -= np.kron(np.ones((K,1)),WG.max(axis=0).reshape(1,N))
        expWG = np.exp(WG) # K x N
        sumexpWG = expWG.sum(axis=0) # N x 1
        df = np.zeros((d,K))
        for k in range(K):
            indk = np.where(y==k)[0]    
            df[:,k] = -1./N*G[:,indk].sum(axis=1).reshape((d,)) \
                + 1./N*np.dot(G,(expWG[k,:]/sumexpWG).T).reshape((d,)) \
                + 2.*l*W[:,k].reshape((d,))

        assert np.isnan(df).any()==False        

        return df.reshape(shapeW)
var.py 文件源码 项目:pyflux 作者: RJT1990 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def estimator_cov(self,method):
        """ Creates covariance matrix for the estimators

        Parameters
        ----------
        method : str
            Estimation method

        Returns
        ----------
        A Covariance Matrix
        """         

        Y = np.array([reg[self.lags:] for reg in self.data])    
        Z = self._create_Z(Y)
        if method == 'OLS':
            sigma = self.ols_covariance()
        else:           
            sigma = self.custom_covariance(self.latent_variables.get_z_values())
        return np.kron(np.linalg.inv(np.dot(Z,np.transpose(Z))), sigma)
Cliffords.py 文件源码 项目:QGL 作者: BBN-Q 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def entangling_mat(gate):
    """
    Helper function to create the entangling gate matrix
    """
    echoCR = expm(1j * pi / 4 * np.kron(pX, pZ))
    if gate == "CNOT":
        return echoCR
    elif gate == "iSWAP":
        return reduce(lambda x, y: np.dot(y, x),
                      [echoCR, np.kron(C1[6], C1[6]), echoCR])
    elif gate == "SWAP":
        return reduce(lambda x, y: np.dot(y, x),
                      [echoCR, np.kron(C1[6], C1[6]), echoCR, np.kron(
                          np.dot(C1[6], C1[1]), C1[1]), echoCR])
    else:
        raise ValueError("Entangling gate must be one of: CNOT, iSWAP, SWAP.")
Cliffords.py 文件源码 项目:QGL 作者: BBN-Q 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def clifford_mat(c, numQubits):
    """
    Return the matrix unitary the implements the qubit clifford C
    """
    assert numQubits <= 2, "Oops! I only handle one or two qubits"
    if numQubits == 1:
        return C1[c]
    else:
        c = C2Seqs[c]
        mat = np.kron(clifford_mat(c[0][0], 1), clifford_mat(c[0][1], 1))
        if c[1]:
            mat = np.dot(entangling_mat(c[1]), mat)
        if c[2]:
            mat = np.dot(
                np.kron(
                    clifford_mat(c[2][0], 1), clifford_mat(c[2][1], 1)), mat)
        return mat
data_generation.py 文件源码 项目:deep-action-proposals 作者: escorciav 项目源码 文件源码 阅读 44 收藏 0 点赞 0 评论 0
def proposals(self, X, return_index=False):
        """Retrieve proposals for a video based on its duration

        Parameters
        ----------
        X : ndarray
            m x 1 array with video duration

        Outputs
        -------
        Y : ndarray
            m * n_prop x 2 array with temporal proposals

        """
        if self.priors is None:
            raise ValueError('model has not been trained')

        Y = np.kron(np.expand_dims(X, 1), self.priors)
        idx = np.repeat(np.arange(X.shape[0]), self.n_prop)
        if return_index:
            return Y, idx
        return Y
baseline.py 文件源码 项目:deep-action-proposals 作者: escorciav 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def proposals(self, X, return_index=False):
        """Retrieve proposals for a video based on its duration

        Parameters
        ----------
        X : ndarray
            m x 1 array with video duration

        Outputs
        -------
        Y : ndarray
            m * n_prop x 2 array with temporal proposals

        """
        if self.priors is None:
            raise ValueError('model has not been trained')

        Y = np.kron(np.expand_dims(X, 1), self.priors)
        idx = np.repeat(np.arange(X.shape[0]), self.n_prop)
        if return_index:
            return Y, idx
        return Y
QuantumComputer.py 文件源码 项目:QuantumComputingEvolutionaryAlgorithmDesign 作者: llens 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def apply_gate(self,gate,on_qubit_name):
        on_qubit=self.qubits.get_quantum_register_containing(on_qubit_name)
        if len(on_qubit.get_noop()) > 0:
            print "NOTE this qubit has been measured previously, there should be no more gates allowed but we are reverting that measurement for consistency with IBM's language"
            on_qubit.set_state(on_qubit.get_noop())
            on_qubit.set_noop([])
        if not on_qubit.is_entangled():
            if on_qubit.get_num_qubits()!=1:
                raise Exception("This qubit is not marked as entangled but it has an entangled state")
            on_qubit.set_state(gate*on_qubit.get_state())
        else:
            if not on_qubit.get_num_qubits()>1:
                raise Exception("This qubit is marked as entangled but it does not have an entangled state")
            n_entangled=len(on_qubit.get_entangled())
            apply_gate_to_qubit_idx=[qb.name for qb in on_qubit.get_entangled()].index(on_qubit_name)
            if apply_gate_to_qubit_idx==0:
                entangled_gate=gate
            else:
                entangled_gate=Gate.eye
            for i in range(1,n_entangled):
                if apply_gate_to_qubit_idx==i:
                    entangled_gate=np.kron(entangled_gate,gate)
                else:
                    entangled_gate=np.kron(entangled_gate,Gate.eye)
            on_qubit.set_state(entangled_gate*on_qubit.get_state())
fns.py 文件源码 项目:pysptools 作者: ctherien 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def cov(M):
    """
    Compute the sample covariance matrix of a 2D matrix.

    Parameters:
      M: `numpy array`
        2d matrix of HSI data (N x p)

    Returns: `numpy array`
        sample covariance matrix
    """
    N = M.shape[0]
    u = M.mean(axis=0)
    M = M - np.kron(np.ones((N, 1)), u)
    C = np.dot(M.T, M) / (N-1)
    return C
utilities.py 文件源码 项目:SCaIP 作者: simonsfoundation 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def com(A, d1, d2):
    """Calculation of the center of mass for spatial components
     Inputs:
     A:   np.ndarray
          matrix of spatial components (d x K)
     d1:  int
          number of pixels in x-direction
     d2:  int
          number of pixels in y-direction

     Output:
     cm:  np.ndarray
          center of mass for spatial components (K x 2)
    """
    nr = np.shape(A)[-1]
    Coor = dict()
    Coor['x'] = np.kron(np.ones((d2, 1)), np.expand_dims(range(d1), axis=1))
    Coor['y'] = np.kron(np.expand_dims(range(d2), axis=1), np.ones((d1, 1)))
    cm = np.zeros((nr, 2))        # vector for center of mass
    cm[:, 0] = np.dot(Coor['x'].T, A) / A.sum(axis=0)
    cm[:, 1] = np.dot(Coor['y'].T, A) / A.sum(axis=0)

    return cm
utilities.py 文件源码 项目:SCaIP 作者: simonsfoundation 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def find_activity_intervals(C,Npeaks = 5, tB=-5, tA = 25, thres = 0.3):

    import peakutils
    K,T = np.shape(C)
    L = []
    for i in range(K):
        indexes = peakutils.indexes(C[i,:],thres=thres)        
        srt_ind = indexes[np.argsort(C[i,indexes])][::-1]
        srt_ind = srt_ind[:Npeaks]
        L.append(srt_ind)

    LOC = []
    for i in range(K):
        if len(L[i])>0:
            interval = np.kron(L[i],np.ones(tA-tB,dtype=int)) + np.kron(np.ones(len(L[i]),dtype=int),np.arange(tB,tA))                        
            interval[interval<0] = 0
            interval[interval>T-1] = T-1
            LOC.append(np.array(list(set(interval))))        
        else:
            LOC.append(None)                        


    return LOC
tebd.py 文件源码 项目:tensor_networks 作者: alewis 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def paulidouble(i, j, tensor=True):
    pauli_i = pauli(i)
    pauli_j = pauli(j)
    outer = np.zeros((4, 4), dtype=np.complex)
    outer[:2, :2] = pauli_i
    outer[2:, 2:] = pauli_j
    if tensor:
        outer.shape = (2, 2, 2, 2)
    return outer

# def paulitwo_left(i):
    # return np.kron(pauli(i), pauli(0)) 

# def paulitwo_right(i):
    # return np.kron(pauli(0), pauli(i))

# def newrho_DK(Lket, theta_ij):
    # Lbra = np.conjugate(L_before)
    # theta_star = np.conjugate(theta_ij)
    # in_bracket = scon(Lbra, Lket, theta_ij, theta_star,
                # [1], [1], [2, 3, 1,
ptm.py 文件源码 项目:quantumsim 作者: brianzi 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def to_0xyz_basis(ptm):
    """Transform a Pauli transfer in the 0xy1 basis [1],
    to the the usual 0xyz. The inverse of to_0xy1_basis.

    ptm: The input transfer matrix in 0xy1 basis. Must be 4x4.

    [1] Daniel Greenbaum, Introduction to Quantum Gate Set Tomography, http://arxiv.org/abs/1509.02921v1
    """

    ptm = np.array(ptm)
    if ptm.shape == (4, 4):
        trans_mat = basis_transformation_matrix
        return np.dot(trans_mat, np.dot(ptm, trans_mat))
    elif ptm.shape == (16, 16):
        trans_mat = np.kron(basis_transformation_matrix, basis_transformation_matrix)
        return np.dot(trans_mat, np.dot(ptm, trans_mat))
    else:
        raise ValueError("Dimensions wrong, must be one- or two Pauli transfer matrix ")
sparsedm.py 文件源码 项目:quantumsim 作者: brianzi 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def apply_two_ptm(self, bit0, bit1, two_ptm):
        """Apply a two_bit_ptm between bit0 and bit1.
        """
        self.ensure_dense(bit0)
        self.ensure_dense(bit1)

        ptm0 = np.eye(4)
        if bit0 in self.single_ptms_to_do:
            for ptm2 in self.single_ptms_to_do[bit0]:
                ptm0 = ptm2.dot(ptm0)
            del self.single_ptms_to_do[bit0]

        ptm1 = np.eye(4)
        if bit1 in self.single_ptms_to_do:
            for ptm2 in self.single_ptms_to_do[bit1]:
                ptm1 = ptm2.dot(ptm1)
            del self.single_ptms_to_do[bit1]

        full_two_ptm = np.dot(two_ptm, np.kron(ptm1, ptm0))
        self.full_dm.apply_two_ptm(self.idx_in_full_dm[bit0], 
                self.idx_in_full_dm[bit1], full_two_ptm)
grape_functions.py 文件源码 项目:quantum-optimal-control 作者: SchusterLab 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def kron_all(op,num,op_2): 
    # returns an addition of sth like xii + ixi + iix for op =x and op_2 =i
    total = np.zeros([len(op)**num,len(op)**num])
    a=op
    for jj in range(num):
        if jj != 0:
            a = op_2
        else:
            a = op

        for ii in range(num-1):
            if (jj - ii) == 1:

                b = op
            else:
                b = op_2
            a = np.kron(a,b)
        total = total + a
    return a
function_tools.py 文件源码 项目:kafe 作者: dsavoiu 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def outer_product(input_array):
    r'''
    Takes a `NumPy` array and returns the outer (dyadic, Kronecker) product
    with itself. If `input_array` is a vector :math:`\mathbf{x}`, this returns
    :math:`\mathbf{x}\mathbf{x}^T`.
    '''
    la = len(input_array)

    # return outer product as numpy array
    return np.kron(input_array, input_array).reshape(la, la)

##############
# Decorators #
##############


# Main decorator for fit functions
nn_test.py 文件源码 项目:imperative 作者: yaroslavvb 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _upsample_filters(self, filters, rate):
    """Upsamples the filters by a factor of rate along the spatial dimensions.

    Args:
      filters: [h, w, in_depth, out_depth]. Original filters.
      rate: An int, specifying the upsampling rate.

    Returns:
      filters_up: [h_up, w_up, in_depth, out_depth]. Upsampled filters with
        h_up = h + (h - 1) * (rate - 1)
        w_up = w + (w - 1) * (rate - 1)
        containing (rate - 1) zeros between consecutive filter values along
        the filters' spatial dimensions.
    """
    if rate == 1:
      return filters
    # [h, w, in_depth, out_depth] -> [in_depth, out_depth, h, w]
    filters_up = np.transpose(filters, [2, 3, 0, 1])
    ker = np.zeros([rate, rate])
    ker[0, 0] = 1
    filters_up = np.kron(filters_up, ker)[:, :, :-(rate-1), :-(rate-1)]
    # [in_depth, out_depth, h_up, w_up] -> [h_up, w_up, in_depth, out_depth]
    filters_up = np.transpose(filters_up, [2, 3, 0, 1])
    self.assertEqual(np.sum(filters), np.sum(filters_up))
    return filters_up
test_slinalg.py 文件源码 项目:Theano-Deep-learning 作者: GeekLiB 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def test_perform(self):
        if not imported_scipy:
            raise SkipTest('kron tests need the scipy package to be installed')

        for shp0 in [(2,), (2, 3), (2, 3, 4), (2, 3, 4, 5)]:
            x = tensor.tensor(dtype='floatX',
                              broadcastable=(False,) * len(shp0))
            a = numpy.asarray(self.rng.rand(*shp0)).astype(config.floatX)
            for shp1 in [(6,), (6, 7), (6, 7, 8), (6, 7, 8, 9)]:
                if len(shp0) + len(shp1) == 2:
                    continue
                y = tensor.tensor(dtype='floatX',
                                  broadcastable=(False,) * len(shp1))
                f = function([x, y], kron(x, y))
                b = self.rng.rand(*shp1).astype(config.floatX)
                out = f(a, b)
                # Newer versions of scipy want 4 dimensions at least,
                # so we have to add a dimension to a and flatten the result.
                if len(shp0) + len(shp1) == 3:
                    scipy_val = scipy.linalg.kron(
                        a[numpy.newaxis, :], b).flatten()
                else:
                    scipy_val = scipy.linalg.kron(a, b)
                utt.assert_allclose(out, scipy_val)
kronecker_test.py 文件源码 项目:t3f 作者: Bihaqo 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def testCholesky(self):
    # Tests the cholesky function
    np.random.seed(8)

    # generating two symmetric positive-definite tt-cores
    L_1 = np.tril(np.random.normal(scale=2., size=(2, 2)))
    L_2 = np.tril(np.random.normal(scale=2., size=(3, 3)))
    K_1 = L_1.dot(L_1.T)
    K_2 = L_2.dot(L_2.T)
    K = np.kron(K_1, K_2)
    initializer = tensor_train.TensorTrain([K_1[None, :, :, None], 
                                            K_2[None, :, :, None]], 
                                            tt_ranks=7*[1])
    kron_mat = variables.get_variable('kron_mat', initializer=initializer)
    init_op = tf.global_variables_initializer()
    with self.test_session() as sess:
      sess.run(init_op)
      desired = np.linalg.cholesky(K)
      actual = ops.full(kr.cholesky(kron_mat)).eval()
      self.assertAllClose(desired, actual)
parametric.py 文件源码 项目:decoding_challenge_cortana_2016_3rd 作者: kingjr 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _iter_contrasts(n_subjects, factor_levels, effect_picks):
    """ Aux Function: Setup contrasts """
    from scipy.signal import detrend
    sc = []
    n_factors = len(factor_levels)
    # prepare computation of Kronecker products
    for n_levels in factor_levels:
        # for each factor append
        # 1) column vector of length == number of levels,
        # 2) square matrix with diagonal == number of levels

        # main + interaction effects for contrasts
        sc.append([np.ones([n_levels, 1]),
                   detrend(np.eye(n_levels), type='constant')])

    for this_effect in effect_picks:
        contrast_idx = _get_contrast_indices(this_effect + 1, n_factors)
        c_ = sc[0][contrast_idx[n_factors - 1]]
        for i_contrast in range(1, n_factors):
            this_contrast = contrast_idx[(n_factors - 1) - i_contrast]
            c_ = np.kron(c_, sc[i_contrast][this_contrast])
        df1 = matrix_rank(c_)
        df2 = df1 * (n_subjects - 1)
        yield c_, df1, df2
test_covariance.py 文件源码 项目:linearmodels 作者: bashtage 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_homoskedastic_direct(cov_data, debias):
    x, z, eps, sigma = cov_data
    cov = HomoskedasticCovariance(x, eps, sigma, sigma, debiased=debias)
    k = len(x)
    nobs = x[0].shape[0]
    big_x = []
    for i in range(k):
        row = []
        for j in range(k):
            if i == j:
                row.append(x[i])
            else:
                row.append(np.zeros((nobs, x[j].shape[1])))
        big_x.append(np.concatenate(row, 1))
    big_x = np.concatenate(big_x, 0)
    xeex = big_x.T @ np.kron(sigma, np.eye(nobs)) @ big_x / nobs
    xpxi = _xpxi(x)
    direct = xpxi @ xeex @ xpxi / nobs
    direct = (direct + direct.T) / 2
    assert_allclose(np.diag(direct), np.diag(cov.cov))
    s = np.sqrt(np.diag(direct))[:, None]
    r_direct = direct / (s @ s.T)
    s = np.sqrt(np.diag(cov.cov))[:, None]
    c_direct = direct / (s @ s.T)
    assert_allclose(r_direct, c_direct, atol=1e-5)
test_utility.py 文件源码 项目:linearmodels 作者: bashtage 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_inner_product_short_circuit(data):
    y, x, sigma = data
    sigma = np.eye(len(x))
    efficient = blocked_inner_prod(x, sigma)
    nobs = x[0].shape[0]
    omega = np.kron(sigma, np.eye(nobs))
    k = len(x)
    bigx = []
    for i in range(k):
        row = []
        for j in range(k):
            if i == j:
                row.append(x[i])
            else:
                row.append(np.zeros((nobs, x[j].shape[1])))
        bigx.append(np.hstack(row))
    bigx = np.vstack(bigx)
    expected = bigx.T @ omega @ bigx
    assert_allclose(efficient, expected)
test_utility.py 文件源码 项目:linearmodels 作者: bashtage 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_diag_product(data):
    y, x, sigma = data
    efficient = blocked_diag_product(x, sigma)
    nobs = x[0].shape[0]
    omega = np.kron(sigma, np.eye(nobs))
    k = len(x)
    bigx = []
    for i in range(k):
        row = []
        for j in range(k):
            if i == j:
                row.append(x[i])
            else:
                row.append(np.zeros((nobs, x[j].shape[1])))
        bigx.append(np.hstack(row))
    bigx = np.vstack(bigx)
    expected = omega @ bigx
    assert_allclose(efficient, expected)
QuantumNumber.py 文件源码 项目:HamiltonianPy 作者: waltergu 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_quantumnumbers_ordinary():
    print 'test_quantumnumbers_ordinary'
    a=QuantumNumbers('C',([SQN(-1.0),SQN(0.0),SQN(1.0)],[1,1,1]),protocol=QuantumNumbers.COUNTS)
    print 'a: %s'%a
    print 'copy(a): %s'%copy(a)
    print 'deepcopy(a): %s'%deepcopy(a)

    b,permutation=QuantumNumbers.kron([a]*2).sort(history=True)
    print 'b: ',b
    print 'permutation of b:%s'%permutation
    print 'b.reorder(permutation,protocol="EXPANSION"): \n%s'%b.reorder(permutation,protocol="EXPANSION")
    print 'b.reorder([4,3,2,1,0],protocol="CONTENTS"): \n%s'%b.reorder([4,3,2,1,0],protocol="CONTENTS")

    c=b.to_ordereddict(protocol=QuantumNumbers.COUNTS)
    print 'c(b.to_ordereddict(protocol=QuantumNumbers.COUNTS)):\n%s'%('\n'.join('%s: %s'%(key,value) for key,value in c.iteritems()))
    print 'QuantumNumbers.from_ordereddict(SQN,c,protocol=QuantumNumbers.COUNTS):\n%s'%QuantumNumbers.from_ordereddict(SQN,c,protocol=QuantumNumbers.COUNTS)

    d=b.to_ordereddict(protocol=QuantumNumbers.INDPTR)
    print 'd(b.to_ordereddict(protocol=QuantumNumbers.INDPTR)):\n%s'%('\n'.join('%s: %s'%(key,value)for key,value in d.iteritems()))
    print 'QuantumNumbers.from_ordereddict(SQN,d,protocol=QuantumNumbers.INDPTR):\n%s'%QuantumNumbers.from_ordereddict(SQN,d,protocol=QuantumNumbers.INDPTR)
    print


问题


面经


文章

微信
公众号

扫码关注公众号