Python numpy.asmatrix() Examples

The following are 30 code examples of numpy.asmatrix(). 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 also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: fisheye.py    From DualFisheye with MIT License 6 votes vote down vote up
def add_pixels(self, uv_px, img1d, weight=None):
        # Lookup row & column for each in-bounds coordinate.
        mask = self.get_mask(uv_px)
        xx = uv_px[0,mask]
        yy = uv_px[1,mask]
        # Update matrix according to assigned weight.
        if weight is None:
            img1d[mask] = self.img[yy,xx]
        elif np.isscalar(weight):
            img1d[mask] += self.img[yy,xx] * weight
        else:
            w1 = np.asmatrix(weight, dtype='float32')
            w3 = w1.transpose() * np.ones((1,3))
            img1d[mask] += np.multiply(self.img[yy,xx], w3[mask])


# A panorama image made from several FisheyeImage sources.
# TODO: Add support for supersampled anti-aliasing filters. 
Example #2
Source File: util.py    From sfa-numpy with MIT License 6 votes vote down vote up
def coherence_of_columns(A):
    """Mutual coherence of columns of A.

    Parameters
    ----------
    A : array_like
        Input matrix.
    p : int, optional
        p-th norm.

    Returns
    -------
    array_like
        Mutual coherence of columns of A.
    """
    A = np.asmatrix(A)
    _, N = A.shape
    A = A * np.asmatrix(np.diag(1/norm_of_columns(A)))
    Gram_A = A.H*A
    for j in range(N):
        Gram_A[j, j] = 0
    return np.max(np.abs(Gram_A)) 
Example #3
Source File: label_ranker.py    From chowmein with MIT License 6 votes vote down vote up
def label_relevance_score(self,
                              topic_models,
                              pmi_w2l):
        """
        Calculate the relevance scores between each label and each topic

        Parameters:
        ---------------
        topic_models: numpy.ndarray(#topics, #words)
           the topic models

        pmi_w2l: numpy.ndarray(#words, #labels)
           the Point-wise Mutual Information(PMI) table of
           the form, PMI(w, l | C)
        
        Returns;
        -------------
        numpy.ndarray, shape (#topics, #labels)
            the scores of each label on each topic
        """
        assert topic_models.shape[1] == pmi_w2l.shape[0]
        return np.asarray(np.asmatrix(topic_models) *
                          np.asmatrix(pmi_w2l)) 
Example #4
Source File: model.py    From vadnet with GNU Lesser General Public License v3.0 6 votes vote down vote up
def transform(info, sin, sout, sxtra, board, opts, vars): 
     
    if vars['loaded']:	

        sess = vars['sess']
        x = vars['x']
        y = vars['y']
        ph_n_shuffle = vars['ph_n_shuffle']
        ph_n_repeat = vars['ph_n_repeat']
        ph_n_batch = vars['ph_n_batch']
        init = vars['init']
        logits = vars['logits']

        input = np.asmatrix(sin).reshape(-1, x.shape[1]) 

        dummy = np.zeros((input.shape[0],), dtype=np.int32)
        sess.run(init, feed_dict = { x : input, y : dummy, ph_n_shuffle : 1, ph_n_repeat : 1, ph_n_batch : input.shape[0] })    
        output = sess.run(logits)    
        output = np.mean(output, axis=0)

        for i in range(sout.dim):
            sout[i] = output[i] 
Example #5
Source File: test_shape_base.py    From lambda-packs with MIT License 6 votes vote down vote up
def test_return_type(self):
        a = np.ones([2, 2])
        m = np.asmatrix(a)
        assert_equal(type(kron(a, a)), np.ndarray)
        assert_equal(type(kron(m, m)), np.matrix)
        assert_equal(type(kron(a, m)), np.matrix)
        assert_equal(type(kron(m, a)), np.matrix)

        class myarray(np.ndarray):
            __array_priority__ = 0.0

        ma = myarray(a.shape, a.dtype, a.data)
        assert_equal(type(kron(a, a)), np.ndarray)
        assert_equal(type(kron(ma, ma)), myarray)
        assert_equal(type(kron(a, ma)), np.ndarray)
        assert_equal(type(kron(ma, a)), myarray) 
Example #6
Source File: vis.py    From calfem-python with MIT License 5 votes vote down vote up
def _bspline(controlPoints, pointsOnCurve=20):
    '''
    Uniform cubic B-spline.
    
    Params:
    controlPoints - Control points. Numpy array. One coordinate per row.
    pointsOnCurve - number of sub points per segment
    
    Mirrored start- and end-points are added if the curve is not closed.
    If the curve is closed some points are duplicated to make the closed 
    spline continuous. 
    (See http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/B-spline/bspline-curve-closed.html)
    
    Based on descriptions on:
    http://www.siggraph.org/education/materials/HyperGraph/modeling/splines/b_spline.htm
    http://en.wikipedia.org/wiki/B-spline#Uniform_cubic_B-splines
    '''
    controlPoints = np.asarray(controlPoints) #Convert to array if input is a list.
    if (controlPoints[0,:] == controlPoints[-1,:]).all():
        #If the curve is closed we extend each opposite endpoint to the other side  
        CPs = np.asmatrix(np.vstack((controlPoints[-2,:],
                                controlPoints,
                                controlPoints[1,:])))
    else:#Else make mirrored endpoints:
        CPs = np.asmatrix(np.vstack((2*controlPoints[0,:] - controlPoints[1,:],
                                controlPoints,
                                2*controlPoints[-1,:] - controlPoints[-2,:])))
    M = (1.0/6) * np.matrix([[-1,  3, -3, 1],
                          [ 3, -6,  3, 0],
                          [-3,  0,  3, 0],
                          [ 1,  4,  1, 0]])
    t = np.linspace(0, 1, pointsOnCurve)
    T = np.matrix([[pow(s,3), pow(s,2), s, 1] for s in t])
    return np.asarray( np.vstack( T * M * CPs[i-1 : i+3, :] for i in range( 1, len(CPs)-2 ) ) ) 
Example #7
Source File: test_defmatrix.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_scalar_indexing(self):
        x = asmatrix(np.zeros((3, 2), float))
        assert_equal(x[0, 0], x[0][0]) 
Example #8
Source File: test_defmatrix.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_asmatrix(self):
        A = np.arange(100).reshape(10, 10)
        mA = asmatrix(A)
        A[0, 0] = -10
        assert_(A[0, 0] == mA[0, 0]) 
Example #9
Source File: pycalfem_vis.py    From calfem-python with MIT License 5 votes vote down vote up
def _catmullspline(controlPoints, pointsOnEachSegment=10):
    """
    Returns points on a Catmull-Rom spline that interpolated the control points.
    Inital/end tangents are created by mirroring the second/second-to-last)
    control points in the first/last points.
    
    Params:
    controlPoints - Numpy array containing the control points of the spline. 
                    Each row should contain the x,y,(z) values.
                    [[x1, y2],
                     [x2, y2],
                        ...    
                     [xn, yn]]
                     
    pointsOnEachSegment - The number of points on each segment of the curve.
                        If there are n control points and k samplesPerSegment, 
                        then there will be (n+1)*k numeric points on the curve.
    """
    controlPoints = np.asarray(controlPoints) #Convert to array if input is a list.
    if (controlPoints[0,:] == controlPoints[-1,:]).all():
        #If the curve is closed we extend each opposite endpoint to the other side  
        CPs = np.asmatrix(np.vstack((controlPoints[-2,:],
                                controlPoints,
                                controlPoints[1,:])))
    else: #Else make mirrored endpoints:
        CPs = np.asmatrix(np.vstack((2*controlPoints[0,:] - controlPoints[1,:],
                                controlPoints,
                                2*controlPoints[-1,:] - controlPoints[-2,:])))
    M = 0.5 * np.matrix([[ 0,  2,  0,  0],[-1,  0,  1,  0],[ 2, -5,  4, -1],[-1,  3, -3,  1]])
    t = np.linspace(0, 1, pointsOnEachSegment)
    T = np.matrix([[1, s, pow(s,2), pow(s,3)] for s in t])
    return np.asarray( np.vstack( T * M * CPs[j-1:j+3,:] for j in range( 1, len(CPs)-2 ) ) ) 
Example #10
Source File: test_regression.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_matrix_std_argmax(self):
        # Ticket #83
        x = np.asmatrix(np.random.uniform(0, 1, (3, 3)))
        assert_equal(x.std().shape, ())
        assert_equal(x.argmax().shape, ()) 
Example #11
Source File: test_indexing.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_matrix_fancy(self):
        # The matrix class messes with the shape. While this is always
        # weird (getitem is not used, it does not have setitem nor knows
        # about fancy indexing), this tests gh-3110
        m = np.matrix([[1, 2], [3, 4]])

        assert_(isinstance(m[[0,1,0], :], np.matrix))

        # gh-3110. Note the transpose currently because matrices do *not*
        # support dimension fixing for fancy indexing correctly.
        x = np.asmatrix(np.arange(50).reshape(5,10))
        assert_equal(x[:2, np.array(-1)], x[:2, -1].T) 
Example #12
Source File: Transform.py    From PyEngine3D with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def transform(m, v):
    return np.asarray(m * np.asmatrix(v).T)[:, 0] 
Example #13
Source File: matlib.py    From Computable with MIT License 5 votes vote down vote up
def eye(n,M=None, k=0, dtype=float):
    """
    Return a matrix with ones on the diagonal and zeros elsewhere.

    Parameters
    ----------
    n : int
        Number of rows in the output.
    M : int, optional
        Number of columns in the output, defaults to `n`.
    k : int, optional
        Index of the diagonal: 0 refers to the main diagonal,
        a positive value refers to an upper diagonal,
        and a negative value to a lower diagonal.
    dtype : dtype, optional
        Data-type of the returned matrix.

    Returns
    -------
    I : matrix
        A `n` x `M` matrix where all elements are equal to zero,
        except for the `k`-th diagonal, whose values are equal to one.

    See Also
    --------
    numpy.eye : Equivalent array function.
    identity : Square identity matrix.

    Examples
    --------
    >>> import numpy.matlib
    >>> np.matlib.eye(3, k=1, dtype=float)
    matrix([[ 0.,  1.,  0.],
            [ 0.,  0.,  1.],
            [ 0.,  0.,  0.]])

    """
    return asmatrix(np.eye(n, M, k, dtype)) 
Example #14
Source File: test_defmatrix.py    From Computable with MIT License 5 votes vote down vote up
def test_asmatrix(self):
        A = arange(100).reshape(10, 10)
        mA = asmatrix(A)
        A[0, 0] = -10
        assert_(A[0, 0] == mA[0, 0]) 
Example #15
Source File: test_defmatrix.py    From Computable with MIT License 5 votes vote down vote up
def test_scalar_indexing(self):
        x = asmatrix(zeros((3, 2), float))
        assert_equal(x[0, 0], x[0][0]) 
Example #16
Source File: heston.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
def get_correlated_geometric_brownian_motions(params: ModelParameters,
                                              correlation_matrix: np.array,
                                              n: int):
    """
    Constructs a basket of correlated asset paths using the Cholesky
    decomposition method.

    Arguments:
        params : ModelParameters
            The parameters for the stochastic model.
        correlation_matrix : np.array
            An n x n correlation matrix.
        n : int
            Number of assets (number of paths to return)

    Returns:
        n correlated log return geometric brownian motion processes
    """
    decomposition = sp.linalg.cholesky(correlation_matrix, lower=False)
    uncorrelated_paths = []
    sqrt_delta_sigma = np.sqrt(params.all_delta) * params.all_sigma
    # Construct uncorrelated paths to convert into correlated paths
    for i in range(params.all_time):
        uncorrelated_random_numbers = []
        for j in range(n):
            uncorrelated_random_numbers.append(random.normalvariate(0, sqrt_delta_sigma))
        uncorrelated_paths.append(np.array(uncorrelated_random_numbers))
    uncorrelated_matrix = np.asmatrix(uncorrelated_paths)
    correlated_matrix = uncorrelated_matrix * decomposition
    assert isinstance(correlated_matrix, np.matrix)
    # The rest of this method just extracts paths from the matrix
    extracted_paths = []
    for i in range(1, n + 1):
        extracted_paths.append([])
    for j in range(0, len(correlated_matrix) * n - n, n):
        for i in range(n):
            extracted_paths[i].append(correlated_matrix.item(j + i))
    return extracted_paths 
Example #17
Source File: test_defmatrix.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_list_indexing(self):
        A = np.arange(6)
        A.shape = (3, 2)
        x = asmatrix(A)
        assert_array_equal(x[:, [1, 0]], x[:, ::-1])
        assert_array_equal(x[[2, 1, 0],:], x[::-1,:]) 
Example #18
Source File: vis_mpl.py    From calfem-python with MIT License 5 votes vote down vote up
def _catmullspline(controlPoints, pointsOnEachSegment=10):
    """
    Returns points on a Catmull-Rom spline that interpolated the control points.
    Inital/end tangents are created by mirroring the second/second-to-last)
    control points in the first/last points.

    Params:
    controlPoints - Numpy array containing the control points of the spline.
                    Each row should contain the x,y,(z) values.
                    [[x1, y2],
                     [x2, y2],
                        ...
                     [xn, yn]]

    pointsOnEachSegment - The number of points on each segment of the curve.
                        If there are n control points and k samplesPerSegment,
                        then there will be (n+1)*k numeric points on the curve.
    """
    controlPoints = np.asarray(
        controlPoints)  # Convert to array if input is a list.
    if (controlPoints[0, :] == controlPoints[-1, :]).all():
        # If the curve is closed we extend each opposite endpoint to the other side
        CPs = np.asmatrix(np.vstack((controlPoints[-2, :],
                                     controlPoints,
                                     controlPoints[1, :])))
    else:  # Else make mirrored endpoints:
        CPs = np.asmatrix(np.vstack((2*controlPoints[0, :] - controlPoints[1, :],
                                     controlPoints,
                                     2*controlPoints[-1, :] - controlPoints[-2, :])))
    M = 0.5 * np.matrix([[0,  2,  0,  0], [-1,  0,  1,  0],
                         [2, -5,  4, -1], [-1,  3, -3,  1]])
    t = np.linspace(0, 1, pointsOnEachSegment)
    T = np.matrix([[1, s, pow(s, 2), pow(s, 3)] for s in t])
    return np.asarray(np.vstack([T * M * CPs[j-1:j+3, :] for j in range(1, len(CPs)-2)])) 
Example #19
Source File: matlib.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def eye(n,M=None, k=0, dtype=float):
    """
    Return a matrix with ones on the diagonal and zeros elsewhere.

    Parameters
    ----------
    n : int
        Number of rows in the output.
    M : int, optional
        Number of columns in the output, defaults to `n`.
    k : int, optional
        Index of the diagonal: 0 refers to the main diagonal,
        a positive value refers to an upper diagonal,
        and a negative value to a lower diagonal.
    dtype : dtype, optional
        Data-type of the returned matrix.

    Returns
    -------
    I : matrix
        A `n` x `M` matrix where all elements are equal to zero,
        except for the `k`-th diagonal, whose values are equal to one.

    See Also
    --------
    numpy.eye : Equivalent array function.
    identity : Square identity matrix.

    Examples
    --------
    >>> import numpy.matlib
    >>> np.matlib.eye(3, k=1, dtype=float)
    matrix([[ 0.,  1.,  0.],
            [ 0.,  0.,  1.],
            [ 0.,  0.,  0.]])

    """
    return asmatrix(np.eye(n, M, k, dtype)) 
Example #20
Source File: vis.py    From calfem-python with MIT License 5 votes vote down vote up
def _catmullspline(controlPoints, pointsOnEachSegment=10):
    """
    Returns points on a Catmull-Rom spline that interpolated the control points.
    Inital/end tangents are created by mirroring the second/second-to-last)
    control points in the first/last points.
    
    Params:
    controlPoints - Numpy array containing the control points of the spline. 
                    Each row should contain the x,y,(z) values.
                    [[x1, y2],
                     [x2, y2],
                        ...    
                     [xn, yn]]
                     
    pointsOnEachSegment - The number of points on each segment of the curve.
                        If there are n control points and k samplesPerSegment, 
                        then there will be (n+1)*k numeric points on the curve.
    """
    controlPoints = np.asarray(controlPoints) #Convert to array if input is a list.
    if (controlPoints[0,:] == controlPoints[-1,:]).all():
        #If the curve is closed we extend each opposite endpoint to the other side  
        CPs = np.asmatrix(np.vstack((controlPoints[-2,:],
                                controlPoints,
                                controlPoints[1,:])))
    else: #Else make mirrored endpoints:
        CPs = np.asmatrix(np.vstack((2*controlPoints[0,:] - controlPoints[1,:],
                                controlPoints,
                                2*controlPoints[-1,:] - controlPoints[-2,:])))
    M = 0.5 * np.matrix([[ 0,  2,  0,  0],[-1,  0,  1,  0],[ 2, -5,  4, -1],[-1,  3, -3,  1]])
    t = np.linspace(0, 1, pointsOnEachSegment)
    T = np.matrix([[1, s, pow(s,2), pow(s,3)] for s in t])
    return np.asarray( np.vstack( T * M * CPs[j-1:j+3,:] for j in range( 1, len(CPs)-2 ) ) ) 
Example #21
Source File: test_regression.py    From lambda-packs with MIT License 5 votes vote down vote up
def test_matrix_std_argmax(self,level=rlevel):
        # Ticket #83
        x = np.asmatrix(np.random.uniform(0, 1, (3, 3)))
        self.assertEqual(x.std().shape, ())
        self.assertEqual(x.argmax().shape, ()) 
Example #22
Source File: test_defmatrix.py    From Computable with MIT License 5 votes vote down vote up
def test_row_column_indexing(self):
        x = asmatrix(np.eye(2))
        assert_array_equal(x[0,:], [[1, 0]])
        assert_array_equal(x[1,:], [[0, 1]])
        assert_array_equal(x[:, 0], [[1], [0]])
        assert_array_equal(x[:, 1], [[0], [1]]) 
Example #23
Source File: STFIWF.py    From 2016CCF-sougou with Apache License 2.0 5 votes vote down vote up
def inverse_transform(self, X):
        """Return terms per document with nonzero entries in X.

        Parameters
        ----------
        X : {array, sparse matrix}, shape = [n_samples, n_features]

        Returns
        -------
        X_inv : list of arrays, len = n_samples
            List of arrays of terms.
        """
        self._check_vocabulary()

        if sp.issparse(X):
            # We need CSR format for fast row manipulations.
            X = X.tocsr()
        else:
            # We need to convert X to a matrix, so that the indexing
            # returns 2D objects
            X = np.asmatrix(X)
        n_samples = X.shape[0]

        terms = np.array(list(self.vocabulary_.keys()))
        indices = np.array(list(self.vocabulary_.values()))
        inverse_vocabulary = terms[np.argsort(indices)]

        return [inverse_vocabulary[X[i, :].nonzero()[1]].ravel()
                for i in range(n_samples)] 
Example #24
Source File: test_indexing.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_matrix_fancy(self):
        # The matrix class messes with the shape. While this is always
        # weird (getitem is not used, it does not have setitem nor knows
        # about fancy indexing), this tests gh-3110
        m = np.matrix([[1, 2], [3, 4]])

        assert_(isinstance(m[[0,1,0], :], np.matrix))

        # gh-3110. Note the transpose currently because matrices do *not*
        # support dimension fixing for fancy indexing correctly.
        x = np.asmatrix(np.arange(50).reshape(5,10))
        assert_equal(x[:2, np.array(-1)], x[:2, -1].T) 
Example #25
Source File: test_regression.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_matrix_std_argmax(self,level=rlevel):
        # Ticket #83
        x = np.asmatrix(np.random.uniform(0, 1, (3, 3)))
        self.assertEqual(x.std().shape, ())
        self.assertEqual(x.argmax().shape, ()) 
Example #26
Source File: test_defmatrix.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_list_indexing(self):
        A = np.arange(6)
        A.shape = (3, 2)
        x = asmatrix(A)
        assert_array_equal(x[:, [1, 0]], x[:, ::-1])
        assert_array_equal(x[[2, 1, 0],:], x[::-1,:]) 
Example #27
Source File: test_defmatrix.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_boolean_indexing(self):
        A = np.arange(6)
        A.shape = (3, 2)
        x = asmatrix(A)
        assert_array_equal(x[:, np.array([True, False])], x[:, 0])
        assert_array_equal(x[np.array([True, False, False]),:], x[0,:]) 
Example #28
Source File: test_defmatrix.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_row_column_indexing(self):
        x = asmatrix(np.eye(2))
        assert_array_equal(x[0,:], [[1, 0]])
        assert_array_equal(x[1,:], [[0, 1]])
        assert_array_equal(x[:, 0], [[1], [0]])
        assert_array_equal(x[:, 1], [[0], [1]]) 
Example #29
Source File: test_defmatrix.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_scalar_indexing(self):
        x = asmatrix(np.zeros((3, 2), float))
        assert_equal(x[0, 0], x[0][0]) 
Example #30
Source File: test_defmatrix.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_asmatrix(self):
        A = np.arange(100).reshape(10, 10)
        mA = asmatrix(A)
        A[0, 0] = -10
        assert_(A[0, 0] == mA[0, 0])