Python numpy.linalg.inv() Examples

The following are code examples for showing how to use numpy.linalg.inv(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyberny   Author: jhrmnn   File: geomlib.py    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 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 2
Project: LaserTOF   Author: kyleuckert   File: test_defmatrix.py    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 3
Project: LaserTOF   Author: kyleuckert   File: test_defmatrix.py    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 4
Project: LaserTOF   Author: kyleuckert   File: test_linalg.py    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 5
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_defmatrix.py    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 6
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_defmatrix.py    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 7
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_linalg.py    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
Project: neurocombat_sklearn   Author: Warvito   File: neurocombat_sklearn.py    MIT License 6 votes vote down vote up
def _fit_ls_model(self, standardized_data, design, idx_per_site):
        """Location and scale (L/S) adjustments

        Parameters
        ----------
        standardized_data : array-like
        design : array-like
        idx_per_site : list of list of integer
        """
        site_design = design[:, :self.n_sites]
        gamma_hat = np.dot(np.dot(la.inv(np.dot(site_design.T, site_design)), site_design.T), standardized_data.T)

        delta_hat = []
        for i, site_idxs in enumerate(idx_per_site):
            delta_hat.append(np.var(standardized_data[:, site_idxs], axis=1, ddof=1))

        return gamma_hat, delta_hat 
Example 9
Project: recruit   Author: Frank-qlu   File: test_defmatrix.py    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 10
Project: recruit   Author: Frank-qlu   File: test_defmatrix.py    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 11
Project: recruit   Author: Frank-qlu   File: test_linalg.py    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 12
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_defmatrix.py    GNU General Public License v3.0 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
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_defmatrix.py    GNU General Public License v3.0 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 14
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_linalg.py    GNU General Public License v3.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 15
Project: spaceggs   Author: SFUSatClub   File: ukf.py    MIT License 6 votes vote down vote up
def update(self, z):
        sigmas_f, sigmas_h = self.sigmas_f, self.sigmas_h
        
        for i in range(self.M.num_sigmas):
            sigmas_h[i] = self.h(sigmas_f[i])
        
        zp, Pz = self.unscented_transform(sigmas_h, self.M.Wm, self.M.Wc, self._R)
        
        Pxz = np.zeros((self._n, self._k))
        for i in range(self.M.num_sigmas):
            Pxz += self.M.Wc[i] * np.outer(sigmas_f[i] - self.xp, sigmas_h[i] - zp)

        K = Pxz.dot(inv(Pz)) # Kalman gain

        self._x = self.xp + K.dot(z-zp)
        self._P = self.Pp - K.dot(Pz).dot(K.T) 
Example 16
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_defmatrix.py    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 17
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_defmatrix.py    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 18
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_linalg.py    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 19
Project: MARRtino-2.0   Author: DaniAffCH   File: test_defmatrix.py    GNU General Public License v3.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 20
Project: MARRtino-2.0   Author: DaniAffCH   File: test_defmatrix.py    GNU General Public License v3.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 21
Project: MARRtino-2.0   Author: DaniAffCH   File: test_linalg.py    GNU General Public License v3.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 22
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_defmatrix.py    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 23
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_defmatrix.py    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 24
Project: ml_news_popularity   Author: khaledJabr   File: svr.py    MIT License 5 votes vote down vote up
def fit(self, input_data , target) : 
		self.training_data = np.copy(input_data)
		# print("Training data shape : " , self.training_data.shape)
		k_matrix = self.calc_K_Mat(input_data ,self.degree , self.reg)
		target = np.insert(target, 0 , 0)
		p1 = inv(np.matmul(k_matrix.T , k_matrix ))
		p2 = np.matmul( k_matrix.T , target)
		alphas = np.matmul(p1 ,p2 )
		self.alphas = alphas 
Example 25
Project: CIMtools   Author: stsouko   File: leverage.py    GNU General Public License v3.0 5 votes vote down vote up
def __make_inverse_matrix(X):
        X = column_stack(((ones(X.shape[0])), X))
        influence_matrix = X.T.dot(X) + eye(X.shape[1]).dot(1e-8)
        return linalg.inv(influence_matrix) 
Example 26
Project: 4Dsegment   Author: j-duan   File: image_utils.py    GNU General Public License v3.0 5 votes vote down vote up
def removeSegsAboveBase(data_dir, output_name):

    # Read segmentations
    nim = nib.load('{0}/{1}'.format(data_dir, output_name))
    seg = nim.get_data()
    if seg.ndim == 4:
        seg = np.squeeze(seg, axis=-1).astype(np.int16)
    os.system('vtk2txt {0}/landmarks.vtk {0}/landmarks.txt'.format(data_dir)) 
    
    # convert txt file into matrix
    file = open('{0}/landmarks.txt'.format(data_dir), 'r') 
    A = file.read()
    tmp = np.zeros(18)  
    i, c = 0, 0
    for p in range(len(A)):
        if A[p] == ' ' or A[p] == '\n':
            tmp[i] = np.float32(A[c:p])
            i = i + 1
            c = p + 1;
    tmp = np.reshape(tmp,(6,3))        
    landmarks = np.ones((6,4)) 
    landmarks[:,:-1] = tmp
    landmarks = np.transpose(landmarks).astype(np.float32)           
    os.system('rm {0}/landmarks.txt'.format(data_dir))    
       
    # map world coordinate system to image pixel position
    pixelsPositions = np.ceil(np.dot(inv(nim.affine),landmarks)).astype(np.int16) 
    pixelsPositions = np.delete(pixelsPositions, (-1), axis=0)
    pixelsPositions = np.transpose(pixelsPositions).astype(np.int16) 
    
    if output_name[9:11]=='ED':
        seg[:,:,pixelsPositions[5,2]+1:] = 0
    else:
        seg[:,:,pixelsPositions[5,2]:] = 0
    
    nim2 = nib.Nifti1Image(seg, nim.affine)
    nim2.header['pixdim'] = nim.header['pixdim']
    nib.save(nim2, '{0}/{1}'.format(data_dir, output_name)) 
Example 27
Project: DRCOG_Urbansim   Author: apdjustino   File: bfgs_mnl_estimation.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_hessian(self, derivative):
        return inv(dot(transpose(derivative),derivative)) 
Example 28
Project: DRCOG_Urbansim   Author: apdjustino   File: bhhh_mnl_estimation.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_hessian(self, derivative):
        return inv(dot(transpose(derivative),derivative)) 
Example 29
Project: LaserTOF   Author: kyleuckert   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b):
        a_inv = linalg.inv(a)
        assert_almost_equal(dot_generalized(a, a_inv),
                            identity_like_generalized(a))
        assert_(imply(isinstance(a, matrix), isinstance(a_inv, matrix))) 
Example 30
Project: LaserTOF   Author: kyleuckert   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_types(self):
        def check(dtype):
            x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
            assert_equal(linalg.inv(x).dtype, dtype)
        for dtype in [single, double, csingle, cdouble]:
            yield check, dtype 
Example 31
Project: LaserTOF   Author: kyleuckert   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_generalized_raise_multiloop():
    # It should raise an error even if the error doesn't occur in the
    # last iteration of the ufunc inner loop

    invertible = np.array([[1, 2], [3, 4]])
    non_invertible = np.array([[1, 1], [1, 1]])

    x = np.zeros([4, 4, 2, 2])[1::2]
    x[...] = invertible
    x[0, 0] = non_invertible

    assert_raises(np.linalg.LinAlgError, np.linalg.inv, x) 
Example 32
Project: LaserTOF   Author: kyleuckert   File: transforms.py    MIT License 5 votes vote down vote up
def inverted(self):
        if self._inverted is None or self._invalid:
            mtx = self.get_matrix()
            shorthand_name = None
            if self._shorthand_name:
                shorthand_name = '(%s)-1' % self._shorthand_name
            self._inverted = Affine2D(inv(mtx), shorthand_name=shorthand_name)
            self._invalid = 0
        return self._inverted 
Example 33
Project: LaserTOF   Author: kyleuckert   File: test_nonlin.py    MIT License 5 votes vote down vote up
def test_broyden2_update(self):
        # Check that BroydenSecond update works as for a dense matrix
        jac = nonlin.BroydenSecond(alpha=0.1)
        jac.setup(self.xs[0], self.fs[0], None)

        H = np.identity(5) * (-0.1)

        for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])):
            df = f - self.fs[last_j]
            dx = x - self.xs[last_j]
            H += (dx - dot(H, df))[:,None] * df[None,:] / dot(df, df)
            jac.update(x, f)
            assert_(np.allclose(jac.todense(), inv(H), rtol=1e-10, atol=1e-13)) 
Example 34
Project: LaserTOF   Author: kyleuckert   File: _solvers.py    MIT License 5 votes vote down vote up
def _solve_discrete_lyapunov_bilinear(a, q):
    """
    Solves the discrete Lyapunov equation using a bilinear transformation.

    This function is called by the `solve_discrete_lyapunov` function with
    `method=bilinear`. It is not supposed to be called directly.
    """
    eye = np.eye(a.shape[0])
    aH = a.conj().transpose()
    aHI_inv = inv(aH + eye)
    b = np.dot(aH - eye, aHI_inv)
    c = 2*np.dot(np.dot(inv(a + eye), q), aHI_inv)
    return solve_lyapunov(b.conj().transpose(), -c) 
Example 35
Project: https-github.com-ZhengyaoJiang-PGPortfolio   Author: stevep2007   File: cwmr_std.py    GNU General Public License v3.0 5 votes vote down vote up
def update(self, x, x_upper, mu, sigma, M, V, theta, eps):
        # lambda from equation 7
        foo = (V - x_upper * x.T * np.sum(sigma, axis=1)) / M**2 + V * theta**2 / 2.
        a = foo**2 - V**2 * theta**4 / 4
        b = 2 * (eps - np.log(M)) * foo
        c = (eps - np.log(M))**2 - V * theta**2

        a,b,c = a[0,0], b[0,0], c[0,0]

        lam = np.amax([0,
                  (-b + sqrt(b**2 - 4 * a * c)) / (2. * a),
                  (-b - sqrt(b**2 - 4 * a * c)) / (2. * a)])
        # bound it due to numerical problems
        lam = np.minimum(lam, 1E+7)

        # update mu and sigma
        U_sqroot = 0.5 * (-lam * theta * V + sqrt(lam**2 * theta**2 * V**2 + 4*V))
        mu = mu - lam * sigma * (x - x_upper) / M
        sigma = inv(inv(sigma) + theta * lam / U_sqroot * diag(x)**2)
        """
        tmp_sigma = inv(inv(sigma) + theta*lam/U_sqroot*diag(xt)^2);
        % Don't update sigma if results are badly scaled.
        if all(~isnan(tmp_sigma(:)) & ~isinf(tmp_sigma(:)))
            sigma = tmp_sigma;
        end
        """
        return mu, sigma 
Example 36
Project: qfit-3.0   Author: ExcitedStates   File: unitcell.py    MIT License 5 votes vote down vote up
def __init__(self, a=1.0, b=1.0, c=1.0,
                 alpha=90.0, beta=90.0, gamma=90.0,
                 space_group="P1"):

        self.a = a
        self.b = b
        self.c = c

        self.alpha = alpha
        self.beta  = beta
        self.gamma = gamma

        self.set_space_group(space_group)

        self._sin_alpha = np.sin(np.deg2rad(self.alpha))
        self._sin_beta  = np.sin(np.deg2rad(self.beta))
        self._sin_gamma = np.sin(np.deg2rad(self.gamma))

        self._cos_alpha = np.cos(np.deg2rad(self.alpha))
        self._cos_beta  = np.cos(np.deg2rad(self.beta))
        self._cos_gamma = np.cos(np.deg2rad(self.gamma))

        self.orth_to_frac = self.calc_fractionalization_matrix()
        self.frac_to_orth = self.calc_orthogonalization_matrix()

        ## check our math!
        #assert np.allclose(self.orth_to_frac, la.inv(self.frac_to_orth)) 
Example 37
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        a_inv = linalg.inv(a)
        assert_almost_equal(dot_generalized(a, a_inv),
                            identity_like_generalized(a))
        assert_(consistent_subclass(a_inv, a)) 
Example 38
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_types(self, dtype):
        x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
        assert_equal(linalg.inv(x).dtype, dtype) 
Example 39
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_0_size(self):
        # Check that all kinds of 0-sized arrays work
        class ArraySubclass(np.ndarray):
            pass
        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
        res = linalg.inv(a)
        assert_(res.dtype.type is np.float64)
        assert_equal(a.shape, res.shape)
        assert_(isinstance(res, ArraySubclass))

        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
        res = linalg.inv(a)
        assert_(res.dtype.type is np.complex64)
        assert_equal(a.shape, res.shape)
        assert_(isinstance(res, ArraySubclass)) 
Example 40
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_generalized_raise_multiloop():
    # It should raise an error even if the error doesn't occur in the
    # last iteration of the ufunc inner loop

    invertible = np.array([[1, 2], [3, 4]])
    non_invertible = np.array([[1, 1], [1, 1]])

    x = np.zeros([4, 4, 2, 2])[1::2]
    x[...] = invertible
    x[0, 0] = non_invertible

    assert_raises(np.linalg.LinAlgError, np.linalg.inv, x) 
Example 41
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: transforms.py    MIT License 5 votes vote down vote up
def inverted(self):
        # docstring inherited
        if self._inverted is None or self._invalid:
            mtx = self.get_matrix()
            shorthand_name = None
            if self._shorthand_name:
                shorthand_name = '(%s)-1' % self._shorthand_name
            self._inverted = Affine2D(inv(mtx), shorthand_name=shorthand_name)
            self._invalid = 0
        return self._inverted 
Example 42
Project: neurocombat_sklearn   Author: Warvito   File: neurocombat_sklearn.py    MIT License 5 votes vote down vote up
def _standardize_across_features(self, data, design, n_samples, n_samples_per_site, fitting=False):
        """Standardization of the features

        The magnitude of the features could create bias in the empirical Bayes estimates of the prior distribution.
        To avoid this, the features are standardized to all of them have similar overall mean and variance.

        Parameters
        ----------
        data : array-like
        design : array-like
        n_samples : integer
        n_samples_per_site : list of integer
        fitting : boolean, default is False
            Indicates if this method is executed inside the
            fit method (in order to save the parameters to use later).

        Returns
        -------
        standardized_data : array-like
        standardized_mean : array-like
            Standardized mean used during the process
        """
        if fitting:
            self.beta_hat = np.dot(np.dot(la.inv(np.dot(design.T, design)), design.T), data.T)

            # Standardization Model
            self.grand_mean = np.dot((n_samples_per_site / float(n_samples)).T, self.beta_hat[:self.n_sites, :])
            self.var_pooled = np.dot(((data - np.dot(design, self.beta_hat).T) ** 2),
                                     np.ones((n_samples, 1)) / float(n_samples))

        standardized_mean = np.dot(self.grand_mean.T[:, np.newaxis], np.ones((1, n_samples)))

        tmp = np.array(design.copy())
        tmp[:, :self.n_sites] = 0
        standardized_mean += np.dot(tmp, self.beta_hat).T

        standardized_data = ((data - standardized_mean) / np.dot(np.sqrt(self.var_pooled), np.ones((1, n_samples))))

        return standardized_data, standardized_mean 
Example 43
Project: recruit   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
def do(self, a, b, tags):
        a_inv = linalg.inv(a)
        assert_almost_equal(dot_generalized(a, a_inv),
                            identity_like_generalized(a))
        assert_(consistent_subclass(a_inv, a)) 
Example 44
Project: recruit   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
def test_types(self, dtype):
        x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
        assert_equal(linalg.inv(x).dtype, dtype) 
Example 45
Project: recruit   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
def test_0_size(self):
        # Check that all kinds of 0-sized arrays work
        class ArraySubclass(np.ndarray):
            pass
        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
        res = linalg.inv(a)
        assert_(res.dtype.type is np.float64)
        assert_equal(a.shape, res.shape)
        assert_(isinstance(res, ArraySubclass))

        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
        res = linalg.inv(a)
        assert_(res.dtype.type is np.complex64)
        assert_equal(a.shape, res.shape)
        assert_(isinstance(res, ArraySubclass)) 
Example 46
Project: recruit   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
def test_generalized_raise_multiloop():
    # It should raise an error even if the error doesn't occur in the
    # last iteration of the ufunc inner loop

    invertible = np.array([[1, 2], [3, 4]])
    non_invertible = np.array([[1, 1], [1, 1]])

    x = np.zeros([4, 4, 2, 2])[1::2]
    x[...] = invertible
    x[0, 0] = non_invertible

    assert_raises(np.linalg.LinAlgError, np.linalg.inv, x) 
Example 47
Project: pyBMA   Author: JakeColtman   File: CoxPHFitter.py    MIT License 5 votes vote down vote up
def _generate_model_definnitions(self):
        names, coefs, var = self.full_model.summary()
        variance_covariance = inv(-self.full_model._cf._hessian_)
        all_models = []
        for i in range(1, len(names)):
            all_models.append(list(combinations(names, i)))
        all_models = [list(item) for sublist in all_models for item in sublist]
        return all_models 
Example 48
Project: BANE   Author: benedekrozemberczki   File: bane.py    MIT License 5 votes vote down vote up
def update_G(self):
        """
        Updating the kernel matrix.
        """
        self.G = np.dot(self.B.transpose(), self.B)
        self.G = self.G + self.args.alpha*np.eye(self.args.dimensions)
        self.G = inv(self.G)
        self.G = self.G.dot(self.B.transpose()).dot(self.P) 
Example 49
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def do(self, a, b):
        a_inv = linalg.inv(a)
        assert_almost_equal(dot_generalized(a, a_inv),
                            identity_like_generalized(a))
        assert_(imply(isinstance(a, matrix), isinstance(a_inv, matrix))) 
Example 50
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def test_types(self):
        def check(dtype):
            x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
            assert_equal(linalg.inv(x).dtype, dtype)
        for dtype in [single, double, csingle, cdouble]:
            yield check, dtype 
Example 51
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def test_generalized_raise_multiloop():
    # It should raise an error even if the error doesn't occur in the
    # last iteration of the ufunc inner loop

    invertible = np.array([[1, 2], [3, 4]])
    non_invertible = np.array([[1, 1], [1, 1]])

    x = np.zeros([4, 4, 2, 2])[1::2]
    x[...] = invertible
    x[0, 0] = non_invertible

    assert_raises(np.linalg.LinAlgError, np.linalg.inv, x) 
Example 52
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_nonlin.py    GNU General Public License v3.0 5 votes vote down vote up
def test_broyden2_update(self):
        # Check that BroydenSecond update works as for a dense matrix
        jac = nonlin.BroydenSecond(alpha=0.1)
        jac.setup(self.xs[0], self.fs[0], None)

        H = np.identity(5) * (-0.1)

        for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])):
            df = f - self.fs[last_j]
            dx = x - self.xs[last_j]
            H += (dx - dot(H, df))[:,None] * df[None,:] / dot(df, df)
            jac.update(x, f)
            assert_(np.allclose(jac.todense(), inv(H), rtol=1e-10, atol=1e-13)) 
Example 53
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: _solvers.py    GNU General Public License v3.0 5 votes vote down vote up
def _solve_discrete_lyapunov_bilinear(a, q):
    """
    Solves the discrete Lyapunov equation using a bilinear transformation.

    This function is called by the `solve_discrete_lyapunov` function with
    `method=bilinear`. It is not supposed to be called directly.
    """
    eye = np.eye(a.shape[0])
    aH = a.conj().transpose()
    aHI_inv = inv(aH + eye)
    b = np.dot(aH - eye, aHI_inv)
    c = 2*np.dot(np.dot(inv(a + eye), q), aHI_inv)
    return solve_lyapunov(b.conj().transpose(), -c) 
Example 54
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: bench_basic.py    GNU General Public License v3.0 5 votes vote down vote up
def bench_random(self):
        numpy_inv = nl.inv
        scipy_inv = sl.inv
        print()
        print('           Finding matrix inverse')
        print('      ==================================')
        print('      |    contiguous     |   non-contiguous ')
        print('----------------------------------------------')
        print(' size |  scipy  | numpy   |  scipy  | numpy')

        for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]:
            repeat *= 2
            print('%5s' % size, end=' ')
            sys.stdout.flush()

            a = random([size,size])
            # large diagonal ensures non-singularity:
            for i in range(size):
                a[i,i] = 10*(.1+a[i,i])

            print('| %6.2f ' % measure('scipy_inv(a)',repeat), end=' ')
            sys.stdout.flush()

            print('| %6.2f ' % measure('numpy_inv(a)',repeat), end=' ')
            sys.stdout.flush()

            a = a[-1::-1,-1::-1]  # turn into a non-contiguous array
            assert_(not a.flags['CONTIGUOUS'])

            print('| %6.2f ' % measure('scipy_inv(a)',repeat), end=' ')
            sys.stdout.flush()

            print('| %6.2f ' % measure('numpy_inv(a)',repeat), end=' ')
            sys.stdout.flush()

            print('   (secs for %s calls)' % (repeat)) 
Example 55
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_solvers.py    GNU General Public License v3.0 5 votes vote down vote up
def check_case(self, a, b, q, r):
        """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true"""

        x = solve_discrete_are(a, b, q, r)
        assert_array_almost_equal(
            a.getH()*x*a-(a.getH()*x*b)*inv(r+b.getH()*x*b)*(b.getH()*x*a)+q-x, 0.0) 
Example 56
Project: multi-object-tracking   Author: jguoaj   File: estimateFeatureTranslation.py    GNU General Public License v3.0 5 votes vote down vote up
def estimateFeatureTranslation(startX,startY,Ix,Iy,img1,img2):
    X=startX
    Y=startY
    mesh_x,mesh_y=np.meshgrid(np.arange(WINDOW_SIZE),np.arange(WINDOW_SIZE))
    img1_gray = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY)
    img2_gray = cv2.cvtColor(img2, cv2.COLOR_RGB2GRAY)
    mesh_x_flat_fix =mesh_x.flatten() + X - np.floor(WINDOW_SIZE / 2)
    mesh_y_flat_fix =mesh_y.flatten() + Y - np.floor(WINDOW_SIZE / 2)
    coor_fix = np.vstack((mesh_x_flat_fix,mesh_y_flat_fix))
    I1_value = interp2(img1_gray, coor_fix[[0],:], coor_fix[[1],:])
    Ix_value = interp2(Ix, coor_fix[[0],:], coor_fix[[1],:])
    Iy_value = interp2(Iy, coor_fix[[0],:], coor_fix[[1],:])
    I=np.vstack((Ix_value,Iy_value))
    A=I.dot(I.T)
   

    for _ in range(15):
        mesh_x_flat=mesh_x.flatten() + X - np.floor(WINDOW_SIZE / 2)
        mesh_y_flat=mesh_y.flatten() + Y - np.floor(WINDOW_SIZE / 2)
        coor=np.vstack((mesh_x_flat,mesh_y_flat))
        I2_value = interp2(img2_gray, coor[[0],:], coor[[1],:])
        Ip=(I2_value-I1_value).reshape((-1,1))
        b=-I.dot(Ip)
        solution=inv(A).dot(b)
        # solution = np.linalg.solve(A, b)
        X += solution[0,0]
        Y += solution[1,0]
    
    return X, Y 
Example 57
Project: brain_language_nlp   Author: mtoneva   File: ridge_tools.py    MIT License 5 votes vote down vote up
def ridge(X,Y,lmbda):
    return np.dot(inv(X.T.dot(X)+lmbda*np.eye(X.shape[1])),X.T.dot(Y)) 
Example 58
Project: brain_language_nlp   Author: mtoneva   File: ridge_tools.py    MIT License 5 votes vote down vote up
def kernel_ridge(X,Y,lmbda):
    return np.dot(X.T.dot(inv(X.dot(X.T)+lmbda*np.eye(X.shape[0]))),Y) 
Example 59
Project: surface   Author: africker   File: surface.py    MIT License 5 votes vote down vote up
def fit(self):
		"""Matrix regression
		F(x,y) = ax2+by2+cxy+dx+ey+f
		B = inv(X'X)X'y
		where B is vector of coefficients for F(x,y).
		"""
		self._setX()
		self._getZ()
		XTXinv = inv(np.dot(self.X.T, self.X))
		XTy = np.dot(self.X.T, self.Z)
		self.B = np.dot(XTXinv, XTy) 
Example 60
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def invwishartrand_prec(nu,phi):
    return inv(wishartrand(nu,phi)) 
Example 61
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def invwishartrand(nu, phi):
    return inv(wishartrand(nu, inv(phi))) 
Example 62
Project: GP-MVS   Author: AaltoML   File: test.py    MIT License 5 votes vote down vote up
def pose_distance(p1, p2):
    rel_pose = np.dot(p1, inv(p2))
    R = rel_pose[:3, :3]
    t = rel_pose[:3, 3]

    return round(np.sqrt(np.linalg.norm(t) ** 2 + 2 * (1 - min(3.0, np.matrix.trace(R)) / 3)), 4) 
Example 63
Project: GP-MVS   Author: AaltoML   File: test_online.py    MIT License 5 votes vote down vote up
def pose_distance(p1, p2):
    rel_pose = np.dot(p1, inv(p2))
    R = rel_pose[:3, :3]
    t = rel_pose[:3, 3]

    return round(np.sqrt(np.linalg.norm(t) ** 2 + 2 * (1 - min(3.0, np.matrix.trace(R)) / 3)), 4) 
Example 64
Project: carla-training-data   Author: enginBozkurt   File: camera_utils.py    MIT License 5 votes vote down vote up
def proj_to_camera(pos_vector, extrinsic_mat):
    # transform the points to camera
    #print("Multiplied {} matrix with {} vector".format(extrinsic_mat.shape, pos_vector.shape))
    transformed_3d_pos = np.dot(inv(extrinsic_mat), pos_vector)
    return transformed_3d_pos 
Example 65
Project: scikit-tensor-py3   Author: evertrol   File: rescal.py    GNU General Public License v3.0 5 votes vote down vote up
def _updateZ(A, P, lmbdaZ):
    Z = []
    if len(P) == 0:
        return Z
    #_log.debug('Updating Z (Norm EQ, %d)' % len(P))
    pinvAt = inv(np.dot(A.T, A) + lmbdaZ * np.eye(A.shape[1], dtype=A.dtype))
    pinvAt = np.dot(pinvAt, A.T).T
    for i in range(len(P)):
        if issparse(P[i]):
            Zn = P[i].tocoo().T.tocsr().dot(pinvAt).T
        else:
            Zn = np.dot(pinvAt.T, P[i])
        Z.append(Zn)
    return Z 
Example 66
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        a_inv = linalg.inv(a)
        assert_almost_equal(dot_generalized(a, a_inv),
                            identity_like_generalized(a))
        assert_(consistent_subclass(a_inv, a)) 
Example 67
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_types(self):
        def check(dtype):
            x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
            assert_equal(linalg.inv(x).dtype, dtype)
        for dtype in [single, double, csingle, cdouble]:
            check(dtype) 
Example 68
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_0_size(self):
        # Check that all kinds of 0-sized arrays work
        class ArraySubclass(np.ndarray):
            pass
        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
        res = linalg.inv(a)
        assert_(res.dtype.type is np.float64)
        assert_equal(a.shape, res.shape)
        assert_(isinstance(res, ArraySubclass))

        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
        res = linalg.inv(a)
        assert_(res.dtype.type is np.complex64)
        assert_equal(a.shape, res.shape)
        assert_(isinstance(res, ArraySubclass)) 
Example 69
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_generalized_raise_multiloop():
    # It should raise an error even if the error doesn't occur in the
    # last iteration of the ufunc inner loop

    invertible = np.array([[1, 2], [3, 4]])
    non_invertible = np.array([[1, 1], [1, 1]])

    x = np.zeros([4, 4, 2, 2])[1::2]
    x[...] = invertible
    x[0, 0] = non_invertible

    assert_raises(np.linalg.LinAlgError, np.linalg.inv, x) 
Example 70
Project: inception_loop2019   Author: cajal   File: multi_mei.py    MIT License 5 votes vote down vote up
def gauss2d(vx, vy, mu, cov):
    input_shape = vx.shape
    mu_x, mu_y = mu
    v = np.stack([vx.ravel() - mu_x, vy.ravel() - mu_y])
    cinv = inv(cholesky(cov))
    y = cinv @ v
    g = np.exp(-0.5 * (y * y).sum(axis=0))
    return g.reshape(input_shape) 
Example 71
Project: PyRiemann   Author: DaRochaRomain   File: CovMat.py    GNU General Public License v3.0 5 votes vote down vote up
def inverse(self):
        if self.__inverse is not None:
            return self.__inverse

        self.__inverse = CovMat(inv(self._numpy_array), False)
        return self.__inverse 
Example 72
Project: MARRtino-2.0   Author: DaniAffCH   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def do(self, a, b, tags):
        a_inv = linalg.inv(a)
        assert_almost_equal(dot_generalized(a, a_inv),
                            identity_like_generalized(a))
        assert_(consistent_subclass(a_inv, a)) 
Example 73
Project: MARRtino-2.0   Author: DaniAffCH   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def test_types(self, dtype):
        x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
        assert_equal(linalg.inv(x).dtype, dtype) 
Example 74
Project: MARRtino-2.0   Author: DaniAffCH   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def test_0_size(self):
        # Check that all kinds of 0-sized arrays work
        class ArraySubclass(np.ndarray):
            pass
        a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
        res = linalg.inv(a)
        assert_(res.dtype.type is np.float64)
        assert_equal(a.shape, res.shape)
        assert_(isinstance(res, ArraySubclass))

        a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
        res = linalg.inv(a)
        assert_(res.dtype.type is np.complex64)
        assert_equal(a.shape, res.shape)
        assert_(isinstance(res, ArraySubclass)) 
Example 75
Project: MARRtino-2.0   Author: DaniAffCH   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def test_generalized_raise_multiloop():
    # It should raise an error even if the error doesn't occur in the
    # last iteration of the ufunc inner loop

    invertible = np.array([[1, 2], [3, 4]])
    non_invertible = np.array([[1, 1], [1, 1]])

    x = np.zeros([4, 4, 2, 2])[1::2]
    x[...] = invertible
    x[0, 0] = non_invertible

    assert_raises(np.linalg.LinAlgError, np.linalg.inv, x) 
Example 76
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b):
        a_inv = linalg.inv(a)
        assert_almost_equal(dot_generalized(a, a_inv),
                            identity_like_generalized(a))
        assert_(imply(isinstance(a, matrix), isinstance(a_inv, matrix))) 
Example 77
Project: LaserTOF   Author: kyleuckert   File: defmatrix.py    MIT License 4 votes vote down vote up
def getI(self):
        """
        Returns the (multiplicative) inverse of invertible `self`.

        Parameters
        ----------
        None

        Returns
        -------
        ret : matrix object
            If `self` is non-singular, `ret` is such that ``ret * self`` ==
            ``self * ret`` == ``np.matrix(np.eye(self[0,:].size)`` all return
            ``True``.

        Raises
        ------
        numpy.linalg.LinAlgError: Singular matrix
            If `self` is singular.

        See Also
        --------
        linalg.inv

        Examples
        --------
        >>> m = np.matrix('[1, 2; 3, 4]'); m
        matrix([[1, 2],
                [3, 4]])
        >>> m.getI()
        matrix([[-2. ,  1. ],
                [ 1.5, -0.5]])
        >>> m.getI() * m
        matrix([[ 1.,  0.],
                [ 0.,  1.]])

        """
        M, N = self.shape
        if M == N:
            from numpy.dual import inv as func
        else:
            from numpy.dual import pinv as func
        return asmatrix(func(self)) 
Example 78
Project: GenEML   Author: nirbhayjm   File: model.py    MIT License 4 votes vote down vote up
def update_W(m_opts, m_vars):
    # print "Updating W"
    if not m_opts['use_grad']:
        sigma = m_vars['X_batch_T'].dot(m_vars['X_batch']) + m_opts['lam_w']*ssp.eye(m_vars['n_features'], format="csr")
        m_vars['sigma_W'] = (1-m_vars['gamma'])*m_vars['sigma_W'] + m_vars['gamma']*sigma

        x = m_vars['X_batch'].T.dot(m_vars['U_batch'])
        m_vars['x_W'] = (1-m_vars['gamma'])*m_vars['x_W'] + m_vars['gamma']*x

    if m_opts['use_cg'] != True: # For the Ridge regression on W matrix with the closed form solutions
        if ssp.issparse(m_vars['sigma_W']):
            m_vars['sigma_W'] = m_vars['sigma_W'].todense()
        sigma = linalg.inv(m_vars['sigma_W']) # O(N^3) time for N x N matrix inversion 
        m_vars['W'] = np.asarray(sigma.dot(m_vars['x_W'])).T
    else: # For the CG on the ridge loss to calculate W matrix
        if not m_opts['use_grad']:
            # assert m_vars['X_batch'].shape[0] == m_vars['U_batch'].shape[0]
            X = m_vars['sigma_W']
            for i in range(m_opts['n_components']):
                y = m_vars['x_W'][:, i]
                w,info = sp_linalg.cg(X, y, x0=m_vars['W'][i,:], maxiter=m_opts['cg_iters'])
                if info < 0:
                    print "WARNING: sp_linalg.cg info: illegal input or breakdown"
                m_vars['W'][i, :] = w.T
        else:
            ''' Solving X*W' = U '''
            # print "Using grad!"
            my_invert = lambda x: x if x<1 else 1.0/x
            l2_norm = lambda x: np.sqrt((x**2).sum())
            def clip_by_norm(x, clip_max):
                x_norm = l2_norm(x)
                if x_norm > clip_max:
                    # print "Clipped!",clip_max
                    x = clip_max*(x/x_norm)
                return x

            lr = m_opts['grad_alpha']*(1.0 + np.arange(m_opts['cg_iters']*10))**(-0.9) #(-0.75)
            try:
                W_old = m_vars['W'].copy()
                tail_norm, curr_norm = 1.0,1.0
                for iter_idx in range(m_opts['cg_iters']*10):
                    grad = m_vars['X_batch_T'].dot(m_vars['X_batch'].dot(m_vars['W'].T) - m_vars['U_batch'])
                    grad = lr[iter_idx]*(grad.T + m_opts['lam_w']*m_vars['W'])
                    tail_norm = 0.5*curr_norm + (1-0.5)*tail_norm
                    curr_norm = l2_norm(grad)
                    if curr_norm < 1e-15:
                        return
                    elif iter_idx > 10 and my_invert(np.abs(tail_norm/curr_norm)) > 0.8:
                        # print "Halved!"
                        lr = lr/2.0

                    m_vars['W'] = m_vars['W'] - clip_by_norm(grad, 1e0) # Clip by norm

                Delta_W = l2_norm(m_vars['W']-W_old)
            except FloatingPointError:
                print "FloatingPointError in:"
                print grad
                assert False 
Example 79
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: defmatrix.py    GNU General Public License v3.0 4 votes vote down vote up
def getI(self):
        """
        Returns the (multiplicative) inverse of invertible `self`.

        Parameters
        ----------
        None

        Returns
        -------
        ret : matrix object
            If `self` is non-singular, `ret` is such that ``ret * self`` ==
            ``self * ret`` == ``np.matrix(np.eye(self[0,:].size)`` all return
            ``True``.

        Raises
        ------
        numpy.linalg.LinAlgError: Singular matrix
            If `self` is singular.

        See Also
        --------
        linalg.inv

        Examples
        --------
        >>> m = np.matrix('[1, 2; 3, 4]'); m
        matrix([[1, 2],
                [3, 4]])
        >>> m.getI()
        matrix([[-2. ,  1. ],
                [ 1.5, -0.5]])
        >>> m.getI() * m
        matrix([[ 1.,  0.],
                [ 0.,  1.]])

        """
        M, N = self.shape
        if M == N:
            from numpy.dual import inv as func
        else:
            from numpy.dual import pinv as func
        return asmatrix(func(self)) 
Example 80
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: defmatrix.py    MIT License 4 votes vote down vote up
def getI(self):
        """
        Returns the (multiplicative) inverse of invertible `self`.

        Parameters
        ----------
        None

        Returns
        -------
        ret : matrix object
            If `self` is non-singular, `ret` is such that ``ret * self`` ==
            ``self * ret`` == ``np.matrix(np.eye(self[0,:].size)`` all return
            ``True``.

        Raises
        ------
        numpy.linalg.LinAlgError: Singular matrix
            If `self` is singular.

        See Also
        --------
        linalg.inv

        Examples
        --------
        >>> m = np.matrix('[1, 2; 3, 4]'); m
        matrix([[1, 2],
                [3, 4]])
        >>> m.getI()
        matrix([[-2. ,  1. ],
                [ 1.5, -0.5]])
        >>> m.getI() * m
        matrix([[ 1.,  0.],
                [ 0.,  1.]])

        """
        M, N = self.shape
        if M == N:
            from numpy.dual import inv as func
        else:
            from numpy.dual import pinv as func
        return asmatrix(func(self))