Initial commit
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
``numpy.linalg``
|
||||
================
|
||||
|
||||
The NumPy linear algebra functions rely on BLAS and LAPACK to provide efficient
|
||||
low level implementations of standard linear algebra algorithms. Those
|
||||
libraries may be provided by NumPy itself using C versions of a subset of their
|
||||
reference implementations but, when possible, highly optimized libraries that
|
||||
take advantage of specialized processor functionality are preferred. Examples
|
||||
of such libraries are OpenBLAS, MKL (TM), and ATLAS. Because those libraries
|
||||
are multithreaded and processor dependent, environmental variables and external
|
||||
packages such as threadpoolctl may be needed to control the number of threads
|
||||
or specify the processor architecture.
|
||||
|
||||
- OpenBLAS: https://www.openblas.net/
|
||||
- threadpoolctl: https://github.com/joblib/threadpoolctl
|
||||
|
||||
Please note that the most-used linear algebra functions in NumPy are present in
|
||||
the main ``numpy`` namespace rather than in ``numpy.linalg``. There are:
|
||||
``dot``, ``vdot``, ``inner``, ``outer``, ``matmul``, ``tensordot``, ``einsum``,
|
||||
``einsum_path`` and ``kron``.
|
||||
|
||||
Functions present in numpy.linalg are listed below.
|
||||
|
||||
|
||||
Matrix and vector products
|
||||
--------------------------
|
||||
|
||||
multi_dot
|
||||
matrix_power
|
||||
|
||||
Decompositions
|
||||
--------------
|
||||
|
||||
cholesky
|
||||
qr
|
||||
svd
|
||||
|
||||
Matrix eigenvalues
|
||||
------------------
|
||||
|
||||
eig
|
||||
eigh
|
||||
eigvals
|
||||
eigvalsh
|
||||
|
||||
Norms and other numbers
|
||||
-----------------------
|
||||
|
||||
norm
|
||||
cond
|
||||
det
|
||||
matrix_rank
|
||||
slogdet
|
||||
|
||||
Solving equations and inverting matrices
|
||||
----------------------------------------
|
||||
|
||||
solve
|
||||
tensorsolve
|
||||
lstsq
|
||||
inv
|
||||
pinv
|
||||
tensorinv
|
||||
|
||||
Exceptions
|
||||
----------
|
||||
|
||||
LinAlgError
|
||||
|
||||
"""
|
||||
# To get sub-modules
|
||||
from . import linalg
|
||||
from .linalg import *
|
||||
|
||||
__all__ = linalg.__all__.copy()
|
||||
|
||||
from numpy._pytesttester import PytestTester
|
||||
test = PytestTester(__name__)
|
||||
del PytestTester
|
||||
@@ -0,0 +1,26 @@
|
||||
from typing import Any, List
|
||||
|
||||
__all__: List[str]
|
||||
|
||||
class LinAlgError(Exception): ...
|
||||
|
||||
def tensorsolve(a, b, axes=...): ...
|
||||
def solve(a, b): ...
|
||||
def tensorinv(a, ind=...): ...
|
||||
def inv(a): ...
|
||||
def matrix_power(a, n): ...
|
||||
def cholesky(a): ...
|
||||
def qr(a, mode=...): ...
|
||||
def eigvals(a): ...
|
||||
def eigvalsh(a, UPLO=...): ...
|
||||
def eig(a): ...
|
||||
def eigh(a, UPLO=...): ...
|
||||
def svd(a, full_matrices=..., compute_uv=..., hermitian=...): ...
|
||||
def cond(x, p=...): ...
|
||||
def matrix_rank(M, tol=..., hermitian=...): ...
|
||||
def pinv(a, rcond=..., hermitian=...): ...
|
||||
def slogdet(a): ...
|
||||
def det(a): ...
|
||||
def lstsq(a, b, rcond=...): ...
|
||||
def norm(x, ord=..., axis=..., keepdims=...): ...
|
||||
def multi_dot(arrays, *, out=...): ...
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,83 @@
|
||||
import os
|
||||
import sys
|
||||
|
||||
def configuration(parent_package='', top_path=None):
|
||||
from numpy.distutils.misc_util import Configuration
|
||||
from numpy.distutils.system_info import (
|
||||
get_info, system_info, lapack_opt_info, blas_opt_info)
|
||||
config = Configuration('linalg', parent_package, top_path)
|
||||
|
||||
config.add_subpackage('tests')
|
||||
|
||||
# Configure lapack_lite
|
||||
|
||||
src_dir = 'lapack_lite'
|
||||
lapack_lite_src = [
|
||||
os.path.join(src_dir, 'python_xerbla.c'),
|
||||
os.path.join(src_dir, 'f2c_z_lapack.c'),
|
||||
os.path.join(src_dir, 'f2c_c_lapack.c'),
|
||||
os.path.join(src_dir, 'f2c_d_lapack.c'),
|
||||
os.path.join(src_dir, 'f2c_s_lapack.c'),
|
||||
os.path.join(src_dir, 'f2c_lapack.c'),
|
||||
os.path.join(src_dir, 'f2c_blas.c'),
|
||||
os.path.join(src_dir, 'f2c_config.c'),
|
||||
os.path.join(src_dir, 'f2c.c'),
|
||||
]
|
||||
all_sources = config.paths(lapack_lite_src)
|
||||
|
||||
if os.environ.get('NPY_USE_BLAS_ILP64', "0") != "0":
|
||||
lapack_info = get_info('lapack_ilp64_opt', 2)
|
||||
else:
|
||||
lapack_info = get_info('lapack_opt', 0) # and {}
|
||||
|
||||
use_lapack_lite = not lapack_info
|
||||
|
||||
if use_lapack_lite:
|
||||
# This makes numpy.distutils write the fact that lapack_lite
|
||||
# is being used to numpy.__config__
|
||||
class numpy_linalg_lapack_lite(system_info):
|
||||
def calc_info(self):
|
||||
info = {'language': 'c'}
|
||||
if sys.maxsize > 2**32:
|
||||
# Build lapack-lite in 64-bit integer mode.
|
||||
# The suffix is arbitrary (lapack_lite symbols follow it),
|
||||
# but use the "64_" convention here.
|
||||
info['define_macros'] = [
|
||||
('HAVE_BLAS_ILP64', None),
|
||||
('BLAS_SYMBOL_SUFFIX', '64_')
|
||||
]
|
||||
self.set_info(**info)
|
||||
|
||||
lapack_info = numpy_linalg_lapack_lite().get_info(2)
|
||||
|
||||
def get_lapack_lite_sources(ext, build_dir):
|
||||
if use_lapack_lite:
|
||||
print("### Warning: Using unoptimized lapack ###")
|
||||
return all_sources
|
||||
else:
|
||||
if sys.platform == 'win32':
|
||||
print("### Warning: python_xerbla.c is disabled ###")
|
||||
return []
|
||||
return [all_sources[0]]
|
||||
|
||||
config.add_extension(
|
||||
'lapack_lite',
|
||||
sources=['lapack_litemodule.c', get_lapack_lite_sources],
|
||||
depends=['lapack_lite/f2c.h'],
|
||||
extra_info=lapack_info,
|
||||
)
|
||||
|
||||
# umath_linalg module
|
||||
config.add_extension(
|
||||
'_umath_linalg',
|
||||
sources=['umath_linalg.c.src', get_lapack_lite_sources],
|
||||
depends=['lapack_lite/f2c.h'],
|
||||
extra_info=lapack_info,
|
||||
libraries=['npymath'],
|
||||
)
|
||||
config.add_data_files('*.pyi')
|
||||
return config
|
||||
|
||||
if __name__ == '__main__':
|
||||
from numpy.distutils.core import setup
|
||||
setup(configuration=configuration)
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,53 @@
|
||||
from subprocess import PIPE, Popen
|
||||
import sys
|
||||
import re
|
||||
import pytest
|
||||
|
||||
from numpy.linalg import lapack_lite
|
||||
from numpy.testing import assert_
|
||||
|
||||
|
||||
class FindDependenciesLdd:
|
||||
|
||||
def __init__(self):
|
||||
self.cmd = ['ldd']
|
||||
|
||||
try:
|
||||
p = Popen(self.cmd, stdout=PIPE, stderr=PIPE)
|
||||
stdout, stderr = p.communicate()
|
||||
except OSError as e:
|
||||
raise RuntimeError(f'command {self.cmd} cannot be run') from e
|
||||
|
||||
def get_dependencies(self, lfile):
|
||||
p = Popen(self.cmd + [lfile], stdout=PIPE, stderr=PIPE)
|
||||
stdout, stderr = p.communicate()
|
||||
if not (p.returncode == 0):
|
||||
raise RuntimeError(f'failed dependencies check for {lfile}')
|
||||
|
||||
return stdout
|
||||
|
||||
def grep_dependencies(self, lfile, deps):
|
||||
stdout = self.get_dependencies(lfile)
|
||||
|
||||
rdeps = dict([(dep, re.compile(dep)) for dep in deps])
|
||||
founds = []
|
||||
for l in stdout.splitlines():
|
||||
for k, v in rdeps.items():
|
||||
if v.search(l):
|
||||
founds.append(k)
|
||||
|
||||
return founds
|
||||
|
||||
|
||||
class TestF77Mismatch:
|
||||
|
||||
@pytest.mark.skipif(not(sys.platform[:5] == 'linux'),
|
||||
reason="no fortran compiler on non-Linux platform")
|
||||
def test_lapack(self):
|
||||
f = FindDependenciesLdd()
|
||||
deps = f.grep_dependencies(lapack_lite.__file__,
|
||||
[b'libg2c', b'libgfortran'])
|
||||
assert_(len(deps) <= 1,
|
||||
"""Both g77 and gfortran runtimes linked in lapack_lite ! This is likely to
|
||||
cause random crashes and wrong results. See numpy INSTALL.txt for more
|
||||
information.""")
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Test deprecation and future warnings.
|
||||
|
||||
"""
|
||||
import numpy as np
|
||||
from numpy.testing import assert_warns
|
||||
|
||||
|
||||
def test_qr_mode_full_future_warning():
|
||||
"""Check mode='full' FutureWarning.
|
||||
|
||||
In numpy 1.8 the mode options 'full' and 'economic' in linalg.qr were
|
||||
deprecated. The release date will probably be sometime in the summer
|
||||
of 2013.
|
||||
|
||||
"""
|
||||
a = np.eye(2)
|
||||
assert_warns(DeprecationWarning, np.linalg.qr, a, mode='full')
|
||||
assert_warns(DeprecationWarning, np.linalg.qr, a, mode='f')
|
||||
assert_warns(DeprecationWarning, np.linalg.qr, a, mode='economic')
|
||||
assert_warns(DeprecationWarning, np.linalg.qr, a, mode='e')
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,148 @@
|
||||
""" Test functions for linalg module
|
||||
"""
|
||||
import warnings
|
||||
|
||||
import numpy as np
|
||||
from numpy import linalg, arange, float64, array, dot, transpose
|
||||
from numpy.testing import (
|
||||
assert_, assert_raises, assert_equal, assert_array_equal,
|
||||
assert_array_almost_equal, assert_array_less
|
||||
)
|
||||
|
||||
|
||||
class TestRegression:
|
||||
|
||||
def test_eig_build(self):
|
||||
# Ticket #652
|
||||
rva = array([1.03221168e+02 + 0.j,
|
||||
-1.91843603e+01 + 0.j,
|
||||
-6.04004526e-01 + 15.84422474j,
|
||||
-6.04004526e-01 - 15.84422474j,
|
||||
-1.13692929e+01 + 0.j,
|
||||
-6.57612485e-01 + 10.41755503j,
|
||||
-6.57612485e-01 - 10.41755503j,
|
||||
1.82126812e+01 + 0.j,
|
||||
1.06011014e+01 + 0.j,
|
||||
7.80732773e+00 + 0.j,
|
||||
-7.65390898e-01 + 0.j,
|
||||
1.51971555e-15 + 0.j,
|
||||
-1.51308713e-15 + 0.j])
|
||||
a = arange(13 * 13, dtype=float64)
|
||||
a.shape = (13, 13)
|
||||
a = a % 17
|
||||
va, ve = linalg.eig(a)
|
||||
va.sort()
|
||||
rva.sort()
|
||||
assert_array_almost_equal(va, rva)
|
||||
|
||||
def test_eigh_build(self):
|
||||
# Ticket 662.
|
||||
rvals = [68.60568999, 89.57756725, 106.67185574]
|
||||
|
||||
cov = array([[77.70273908, 3.51489954, 15.64602427],
|
||||
[3.51489954, 88.97013878, -1.07431931],
|
||||
[15.64602427, -1.07431931, 98.18223512]])
|
||||
|
||||
vals, vecs = linalg.eigh(cov)
|
||||
assert_array_almost_equal(vals, rvals)
|
||||
|
||||
def test_svd_build(self):
|
||||
# Ticket 627.
|
||||
a = array([[0., 1.], [1., 1.], [2., 1.], [3., 1.]])
|
||||
m, n = a.shape
|
||||
u, s, vh = linalg.svd(a)
|
||||
|
||||
b = dot(transpose(u[:, n:]), a)
|
||||
|
||||
assert_array_almost_equal(b, np.zeros((2, 2)))
|
||||
|
||||
def test_norm_vector_badarg(self):
|
||||
# Regression for #786: Frobenius norm for vectors raises
|
||||
# ValueError.
|
||||
assert_raises(ValueError, linalg.norm, array([1., 2., 3.]), 'fro')
|
||||
|
||||
def test_lapack_endian(self):
|
||||
# For bug #1482
|
||||
a = array([[5.7998084, -2.1825367],
|
||||
[-2.1825367, 9.85910595]], dtype='>f8')
|
||||
b = array(a, dtype='<f8')
|
||||
|
||||
ap = linalg.cholesky(a)
|
||||
bp = linalg.cholesky(b)
|
||||
assert_array_equal(ap, bp)
|
||||
|
||||
def test_large_svd_32bit(self):
|
||||
# See gh-4442, 64bit would require very large/slow matrices.
|
||||
x = np.eye(1000, 66)
|
||||
np.linalg.svd(x)
|
||||
|
||||
def test_svd_no_uv(self):
|
||||
# gh-4733
|
||||
for shape in (3, 4), (4, 4), (4, 3):
|
||||
for t in float, complex:
|
||||
a = np.ones(shape, dtype=t)
|
||||
w = linalg.svd(a, compute_uv=False)
|
||||
c = np.count_nonzero(np.absolute(w) > 0.5)
|
||||
assert_equal(c, 1)
|
||||
assert_equal(np.linalg.matrix_rank(a), 1)
|
||||
assert_array_less(1, np.linalg.norm(a, ord=2))
|
||||
|
||||
def test_norm_object_array(self):
|
||||
# gh-7575
|
||||
testvector = np.array([np.array([0, 1]), 0, 0], dtype=object)
|
||||
|
||||
norm = linalg.norm(testvector)
|
||||
assert_array_equal(norm, [0, 1])
|
||||
assert_(norm.dtype == np.dtype('float64'))
|
||||
|
||||
norm = linalg.norm(testvector, ord=1)
|
||||
assert_array_equal(norm, [0, 1])
|
||||
assert_(norm.dtype != np.dtype('float64'))
|
||||
|
||||
norm = linalg.norm(testvector, ord=2)
|
||||
assert_array_equal(norm, [0, 1])
|
||||
assert_(norm.dtype == np.dtype('float64'))
|
||||
|
||||
assert_raises(ValueError, linalg.norm, testvector, ord='fro')
|
||||
assert_raises(ValueError, linalg.norm, testvector, ord='nuc')
|
||||
assert_raises(ValueError, linalg.norm, testvector, ord=np.inf)
|
||||
assert_raises(ValueError, linalg.norm, testvector, ord=-np.inf)
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", DeprecationWarning)
|
||||
assert_raises((AttributeError, DeprecationWarning),
|
||||
linalg.norm, testvector, ord=0)
|
||||
assert_raises(ValueError, linalg.norm, testvector, ord=-1)
|
||||
assert_raises(ValueError, linalg.norm, testvector, ord=-2)
|
||||
|
||||
testmatrix = np.array([[np.array([0, 1]), 0, 0],
|
||||
[0, 0, 0]], dtype=object)
|
||||
|
||||
norm = linalg.norm(testmatrix)
|
||||
assert_array_equal(norm, [0, 1])
|
||||
assert_(norm.dtype == np.dtype('float64'))
|
||||
|
||||
norm = linalg.norm(testmatrix, ord='fro')
|
||||
assert_array_equal(norm, [0, 1])
|
||||
assert_(norm.dtype == np.dtype('float64'))
|
||||
|
||||
assert_raises(TypeError, linalg.norm, testmatrix, ord='nuc')
|
||||
assert_raises(ValueError, linalg.norm, testmatrix, ord=np.inf)
|
||||
assert_raises(ValueError, linalg.norm, testmatrix, ord=-np.inf)
|
||||
assert_raises(ValueError, linalg.norm, testmatrix, ord=0)
|
||||
assert_raises(ValueError, linalg.norm, testmatrix, ord=1)
|
||||
assert_raises(ValueError, linalg.norm, testmatrix, ord=-1)
|
||||
assert_raises(TypeError, linalg.norm, testmatrix, ord=2)
|
||||
assert_raises(TypeError, linalg.norm, testmatrix, ord=-2)
|
||||
assert_raises(ValueError, linalg.norm, testmatrix, ord=3)
|
||||
|
||||
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)
|
||||
Reference in New Issue
Block a user