Python numpy.linalg.inv() Examples

The following are 30 code examples of numpy.linalg.inv(). 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.linalg , or try the search function .
Example #1
Source File: test_defmatrix.py    From lambda-packs with MIT License 6 votes vote down vote up
def test_basic(self):
        import numpy.linalg as linalg

        A = np.array([[1., 2.], [3., 4.]])
        mA = matrix(A)

        B = np.identity(2)
        for i in range(6):
            assert_(np.allclose((mA ** i).A, B))
            B = np.dot(B, A)

        Ainv = linalg.inv(A)
        B = np.identity(2)
        for i in range(6):
            assert_(np.allclose((mA ** -i).A, B))
            B = np.dot(B, Ainv)

        assert_(np.allclose((mA * mA).A, np.dot(A, A)))
        assert_(np.allclose((mA + mA).A, (A + A)))
        assert_(np.allclose((3*mA).A, (3*A)))

        mA2 = matrix(A)
        mA2 *= 3
        assert_(np.allclose(mA2.A, 3*A)) 
Example #2
Source File: test_defmatrix.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_basic(self):
        import numpy.linalg as linalg

        A = np.array([[1., 2.], [3., 4.]])
        mA = matrix(A)

        B = np.identity(2)
        for i in range(6):
            assert_(np.allclose((mA ** i).A, B))
            B = np.dot(B, A)

        Ainv = linalg.inv(A)
        B = np.identity(2)
        for i in range(6):
            assert_(np.allclose((mA ** -i).A, B))
            B = np.dot(B, Ainv)

        assert_(np.allclose((mA * mA).A, np.dot(A, A)))
        assert_(np.allclose((mA + mA).A, (A + A)))
        assert_(np.allclose((3*mA).A, (3*A)))

        mA2 = matrix(A)
        mA2 *= 3
        assert_(np.allclose(mA2.A, 3*A)) 
Example #3
Source File: test_defmatrix.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_basic(self):
        import numpy.linalg as linalg

        A = np.array([[1., 2.],
                      [3., 4.]])
        mA = matrix(A)
        assert_(np.allclose(linalg.inv(A), mA.I))
        assert_(np.all(np.array(np.transpose(A) == mA.T)))
        assert_(np.all(np.array(np.transpose(A) == mA.H)))
        assert_(np.all(A == mA.A))

        B = A + 2j*A
        mB = matrix(B)
        assert_(np.allclose(linalg.inv(B), mB.I))
        assert_(np.all(np.array(np.transpose(B) == mB.T)))
        assert_(np.all(np.array(np.transpose(B).conj() == mB.H))) 
Example #4
Source File: geomlib.py    From pyberny with Mozilla Public License 2.0 6 votes vote down vote up
def super_circum(self, radius):
        """
        Supercell dimensions such that the supercell circumsribes a sphere.

        :param float radius: circumscribed radius in angstroms

        Returns :data:`None` when geometry is not a crystal.
        """
        if self.lattice is None:
            return
        rec_lattice = 2 * pi * inv(self.lattice.T)
        layer_sep = np.array(
            [
                sum(vec * rvec / norm(rvec))
                for vec, rvec in zip(self.lattice, rec_lattice)
            ]
        )
        return np.array(np.ceil(radius / layer_sep + 0.5), dtype=int) 
Example #5
Source File: test_linalg.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_byteorder_check():
    # Byte order check should pass for native order
    if sys.byteorder == 'little':
        native = '<'
    else:
        native = '>'

    for dtt in (np.float32, np.float64):
        arr = np.eye(4, dtype=dtt)
        n_arr = arr.newbyteorder(native)
        sw_arr = arr.newbyteorder('S').byteswap()
        assert_equal(arr.dtype.byteorder, '=')
        for routine in (linalg.inv, linalg.det, linalg.pinv):
            # Normal call
            res = routine(arr)
            # Native but not '='
            assert_array_equal(res, routine(n_arr))
            # Swapped
            assert_array_equal(res, routine(sw_arr)) 
Example #6
Source File: ar_model.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def _presample_varcov(self, params):
        """
        Returns the inverse of the presample variance-covariance.

        Notes
        -----
        See Hamilton p. 125
        """
        k = self.k_trend
        p = self.k_ar
        p1 = p+1

        # get inv(Vp) Hamilton 5.3.7
        params0 = np.r_[-1, params[k:]]

        Vpinv = np.zeros((p, p), dtype=params.dtype)
        for i in range(1, p1):
            Vpinv[i-1, i-1:] = np.correlate(params0, params0[:i],)[:-1]
            Vpinv[i-1, i-1:] -= np.correlate(params0[-i:], params0,)[:-1]

        Vpinv = Vpinv + Vpinv.T - np.diag(Vpinv.diagonal())
        return Vpinv 
Example #7
Source File: test_linalg.py    From Computable with MIT License 6 votes vote down vote up
def test_byteorder_check():
    # Byte order check should pass for native order
    if sys.byteorder == 'little':
        native = '<'
    else:
        native = '>'

    for dtt in (np.float32, np.float64):
        arr = np.eye(4, dtype=dtt)
        n_arr = arr.newbyteorder(native)
        sw_arr = arr.newbyteorder('S').byteswap()
        assert_equal(arr.dtype.byteorder, '=')
        for routine in (linalg.inv, linalg.det, linalg.pinv):
            # Normal call
            res = routine(arr)
            # Native but not '='
            assert_array_equal(res, routine(n_arr))
            # Swapped
            assert_array_equal(res, routine(sw_arr)) 
Example #8
Source File: test_linalg.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_byteorder_check():
    # Byte order check should pass for native order
    if sys.byteorder == 'little':
        native = '<'
    else:
        native = '>'

    for dtt in (np.float32, np.float64):
        arr = np.eye(4, dtype=dtt)
        n_arr = arr.newbyteorder(native)
        sw_arr = arr.newbyteorder('S').byteswap()
        assert_equal(arr.dtype.byteorder, '=')
        for routine in (linalg.inv, linalg.det, linalg.pinv):
            # Normal call
            res = routine(arr)
            # Native but not '='
            assert_array_equal(res, routine(n_arr))
            # Swapped
            assert_array_equal(res, routine(sw_arr)) 
Example #9
Source File: vecm.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def cov_params_default(self):  # p.296 (7.2.21)
        # Sigma_co described on p. 287
        beta = self.beta
        if self.det_coef_coint.size > 0:
            beta = vstack((beta, self.det_coef_coint))
        dt = self.deterministic
        num_det = ("co" in dt) + ("lo" in dt)
        num_det += (self.seasons-1) if self.seasons else 0
        if self.exog is not None:
            num_det += self.exog.shape[1]
        b_id = scipy.linalg.block_diag(beta,
                                       np.identity(self.neqs * (self.k_ar-1) +
                                                   num_det))

        y_lag1 = self._y_lag1
        b_y = beta.T.dot(y_lag1)
        omega11 = b_y.dot(b_y.T)
        omega12 = b_y.dot(self._delta_x.T)
        omega21 = omega12.T
        omega22 = self._delta_x.dot(self._delta_x.T)
        omega = np.bmat([[omega11, omega12],
                         [omega21, omega22]]).A

        mat1 = b_id.dot(inv(omega)).dot(b_id.T)
        return np.kron(mat1, self.sigma_u) 
Example #10
Source File: test_defmatrix.py    From lambda-packs with MIT License 6 votes vote down vote up
def test_basic(self):
        import numpy.linalg as linalg

        A = np.array([[1., 2.],
                      [3., 4.]])
        mA = matrix(A)
        assert_(np.allclose(linalg.inv(A), mA.I))
        assert_(np.all(np.array(np.transpose(A) == mA.T)))
        assert_(np.all(np.array(np.transpose(A) == mA.H)))
        assert_(np.all(A == mA.A))

        B = A + 2j*A
        mB = matrix(B)
        assert_(np.allclose(linalg.inv(B), mB.I))
        assert_(np.all(np.array(np.transpose(B) == mB.T)))
        assert_(np.all(np.array(np.transpose(B).conj() == mB.H))) 
Example #11
Source File: test_defmatrix.py    From Computable with MIT License 6 votes vote down vote up
def test_basic(self):
        import numpy.linalg as linalg

        A = array([[1., 2.],
                   [3., 4.]])
        mA = matrix(A)

        B = identity(2)
        for i in range(6):
            assert_(allclose((mA ** i).A, B))
            B = dot(B, A)

        Ainv = linalg.inv(A)
        B = identity(2)
        for i in range(6):
            assert_(allclose((mA ** -i).A, B))
            B = dot(B, Ainv)

        assert_(allclose((mA * mA).A, dot(A, A)))
        assert_(allclose((mA + mA).A, (A + A)))
        assert_(allclose((3*mA).A, (3*A)))

        mA2 = matrix(A)
        mA2 *= 3
        assert_(allclose(mA2.A, 3*A)) 
Example #12
Source File: test_defmatrix.py    From Computable with MIT License 6 votes vote down vote up
def test_basic(self):
        import numpy.linalg as linalg

        A = array([[1., 2.],
                   [3., 4.]])
        mA = matrix(A)
        assert_(allclose(linalg.inv(A), mA.I))
        assert_(all(array(transpose(A) == mA.T)))
        assert_(all(array(transpose(A) == mA.H)))
        assert_(all(A == mA.A))

        B = A + 2j*A
        mB = matrix(B)
        assert_(allclose(linalg.inv(B), mB.I))
        assert_(all(array(transpose(B) == mB.T)))
        assert_(all(array(conjugate(transpose(B)) == mB.H))) 
Example #13
Source File: test_linalg.py    From lambda-packs with MIT License 6 votes vote down vote up
def test_byteorder_check():
    # Byte order check should pass for native order
    if sys.byteorder == 'little':
        native = '<'
    else:
        native = '>'

    for dtt in (np.float32, np.float64):
        arr = np.eye(4, dtype=dtt)
        n_arr = arr.newbyteorder(native)
        sw_arr = arr.newbyteorder('S').byteswap()
        assert_equal(arr.dtype.byteorder, '=')
        for routine in (linalg.inv, linalg.det, linalg.pinv):
            # Normal call
            res = routine(arr)
            # Native but not '='
            assert_array_equal(res, routine(n_arr))
            # Swapped
            assert_array_equal(res, routine(sw_arr)) 
Example #14
Source File: test_defmatrix.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_basic(self):
        import numpy.linalg as linalg

        A = np.array([[1., 2.], [3., 4.]])
        mA = matrix(A)

        B = np.identity(2)
        for i in range(6):
            assert_(np.allclose((mA ** i).A, B))
            B = np.dot(B, A)

        Ainv = linalg.inv(A)
        B = np.identity(2)
        for i in range(6):
            assert_(np.allclose((mA ** -i).A, B))
            B = np.dot(B, Ainv)

        assert_(np.allclose((mA * mA).A, np.dot(A, A)))
        assert_(np.allclose((mA + mA).A, (A + A)))
        assert_(np.allclose((3*mA).A, (3*A)))

        mA2 = matrix(A)
        mA2 *= 3
        assert_(np.allclose(mA2.A, 3*A)) 
Example #15
Source File: test_defmatrix.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def test_basic(self):
        import numpy.linalg as linalg

        A = np.array([[1., 2.],
                      [3., 4.]])
        mA = matrix(A)
        assert_(np.allclose(linalg.inv(A), mA.I))
        assert_(np.all(np.array(np.transpose(A) == mA.T)))
        assert_(np.all(np.array(np.transpose(A) == mA.H)))
        assert_(np.all(A == mA.A))

        B = A + 2j*A
        mB = matrix(B)
        assert_(np.allclose(linalg.inv(B), mB.I))
        assert_(np.all(np.array(np.transpose(B) == mB.T)))
        assert_(np.all(np.array(np.transpose(B).conj() == mB.H))) 
Example #16
Source File: test_defmatrix.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def test_basic(self):
        import numpy.linalg as linalg

        A = np.array([[1., 2.], [3., 4.]])
        mA = matrix(A)

        B = np.identity(2)
        for i in range(6):
            assert_(np.allclose((mA ** i).A, B))
            B = np.dot(B, A)

        Ainv = linalg.inv(A)
        B = np.identity(2)
        for i in range(6):
            assert_(np.allclose((mA ** -i).A, B))
            B = np.dot(B, Ainv)

        assert_(np.allclose((mA * mA).A, np.dot(A, A)))
        assert_(np.allclose((mA + mA).A, (A + A)))
        assert_(np.allclose((3*mA).A, (3*A)))

        mA2 = matrix(A)
        mA2 *= 3
        assert_(np.allclose(mA2.A, 3*A)) 
Example #17
Source File: anmly_detc.py    From touvlo with MIT License 6 votes vote down vote up
def multi_gaussian(X, mu, sigma):
    """Estimates probability that examples belong to Multivariate Gaussian.

    Args:
        X (numpy.array): Features' dataset.
        mu (numpy.array): Mean of each feature/column of X.
        sigma (numpy.array): Covariance matrix for X.

    Returns:
        numpy.array: Probability density function for each example
    """
    m, n = X.shape
    X = X - mu

    factor = X.dot(inv(sigma))
    factor = multiply(factor, X)
    factor = - (1 / 2) * sum(factor, axis=1, keepdims=True)

    p = 1 / (power(2 * pi, n / 2) * sqrt(det(sigma)))
    p = p * exp(factor)

    return p 
Example #18
Source File: lin_rg.py    From touvlo with MIT License 6 votes vote down vote up
def reg_normal_eqn(X, y, _lambda):
    """Produces optimal theta via normal equation.

    Args:
        X (numpy.array): Features' dataset plus bias column.
        y (numpy.array): Column vector of expected values.
        _lambda (float): The regularization hyperparameter.

    Returns:
        numpy.array: Optimized model parameters theta.
    """
    n = X.shape[1]  # number of columns, already has bias
    theta = zeros((n, 1), dtype=float64)
    L = identity(n)
    L[0, 0] = 0
    X_T = X.T

    theta = inv(X_T.dot(X) + _lambda * L).dot(X_T).dot(y)

    return theta 
Example #19
Source File: test_linalg.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def test_byteorder_check():
    # Byte order check should pass for native order
    if sys.byteorder == 'little':
        native = '<'
    else:
        native = '>'

    for dtt in (np.float32, np.float64):
        arr = np.eye(4, dtype=dtt)
        n_arr = arr.newbyteorder(native)
        sw_arr = arr.newbyteorder('S').byteswap()
        assert_equal(arr.dtype.byteorder, '=')
        for routine in (linalg.inv, linalg.det, linalg.pinv):
            # Normal call
            res = routine(arr)
            # Native but not '='
            assert_array_equal(res, routine(n_arr))
            # Swapped
            assert_array_equal(res, routine(sw_arr)) 
Example #20
Source File: lin_rg.py    From touvlo with MIT License 6 votes vote down vote up
def normal_eqn(X, y):
    """Produces optimal theta via normal equation.

    Args:
        X (numpy.array): Features' dataset plus bias column.
        y (numpy.array): Column vector of expected values.

    Raises:
        LinAlgError

    Returns:
        numpy.array: Optimized model parameters theta.
    """
    n = X.shape[1]  # number of columns
    theta = zeros((n, 1), dtype=float64)

    X_T = X.T
    theta = inv(X_T.dot(X)).dot(X_T).dot(y)

    return theta 
Example #21
Source File: test_defmatrix.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_basic(self):
        import numpy.linalg as linalg

        A = np.array([[1., 2.],
                      [3., 4.]])
        mA = matrix(A)
        assert_(np.allclose(linalg.inv(A), mA.I))
        assert_(np.all(np.array(np.transpose(A) == mA.T)))
        assert_(np.all(np.array(np.transpose(A) == mA.H)))
        assert_(np.all(A == mA.A))

        B = A + 2j*A
        mB = matrix(B)
        assert_(np.allclose(linalg.inv(B), mB.I))
        assert_(np.all(np.array(np.transpose(B) == mB.T)))
        assert_(np.all(np.array(np.transpose(B).conj() == mB.H))) 
Example #22
Source File: multivariate_ols.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def _multivariate_ols_test(hypotheses, fit_results, exog_names,
                            endog_names):
    def fn(L, M, C):
        # .. [1] https://support.sas.com/documentation/cdl/en/statug/63033/HTML/default/viewer.htm#statug_introreg_sect012.htm
        params, df_resid, inv_cov, sscpr = fit_results
        # t1 = (L * params)M
        t1 = L.dot(params).dot(M) - C
        # H = t1'L(X'X)^L't1
        t2 = L.dot(inv_cov).dot(L.T)
        q = matrix_rank(t2)
        H = t1.T.dot(inv(t2)).dot(t1)

        # E = M'(Y'Y - B'(X'X)B)M
        E = M.T.dot(sscpr).dot(M)
        return E, H, q, df_resid

    return _multivariate_test(hypotheses, exog_names, endog_names, fn) 
Example #23
Source File: arima_model.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def bse(self):
        params = self.params
        hess = self.model.hessian(params)
        if len(params) == 1:  # can't take an inverse, ensure 1d
            return np.sqrt(-1./hess[0])
        return np.sqrt(np.diag(-inv(hess))) 
Example #24
Source File: mixed.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def fit(self, a, D, sigma):
        """
        Compute unit specific parameters in
        Laird, Lange, Stram (see help(Unit)).

        Displays (3.2)-(3.5).
        """

        self._compute_S(D, sigma)    #random effect plus error covariance
        self._compute_W()            #inv(S)
        self._compute_r(a)           #residual after removing fixed effects/exogs
        self._compute_b(D)           #?  coefficients on random exog, Z ? 
Example #25
Source File: ar_model.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def bse(self):  # allow user to specify?
        if self.model.method == "cmle":  # uses different scale/sigma def.
            resid = self.resid
            ssr = np.dot(resid, resid)
            ols_scale = ssr / (self.nobs - self.k_ar - self.k_trend)
            return np.sqrt(np.diag(self.cov_params(scale=ols_scale)))
        else:
            hess = approx_hess(self.params, self.model.loglike)
            return np.sqrt(np.diag(-np.linalg.inv(hess))) 
Example #26
Source File: ar_model.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _presample_fit(self, params, start, p, end, y, predictedvalues):
        """
        Return the pre-sample predicted values using the Kalman Filter

        Notes
        -----
        See predict method for how to use start and p.
        """
        k = self.k_trend

        # build system matrices
        T_mat = KalmanFilter.T(params, p, k, p)
        R_mat = KalmanFilter.R(params, p, k, 0, p)

        # Initial State mean and variance
        alpha = np.zeros((p, 1))
        Q_0 = dot(inv(identity(p**2)-np.kron(T_mat, T_mat)),
                  dot(R_mat, R_mat.T).ravel('F'))

        Q_0 = Q_0.reshape(p, p, order='F')  # TODO: order might need to be p+k
        P = Q_0
        Z_mat = KalmanFilter.Z(p)
        for i in range(end):  # iterate p-1 times to fit presample
            v_mat = y[i] - dot(Z_mat, alpha)
            F_mat = dot(dot(Z_mat, P), Z_mat.T)
            Finv = 1./F_mat  # inv. always scalar
            K = dot(dot(dot(T_mat, P), Z_mat.T), Finv)
            # update state
            alpha = dot(T_mat, alpha) + dot(K, v_mat)
            L = T_mat - dot(K, Z_mat)
            P = dot(dot(T_mat, P), L.T) + dot(R_mat, R_mat.T)
            #P[0,0] += 1 # for MA part, R_mat.R_mat.T above
            if i >= start - 1:  # only record if we ask for it
                predictedvalues[i + 1 - start] = dot(Z_mat, alpha) 
Example #27
Source File: kalmanfilter.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _init_diffuse(T,R):
    m = T.shape[1] # number of states
    r = R.shape[1] # should also be the number of states?
    Q_0 = dot(inv(identity(m**2)-kron(T,T)),dot(R,R.T).ravel('F'))
    return zeros((m,1)), Q_0.reshape(r,r,order='F') 
Example #28
Source File: vecm.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def stderr_coint(self):
        """
        Standard errors of beta and deterministic terms inside the
        cointegration relation.

        Notes
        -----
        See p. 297 in [1]_. Using the rule

        .. math::

           vec(B R) = (B' \\otimes I) vec(R)

        for two matrices B and R which are compatible for multiplication.
        This is rule (3) on p. 662 in [1]_.

        References
        ----------
        .. [1] Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer.
        """
        r = self.coint_rank
        _, r1 = _r_matrices(self._delta_y_1_T, self._y_lag1, self._delta_x)
        r12 = r1[r:]
        if r12.size == 0:
            return np.zeros((r, r))
        mat1 = inv(r12.dot(r12.T))
        mat1 = np.kron(mat1.T, np.identity(r))
        det = self.det_coef_coint.shape[0]
        mat2 = np.kron(np.identity(self.neqs-r+det),
                       inv(chain_dot(
                               self.alpha.T, inv(self.sigma_u), self.alpha)))
        first_rows = np.zeros((r, r))
        last_rows_1d = np.sqrt(np.diag(mat1.dot(mat2)))
        last_rows = last_rows_1d.reshape((self.neqs-r+det, r),
                                         order="F")
        return vstack((first_rows,
                       last_rows)) 
Example #29
Source File: mixed.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _compute_W(self):
        """inverse covariance of observations (nobs_i, nobs_i)  (JP check)
        Display (3.2) from Laird, Lange, Stram (see help(Unit))
        """
        self.W = L.inv(self.S) 
Example #30
Source File: utils.py    From RSA_pycaffe with MIT License 5 votes vote down vote up
def tforminv(trans, uv):
    Tinv = inv(trans)
    xy = tformfwd(Tinv, uv)
    return xy