Python numpy.vdot() Examples

The following are 30 code examples for showing how to use numpy.vdot(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: pyscf   Author: pyscf   File: linalg_helper.py    License: Apache License 2.0 6 votes vote down vote up
def guessInitial(self):
        nrm = np.linalg.norm(self.x0)
        self.x0 *= 1./nrm
        self.currentSize = self.nEigen
        for i in range(self.currentSize):
            self.vlist[i] *= 0.0
            self.vlist[i,:] += np.random.rand(self.size)
            self.vlist[i,i] /= np.linalg.norm(self.vlist[i,i])
            self.vlist[i,i] *= 12.
            for j in range(i):
                fac = np.vdot( self.vlist[j,:], self.vlist[i,:] )
                self.vlist[i,:] -= fac * self.vlist[j,:]
            self.vlist[i,:] /= np.linalg.norm(self.vlist[i,:])
        for i in range(self.currentSize):
            self.cv = self.vlist[i].copy()
            self.hMult()
            self.Avlist[i] = self.cAv.copy()
        self.constructSubspace() 
Example 2
Project: pyscf   Author: pyscf   File: linalg_helper.py    License: Apache License 2.0 6 votes vote down vote up
def gramSchmidtCurrentVec(self,northo):
        for k in range(northo):
            fac = np.vdot( self.vlist[k,:], self.cv )
            self.cv -= fac * self.vlist[k,:] #/ np.vdot(self.vlist[i],self.vlist[i])
        cvnorm = np.linalg.norm(self.cv)
        if cvnorm < 1e-4:
            self.cv = np.random.rand(self.size)
            for k in range(northo):
                fac = np.vdot( self.vlist[k,:], self.cv )
                self.cv -= fac * self.vlist[k,:] #/ np.vdot(self.vlist[i],self.vlist[i])
            ########################################################################
            #  Sometimes some of the created vectors are linearly dependent.  i
            #  To get around this I'm not sure what to do other than to throw that
            #  solution out and start at that eigenvalue
            ########################################################################
            print(" ERROR!!!! ... restarting at eigenvalue #%" % \
                        (northo, cvnorm))
            self.ciEig = northo
        self.cv /= np.linalg.norm(self.cv) 
Example 3
Project: pyscf   Author: pyscf   File: linalg_helper.py    License: Apache License 2.0 6 votes vote down vote up
def checkDeflate(self):
        if self.currentSize == self.maxM-1:
            self.deflated = 1
            for i in range(self.nEigen):
                self.sol[:self.currentSize] = self.evecs[:self.currentSize,i]
                self.constructSolV()            # Finds the "best" eigenvector for this eigenvalue
                self.Avlist[i,:] = self.cv.copy() # Puts this guess in self.Avlist rather than self.vlist for now...
                                                # since this would mess up self.constructSolV()'s solution
            for i in range(self.nEigen):
                self.cv = self.Avlist[i,:].copy() # This is actually the "best" eigenvector v, not A*v (see above)
                self.gramSchmidtCurrentVec(i)
                self.vlist[i,:] = self.cv.copy()

            orthog = 0.0
            for j in range(self.nEigen):
                for i in range(j):
                    orthog += np.vdot(self.vlist[j,:],self.vlist[i,:])**2.0

            for i in range(self.nEigen):
                self.cv = self.vlist[i].copy() # This is actually the "best" eigenvector v, not A*v (see above)
                self.hMult()                   # Use current vector cv to create cAv
                self.Avlist[i] = self.cAv.copy() 
Example 4
Project: mars   Author: mars-project   File: test_linalg_execute.py    License: Apache License 2.0 6 votes vote down vote up
def testVdotExecution(self):
        a_data = np.array([1 + 2j, 3 + 4j])
        b_data = np.array([5 + 6j, 7 + 8j])
        a = tensor(a_data, chunk_size=1)
        b = tensor(b_data, chunk_size=1)

        t = vdot(a, b)

        res = self.executor.execute_tensor(t)[0]
        expected = np.vdot(a_data, b_data)
        np.testing.assert_equal(res, expected)

        a_data = np.array([[1, 4], [5, 6]])
        b_data = np.array([[4, 1], [2, 2]])
        a = tensor(a_data, chunk_size=1)
        b = tensor(b_data, chunk_size=1)

        t = vdot(a, b)

        res = self.executor.execute_tensor(t)[0]
        expected = np.vdot(a_data, b_data)
        np.testing.assert_equal(res, expected) 
Example 5
Project: lambda-packs   Author: ryfeus   File: nonlin.py    License: MIT License 6 votes vote down vote up
def solve(self, f, tol=0):
        dx = -self.alpha*f

        n = len(self.dx)
        if n == 0:
            return dx

        df_f = np.empty(n, dtype=f.dtype)
        for k in xrange(n):
            df_f[k] = vdot(self.df[k], f)

        try:
            gamma = solve(self.a, df_f)
        except LinAlgError:
            # singular; reset the Jacobian approximation
            del self.dx[:]
            del self.df[:]
            return dx

        for m in xrange(n):
            dx += gamma[m]*(self.dx[m] + self.alpha*self.df[m])
        return dx 
Example 6
Project: lambda-packs   Author: ryfeus   File: nonlin.py    License: MIT License 6 votes vote down vote up
def matvec(self, f):
        dx = -f/self.alpha

        n = len(self.dx)
        if n == 0:
            return dx

        df_f = np.empty(n, dtype=f.dtype)
        for k in xrange(n):
            df_f[k] = vdot(self.df[k], f)

        b = np.empty((n, n), dtype=f.dtype)
        for i in xrange(n):
            for j in xrange(n):
                b[i,j] = vdot(self.df[i], self.dx[j])
                if i == j and self.w0 != 0:
                    b[i,j] -= vdot(self.df[i], self.df[i])*self.w0**2*self.alpha
        gamma = solve(b, df_f)

        for m in xrange(n):
            dx += gamma[m]*(self.df[m] + self.dx[m]/self.alpha)
        return dx 
Example 7
Project: strawberryfields   Author: XanaduAI   File: states.py    License: Apache License 2.0 6 votes vote down vote up
def trace(self, **kwargs):
        r"""Trace of the density operator corresponding to the state.

        For pure states the trace corresponds to the squared norm of the ket vector.

        For physical states this should always be 1, any deviations from this value are due
        to numerical errors and Hilbert space truncation artefacts.

        Returns:
          float: trace of the state
        """
        # pylint: disable=unused-argument
        if self.is_pure:
            return np.vdot(self.ket(), self.ket()).real  # <s|s>

        # need some extra steps to trace over multimode matrices
        eqn_indices = [
            [indices[idx]] * 2 for idx in range(self._modes)
        ]  # doubled indices [['i','i'],['j','j'], ... ]
        eqn = "".join(
            chain.from_iterable(eqn_indices)
        )  # flatten indices into a single string 'iijj...'
        return np.einsum(eqn, self.dm()).real 
Example 8
Project: Computable   Author: ktraunmueller   File: nonlin.py    License: MIT License 6 votes vote down vote up
def solve(self, f, tol=0):
        dx = -self.alpha*f

        n = len(self.dx)
        if n == 0:
            return dx

        df_f = np.empty(n, dtype=f.dtype)
        for k in xrange(n):
            df_f[k] = vdot(self.df[k], f)

        try:
            gamma = solve(self.a, df_f)
        except LinAlgError:
            # singular; reset the Jacobian approximation
            del self.dx[:]
            del self.df[:]
            return dx

        for m in xrange(n):
            dx += gamma[m]*(self.dx[m] + self.alpha*self.df[m])
        return dx 
Example 9
Project: Computable   Author: ktraunmueller   File: nonlin.py    License: MIT License 6 votes vote down vote up
def matvec(self, f):
        dx = -f/self.alpha

        n = len(self.dx)
        if n == 0:
            return dx

        df_f = np.empty(n, dtype=f.dtype)
        for k in xrange(n):
            df_f[k] = vdot(self.df[k], f)

        b = np.empty((n, n), dtype=f.dtype)
        for i in xrange(n):
            for j in xrange(n):
                b[i,j] = vdot(self.df[i], self.dx[j])
                if i == j and self.w0 != 0:
                    b[i,j] -= vdot(self.df[i], self.df[i])*self.w0**2*self.alpha
        gamma = solve(b, df_f)

        for m in xrange(n):
            dx += gamma[m]*(self.df[m] + self.dx[m]/self.alpha)
        return dx 
Example 10
Project: modred   Author: belson17   File: benchmark.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def symm_inner_product_array(
    num_states, num_vecs, max_vecs_per_node, verbosity=1):
    """
    Computes symmetric inner product array from known vecs (as in POD).
    """
    vec_handles = [mr.VecHandlePickle(join(data_dir, row_vec_name%row_num))
        for row_num in mr.range(num_vecs)]

    generate_vecs(data_dir, num_states, vec_handles)

    my_VS = mr.VectorSpaceHandles(
        inner_product=np.vdot, max_vecs_per_node=max_vecs_per_node,
        verbosity=verbosity)

    prof = cProfile.Profile()
    start_time = time.time()
    prof.runcall(my_VS.compute_symm_inner_product_array, vec_handles)
    total_time = time.time() - start_time
    prof.dump_stats('IP_symm_array_r%d.prof'%mr.parallel.get_rank())

    return total_time 
Example 11
Project: modred   Author: belson17   File: testvectorspace.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def setUp(self):
        if not os.access('.', os.W_OK):
            raise RuntimeError('Cannot write to current directory')
        self.test_dir = 'files_vectorspace_DELETE_ME'
        if not os.path.isdir(self.test_dir):
            parallel.call_from_rank_zero(os.mkdir, self.test_dir)

        self.max_vecs_per_proc = 10
        self.total_num_vecs_in_mem = (
            parallel.get_num_procs() * self.max_vecs_per_proc)

        self.vec_space = vspc.VectorSpaceHandles(
            inner_product=np.vdot, verbosity=0)
        self.vec_space.max_vecs_per_proc = self.max_vecs_per_proc

        # Default data members; set verbosity to 0 even though default is 1
        # so messages won't print during tests
        self.default_data_members = {
            'inner_product': np.vdot, 'max_vecs_per_node': 10000,
            'max_vecs_per_proc': (
                10000 * parallel.get_num_nodes() // parallel.get_num_procs()),
            'verbosity': 0, 'print_interval': 10, 'prev_print_time': 0.}
        parallel.barrier() 
Example 12
Project: GraphicDesignPatternByPython   Author: Relph1119   File: nonlin.py    License: MIT License 6 votes vote down vote up
def solve(self, f, tol=0):
        dx = -self.alpha*f

        n = len(self.dx)
        if n == 0:
            return dx

        df_f = np.empty(n, dtype=f.dtype)
        for k in xrange(n):
            df_f[k] = vdot(self.df[k], f)

        try:
            gamma = solve(self.a, df_f)
        except LinAlgError:
            # singular; reset the Jacobian approximation
            del self.dx[:]
            del self.df[:]
            return dx

        for m in xrange(n):
            dx += gamma[m]*(self.dx[m] + self.alpha*self.df[m])
        return dx 
Example 13
Project: GraphicDesignPatternByPython   Author: Relph1119   File: nonlin.py    License: MIT License 6 votes vote down vote up
def matvec(self, f):
        dx = -f/self.alpha

        n = len(self.dx)
        if n == 0:
            return dx

        df_f = np.empty(n, dtype=f.dtype)
        for k in xrange(n):
            df_f[k] = vdot(self.df[k], f)

        b = np.empty((n, n), dtype=f.dtype)
        for i in xrange(n):
            for j in xrange(n):
                b[i,j] = vdot(self.df[i], self.dx[j])
                if i == j and self.w0 != 0:
                    b[i,j] -= vdot(self.df[i], self.df[i])*self.w0**2*self.alpha
        gamma = solve(b, df_f)

        for m in xrange(n):
            dx += gamma[m]*(self.df[m] + self.dx[m]/self.alpha)
        return dx 
Example 14
Project: mpnum   Author: dsuess   File: mparray_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_sandwich(nr_sites, local_dim, rank, rgen, dtype):
    mps = factory.random_mpa(nr_sites, local_dim, rank,
                             randstate=rgen, dtype=dtype, normalized=True)
    mps2 = factory.random_mpa(nr_sites, local_dim, rank,
                              randstate=rgen, dtype=dtype, normalized=True)
    mpo = factory.random_mpa(nr_sites, [local_dim] * 2, rank,
                             randstate=rgen, dtype=dtype)
    mpo.canonicalize()
    mpo /= mp.trace(mpo)

    vec = mps.to_array().ravel()
    op = mpo.to_array_global().reshape([local_dim**nr_sites] * 2)
    res_arr = np.vdot(vec, np.dot(op, vec))
    res_mpo = mp.inner(mps, mp.dot(mpo, mps))
    res_sandwich = mp.sandwich(mpo, mps)
    assert_almost_equal(res_mpo, res_arr)
    assert_almost_equal(res_sandwich, res_arr)

    vec2 = mps2.to_array().ravel()
    res_arr = np.vdot(vec2, np.dot(op, vec))
    res_mpo = mp.inner(mps2, mp.dot(mpo, mps))
    res_sandwich = mp.sandwich(mpo, mps, mps2)
    assert_almost_equal(res_mpo, res_arr)
    assert_almost_equal(res_sandwich, res_arr) 
Example 15
Project: pdftabextract   Author: WZBSocialScienceCenter   File: geom.py    License: Apache License 2.0 6 votes vote down vote up
def vecangle(v1, v2):
    """angle between two vectors v1, v2 in radians"""
    v0 = pt(0, 0)
        
    if np.allclose(v1, v0) or np.allclose(v2, v0):
        return np.nan
    
    if np.allclose(v1, v2):
        return 0
    
    num = np.vdot(v1, v2)
    denom = (np.linalg.norm(v1) * np.linalg.norm(v2))
    
    if np.isclose(num, denom):
        return 0
    
    return math.acos(num / denom) 
Example 16
Project: qiskit-aqua   Author: Qiskit   File: matrix_operator.py    License: Apache License 2.0 6 votes vote down vote up
def evaluate_with_statevector(self, quantum_state):
        """

        Args:
            quantum_state (numpy.ndarray): quantum state

        Returns:
            float: the mean value
            float: the standard deviation
        Raises:
            AquaError: if Operator is empty
        """
        if self.is_empty():
            raise AquaError("Operator is empty, check the operator.")

        avg = np.vdot(quantum_state, self._matrix.dot(quantum_state))
        return avg, 0.0 
Example 17
Project: qiskit-aqua   Author: Qiskit   File: weighted_pauli_operator.py    License: Apache License 2.0 6 votes vote down vote up
def evaluate_with_statevector(self, quantum_state):
        """
        Args:
            quantum_state (numpy.ndarray): a quantum state.

        Returns:
            float: the mean value
            float: the standard deviation
        Raises:
            AquaError: if Operator is empty
        """
        if self.is_empty():
            raise AquaError("Operator is empty, check the operator.")
        # convert to matrix first?
        # pylint: disable=import-outside-toplevel
        from .op_converter import to_matrix_operator
        mat_op = to_matrix_operator(self)
        avg = np.vdot(quantum_state, mat_op._matrix.dot(quantum_state))
        return avg, 0.0

    # pylint: disable=arguments-differ 
Example 18
Project: pyscf   Author: pyscf   File: arnoldi.py    License: Apache License 2.0 5 votes vote down vote up
def constructSubspace(self):
        if self.totalIter == 0 or self.deflated == 1: # construct the full block of v^*Av
            for i in range(self.currentSize):
                for j in range(self.currentSize):
                   val = np.vdot(self.vlist[i],self.Avlist[j])
                   self.subH[i,j] = val
        else:
            for j in range(self.currentSize):
                if j <= (self.currentSize-1):
                    val = np.vdot(self.vlist[j],self.Avlist[self.currentSize-1])
                    self.subH[j,self.currentSize-1] = val
                if j < (self.currentSize-1):
                    val = np.vdot(self.vlist[self.currentSize-1],self.Avlist[j])
                    self.subH[self.currentSize-1,j] = val 
Example 19
Project: pyscf   Author: pyscf   File: arnoldi.py    License: Apache License 2.0 5 votes vote down vote up
def computeResidual(self):
        self.res = self.cAv - self.cvEig * self.cv
        self.dres = np.vdot(self.res,self.res)**0.5
        #
        # gram-schmidt for residual vector
        #
        for i in range(self.currentSize):
            self.dgks[i] = np.vdot( self.vlist[i], self.res )
            self.res -= self.dgks[i]*self.vlist[i]
        #
        # second gram-schmidt to make them really orthogonal
        #
        for i in range(self.currentSize):
            self.dgks[i] = np.vdot( self.vlist[i], self.res )
            self.res -= self.dgks[i]*self.vlist[i]
        self.resnorm = np.linalg.norm(self.res)
        self.res /= self.resnorm

        orthog = 0.0
        for i in range(self.currentSize):
            orthog += np.vdot(self.res,self.vlist[i])**2.0
        orthog = orthog ** 0.5
        if not self.deflated:
            if VERBOSE:
                print("%3d %20.14f %20.14f  %10.4g" % (self.ciEig, self.cvEig.real, self.resnorm.real, orthog.real))
        #else:
        #    print "%3d %20.14f %20.14f %20.14f (deflated)" % (self.ciEig, self.cvEig,
        #                                                      self.resnorm, orthog)

        self.iteration += 1 
Example 20
Project: pyscf   Author: pyscf   File: arnoldi.py    License: Apache License 2.0 5 votes vote down vote up
def gramSchmidtCurrentVec(self,northo):
        for i in range(northo):
            self.dgks[i] = np.vdot( self.vlist[i], self.cv )
            self.cv -= self.dgks[i]*self.vlist[i] #/ np.vdot(self.vlist[i],self.vlist[i])
        self.cv /= np.linalg.norm(self.cv) 
Example 21
Project: pyscf   Author: pyscf   File: linalg_helper.py    License: Apache License 2.0 5 votes vote down vote up
def constructSubspace(self):
        if self.totalIter == 0 or self.deflated == 1: # construct the full block of v^*Av
            for i in range(self.currentSize):
                for j in range(self.currentSize):
                   val = np.vdot(self.vlist[i],self.Avlist[j])
                   self.subH[i,j] = val
        else:
            for j in range(self.currentSize):
                if j <= (self.currentSize-1):
                    val = np.vdot(self.vlist[j,:],self.Avlist[self.currentSize-1,:])
                    self.subH[j,self.currentSize-1] = val
                if j < (self.currentSize-1):
                    val = np.vdot(self.vlist[self.currentSize-1,:],self.Avlist[j,:])
                    self.subH[self.currentSize-1,j] = val 
Example 22
Project: pyGSTi   Author: pyGSTio   File: slowreplib.py    License: Apache License 2.0 5 votes vote down vote up
def probability(self, state):
        # can assume state is a DMStateRep
        return _np.dot(self.base, state.base)  # not vdot b/c *real* data 
Example 23
Project: pyGSTi   Author: pyGSTio   File: slowreplib.py    License: Apache License 2.0 5 votes vote down vote up
def probability(self, state):  # allow scratch to be passed in?
        scratch = _np.empty(self.dim, 'd')
        Edense = self.todense(scratch)
        return _np.dot(Edense, state.base)  # not vdot b/c data is *real* 
Example 24
Project: pyGSTi   Author: pyGSTio   File: slowreplib.py    License: Apache License 2.0 5 votes vote down vote up
def probability(self, state):
        scratch = _np.empty(self.dim, 'd')
        Edense = self.todense(scratch)
        return _np.dot(Edense, state.base)  # not vdot b/c data is *real* 
Example 25
Project: pyGSTi   Author: pyGSTio   File: slowreplib.py    License: Apache License 2.0 5 votes vote down vote up
def amplitude(self, state):
        # can assume state is a SVStateRep
        return _np.vdot(self.base, state.base)  # (or just 'dot') 
Example 26
Project: pyGSTi   Author: pyGSTio   File: slowreplib.py    License: Apache License 2.0 5 votes vote down vote up
def amplitude(self, state):  # allow scratch to be passed in?
        scratch = _np.empty(self.dim, complex)
        Edense = self.todense(scratch)
        return _np.vdot(Edense, state.base) 
Example 27
Project: pyGSTi   Author: pyGSTio   File: spamvec.py    License: Apache License 2.0 5 votes vote down vote up
def _construct_vector(self):
        dmDim = self.dmDim

        #  params is an array of length dmDim^2-1 that
        #  encodes a lower-triangular matrix "Lmx" via:
        #  Lmx[i,i] = params[i*dmDim + i] / param-norm  # i = 0...dmDim-2
        #     *last diagonal el is given by sqrt(1.0 - sum(L[i,j]**2))
        #  Lmx[i,j] = params[i*dmDim + j] + 1j*params[j*dmDim+i] (i > j)

        param2Sum = _np.vdot(self.params, self.params)  # or "dot" would work, since params are real
        paramNorm = _np.sqrt(param2Sum)  # also the norm of *all* Lmx els

        for i in range(dmDim):
            self.Lmx[i, i] = self.params[i * dmDim + i] / paramNorm
            for j in range(i):
                self.Lmx[i, j] = (self.params[i * dmDim + j] + 1j * self.params[j * dmDim + i]) / paramNorm

        Lmx_norm = _np.trace(_np.dot(self.Lmx.T.conjugate(), self.Lmx))  # sum of magnitude^2 of all els
        assert(_np.isclose(Lmx_norm, 1.0)), "Violated trace=1 condition!"

        #The (complex, Hermitian) density matrix is build by
        # assuming Lmx is its Cholesky decomp, which makes
        # the density matrix is pos-def.
        density_mx = _np.dot(self.Lmx, self.Lmx.T.conjugate())
        assert(_np.isclose(_np.trace(density_mx), 1.0)), "density matrix must be trace == 1"

        # write density matrix in given basis: = sum_i alpha_i B_i
        # ASSUME that basis is orthogonal, i.e. Tr(Bi^dag*Bj) = delta_ij
        basis_mxs = _np.rollaxis(self.basis_mxs, 2)  # shape (dmDim, dmDim, len(vec))
        vec = _np.array([_np.trace(_np.dot(M.T.conjugate(), density_mx)) for M in basis_mxs])

        #for now, assume Liouville vector should always be real (TODO: add 'real' flag later?)
        assert(_np.linalg.norm(_np.imag(vec)) < IMAG_TOL)
        vec = _np.real(vec)

        self.base1D.flags.writeable = True
        self.base1D[:] = vec[:]  # so shape is (dim,1) - the convention for spam vectors
        self.base1D.flags.writeable = False 
Example 28
Project: pyGSTi   Author: pyGSTio   File: reportables.py    License: Apache License 2.0 5 votes vote down vote up
def spam_dotprods(rhoVecs, povms):
    """SPAM dot products (concatenates POVMS)"""
    nEVecs = sum(len(povm) for povm in povms)
    ret = _np.empty((len(rhoVecs), nEVecs), 'd')
    for i, rhoVec in enumerate(rhoVecs):
        j = 0
        for povm in povms:
            for EVec in povm.values():
                ret[i, j] = _np.vdot(EVec.todense(), rhoVec.todense()); j += 1
                # todense() gives a 1D array, so no need to transpose EVec
    return ret 
Example 29
Project: pyGSTi   Author: pyGSTio   File: reportables.py    License: Apache License 2.0 5 votes vote down vote up
def eigenvalue_unitarity(A, B):
    """ A gauge-invariant quantity that behaves like the unitarity """
    Lambda = _np.dot(A, _np.linalg.inv(B))
    d2 = Lambda.shape[0]
    lmb = _np.linalg.eigvals(Lambda)
    return float(_np.real(_np.vdot(lmb, lmb)) - 1.0) / (d2 - 1.0) 
Example 30
Project: recruit   Author: Frank-qlu   File: test_regression.py    License: Apache License 2.0 5 votes vote down vote up
def test_refcount_vdot(self):
        # Changeset #3443
        _assert_valid_refcount(np.vdot)