Python numpy.vdot() 使用实例

The following are code examples for showing how to use . They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don’t like. You can also save this page to your account.

Example 1

def vdot(a, b):
    """Returns the dot product of two vectors.

    The input arrays are flattened into 1-D vectors and then it performs inner
    product of these vectors.

    Args:
        a (cupy.ndarray): The first argument.
        b (cupy.ndarray): The second argument.

    Returns:
        cupy.ndarray: Zero-dimensional array of the dot product result.

    .. seealso:: :func:`numpy.vdot`

    """
    if a.size != b.size:
        raise ValueError('Axis dimension mismatch')
    if a.dtype.kind == 'c':
        a = a.conj()

    return core.tensordot_core(a, b, None, 1, 1, a.size, ()) 

Example 2

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 3

def test_adjoint(dtype, shearletSystem):
    """Validate the adjoint."""
    shape = tuple(shearletSystem['size'])

    # load data
    X = np.random.randn(*shape).astype(dtype)

    # decomposition
    coeffs = pyshearlab.SLsheardec2D(X, shearletSystem)

    # adjoint
    Xadj = pyshearlab.SLshearadjoint2D(coeffs, shearletSystem)
    assert Xadj.dtype == X.dtype
    assert Xadj.shape == X.shape

    # <Ax, Ax> should equal <x, AtAx>
    assert (pytest.approx(np.vdot(coeffs, coeffs), rel=1e-3, abs=0) ==
            np.vdot(X, Xadj)) 

Example 4

def test_adjoint_of_inverse(dtype, shearletSystem):
    """Validate the adjoint of the inverse."""
    X = np.random.randn(*shearletSystem['size']).astype(dtype)

    # decomposition
    coeffs = pyshearlab.SLsheardec2D(X, shearletSystem)

    # reconstruction
    Xrec = pyshearlab.SLshearrec2D(coeffs, shearletSystem)
    Xrecadj = pyshearlab.SLshearrecadjoint2D(Xrec, shearletSystem)
    assert Xrecadj.dtype == X.dtype
    assert Xrecadj.shape == coeffs.shape

    # <A^-1x, A^-1x> = <A^-* A^-1 x, x>.
    assert (pytest.approx(np.vdot(Xrec, Xrec), rel=1e-3, abs=0) ==
            np.vdot(Xrecadj, coeffs)) 

Example 5

def test_basic(self):
        dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
        dt_complex = np.typecodes['Complex']

        # test real
        a = np.eye(3)
        for dt in dt_numeric + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test complex
        a = np.eye(3) * 1j
        for dt in dt_complex + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test boolean
        b = np.eye(3, dtype=np.bool)
        res = np.vdot(b, b)
        assert_(np.isscalar(res))
        assert_equal(np.vdot(b, b), True) 

Example 6

def test_vdot_uncontiguous(self):
        for size in [2, 1000]:
            # Different sizes match different branches in vdot.
            a = np.zeros((size, 2, 2))
            b = np.zeros((size, 2, 2))
            a[:, 0, 0] = np.arange(size)
            b[:, 0, 0] = np.arange(size) + 1
            # Make a and b uncontiguous:
            a = a[..., 0]
            b = b[..., 0]

            assert_equal(np.vdot(a, b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a, b.copy()),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a.copy(), b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a.copy('F'), b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a, b.copy('F')),
                         np.vdot(a.flatten(), b.flatten())) 

Example 7

def test_basic(self):
        dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
        dt_complex = np.typecodes['Complex']

        # test real
        a = np.eye(3)
        for dt in dt_numeric + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test complex
        a = np.eye(3) * 1j
        for dt in dt_complex + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test boolean
        b = np.eye(3, dtype=np.bool)
        res = np.vdot(b, b)
        assert_(np.isscalar(res))
        assert_equal(np.vdot(b, b), True) 

Example 8

def test_vdot_uncontiguous(self):
        for size in [2, 1000]:
            # Different sizes match different branches in vdot.
            a = np.zeros((size, 2, 2))
            b = np.zeros((size, 2, 2))
            a[:, 0, 0] = np.arange(size)
            b[:, 0, 0] = np.arange(size) + 1
            # Make a and b uncontiguous:
            a = a[..., 0]
            b = b[..., 0]

            assert_equal(np.vdot(a, b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a, b.copy()),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a.copy(), b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a.copy('F'), b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a, b.copy('F')),
                         np.vdot(a.flatten(), b.flatten())) 

Example 9

def vdot(a, b):
    """Returns the dot product of two vectors.

    The input arrays are flattened into 1-D vectors and then it performs inner
    product of these vectors.

    Args:
        a (cupy.ndarray): The first argument.
        b (cupy.ndarray): The second argument.

    Returns:
        cupy.ndarray: Zero-dimensional array of the dot product result.

    .. seealso:: :func:`numpy.vdot`

    """
    if a.size != b.size:
        raise ValueError('Axis dimension mismatch')

    return core.tensordot_core(a, b, None, 1, 1, a.size, ()) 

Example 10

def test_basic(self):
        dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
        dt_complex = np.typecodes['Complex']

        # test real
        a = np.eye(3)
        for dt in dt_numeric + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test complex
        a = np.eye(3) * 1j
        for dt in dt_complex + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test boolean
        b = np.eye(3, dtype=np.bool)
        res = np.vdot(b, b)
        assert_(np.isscalar(res))
        assert_equal(np.vdot(b, b), True) 

Example 11

def test_vdot_uncontiguous(self):
        for size in [2, 1000]:
            # Different sizes match different branches in vdot.
            a = np.zeros((size, 2, 2))
            b = np.zeros((size, 2, 2))
            a[:, 0, 0] = np.arange(size)
            b[:, 0, 0] = np.arange(size) + 1
            # Make a and b uncontiguous:
            a = a[..., 0]
            b = b[..., 0]

            assert_equal(np.vdot(a, b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a, b.copy()),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a.copy(), b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a.copy('F'), b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a, b.copy('F')),
                         np.vdot(a.flatten(), b.flatten())) 

Example 12

def rotation_matrix(a, b):
    """
    Create rotation matrix to rotate vector a into b.

    After http://math.stackexchange.com/a/476311

    Parameters
    ----------
    a,b
        xyz-vectors
    """

    v = np.cross(a, b)
    sin = np.linalg.norm(v)
    if sin == 0:
        return np.identity(3)
    cos = np.vdot(a, b)
    vx = np.mat([[0, -v[2], v[1]], [v[2], 0., -v[0]], [-v[1], v[0], 0.]])

    R = np.identity(3) + vx + vx * vx * (1 - cos) / (sin ** 2)

    return R 

Example 13

def test_basic(self):
        dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
        dt_complex = np.typecodes['Complex']

        # test real
        a = np.eye(3)
        for dt in dt_numeric + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test complex
        a = np.eye(3) * 1j
        for dt in dt_complex + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test boolean
        b = np.eye(3, dtype=np.bool)
        res = np.vdot(b, b)
        assert_(np.isscalar(res))
        assert_equal(np.vdot(b, b), True) 

Example 14

def test_vdot_uncontiguous(self):
        for size in [2, 1000]:
            # Different sizes match different branches in vdot.
            a = np.zeros((size, 2, 2))
            b = np.zeros((size, 2, 2))
            a[:, 0, 0] = np.arange(size)
            b[:, 0, 0] = np.arange(size) + 1
            # Make a and b uncontiguous:
            a = a[..., 0]
            b = b[..., 0]

            assert_equal(np.vdot(a, b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a, b.copy()),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a.copy(), b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a.copy('F'), b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a, b.copy('F')),
                         np.vdot(a.flatten(), b.flatten())) 

Example 15

def test_basic(self):
        dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
        dt_complex = np.typecodes['Complex']

        # test real
        a = np.eye(3)
        for dt in dt_numeric + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test complex
        a = np.eye(3) * 1j
        for dt in dt_complex + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test boolean
        b = np.eye(3, dtype=np.bool)
        res = np.vdot(b, b)
        assert_(np.isscalar(res))
        assert_equal(np.vdot(b, b), True) 

Example 16

def test_vdot_uncontiguous(self):
        for size in [2, 1000]:
            # Different sizes match different branches in vdot.
            a = np.zeros((size, 2, 2))
            b = np.zeros((size, 2, 2))
            a[:, 0, 0] = np.arange(size)
            b[:, 0, 0] = np.arange(size) + 1
            # Make a and b uncontiguous:
            a = a[..., 0]
            b = b[..., 0]

            assert_equal(np.vdot(a, b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a, b.copy()),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a.copy(), b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a.copy('F'), b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a, b.copy('F')),
                         np.vdot(a.flatten(), b.flatten())) 

Example 17

def test_basic(self):
        dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
        dt_complex = np.typecodes['Complex']

        # test real
        a = np.eye(3)
        for dt in dt_numeric + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test complex
        a = np.eye(3) * 1j
        for dt in dt_complex + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test boolean
        b = np.eye(3, dtype=np.bool)
        res = np.vdot(b, b)
        assert_(np.isscalar(res))
        assert_equal(np.vdot(b, b), True) 

Example 18

def test_vdot_uncontiguous(self):
        for size in [2, 1000]:
            # Different sizes match different branches in vdot.
            a = np.zeros((size, 2, 2))
            b = np.zeros((size, 2, 2))
            a[:, 0, 0] = np.arange(size)
            b[:, 0, 0] = np.arange(size) + 1
            # Make a and b uncontiguous:
            a = a[..., 0]
            b = b[..., 0]

            assert_equal(np.vdot(a, b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a, b.copy()),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a.copy(), b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a.copy('F'), b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a, b.copy('F')),
                         np.vdot(a.flatten(), b.flatten())) 

Example 19

def get_expectation_value(self, terms_dict, ids):
        """
        Return the expectation value of a qubit operator w.r.t. qubit ids.

        Args:
            terms_dict (dict): Operator dictionary (see QubitOperator.terms)
            ids (list[int]): List of qubit ids upon which the operator acts.

        Returns:
            Expectation value
        """
        expectation = 0.
        current_state = _np.copy(self._state)
        for (term, coefficient) in terms_dict:
            self._apply_term(term, ids)
            delta = coefficient * _np.vdot(current_state, self._state).real
            expectation += delta
            self._state = _np.copy(current_state)
        return expectation 

Example 20

def berry_curvature(H,kx,ky,mu,d=10**-6):
    '''
    Calculate the Berry curvature of the occupied bands for a Hamiltonian with the given chemical potential using the Kubo formula.

    Parameters
    ----------
    H : callable
        Input function which returns the Hamiltonian as a 2D array.
    kx,ky : float
        The two parameters which specify the 2D point at which the Berry curvature is to be calculated.
        They are also the input parameters to be conveyed to the function H.
    mu : float
        The chemical potential.
    d : float, optional
        The spacing to be used to calculate the derivatives.

    Returns
    -------
    float
        The calculated Berry curvature for function H at point kx,ky with chemical potential mu.
    '''
    result=0
    Vx=(H(kx+d,ky)-H(kx-d,ky))/(2*d)
    Vy=(H(kx,ky+d)-H(kx,ky-d))/(2*d)
    Es,Evs=eigh(H(kx,ky))
    for n in xrange(Es.shape[0]):
        for m in xrange(Es.shape[0]):
            if Es[n]<=mu and Es[m]>mu:
                result-=2*(np.vdot(np.dot(Vx,Evs[:,n]),Evs[:,m])*np.vdot(Evs[:,m],np.dot(Vy,Evs[:,n]))/(Es[n]-Es[m])**2).imag
    return result 

Example 21

def FBFMPOS(engine,app):
    '''
    This method calculates the profiles of spin-1-excitation states.
    '''
    result=[]
    table=engine.config.table(mask=['spin','nambu'])
    U1,U2,vs=engine.basis.U1,engine.basis.U2,sl.eigh(engine.matrix(k=app.k),eigvals_only=False)[1]
    for i,index in enumerate(sorted(table,key=table.get)):
        result.append([i])
        gs=np.vdot(U2[table[index],:,:].reshape(-1),U2[table[index],:,:].reshape(-1))*(1 if engine.basis.polarization=='up' else -1)
        dw=optrep(HP.FQuadratic(1.0,(index.replace(spin=0,nambu=HP.CREATION),index.replace(spin=0,nambu=HP.ANNIHILATION)),seqs=(table[index],table[index])),app.k,engine.basis)
        up=optrep(HP.FQuadratic(1.0,(index.replace(spin=1,nambu=HP.CREATION),index.replace(spin=1,nambu=HP.ANNIHILATION)),seqs=(table[index],table[index])),app.k,engine.basis)
        for pos in app.ns or (0,):
            result[-1].append((np.vdot(vs[:,pos],up.dot(vs[:,pos]))-np.vdot(vs[:,pos],dw.dot(vs[:,pos]))-gs)*(-1 if engine.basis.polarization=='up' else 1))
    result=np.asarray(result)
    assert nl.norm(np.asarray(result).imag)<HP.RZERO
    result=result.real
    name='%s_%s'%(engine,app.name)
    if app.savedata: np.savetxt('%s/%s.dat'%(engine.dout,name),result)
    if app.plot: app.figure('L',result,'%s/%s'%(engine.dout,name),legend=['Level %s'%n for n in app.ns or (0,)])
    if app.returndata: return result 

Example 22

def overlap(*args):
    '''
    Calculate the overlap between two vectors or among a matrix and two vectors.
    Usage:
        * ``overlap(vector1,vector2)``, with 
            vector1,vector2: 1d ndarray
                The vectors between which the overlap is to calculate.
        * ``overlap(vector1,matrix,vector2)``, with
            vector1,vector2: 1d ndarray
                The ket and bra in the overlap.
            matrix: 2d ndarray-like
                The matrix between the two vectors.
    '''
    assert len(args) in (2,3)
    if len(args)==2:
        return np.vdot(args[0],args[1])
    else:
        return np.vdot(args[0],args[1].dot(args[2])) 

Example 23

def test_basic(self):
        dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
        dt_complex = np.typecodes['Complex']

        # test real
        a = np.eye(3)
        for dt in dt_numeric + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test complex
        a = np.eye(3) * 1j
        for dt in dt_complex + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test boolean
        b = np.eye(3, dtype=np.bool)
        res = np.vdot(b, b)
        assert_(np.isscalar(res))
        assert_equal(np.vdot(b, b), True) 

Example 24

def test_vdot_uncontiguous(self):
        for size in [2, 1000]:
            # Different sizes match different branches in vdot.
            a = np.zeros((size, 2, 2))
            b = np.zeros((size, 2, 2))
            a[:, 0, 0] = np.arange(size)
            b[:, 0, 0] = np.arange(size) + 1
            # Make a and b uncontiguous:
            a = a[..., 0]
            b = b[..., 0]

            assert_equal(np.vdot(a, b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a, b.copy()),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a.copy(), b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a.copy('F'), b),
                         np.vdot(a.flatten(), b.flatten()))
            assert_equal(np.vdot(a, b.copy('F')),
                         np.vdot(a.flatten(), b.flatten())) 

Example 25

def test_inner_vec(nr_sites, local_dim, rank, rgen, dtype):
    mp_psi1 = factory.random_mpa(nr_sites, local_dim, rank, randstate=rgen,
                                 dtype=dtype)
    psi1 = mp_psi1.to_array().ravel()
    mp_psi2 = factory.random_mpa(nr_sites, local_dim, rank, randstate=rgen,
                                 dtype=dtype)
    psi2 = mp_psi2.to_array().ravel()

    inner_np = np.vdot(psi1, psi2)
    inner_mp = mp.inner(mp_psi1, mp_psi2)
    assert_almost_equal(inner_mp, inner_np)
    assert inner_mp.dtype == dtype 

Example 26

def test_refcount_vdot(self, level=rlevel):
        # Changeset #3443
        _assert_valid_refcount(np.vdot) 

Example 27

def test_vdot_array_order(self):
        a = np.array([[1, 2], [3, 4]], order='C')
        b = np.array([[1, 2], [3, 4]], order='F')
        res = np.vdot(a, a)

        # integer arrays are exact
        assert_equal(np.vdot(a, b), res)
        assert_equal(np.vdot(b, a), res)
        assert_equal(np.vdot(b, b), res) 

Example 28

def get_shortest_bases_from_extented_bases(extended_bases, tolerance):

    def mycmp(x, y):
        return cmp(np.vdot(x,x), np.vdot(y,y))

    basis = np.zeros((7,3), dtype=float)
    basis[:4] = extended_bases
    basis[4]  = extended_bases[0] + extended_bases[1]
    basis[5]  = extended_bases[1] + extended_bases[2]
    basis[6]  = extended_bases[2] + extended_bases[0]
    # Sort bases by the lengthes (shorter is earlier)
    basis = sorted(basis, cmp=mycmp)
    
    # Choose shortest and linearly independent three bases
    # This algorithm may not be perfect.
    for i in range(7):
        for j in range(i+1, 7):
            for k in range(j+1, 7):
                if abs(np.linalg.det([basis[i],basis[j],basis[k]])) > tolerance:
                    return np.array([basis[i],basis[j],basis[k]])

    print ("Delaunary reduction is failed.")
    return basis[:3]

#
# Other tiny tools
# 

Example 29

def get_angles( lattice ):
    """
    Get alpha, beta and gamma angles from lattice vectors.
    
    >>> get_angles( np.diag([1,2,3]) )
    (90.0, 90.0, 90.0)
    """
    a, b, c = get_cell_parameters( lattice )
    alpha = np.arccos(np.vdot(lattice[1], lattice[2]) / b / c ) / np.pi * 180
    beta  = np.arccos(np.vdot(lattice[2], lattice[0]) / c / a ) / np.pi * 180
    gamma = np.arccos(np.vdot(lattice[0], lattice[1]) / a / b ) / np.pi * 180
    return alpha, beta, gamma 

Example 30

def check_duality_gap(a, b, M, G, u, v, cost):
    cost_dual = np.vdot(a, u) + np.vdot(b, v)
    # Check that dual and primal cost are equal
    np.testing.assert_almost_equal(cost_dual, cost)

    [ind1, ind2] = np.nonzero(G)

    # Check that reduced cost is zero on transport arcs
    np.testing.assert_array_almost_equal((M - u.reshape(-1, 1) - v.reshape(1, -1))[ind1, ind2],
                                         np.zeros(ind1.size)) 

Example 31

def vectorize_and_dot_dataset(dataset):
    dots = numpy.zeros(len(dataset))
    labels = numpy.zeros(len(dataset))
    i = 0
    for row in dataset:
        #Get the vectors for each word in the body and headline
        split_headline = hf.split_words(row['headline'])
        split_body = hf.split_words_special(row['body'], split_code)
        headline_vectors = vectorize_wordlist(split_headline)
        body_vectors = vectorize_wordlist(split_body)
        #Sum the words in the body, sum the words in the headline
        summed_headline_vector = numpy.sum(headline_vectors, axis=0)
        summed_body_vector = numpy.sum(body_vectors, axis=0)
        #Normalize
        normalized_headline_vector = normalize(summed_headline_vector.reshape(1,-1))
        normalized_body_vector = normalize(summed_body_vector.reshape(1,-1))
        #Save the row vector
        row['row_vector'] = numpy.concatenate( (normalized_headline_vector[0], normalized_body_vector[0]), axis=0)
        row['isRelated'] = 0 if row['stance'] == 'unrelated' else 1

        # Data relating to the relationship between the headline/body can be appended to row['row_vector']
        if True:
            extra_nodes = []

            #Save the dot product
            dot = numpy.vdot(normalized_headline_vector, normalized_body_vector)
            extra_nodes.append(dot)
            #Jaccard distance
            jaccard = jaccard_distance(set(split_headline), set(split_body))
            extra_nodes.append(jaccard)
            #Sentiment analysis
            extra_nodes.append( sentiment_analyzer.polarity_scores(row['headline'])['compound'] )
            extra_nodes.append( sentiment_analyzer.polarity_scores(" ".join(split_body))['compound'] )

            row['row_vector'] = numpy.append(row['row_vector'], extra_nodes)


    # return dots, labels 

Example 32

def test_refcount_vdot(self, level=rlevel):
        # Changeset #3443
        _assert_valid_refcount(np.vdot) 

Example 33

def test_vdot_array_order(self):
        a = np.array([[1, 2], [3, 4]], order='C')
        b = np.array([[1, 2], [3, 4]], order='F')
        res = np.vdot(a, a)

        # integer arrays are exact
        assert_equal(np.vdot(a, b), res)
        assert_equal(np.vdot(b, a), res)
        assert_equal(np.vdot(b, b), res) 

Example 34

def _calculate(self):
        min_, max_ = self._bounds
        n = np.prod(self.reference.shape)
        f = n * (max_ - min_)**2

        diff = self.other - self.reference
        value = np.vdot(diff, diff) / f

        # calculate the gradient only when needed
        self._g_diff = diff
        self._g_f = f
        gradient = None
        return value, gradient 

Example 35

def calc_cost(self):
        cost = sum(self.E[key] * self.E[key] for key in self.E)
        cost += self.l*(np.vdot(self.B, self.B) + np.vdot(self.C, self.C))
        return cost 

Example 36

def test_refcount_vdot(self, level=rlevel):
        # Changeset #3443
        _assert_valid_refcount(np.vdot) 

Example 37

def test_vdot_array_order(self):
        a = np.array([[1, 2], [3, 4]], order='C')
        b = np.array([[1, 2], [3, 4]], order='F')
        res = np.vdot(a, a)

        # integer arrays are exact
        assert_equal(np.vdot(a, b), res)
        assert_equal(np.vdot(b, a), res)
        assert_equal(np.vdot(b, b), res) 

Example 38

def test_blas_dot(backend, n):
    b = backend()
    x = (np.random.rand(n) + 1j * np.random.rand(n))
    y = (np.random.rand(n) + 1j * np.random.rand(n))
    x = np.require(x, dtype=np.dtype('complex64'), requirements='F')
    y = np.require(y, dtype=np.dtype('complex64'), requirements='F')
    x_d = b.copy_array(x)
    y_d = b.copy_array(y)

    y_exp = np.vdot(x, y).real
    y_act = b.dot(x_d, y_d)

    np.testing.assert_allclose(y_exp, y_act, atol=1e-5) 

Example 39

def dot(self, x, y):
        """ returns x^T * y """
        assert isinstance(x, self.dndarray)
        assert isinstance(y, self.dndarray)
        return np.vdot( x._arr, y._arr ).real 

Example 40

def test_refcount_vdot(self, level=rlevel):
        # Changeset #3443
        _assert_valid_refcount(np.vdot) 

Example 41

def test_vdot_array_order(self):
        a = np.array([[1, 2], [3, 4]], order='C')
        b = np.array([[1, 2], [3, 4]], order='F')
        res = np.vdot(a, a)

        # integer arrays are exact
        assert_equal(np.vdot(a, b), res)
        assert_equal(np.vdot(b, a), res)
        assert_equal(np.vdot(b, b), res) 

Example 42

def test_refcount_vdot(self, level=rlevel):
        # Changeset #3443
        _assert_valid_refcount(np.vdot) 

Example 43

def test_vdot_array_order(self):
        a = np.array([[1, 2], [3, 4]], order='C')
        b = np.array([[1, 2], [3, 4]], order='F')
        res = np.vdot(a, a)

        # integer arrays are exact
        assert_equal(np.vdot(a, b), res)
        assert_equal(np.vdot(b, a), res)
        assert_equal(np.vdot(b, b), res) 

Example 44

def test_refcount_vdot(self, level=rlevel):
        # Changeset #3443
        _assert_valid_refcount(np.vdot) 

Example 45

def test_vdot_array_order(self):
        a = np.array([[1, 2], [3, 4]], order='C')
        b = np.array([[1, 2], [3, 4]], order='F')
        res = np.vdot(a, a)

        # integer arrays are exact
        assert_equal(np.vdot(a, b), res)
        assert_equal(np.vdot(b, a), res)
        assert_equal(np.vdot(b, b), res) 

Example 46

def Tdot(self, fn, dtype):
        from pyculib.blas.binding import cuBlas

        x = np.random.random(10).astype(dtype)
        y = np.random.random(10).astype(dtype)
        d_x = cuda.to_device(x)
        d_y = cuda.to_device(y)

        blas = cuBlas()
        got = getattr(blas, fn)(x.size, d_x, 1, d_y, 1)
        if fn.endswith('c'):
            exp = np.vdot(x, y)
        else:
            exp = np.dot(x, y)
        self.assertTrue(np.allclose(got, exp)) 

Example 47

def Tdotc(self, fn, dtype):
        x = np.random.random(10).astype(dtype)
        y = np.random.random(10).astype(dtype)
        got = self.blas.dotc(x, y)
        exp = np.vdot(x, y)
        self.assertTrue(np.allclose(got, exp)) 

Example 48

def compute_correlation(matrix_a, matrix_b):
    correlation = numpy.vdot(matrix_a, matrix_b)
    correlation /= numpy.linalg.norm(matrix_a)*numpy.linalg.norm(matrix_b)
    correlation = (correlation + 1)/2
    return correlation 

Example 49

def berry_phase(H,path,ns):
    '''
    Calculate the Berry phase of some bands of a Hamiltonian along a certain path.

    Parameters
    ----------
    H : callable
        Input function which returns the Hamiltonian as a 2D array.
    path : iterable
        The path along which to calculate the Berry phase.
    ns : iterable of int
        The sequences of bands whose Berry phases are wanted.

    Returns
    -------
    1d ndarray
        The wanted Berry phase of the selected bands.
    '''
    ns=np.array(ns)
    for i,parameters in enumerate(path):
        new=eigh(H(**parameters))[1][:,ns]
        if i==0:
            result=np.ones(len(ns),new.dtype)
            evs=new
        else:
            for j in xrange(len(ns)):
                result[j]*=np.vdot(old[:,j],new[:,j])
        old=new
    else:
        for j in xrange(len(ns)):
            result[j]*=np.vdot(old[:,j],evs[:,j])
    return np.angle(result)/np.pi 

Example 50

def iter(self):
        '''
        The Lanczos iteration.
        '''
        while len(self.candidates)>0:
            v=self.candidates.pop(0)
            norm=nl.norm(v)
            if norm>self.dtol:
                break
            elif self.niter>=self.nc:
                self.deflations.append(self.niter-self.nc)
        else:
            self.stop=True
        if not self.stop:
            self.vectors[self.niter]=v/norm
            if self.niter-self.nc-1>=0:
                self._T_[self.niter,self.niter-self.nc-1]=norm
            else:
                self.P[self.niter,self.niter-self.nc-1+self.nv0]=norm
            for k,vc in enumerate(self.candidates):
                overlap=np.vdot(self.vectors[self.niter],vc)
                if k+self.niter>=self.nc:
                    self._T_[self.niter,k+self.niter-self.nc]=overlap
                else:
                    self.P[self.niter,self.niter-self.nc+k+self.nv0]=overlap
                vc-=overlap*self.vectors[self.niter]
            v=self.matrix.dot(self.vectors[self.niter])
            for k in xrange(max(self.niter-self.nc-1,0),self.niter):
                self._T_[k,self.niter]=np.conjugate(self._T_[self.niter,k])
                v-=self._T_[k,self.niter]*self.vectors[k]
            for k in it.chain(self.deflations,[self.niter]):
                overlap=np.vdot(self.vectors[k],v)
                if k in set(self.deflations)|{self.niter}:
                    self._T_[k,self.niter]=overlap
                    self._T_[self.niter,k]=np.conjugate(overlap)
                v-=overlap*self.vectors[k]
            self.candidates.append(v)
            if not self.keepstate and self.niter>=self.nc and self.niter-self.nc not in self.deflations: self.vectors[self.niter-self.nc]=None
            self.niter+=1 
点赞