Python numpy.linalg.lstsq() Examples

The following are code examples for showing how to use numpy.linalg.lstsq(). 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: LaserTOF   Author: kyleuckert   File: test_linalg.py    MIT License 6 votes vote down vote up
def do(self, a, b):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b)
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if len(np.asarray(b).shape) == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
        assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix))) 
Example 2
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_linalg.py    MIT License 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example 3
Project: recruit   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example 4
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_linalg.py    GNU General Public License v3.0 6 votes vote down vote up
def do(self, a, b):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b)
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (np.asarray(abs(np.dot(a, x) - b))**2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if len(np.asarray(b).shape) == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
        assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix))) 
Example 5
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_linalg.py    MIT License 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example 6
Project: MARRtino-2.0   Author: DaniAffCH   File: test_linalg.py    GNU General Public License v3.0 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example 7
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_linalg.py    MIT License 6 votes vote down vote up
def do(self, a, b):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b)
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if len(np.asarray(b).shape) == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
        assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix))) 
Example 8
Project: vnpy_crypto   Author: birforce   File: test_linalg.py    MIT License 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example 9
Project: ble5-nrf52-mac   Author: tomasero   File: test_linalg.py    MIT License 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example 10
Project: Computable   Author: ktraunmueller   File: test_linalg.py    MIT License 6 votes vote down vote up
def do(self, a, b):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b)
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (np.asarray(abs(np.dot(a, x) - b))**2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if len(np.asarray(b).shape) == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = type(x)([])
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
        assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix))) 
Example 11
Project: poker   Author: surgebiswas   File: test_linalg.py    MIT License 6 votes vote down vote up
def do(self, a, b):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b)
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if len(np.asarray(b).shape) == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
        assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix))) 
Example 12
Project: P3_image_processing   Author: latedude2   File: test_linalg.py    MIT License 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example 13
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_linalg.py    MIT License 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example 14
Project: 3dprinteros-client   Author: panasevychol   File: test_linalg.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def do(self, a, b):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b)
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (np.asarray(abs(np.dot(a, x) - b))**2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if len(np.asarray(b).shape) == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
        assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix))) 
Example 15
Project: 3dprinteros-client   Author: panasevychol   File: test_linalg.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def do(self, a, b):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b)
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (np.asarray(abs(np.dot(a, x) - b))**2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if len(np.asarray(b).shape) == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
        assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix))) 
Example 16
Project: predictive-maintenance-using-machine-learning   Author: awslabs   File: test_linalg.py    Apache License 2.0 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example 17
Project: fund   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 6 votes vote down vote up
def test_future_rcond(self):
        a = np.array([[0., 1.,  0.,  1.,  2.,  0.],
                      [0., 2.,  0.,  0.,  1.,  0.],
                      [1., 0.,  1.,  0.,  0.,  4.],
                      [0., 0.,  0.,  2.,  3.,  0.]]).T

        b = np.array([1, 0, 0, 0, 0, 0])
        with suppress_warnings() as sup:
            w = sup.record(FutureWarning, "`rcond` parameter will change")
            x, residuals, rank, s = linalg.lstsq(a, b)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
            assert_(rank == 4)
            x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
            assert_(rank == 3)
            # Warning should be raised exactly once (first command)
            assert_(len(w) == 1) 
Example 18
Project: stalta   Author: PALab   File: textin.py    MIT License 5 votes vote down vote up
def sampleparams(t):
    '''infer t0, dt from the sample times in t
    '''
    A = np.array([np.ones(len(t)), np.arange(len(t))])
    if 0:
        print >> sys.stderr, (A.shape, t.shape)
        print >> sys.stderr, linalg.lstsq(A.transpose(), t)[0:2]
        print >> sys.stderr, t
        print >> sys.stderr, A
    t0, dt = linalg.lstsq(A.transpose(), t)[0]
    t0 = t[0]
    return t0, dt 
Example 19
Project: LaserTOF   Author: kyleuckert   File: test_lsq_linear.py    MIT License 5 votes vote down vote up
def test_dense_no_bounds(self):
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, method=self.method, lsq_solver=lsq_solver)
            assert_allclose(res.x, lstsq(A, b)[0]) 
Example 20
Project: LaserTOF   Author: kyleuckert   File: test_lsq_linear.py    MIT License 5 votes vote down vote up
def test_dense_bounds(self):
        # Solutions for comparison are taken from MATLAB.
        lb = np.array([-1, -10])
        ub = np.array([1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, lstsq(A, b)[0])

        lb = np.array([0.0, -np.inf])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, np.inf), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.0, -4.084174437334673]),
                            atol=1e-6)

        lb = np.array([-1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, np.inf), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.448427311733504, 0]),
                            atol=1e-15)

        ub = np.array([np.inf, -5])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([-0.105560998682388, -5]))

        ub = np.array([-1, np.inf])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([-1, -4.181102129483254]))

        lb = np.array([0, -4])
        ub = np.array([1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.005236663400791, -4])) 
Example 21
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):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
        if m == 0:
            assert_((x == 0).all())
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if np.asarray(b).ndim == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(consistent_subclass(x, b))
        assert_(consistent_subclass(residuals, b)) 
Example 22
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_empty_a_b(self, m, n, n_rhs):
        a = np.arange(m * n).reshape(m, n)
        b = np.ones((m, n_rhs))
        x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
        if m == 0:
            assert_((x == 0).all())
        assert_equal(x.shape, (n, n_rhs))
        assert_equal(residuals.shape, ((n_rhs,) if m > n else (0,)))
        if m > n and n_rhs > 0:
            # residuals are exactly the squared norms of b's columns
            r = b - np.dot(a, x)
            assert_almost_equal(residuals, (r * r).sum(axis=-2))
        assert_equal(rank, min(m, n))
        assert_equal(s.shape, (min(m, n),)) 
Example 23
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_incompatible_dims(self):
        # use modified version of docstring example
        x = np.array([0, 1, 2, 3])
        y = np.array([-1, 0.2, 0.9, 2.1, 3.3])
        A = np.vstack([x, np.ones(len(x))]).T
        with assert_raises_regex(LinAlgError, "Incompatible dimensions"):
            linalg.lstsq(A, y, rcond=None) 
Example 24
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_regression.py    MIT License 5 votes vote down vote up
def test_lstsq_complex_larger_rhs(self):
        # gh-9891
        size = 20
        n_rhs = 70
        G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
        u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
        b = G.dot(u)
        # This should work without segmentation fault.
        u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
        # check results just in case
        assert_array_almost_equal(u_lstsq, u) 
Example 25
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_lsq_linear.py    MIT License 5 votes vote down vote up
def test_dense_bounds(self):
        # Solutions for comparison are taken from MATLAB.
        lb = np.array([-1, -10])
        ub = np.array([1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, lstsq(A, b, rcond=-1)[0])

        lb = np.array([0.0, -np.inf])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, np.inf), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.0, -4.084174437334673]),
                            atol=1e-6)

        lb = np.array([-1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, np.inf), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.448427311733504, 0]),
                            atol=1e-15)

        ub = np.array([np.inf, -5])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([-0.105560998682388, -5]))

        ub = np.array([-1, np.inf])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([-1, -4.181102129483254]))

        lb = np.array([0, -4])
        ub = np.array([1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.005236663400791, -4])) 
Example 26
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):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
        if m == 0:
            assert_((x == 0).all())
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if np.asarray(b).ndim == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(consistent_subclass(x, b))
        assert_(consistent_subclass(residuals, b)) 
Example 27
Project: recruit   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
def test_empty_a_b(self, m, n, n_rhs):
        a = np.arange(m * n).reshape(m, n)
        b = np.ones((m, n_rhs))
        x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
        if m == 0:
            assert_((x == 0).all())
        assert_equal(x.shape, (n, n_rhs))
        assert_equal(residuals.shape, ((n_rhs,) if m > n else (0,)))
        if m > n and n_rhs > 0:
            # residuals are exactly the squared norms of b's columns
            r = b - np.dot(a, x)
            assert_almost_equal(residuals, (r * r).sum(axis=-2))
        assert_equal(rank, min(m, n))
        assert_equal(s.shape, (min(m, n),)) 
Example 28
Project: recruit   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
def test_incompatible_dims(self):
        # use modified version of docstring example
        x = np.array([0, 1, 2, 3])
        y = np.array([-1, 0.2, 0.9, 2.1, 3.3])
        A = np.vstack([x, np.ones(len(x))]).T
        with assert_raises_regex(LinAlgError, "Incompatible dimensions"):
            linalg.lstsq(A, y, rcond=None) 
Example 29
Project: recruit   Author: Frank-qlu   File: test_regression.py    Apache License 2.0 5 votes vote down vote up
def test_lstsq_complex_larger_rhs(self):
        # gh-9891
        size = 20
        n_rhs = 70
        G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
        u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
        b = G.dot(u)
        # This should work without segmentation fault.
        u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
        # check results just in case
        assert_array_almost_equal(u_lstsq, u) 
Example 30
Project: NiaPy   Author: NiaOrg   File: es.py    MIT License 5 votes vote down vote up
def CovarianceMaatrixAdaptionEvolutionStrategyF(task, epsilon=1e-20, rnd=rand):
	lam, alpha_mu, hs, sigma0 = (4 + round(3 * log(task.D))) * 10, 2, 0, 0.3 * task.bcRange()
	mu = int(round(lam / 2))
	w = log(mu + 0.5) - log(range(1, mu + 1))
	w = w / sum(w)
	mueff = 1 / sum(w ** 2)
	cs = (mueff + 2) / (task.D + mueff + 5)
	ds = 1 + cs + 2 * max(sqrt((mueff - 1) / (task.D + 1)) - 1, 0)
	ENN = sqrt(task.D) * (1 - 1 / (4 * task.D) + 1 / (21 * task.D ** 2))
	cc, c1 = (4 + mueff / task.D) / (4 + task.D + 2 * mueff / task.D), 2 / ((task.D + 1.3) ** 2 + mueff)
	cmu, hth = min(1 - c1, alpha_mu * (mueff - 2 + 1 / mueff) / ((task.D + 2) ** 2 + alpha_mu * mueff / 2)), (1.4 + 2 / (task.D + 1)) * ENN
	ps, pc, C, sigma, M = full(task.D, 0.0), full(task.D, 0.0), eye(task.D), sigma0, full(task.D, 0.0)
	x = rnd.uniform(task.bcLower(), task.bcUpper())
	x_f = task.eval(x)
	while not task.stopCondI():
		pop_step = asarray([rnd.multivariate_normal(full(task.D, 0.0), C) for _ in range(int(lam))])
		pop = asarray([task.repair(x + sigma * ps, rnd) for ps in pop_step])
		pop_f = apply_along_axis(task.eval, 1, pop)
		isort = argsort(pop_f)
		pop, pop_f, pop_step = pop[isort[:mu]], pop_f[isort[:mu]], pop_step[isort[:mu]]
		if pop_f[0] < x_f: x, x_f = pop[0], pop_f[0]
		M = sum(w * pop_step.T, axis=1)
		ps = solve(chol(C).conj() + epsilon, ((1 - cs) * ps + sqrt(cs * (2 - cs) * mueff) * M + epsilon).T)[0].T
		sigma *= exp(cs / ds * (norm(ps) / ENN - 1)) ** 0.3
		ifix = where(sigma == inf)
		if any(ifix): sigma[ifix] = sigma0
		if norm(ps) / sqrt(1 - (1 - cs) ** (2 * (task.Iters + 1))) < hth: hs = 1
		else: hs = 0
		delta = (1 - hs) * cc * (2 - cc)
		pc = (1 - cc) * pc + hs * sqrt(cc * (2 - cc) * mueff) * M
		C = (1 - c1 - cmu) * C + c1 * (tile(pc, [len(pc), 1]) * tile(pc.reshape([len(pc), 1]), [1, len(pc)]) + delta * C)
		for i in range(mu): C += cmu * w[i] * tile(pop_step[i], [len(pop_step[i]), 1]) * tile(pop_step[i].reshape([len(pop_step[i]), 1]), [1, len(pop_step[i])])
		E, V = eig(C)
		if any(E < epsilon):
			E = fmax(E, 0)
			C = lstsq(V.T, dot(V, diag(E)).T, rcond=None)[0].T
	return x, x_f 
Example 31
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        if 'size-0' in tags:
            assert_raises(LinAlgError, linalg.lstsq, a, b)
            return

        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if np.asarray(b).ndim == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(consistent_subclass(x, b))
        assert_(consistent_subclass(residuals, b)) 
Example 32
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_regression.py    MIT License 5 votes vote down vote up
def test_lstsq_complex_larger_rhs(self):
        # gh-9891
        size = 20
        n_rhs = 70
        G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
        u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
        b = G.dot(u)
        # This should work without segmentation fault.
        u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
        # check results just in case
        assert_array_almost_equal(u_lstsq, u) 
Example 33
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):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
        if m == 0:
            assert_((x == 0).all())
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if np.asarray(b).ndim == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(consistent_subclass(x, b))
        assert_(consistent_subclass(residuals, b)) 
Example 34
Project: MARRtino-2.0   Author: DaniAffCH   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def test_empty_a_b(self, m, n, n_rhs):
        a = np.arange(m * n).reshape(m, n)
        b = np.ones((m, n_rhs))
        x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
        if m == 0:
            assert_((x == 0).all())
        assert_equal(x.shape, (n, n_rhs))
        assert_equal(residuals.shape, ((n_rhs,) if m > n else (0,)))
        if m > n and n_rhs > 0:
            # residuals are exactly the squared norms of b's columns
            r = b - np.dot(a, x)
            assert_almost_equal(residuals, (r * r).sum(axis=-2))
        assert_equal(rank, min(m, n))
        assert_equal(s.shape, (min(m, n),)) 
Example 35
Project: MARRtino-2.0   Author: DaniAffCH   File: test_linalg.py    GNU General Public License v3.0 5 votes vote down vote up
def test_incompatible_dims(self):
        # use modified version of docstring example
        x = np.array([0, 1, 2, 3])
        y = np.array([-1, 0.2, 0.9, 2.1, 3.3])
        A = np.vstack([x, np.ones(len(x))]).T
        with assert_raises_regex(LinAlgError, "Incompatible dimensions"):
            linalg.lstsq(A, y, rcond=None) 
Example 36
Project: MARRtino-2.0   Author: DaniAffCH   File: test_regression.py    GNU General Public License v3.0 5 votes vote down vote up
def test_lstsq_complex_larger_rhs(self):
        # gh-9891
        size = 20
        n_rhs = 70
        G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
        u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
        b = G.dot(u)
        # This should work without segmentation fault.
        u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
        # check results just in case
        assert_array_almost_equal(u_lstsq, u) 
Example 37
Project: vnpy_crypto   Author: birforce   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        if 'size-0' in tags:
            assert_raises(LinAlgError, linalg.lstsq, a, b)
            return

        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if np.asarray(b).ndim == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
        assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix))) 
Example 38
Project: vnpy_crypto   Author: birforce   File: test_regression.py    MIT License 5 votes vote down vote up
def test_lstsq_complex_larger_rhs(self):
        # gh-9891
        size = 20
        n_rhs = 70
        G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
        u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
        b = G.dot(u)
        # This should work without segmentation fault.
        u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
        # check results just in case
        assert_array_almost_equal(u_lstsq, u) 
Example 39
Project: vnpy_crypto   Author: birforce   File: mixed.py    MIT License 5 votes vote down vote up
def initialize(self):
        S = sum([np.dot(unit.X.T, unit.X) for unit in self.units])
        Y = sum([np.dot(unit.X.T, unit.Y) for unit in self.units])
        self.a = L.lstsq(S, Y, rcond=-1)[0]

        D = 0
        t = 0
        sigmasq = 0
        for unit in self.units:
            unit.r = unit.Y - np.dot(unit.X, self.a)
            if self.q > 1:
                unit.b = L.lstsq(unit.Z, unit.r, rcond=-1)[0]
            else:
                Z = unit.Z.reshape((unit.Z.shape[0], 1))
                unit.b = L.lstsq(Z, unit.r, rcond=-1)[0]

            sigmasq += (np.power(unit.Y, 2).sum() -
                        (self.a * np.dot(unit.X.T, unit.Y)).sum() -
                        (unit.b * np.dot(unit.Z.T, unit.r)).sum())
            D += np.multiply.outer(unit.b, unit.b)
            t += L.pinv(np.dot(unit.Z.T, unit.Z))

        #TODO: JP added df_resid check
        self.df_resid = (self.N - (self.m - 1) * self.q - self.p)
        sigmasq /= (self.N - (self.m - 1) * self.q - self.p)
        self.sigma = np.sqrt(sigmasq)
        self.D = (D - sigmasq * t) / self.m 
Example 40
Project: ble5-nrf52-mac   Author: tomasero   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
        if m == 0:
            assert_((x == 0).all())
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if np.asarray(b).ndim == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(consistent_subclass(x, b))
        assert_(consistent_subclass(residuals, b)) 
Example 41
Project: ble5-nrf52-mac   Author: tomasero   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_empty_a_b(self, m, n, n_rhs):
        a = np.arange(m * n).reshape(m, n)
        b = np.ones((m, n_rhs))
        x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
        if m == 0:
            assert_((x == 0).all())
        assert_equal(x.shape, (n, n_rhs))
        assert_equal(residuals.shape, ((n_rhs,) if m > n else (0,)))
        if m > n and n_rhs > 0:
            # residuals are exactly the squared norms of b's columns
            r = b - np.dot(a, x)
            assert_almost_equal(residuals, (r * r).sum(axis=-2))
        assert_equal(rank, min(m, n))
        assert_equal(s.shape, (min(m, n),)) 
Example 42
Project: ble5-nrf52-mac   Author: tomasero   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_incompatible_dims(self):
        # use modified version of docstring example
        x = np.array([0, 1, 2, 3])
        y = np.array([-1, 0.2, 0.9, 2.1, 3.3])
        A = np.vstack([x, np.ones(len(x))]).T
        with assert_raises_regex(LinAlgError, "Incompatible dimensions"):
            linalg.lstsq(A, y, rcond=None) 
Example 43
Project: ble5-nrf52-mac   Author: tomasero   File: test_regression.py    MIT License 5 votes vote down vote up
def test_lstsq_complex_larger_rhs(self):
        # gh-9891
        size = 20
        n_rhs = 70
        G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
        u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
        b = G.dot(u)
        # This should work without segmentation fault.
        u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
        # check results just in case
        assert_array_almost_equal(u_lstsq, u) 
Example 44
Project: ble5-nrf52-mac   Author: tomasero   File: test_lsq_linear.py    MIT License 5 votes vote down vote up
def test_dense_bounds(self):
        # Solutions for comparison are taken from MATLAB.
        lb = np.array([-1, -10])
        ub = np.array([1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, lstsq(A, b, rcond=-1)[0])

        lb = np.array([0.0, -np.inf])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, np.inf), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.0, -4.084174437334673]),
                            atol=1e-6)

        lb = np.array([-1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, np.inf), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.448427311733504, 0]),
                            atol=1e-15)

        ub = np.array([np.inf, -5])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([-0.105560998682388, -5]))

        ub = np.array([-1, np.inf])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([-1, -4.181102129483254]))

        lb = np.array([0, -4])
        ub = np.array([1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.005236663400791, -4])) 
Example 45
Project: Computable   Author: ktraunmueller   File: linear_algebra.py    MIT License 5 votes vote down vote up
def linear_least_squares(a, b, rcond=1.e-10):
    """returns x,resids,rank,s
where x minimizes 2-norm(|b - Ax|)
      resids is the sum square residuals
      rank is the rank of A
      s is the rank of the singular values of A in descending order

If b is a matrix then x is also a matrix with corresponding columns.
If the rank of A is less than the number of columns of A or greater than
the number of rows, then residuals will be returned as an empty array
otherwise resids = sum((b-dot(A,x)**2).
Singular values less than s[0]*rcond are treated as zero.
"""
    return linalg.lstsq(a, b, rcond) 
Example 46
Project: poker   Author: surgebiswas   File: test_lsq_linear.py    MIT License 5 votes vote down vote up
def test_dense_no_bounds(self):
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, method=self.method, lsq_solver=lsq_solver)
            assert_allclose(res.x, lstsq(A, b)[0]) 
Example 47
Project: poker   Author: surgebiswas   File: test_lsq_linear.py    MIT License 5 votes vote down vote up
def test_dense_bounds(self):
        # Solutions for comparison are taken from MATLAB.
        lb = np.array([-1, -10])
        ub = np.array([1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, lstsq(A, b)[0])

        lb = np.array([0.0, -np.inf])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, np.inf), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.0, -4.084174437334673]),
                            atol=1e-6)

        lb = np.array([-1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, np.inf), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.448427311733504, 0]),
                            atol=1e-15)

        ub = np.array([np.inf, -5])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([-0.105560998682388, -5]))

        ub = np.array([-1, np.inf])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([-1, -4.181102129483254]))

        lb = np.array([0, -4])
        ub = np.array([1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.005236663400791, -4])) 
Example 48
Project: P3_image_processing   Author: latedude2   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
        if m == 0:
            assert_((x == 0).all())
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if np.asarray(b).ndim == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(consistent_subclass(x, b))
        assert_(consistent_subclass(residuals, b)) 
Example 49
Project: P3_image_processing   Author: latedude2   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_empty_a_b(self, m, n, n_rhs):
        a = np.arange(m * n).reshape(m, n)
        b = np.ones((m, n_rhs))
        x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
        if m == 0:
            assert_((x == 0).all())
        assert_equal(x.shape, (n, n_rhs))
        assert_equal(residuals.shape, ((n_rhs,) if m > n else (0,)))
        if m > n and n_rhs > 0:
            # residuals are exactly the squared norms of b's columns
            r = b - np.dot(a, x)
            assert_almost_equal(residuals, (r * r).sum(axis=-2))
        assert_equal(rank, min(m, n))
        assert_equal(s.shape, (min(m, n),)) 
Example 50
Project: P3_image_processing   Author: latedude2   File: test_linalg.py    MIT License 5 votes vote down vote up
def test_incompatible_dims(self):
        # use modified version of docstring example
        x = np.array([0, 1, 2, 3])
        y = np.array([-1, 0.2, 0.9, 2.1, 3.3])
        A = np.vstack([x, np.ones(len(x))]).T
        with assert_raises_regex(LinAlgError, "Incompatible dimensions"):
            linalg.lstsq(A, y, rcond=None) 
Example 51
Project: P3_image_processing   Author: latedude2   File: test_regression.py    MIT License 5 votes vote down vote up
def test_lstsq_complex_larger_rhs(self):
        # gh-9891
        size = 20
        n_rhs = 70
        G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
        u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
        b = G.dot(u)
        # This should work without segmentation fault.
        u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
        # check results just in case
        assert_array_almost_equal(u_lstsq, u) 
Example 52
Project: P3_image_processing   Author: latedude2   File: test_lsq_linear.py    MIT License 5 votes vote down vote up
def test_dense_bounds(self):
        # Solutions for comparison are taken from MATLAB.
        lb = np.array([-1, -10])
        ub = np.array([1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, lstsq(A, b, rcond=-1)[0])

        lb = np.array([0.0, -np.inf])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, np.inf), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.0, -4.084174437334673]),
                            atol=1e-6)

        lb = np.array([-1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, np.inf), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.448427311733504, 0]),
                            atol=1e-15)

        ub = np.array([np.inf, -5])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([-0.105560998682388, -5]))

        ub = np.array([-1, np.inf])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([-1, -4.181102129483254]))

        lb = np.array([0, -4])
        ub = np.array([1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.005236663400791, -4])) 
Example 53
Project: GUESS   Author: jlin0504   File: guess_2dfdr.py    MIT License 5 votes vote down vote up
def decompo(data,inds,neigh,i):#i=range(len(datas))
    print 'decomp ',i
    coeff=(np.array(neigh)).T #dp[0][i] is [[neighb1 coeff],[neighb2 coeff]...], want to take the transpose of this
    decomp=lstsq(coeff,data)
    nil=np.zeros(len(models))
    for kk in range(len(inds)):
        nil[inds[kk]]=decomp[0][kk]
    return nil 
Example 54
Project: nusa   Author: JorgeDeLosSantos   File: model.py    MIT License 5 votes vote down vote up
def solve(self):
        self._check_nodes()
        # Solve LS
        self.VU = [node[key] for node in self.U.values() for key in ("ux","uy")]
        self.VF = [node[key] for node in self.F.values() for key in ("fx","fy")]
        knw = [pos for pos,value in enumerate(self.VU) if not value is np.nan]
        unknw = [pos for pos,value in enumerate(self.VU) if value is np.nan]
        self.K2S = np.delete(np.delete(self.KG,knw,0),knw,1)
        self.F2S = np.delete(self.VF,knw,0)
        
        # For displacements
        try:
            self.solved_u = la.solve(self.K2S,self.F2S)
        except:
            print("Solved using LSTSQ")
            self.solved_u = la.lstsq(self.K2S, self.F2S)[0]
            
        for k,ic in enumerate(unknw):
            nd, var = self.index2key(ic)
            self.U[nd][var] = self.solved_u[k]
            
        # Updating nodes displacements
        for nd in self.nodes.values():
            if np.isnan(nd.ux):
                nd.ux = self.U[nd.label]["ux"]
            if np.isnan(nd.uy):
                nd.uy = self.U[nd.label]["uy"]
                    
        # For nodal forces/reactions
        self.NF = self.F.copy()
        self.VU = [node[key] for node in self.U.values() for key in ("ux","uy")]
        nf_calc = np.dot(self.KG, self.VU)
        for k in range(2*self.get_number_of_nodes()):
            nd, var = self.index2key(k, ("fx","fy"))
            self.NF[nd][var] = nf_calc[k]
            cnlab = np.floor(k/float(self.dof))
            if var=="fx": 
                self.nodes[cnlab].fx = nf_calc[k]
            elif var=="fy": 
                self.nodes[cnlab].fy = nf_calc[k] 
Example 55
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        if 'size-0' in tags:
            assert_raises(LinAlgError, linalg.lstsq, a, b)
            return

        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if np.asarray(b).ndim == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(consistent_subclass(x, b))
        assert_(consistent_subclass(residuals, b)) 
Example 56
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_regression.py    MIT License 5 votes vote down vote up
def test_lstsq_complex_larger_rhs(self):
        # gh-9891
        size = 20
        n_rhs = 70
        G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
        u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
        b = G.dot(u)
        # This should work without segmentation fault.
        u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
        # check results just in case
        assert_array_almost_equal(u_lstsq, u) 
Example 57
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_lsq_linear.py    MIT License 5 votes vote down vote up
def test_dense_no_bounds(self):
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, method=self.method, lsq_solver=lsq_solver)
            assert_allclose(res.x, lstsq(A, b, rcond=-1)[0]) 
Example 58
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_lsq_linear.py    MIT License 5 votes vote down vote up
def test_dense_bounds(self):
        # Solutions for comparison are taken from MATLAB.
        lb = np.array([-1, -10])
        ub = np.array([1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, lstsq(A, b, rcond=-1)[0])

        lb = np.array([0.0, -np.inf])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, np.inf), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.0, -4.084174437334673]),
                            atol=1e-6)

        lb = np.array([-1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, np.inf), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.448427311733504, 0]),
                            atol=1e-15)

        ub = np.array([np.inf, -5])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([-0.105560998682388, -5]))

        ub = np.array([-1, np.inf])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([-1, -4.181102129483254]))

        lb = np.array([0, -4])
        ub = np.array([1, 0])
        for lsq_solver in self.lsq_solvers:
            res = lsq_linear(A, b, (lb, ub), method=self.method,
                             lsq_solver=lsq_solver)
            assert_allclose(res.x, np.array([0.005236663400791, -4])) 
Example 59
Project: pylgrim   Author: kirienko   File: ils.py    GNU General Public License v3.0 5 votes vote down vote up
def mils(A, B, y, p=1):
    """
    x_hat,z_hat = mils(A,B,y,p) produces p pairs of optimal solutions to
                  the mixed integer least squares problem min_{x,z}||y-Ax-Bz||,
                  where x and z are real and integer vectors, respectively.

    Input arguments:
       A - m by k real matrix
       B - m by n real matrix
             [A,B] has full column rank
       y - m-dimensional real vector
       p - the number of optimal solutions

    Output arguments:
       x_hat - k by p real matrix
       z_hat - n by p integer matrix (in double precision).
             The pair {x_hat(:,j),z_hat(:,j)} is the j-th optimal solution
             i.e., its residual is the j-th smallest, so
             ||y-A*x_hat(:,1)-B*z_hat(:,1)|| <= ...
                                             < =||y-A*x_hat(:,p)-B*z_hat(:,p)||
    """
    m, k = A.shape
    m2, n = B.shape
    if m != m2 or m != len(y) or len(y[1]) != 1:
        raise ValueError("Input arguments have a matrix dimension error!")

    if rank(A) + rank(B) < k + n:
        raise ValueError("hmmm...")

    Q, R = qr(A, mode='complete')
    Q_A = Q[:, :k]
    Q_Abar = Q[:, k:]
    R_A = R[:k, :]

    # Compute the p optimal integer least squares solutions
    z_hat = ils(dot(Q_Abar.T, B), dot(Q_Abar.T, y), p)

    # Compute the corresponding real least squares solutions
    x_hat = lstsq(R_A, dot(Q_A.T, (dot(y, ones((1, p))) - dot(B, z_hat))))

    return x_hat, z_hat 
Example 60
Project: nimo   Author: wolfram2012   File: Polynomial.py    GNU General Public License v3.0 5 votes vote down vote up
def trainClassifer(self,labels,vectors,ilog=None):
        '''
        Train the polynomial.  Do not call this function
        manually, instead call the train function on the super
        class.
        '''
        #build matrix
        matrix = []
        for each in vectors:
            if len(each) != 2:
                raise ValueError("ERROR: Vector length=%d.  Polynomial2D only predicts for vectors of length 2."%len(each))
            x,y = each
            matrix.append(self.buildRow(x,y))
        
        matrix = array(matrix)
        labels = array(labels)
        
        x,resids,rank,s = lstsq(matrix,labels)
        
        self.x = x
        self.resids = resids
        self.rank = rank
        self.s = s
        
        if rank != matrix.shape[1]:
            print "WARNING: Polynomial is not fully constrained." 
Example 61
Project: ran_replicate   Author: donydchen   File: align_face.py    MIT License 5 votes vote down vote up
def findNonreflectiveSimilarity(self, uv, xy, options=None):
        options = {'K': 2}

        K = options['K']
        M = xy.shape[0]
        x = xy[:, 0].reshape((-1, 1))
        y = xy[:, 1].reshape((-1, 1))

        tmp1 = np.hstack((x, y, np.ones((M, 1)), np.zeros((M, 1))))
        tmp2 = np.hstack((y, -x, np.zeros((M, 1)), np.ones((M, 1))))
        X = np.vstack((tmp1, tmp2))

        u = uv[:, 0].reshape((-1, 1))
        v = uv[:, 1].reshape((-1, 1))
        U = np.vstack((u, v))

        if rank(X) >= 2 * K:
            r, _, _, _ = lstsq(X, U, rcond=-1)
            r = np.squeeze(r)
        else:
            raise Exception('cp2tform:twoUniquePointsReq')
        sc = r[0]
        ss = r[1]
        tx = r[2]
        ty = r[3]

        Tinv = np.array([
            [sc, -ss, 0],
            [ss, sc, 0],
            [tx, ty, 1]
        ])

        T = inv(Tinv)
        T[:, 2] = np.array([0, 0, 1])
        return T, Tinv 
Example 62
Project: MulensModel   Author: rpoleski   File: numpy_functions.py    MIT License 5 votes vote down vote up
def numpy_chi2_v2(time, obs_flux, obs_flux_err, t_0, u_0, t_E):
    u2 = ((time-t_0)/t_E)**2 + u_0**2
    magnification = (u2 + 2.) / sqrt(u2 * (u2 + 4.))
    x = ones(shape=(2, len(u2)))
    x[0] = magnification
    sigma_inverse = 1. / obs_flux_err
    y = obs_flux * sigma_inverse
    xT = (x * sigma_inverse).T
    results = linalg.lstsq(xT, y, rcond=-1)[0]
    flux = results[0] * magnification + results[1]
    chi2 = sum(square((obs_flux - flux) * sigma_inverse))
    return chi2 
Example 63
Project: MulensModel   Author: rpoleski   File: numpy_functions.py    MIT License 5 votes vote down vote up
def get_fluxes(magnification, obs_flux, obs_flux_err):
    x = ones(shape=(2, len(magnification)))
    x[0] = magnification
    sigma_inverse = 1. / obs_flux_err
    y = obs_flux * sigma_inverse
    xT = (x * sigma_inverse).T
    results = linalg.lstsq(xT, y, rcond=-1)[0]
    return results 
Example 64
Project: nelson_siegel_svensson   Author: luphord   File: calibrate.py    MIT License 5 votes vote down vote up
def betas_ns_ols(tau: float, t: np.ndarray, y: np.ndarray) \
      -> Tuple[NelsonSiegelCurve, Any]:
    '''Calculate the best-fitting beta-values given tau
       for time-value pairs t and y and return a corresponding
       Nelson-Siegel curve instance.
    '''
    _assert_same_shape(t, y)
    curve = NelsonSiegelCurve(0, 0, 0, tau)
    factors = curve.factor_matrix(t)
    lstsq_res = lstsq(factors, y, rcond=None)
    beta = lstsq_res[0]
    return NelsonSiegelCurve(beta[0], beta[1], beta[2], tau), lstsq_res 
Example 65
Project: nelson_siegel_svensson   Author: luphord   File: calibrate.py    MIT License 5 votes vote down vote up
def betas_nss_ols(tau: Tuple[float, float], t: np.ndarray, y: np.ndarray) \
      -> Tuple[NelsonSiegelSvenssonCurve, Any]:
    '''Calculate the best-fitting beta-values given tau (= array of tau1
       and tau2) for time-value pairs t and y and return a corresponding
       Nelson-Siegel-Svensson curve instance.
    '''
    _assert_same_shape(t, y)
    curve = NelsonSiegelSvenssonCurve(0, 0, 0, 0, tau[0], tau[1])
    factors = curve.factor_matrix(t)
    lstsq_res = lstsq(factors, y, rcond=None)
    beta = lstsq_res[0]
    return NelsonSiegelSvenssonCurve(beta[0], beta[1], beta[2], beta[3],
                                     tau[0], tau[1]), lstsq_res 
Example 66
Project: a2dr   Author: cvxgrp   File: test_basic.py    Apache License 2.0 5 votes vote down vote up
def test_unconstrained(self):
        # minimize ||y - X\beta||_2^2.

        # Problem data.
        m, n = 100, 80
        density = 0.1
        X = sparse.random(m, n, density=density, data_rvs=np.random.randn)
        y = np.random.randn(m)
        prox_list = [lambda v, t: prox_sum_squares_affine(v, t, F=X, g=y, method="lstsq")]

        # Solve with NumPy.
        np_result = LA.lstsq(X.todense(), y, rcond=None)
        np_beta = np_result[0]
        np_obj = np.sum(np_result[1])

        # Solve with DRS.
        drs_result = a2dr(prox_list, n_list=[n], anderson=False, max_iter=self.MAX_ITER)
        drs_beta = drs_result["x_vals"][-1]
        drs_obj = np.sum((y - X.dot(drs_beta))**2)
        print("Finish DRS.")

        # Solve with A2DR.
        a2dr_result = a2dr(prox_list, n_list=[n], anderson=True, max_iter=self.MAX_ITER)
        a2dr_beta = a2dr_result["x_vals"][-1]
        a2dr_obj = np.sum((y - X.dot(a2dr_beta))**2)
        print("Finish A2DR.")

        self.assertAlmostEqual(np_obj, drs_obj)
        self.assertAlmostEqual(np_obj, a2dr_obj) 
Example 67
Project: predictive-maintenance-using-machine-learning   Author: awslabs   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
def do(self, a, b, tags):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
        if m == 0:
            assert_((x == 0).all())
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if np.asarray(b).ndim == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(consistent_subclass(x, b))
        assert_(consistent_subclass(residuals, b)) 
Example 68
Project: predictive-maintenance-using-machine-learning   Author: awslabs   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
def test_empty_a_b(self, m, n, n_rhs):
        a = np.arange(m * n).reshape(m, n)
        b = np.ones((m, n_rhs))
        x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
        if m == 0:
            assert_((x == 0).all())
        assert_equal(x.shape, (n, n_rhs))
        assert_equal(residuals.shape, ((n_rhs,) if m > n else (0,)))
        if m > n and n_rhs > 0:
            # residuals are exactly the squared norms of b's columns
            r = b - np.dot(a, x)
            assert_almost_equal(residuals, (r * r).sum(axis=-2))
        assert_equal(rank, min(m, n))
        assert_equal(s.shape, (min(m, n),)) 
Example 69
Project: predictive-maintenance-using-machine-learning   Author: awslabs   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
def test_incompatible_dims(self):
        # use modified version of docstring example
        x = np.array([0, 1, 2, 3])
        y = np.array([-1, 0.2, 0.9, 2.1, 3.3])
        A = np.vstack([x, np.ones(len(x))]).T
        with assert_raises_regex(LinAlgError, "Incompatible dimensions"):
            linalg.lstsq(A, y, rcond=None) 
Example 70
Project: predictive-maintenance-using-machine-learning   Author: awslabs   File: test_regression.py    Apache License 2.0 5 votes vote down vote up
def test_lstsq_complex_larger_rhs(self):
        # gh-9891
        size = 20
        n_rhs = 70
        G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
        u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
        b = G.dot(u)
        # This should work without segmentation fault.
        u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
        # check results just in case
        assert_array_almost_equal(u_lstsq, u) 
Example 71
Project: fund   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
def do(self, a, b, tags):
        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
        if m == 0:
            assert_((x == 0).all())
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if np.asarray(b).ndim == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(consistent_subclass(x, b))
        assert_(consistent_subclass(residuals, b)) 
Example 72
Project: fund   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
def test_empty_a_b(self, m, n, n_rhs):
        a = np.arange(m * n).reshape(m, n)
        b = np.ones((m, n_rhs))
        x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
        if m == 0:
            assert_((x == 0).all())
        assert_equal(x.shape, (n, n_rhs))
        assert_equal(residuals.shape, ((n_rhs,) if m > n else (0,)))
        if m > n and n_rhs > 0:
            # residuals are exactly the squared norms of b's columns
            r = b - np.dot(a, x)
            assert_almost_equal(residuals, (r * r).sum(axis=-2))
        assert_equal(rank, min(m, n))
        assert_equal(s.shape, (min(m, n),)) 
Example 73
Project: fund   Author: Frank-qlu   File: test_linalg.py    Apache License 2.0 5 votes vote down vote up
def test_incompatible_dims(self):
        # use modified version of docstring example
        x = np.array([0, 1, 2, 3])
        y = np.array([-1, 0.2, 0.9, 2.1, 3.3])
        A = np.vstack([x, np.ones(len(x))]).T
        with assert_raises_regex(LinAlgError, "Incompatible dimensions"):
            linalg.lstsq(A, y, rcond=None) 
Example 74
Project: fund   Author: Frank-qlu   File: test_regression.py    Apache License 2.0 5 votes vote down vote up
def test_lstsq_complex_larger_rhs(self):
        # gh-9891
        size = 20
        n_rhs = 70
        G = np.random.randn(size, size) + 1j * np.random.randn(size, size)
        u = np.random.randn(size, n_rhs) + 1j * np.random.randn(size, n_rhs)
        b = G.dot(u)
        # This should work without segmentation fault.
        u_lstsq, res, rank, sv = linalg.lstsq(G, b, rcond=None)
        # check results just in case
        assert_array_almost_equal(u_lstsq, u) 
Example 75
Project: PyMDNet   Author: zhyj3038   File: bbox_regressor.py    GNU General Public License v3.0 5 votes vote down vote up
def solve(A, y, delta, method):
  if method == 'ridge_reg_chol':
    R = cholesky(dot(A.T, A) + delta*np.identity(A.shape[1]))
    z = lstsq(R.T, dot(A.T, y))[0]
    x = lstsq(R, z)[0]
  elif method == 'ridge_reg_inv':
    x = dot(dot(inv(dot(A.T, A) + delta*np.identity(A.shape[1])), A.T), y)
  elif method == 'ls_mldivide':
    if delta > 0:
      print('ignoring lambda; no regularization used')
    x = lstsq(A, y)[0]
  loss = 0.5 * (dot(A, x) - y) **2
  return x.reshape(-1, 1) 
Example 76
Project: pySINDy   Author: luckystarufo   File: test_linalg.py    MIT License 5 votes vote down vote up
def do(self, a, b, tags):
        if 'size-0' in tags:
            assert_raises(LinAlgError, linalg.lstsq, a, b)
            return

        arr = np.asarray(a)
        m, n = arr.shape
        u, s, vt = linalg.svd(a, 0)
        x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
        if m <= n:
            assert_almost_equal(b, dot(a, x))
            assert_equal(rank, m)
        else:
            assert_equal(rank, n)
        assert_almost_equal(sv, sv.__array_wrap__(s))
        if rank == n and m > n:
            expect_resids = (
                np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
            expect_resids = np.asarray(expect_resids)
            if np.asarray(b).ndim == 1:
                expect_resids.shape = (1,)
                assert_equal(residuals.shape, expect_resids.shape)
        else:
            expect_resids = np.array([]).view(type(x))
        assert_almost_equal(residuals, expect_resids)
        assert_(np.issubdtype(residuals.dtype, np.floating))
        assert_(consistent_subclass(x, b))
        assert_(consistent_subclass(residuals, b)) 
Example 77
Project: lps-anchor-pos-estimator   Author: bitcraze   File: toa_3D_bundle_with_smoother.py    GNU General Public License v2.0 4 votes vote down vote up
def bundletoa(D, I, J, xt, yt, debug=1, opts=[]):
    res = None
    jac = None

    for kkk in range(0, 10):

        res, jac = calcresandjac(D, I, J, xt, yt, opts)

        dz = linalg.lstsq(-((jac.conj().T) * jac + 0.1 *
                            np.eye(jac.shape[1])), (jac.conj().T) * res)

        xtn, ytn = updatexy(xt, yt, dz)
        res2, jac2 = calcresandjac(D, I, J, xt, yt, opts)

        cc = np.linalg.norm(jac * dz) / np.linalg.norm(res)

        if np.linalg.norm(res) < np.linalg.norm(res2):

            if cc > 1e-4:

                kkkk = 1
                while (kkkk < 50) and (
                        np.linalg.norm(res) < np.linalg.norm(res2)):
                    dz = dz / 2
                    xtn, ytn = updatexy(xt, yt, dz)
                    res2, jac2 = calcresandjac(D, I, J, xtn, ytn, opts)
                    kkkk = kkkk + 1

        if debug:
            aa_1 = np.linalg.norm(res)
            aa_2 = np.linalg.norm(res + jac * dz)
            aa_3 = np.linalg.norm(res2)
            aa = np.concatenate((aa_1, aa_2, aa_3), 1)

            bb = aa
            bb = bb - bb[1]
            bb = bb / bb[0]

            cc = np.linalg.norm(jac * dz) / np.linalg.norm(res)

            print(aa, bb, cc)

        if np.linalg.norm(res2) < np.linalg.norm(res):

            xt = xtn
            yt = ytn
        else:

            if debug:
                print(kkk, ' stalled')

    xopt = xt
    yopt = yt

    return xopt, yopt, res, jac 
Example 78
Project: RSA_pycaffe   Author: power0341   File: utils.py    MIT License 4 votes vote down vote up
def findNonreflectiveSimilarity(uv, xy, options=None):
    options = {'K': 2}

    K = options['K']
    M = xy.shape[0]
    x = xy[:, 0].reshape((-1, 1))  # use reshape to keep a column vector
    y = xy[:, 1].reshape((-1, 1))  # use reshape to keep a column vector
    # print '--->x, y:\n', x, y

    tmp1 = np.hstack((x, y, np.ones((M, 1)), np.zeros((M, 1))))
    tmp2 = np.hstack((y, -x, np.zeros((M, 1)), np.ones((M, 1))))
    X = np.vstack((tmp1, tmp2))
    # print '--->X.shape: ', X.shape
    # print 'X:\n', X

    u = uv[:, 0].reshape((-1, 1))  # use reshape to keep a column vector
    v = uv[:, 1].reshape((-1, 1))  # use reshape to keep a column vector
    U = np.vstack((u, v))
    # print '--->U.shape: ', U.shape
    # print 'U:\n', U

    # We know that X * r = U
    if rank(X) >= 2 * K:
        r, _, _, _ = lstsq(X, U)
        r = np.squeeze(r)
    else:
        raise Exception('cp2tform:twoUniquePointsReq')

    # print '--->r:\n', r

    sc = r[0]
    ss = r[1]
    tx = r[2]
    ty = r[3]

    Tinv = np.array([
        [sc, -ss, 0],
        [ss,  sc, 0],
        [tx,  ty, 1]
    ])

    # print '--->Tinv:\n', Tinv

    T = inv(Tinv)
    # print '--->T:\n', T

    T[:, 2] = np.array([0, 0, 1])

    return T, Tinv 
Example 79
Project: nimo   Author: wolfram2012   File: Affine.py    GNU General Public License v3.0 4 votes vote down vote up
def AffineFromPointsLS(src,dst,new_size,filter=BILINEAR, normalize=True):  
    '''
     An affine transform that will rotate, translate, and scale to map one 
     set of points to the other. For example, to align eye coordinates in face images.
     
     Find a transform (a,b,tx,ty) such that it maps the source points to the 
     destination points::
     
         a*x1-b*y1+tx = x2
         b*x1+a*y1+ty = y2
     
     This method minimizes the squared error to find an optimal fit between the 
     points.
    
     @param src: a list of link.Points in the source image.
     @param dst: a list of link.Points in the destination image.
     @param new_size: new size for the image.
     @param filter: PIL filter to use.
    '''  
    if normalize:
        # Normalize Points
        src_norm = AffineNormalizePoints(src)
        src = src_norm.transformPoints(src)
        dst_norm = AffineNormalizePoints(dst)
        dst = dst_norm.transformPoints(dst)
    
    # Compute the transformation parameters
    A = []
    b = []
    for i in range(len(src)):
        A.append([src[i].X(),-src[i].Y(),1,0])
        A.append([src[i].Y(), src[i].X(),0,1])
        b.append(dst[i].X())
        b.append(dst[i].Y())
         
    A = array(A)
    b = array(b)
        
    result,resids,rank,s = lstsq(A,b)
    
    a,b,tx,ty = result    
    # Create the transform matrix
    matrix = array([[a,-b,tx],[b,a,ty],[0,0,1]],'d')
    
    if normalize:
        matrix = dot(dst_norm.inverse,dot(matrix,src_norm.matrix))

    return AffineTransform(matrix,new_size,filter) 
Example 80
Project: a2dr   Author: cvxgrp   File: test_basic.py    Apache License 2.0 4 votes vote down vote up
def test_ols(self):
        # minimize ||y - X\beta||_2^2 with respect to \beta >= 0.
        m = 100
        n = 10
        N = 4  # Number of splits. (split X row-wise)
        beta_true = np.array(np.arange(-n / 2, n / 2) + 1)
        X = np.random.randn(m, n)
        y = X.dot(beta_true) + np.random.randn(m)

        # Split problem.
        X_split = np.split(X, N)
        y_split = np.split(y, N)

        # Construct list of proximal operators.
        # Note: We must do it this way to avoid problems caused by late binding:
        # https://docs.python-guide.org/writing/gotchas/#late-binding-closures
        prox_list = [lambda v, t, i=i: prox_sum_squares_affine(v, t, F=X_split[i], g=y_split[i], method="lstsq") \
                        for i in range(N)]
        v_init = N * [np.random.randn(n)]

        # Solve with NumPy.
        np_beta = []
        np_obj = 0
        for i in range(N):
            np_result = LA.lstsq(X_split[i], y_split[i], rcond=None)
            np_beta += [np_result[0]]
            np_obj += np.sum(np_result[1])
        print("NumPy Objective:", np_obj)
        print("NumPy Solution:", np_beta)

        # Solve with DRS (proximal point method).
        drs_result = a2dr(prox_list, v_init=v_init, max_iter=self.MAX_ITER, eps_abs=self.eps_abs, \
                          eps_rel=self.eps_rel, anderson=False)
        drs_beta = drs_result["x_vals"]
        drs_obj = np.sum([(yi - Xi.dot(beta)) ** 2 for yi, Xi, beta in zip(y_split, X_split, drs_beta)])
        print("DRS Objective:", drs_obj)
        print("DRS Solution:", drs_beta)

        # Solve with A2DR (proximal point method with Anderson acceleration).
        a2dr_result = a2dr(prox_list, v_init=v_init, max_iter=self.MAX_ITER, eps_abs=self.eps_abs, \
                           eps_rel=self.eps_rel, anderson=True)
        a2dr_beta = a2dr_result["x_vals"]
        a2dr_obj = np.sum([(yi - Xi.dot(beta)) ** 2 for yi, Xi, beta in zip(y_split, X_split, drs_beta)])
        print("A2DR Objective:", a2dr_obj)
        print("A2DR Solution:", a2dr_beta)

        # Compare results.
        self.assertAlmostEqual(np_obj, drs_obj)
        self.assertAlmostEqual(np_obj, a2dr_obj)
        for i in range(N):
            self.assertItemsAlmostEqual(np_beta[i], drs_beta[i])
            self.assertItemsAlmostEqual(np_beta[i], a2dr_beta[i])