Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step40/zero/10.mlp.dense_h_to_4h.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step40/zero/10.mlp.dense_h_to_4h.weight/fp32.pt +3 -0
- ckpts/universal/global_step40/zero/12.attention.dense.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step40/zero/12.attention.dense.weight/fp32.pt +3 -0
- ckpts/universal/global_step40/zero/14.post_attention_layernorm.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step40/zero/14.post_attention_layernorm.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step40/zero/14.post_attention_layernorm.weight/fp32.pt +3 -0
- ckpts/universal/global_step40/zero/9.attention.dense.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step40/zero/9.attention.dense.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test__datasource.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test__iotools.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test__version.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_arraypad.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_arraysetops.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_arrayterator.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_financial_expired.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_format.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_function_base.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_histograms.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_index_tricks.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_io.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_loadtxt.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_mixins.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_nanfunctions.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_packbits.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_polynomial.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_recfunctions.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_regression.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_shape_base.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_stride_tricks.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_twodim_base.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_type_check.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_ufunclike.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_utils.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/test__datasource.py +350 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/test__iotools.py +353 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/test_arraysetops.py +944 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/test_arrayterator.py +46 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/test_recfunctions.py +1043 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/test_stride_tricks.py +645 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/test_twodim_base.py +541 -0
- venv/lib/python3.10/site-packages/numpy/lib/tests/test_type_check.py +478 -0
- venv/lib/python3.10/site-packages/numpy/polynomial/__init__.py +185 -0
- venv/lib/python3.10/site-packages/numpy/polynomial/__init__.pyi +22 -0
- venv/lib/python3.10/site-packages/numpy/polynomial/_polybase.py +1206 -0
- venv/lib/python3.10/site-packages/numpy/polynomial/_polybase.pyi +71 -0
- venv/lib/python3.10/site-packages/numpy/polynomial/chebyshev.py +2082 -0
- venv/lib/python3.10/site-packages/numpy/polynomial/chebyshev.pyi +51 -0
ckpts/universal/global_step40/zero/10.mlp.dense_h_to_4h.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:07668e3c736ed7aee870347fca555aa27e3e5a06ef1f6b53f324bdb7448b7471
|
3 |
+
size 33555612
|
ckpts/universal/global_step40/zero/10.mlp.dense_h_to_4h.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ec5da508486f706dc14540d9d806bf4295bae6a35ef889438cfc2213d13137e0
|
3 |
+
size 33555533
|
ckpts/universal/global_step40/zero/12.attention.dense.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:69eb65755a49e34601e44dfdee33d5bb2bdb89d9202b41cf33ee53bedd7006ba
|
3 |
+
size 16778396
|
ckpts/universal/global_step40/zero/12.attention.dense.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:879afdd7645f14ea4414233174081716cc2ad3a6ebe0f1e7b3407dcf83e1e060
|
3 |
+
size 16778317
|
ckpts/universal/global_step40/zero/14.post_attention_layernorm.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:503b302db904b251c1af1fdf78675b9c3a05a877edd1d41c361ede0e8747f1c0
|
3 |
+
size 9372
|
ckpts/universal/global_step40/zero/14.post_attention_layernorm.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:aabf39d0bc93dc514cb482dec68214e56a5a73e1c826ad7f4018c093fa26e0d4
|
3 |
+
size 9387
|
ckpts/universal/global_step40/zero/14.post_attention_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3c1d8bf442df2ada37b258ba5a0661fd6b591920a880d29b9d268557f78387e3
|
3 |
+
size 9293
|
ckpts/universal/global_step40/zero/9.attention.dense.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:27380bef40fcbcbbb692a3afd6ead11c83757b56aa28b33ad12cd84aad5eb77e
|
3 |
+
size 16778396
|
ckpts/universal/global_step40/zero/9.attention.dense.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bcac54f2919489c1db2ea365a871abfc284a0413ea41beabf4d9eda7ee8ab422
|
3 |
+
size 16778317
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (183 Bytes). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test__datasource.cpython-310.pyc
ADDED
Binary file (12.4 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test__iotools.cpython-310.pyc
ADDED
Binary file (11.3 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test__version.cpython-310.pyc
ADDED
Binary file (2.21 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_arraypad.cpython-310.pyc
ADDED
Binary file (47.1 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_arraysetops.cpython-310.pyc
ADDED
Binary file (25.5 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_arrayterator.cpython-310.pyc
ADDED
Binary file (1.64 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_financial_expired.cpython-310.pyc
ADDED
Binary file (596 Bytes). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_format.cpython-310.pyc
ADDED
Binary file (36.1 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_function_base.cpython-310.pyc
ADDED
Binary file (143 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_histograms.cpython-310.pyc
ADDED
Binary file (28.9 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_index_tricks.cpython-310.pyc
ADDED
Binary file (19.6 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_io.cpython-310.pyc
ADDED
Binary file (96.5 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_loadtxt.cpython-310.pyc
ADDED
Binary file (37.6 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_mixins.cpython-310.pyc
ADDED
Binary file (7.46 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_nanfunctions.cpython-310.pyc
ADDED
Binary file (40.8 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_packbits.cpython-310.pyc
ADDED
Binary file (14.3 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_polynomial.cpython-310.pyc
ADDED
Binary file (10.5 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_recfunctions.cpython-310.pyc
ADDED
Binary file (32.1 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_regression.cpython-310.pyc
ADDED
Binary file (10.3 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_shape_base.cpython-310.pyc
ADDED
Binary file (30.2 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_stride_tricks.cpython-310.pyc
ADDED
Binary file (16.5 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_twodim_base.cpython-310.pyc
ADDED
Binary file (18.1 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_type_check.cpython-310.pyc
ADDED
Binary file (16.8 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_ufunclike.cpython-310.pyc
ADDED
Binary file (3.46 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_utils.cpython-310.pyc
ADDED
Binary file (7.39 kB). View file
|
|
venv/lib/python3.10/site-packages/numpy/lib/tests/test__datasource.py
ADDED
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import pytest
|
3 |
+
from tempfile import mkdtemp, mkstemp, NamedTemporaryFile
|
4 |
+
from shutil import rmtree
|
5 |
+
|
6 |
+
import numpy.lib._datasource as datasource
|
7 |
+
from numpy.testing import assert_, assert_equal, assert_raises
|
8 |
+
|
9 |
+
import urllib.request as urllib_request
|
10 |
+
from urllib.parse import urlparse
|
11 |
+
from urllib.error import URLError
|
12 |
+
|
13 |
+
|
14 |
+
def urlopen_stub(url, data=None):
|
15 |
+
'''Stub to replace urlopen for testing.'''
|
16 |
+
if url == valid_httpurl():
|
17 |
+
tmpfile = NamedTemporaryFile(prefix='urltmp_')
|
18 |
+
return tmpfile
|
19 |
+
else:
|
20 |
+
raise URLError('Name or service not known')
|
21 |
+
|
22 |
+
# setup and teardown
|
23 |
+
old_urlopen = None
|
24 |
+
|
25 |
+
|
26 |
+
def setup_module():
|
27 |
+
global old_urlopen
|
28 |
+
|
29 |
+
old_urlopen = urllib_request.urlopen
|
30 |
+
urllib_request.urlopen = urlopen_stub
|
31 |
+
|
32 |
+
|
33 |
+
def teardown_module():
|
34 |
+
urllib_request.urlopen = old_urlopen
|
35 |
+
|
36 |
+
# A valid website for more robust testing
|
37 |
+
http_path = 'http://www.google.com/'
|
38 |
+
http_file = 'index.html'
|
39 |
+
|
40 |
+
http_fakepath = 'http://fake.abc.web/site/'
|
41 |
+
http_fakefile = 'fake.txt'
|
42 |
+
|
43 |
+
malicious_files = ['/etc/shadow', '../../shadow',
|
44 |
+
'..\\system.dat', 'c:\\windows\\system.dat']
|
45 |
+
|
46 |
+
magic_line = b'three is the magic number'
|
47 |
+
|
48 |
+
|
49 |
+
# Utility functions used by many tests
|
50 |
+
def valid_textfile(filedir):
|
51 |
+
# Generate and return a valid temporary file.
|
52 |
+
fd, path = mkstemp(suffix='.txt', prefix='dstmp_', dir=filedir, text=True)
|
53 |
+
os.close(fd)
|
54 |
+
return path
|
55 |
+
|
56 |
+
|
57 |
+
def invalid_textfile(filedir):
|
58 |
+
# Generate and return an invalid filename.
|
59 |
+
fd, path = mkstemp(suffix='.txt', prefix='dstmp_', dir=filedir)
|
60 |
+
os.close(fd)
|
61 |
+
os.remove(path)
|
62 |
+
return path
|
63 |
+
|
64 |
+
|
65 |
+
def valid_httpurl():
|
66 |
+
return http_path+http_file
|
67 |
+
|
68 |
+
|
69 |
+
def invalid_httpurl():
|
70 |
+
return http_fakepath+http_fakefile
|
71 |
+
|
72 |
+
|
73 |
+
def valid_baseurl():
|
74 |
+
return http_path
|
75 |
+
|
76 |
+
|
77 |
+
def invalid_baseurl():
|
78 |
+
return http_fakepath
|
79 |
+
|
80 |
+
|
81 |
+
def valid_httpfile():
|
82 |
+
return http_file
|
83 |
+
|
84 |
+
|
85 |
+
def invalid_httpfile():
|
86 |
+
return http_fakefile
|
87 |
+
|
88 |
+
|
89 |
+
class TestDataSourceOpen:
|
90 |
+
def setup_method(self):
|
91 |
+
self.tmpdir = mkdtemp()
|
92 |
+
self.ds = datasource.DataSource(self.tmpdir)
|
93 |
+
|
94 |
+
def teardown_method(self):
|
95 |
+
rmtree(self.tmpdir)
|
96 |
+
del self.ds
|
97 |
+
|
98 |
+
def test_ValidHTTP(self):
|
99 |
+
fh = self.ds.open(valid_httpurl())
|
100 |
+
assert_(fh)
|
101 |
+
fh.close()
|
102 |
+
|
103 |
+
def test_InvalidHTTP(self):
|
104 |
+
url = invalid_httpurl()
|
105 |
+
assert_raises(OSError, self.ds.open, url)
|
106 |
+
try:
|
107 |
+
self.ds.open(url)
|
108 |
+
except OSError as e:
|
109 |
+
# Regression test for bug fixed in r4342.
|
110 |
+
assert_(e.errno is None)
|
111 |
+
|
112 |
+
def test_InvalidHTTPCacheURLError(self):
|
113 |
+
assert_raises(URLError, self.ds._cache, invalid_httpurl())
|
114 |
+
|
115 |
+
def test_ValidFile(self):
|
116 |
+
local_file = valid_textfile(self.tmpdir)
|
117 |
+
fh = self.ds.open(local_file)
|
118 |
+
assert_(fh)
|
119 |
+
fh.close()
|
120 |
+
|
121 |
+
def test_InvalidFile(self):
|
122 |
+
invalid_file = invalid_textfile(self.tmpdir)
|
123 |
+
assert_raises(OSError, self.ds.open, invalid_file)
|
124 |
+
|
125 |
+
def test_ValidGzipFile(self):
|
126 |
+
try:
|
127 |
+
import gzip
|
128 |
+
except ImportError:
|
129 |
+
# We don't have the gzip capabilities to test.
|
130 |
+
pytest.skip()
|
131 |
+
# Test datasource's internal file_opener for Gzip files.
|
132 |
+
filepath = os.path.join(self.tmpdir, 'foobar.txt.gz')
|
133 |
+
fp = gzip.open(filepath, 'w')
|
134 |
+
fp.write(magic_line)
|
135 |
+
fp.close()
|
136 |
+
fp = self.ds.open(filepath)
|
137 |
+
result = fp.readline()
|
138 |
+
fp.close()
|
139 |
+
assert_equal(magic_line, result)
|
140 |
+
|
141 |
+
def test_ValidBz2File(self):
|
142 |
+
try:
|
143 |
+
import bz2
|
144 |
+
except ImportError:
|
145 |
+
# We don't have the bz2 capabilities to test.
|
146 |
+
pytest.skip()
|
147 |
+
# Test datasource's internal file_opener for BZip2 files.
|
148 |
+
filepath = os.path.join(self.tmpdir, 'foobar.txt.bz2')
|
149 |
+
fp = bz2.BZ2File(filepath, 'w')
|
150 |
+
fp.write(magic_line)
|
151 |
+
fp.close()
|
152 |
+
fp = self.ds.open(filepath)
|
153 |
+
result = fp.readline()
|
154 |
+
fp.close()
|
155 |
+
assert_equal(magic_line, result)
|
156 |
+
|
157 |
+
|
158 |
+
class TestDataSourceExists:
|
159 |
+
def setup_method(self):
|
160 |
+
self.tmpdir = mkdtemp()
|
161 |
+
self.ds = datasource.DataSource(self.tmpdir)
|
162 |
+
|
163 |
+
def teardown_method(self):
|
164 |
+
rmtree(self.tmpdir)
|
165 |
+
del self.ds
|
166 |
+
|
167 |
+
def test_ValidHTTP(self):
|
168 |
+
assert_(self.ds.exists(valid_httpurl()))
|
169 |
+
|
170 |
+
def test_InvalidHTTP(self):
|
171 |
+
assert_equal(self.ds.exists(invalid_httpurl()), False)
|
172 |
+
|
173 |
+
def test_ValidFile(self):
|
174 |
+
# Test valid file in destpath
|
175 |
+
tmpfile = valid_textfile(self.tmpdir)
|
176 |
+
assert_(self.ds.exists(tmpfile))
|
177 |
+
# Test valid local file not in destpath
|
178 |
+
localdir = mkdtemp()
|
179 |
+
tmpfile = valid_textfile(localdir)
|
180 |
+
assert_(self.ds.exists(tmpfile))
|
181 |
+
rmtree(localdir)
|
182 |
+
|
183 |
+
def test_InvalidFile(self):
|
184 |
+
tmpfile = invalid_textfile(self.tmpdir)
|
185 |
+
assert_equal(self.ds.exists(tmpfile), False)
|
186 |
+
|
187 |
+
|
188 |
+
class TestDataSourceAbspath:
|
189 |
+
def setup_method(self):
|
190 |
+
self.tmpdir = os.path.abspath(mkdtemp())
|
191 |
+
self.ds = datasource.DataSource(self.tmpdir)
|
192 |
+
|
193 |
+
def teardown_method(self):
|
194 |
+
rmtree(self.tmpdir)
|
195 |
+
del self.ds
|
196 |
+
|
197 |
+
def test_ValidHTTP(self):
|
198 |
+
scheme, netloc, upath, pms, qry, frg = urlparse(valid_httpurl())
|
199 |
+
local_path = os.path.join(self.tmpdir, netloc,
|
200 |
+
upath.strip(os.sep).strip('/'))
|
201 |
+
assert_equal(local_path, self.ds.abspath(valid_httpurl()))
|
202 |
+
|
203 |
+
def test_ValidFile(self):
|
204 |
+
tmpfile = valid_textfile(self.tmpdir)
|
205 |
+
tmpfilename = os.path.split(tmpfile)[-1]
|
206 |
+
# Test with filename only
|
207 |
+
assert_equal(tmpfile, self.ds.abspath(tmpfilename))
|
208 |
+
# Test filename with complete path
|
209 |
+
assert_equal(tmpfile, self.ds.abspath(tmpfile))
|
210 |
+
|
211 |
+
def test_InvalidHTTP(self):
|
212 |
+
scheme, netloc, upath, pms, qry, frg = urlparse(invalid_httpurl())
|
213 |
+
invalidhttp = os.path.join(self.tmpdir, netloc,
|
214 |
+
upath.strip(os.sep).strip('/'))
|
215 |
+
assert_(invalidhttp != self.ds.abspath(valid_httpurl()))
|
216 |
+
|
217 |
+
def test_InvalidFile(self):
|
218 |
+
invalidfile = valid_textfile(self.tmpdir)
|
219 |
+
tmpfile = valid_textfile(self.tmpdir)
|
220 |
+
tmpfilename = os.path.split(tmpfile)[-1]
|
221 |
+
# Test with filename only
|
222 |
+
assert_(invalidfile != self.ds.abspath(tmpfilename))
|
223 |
+
# Test filename with complete path
|
224 |
+
assert_(invalidfile != self.ds.abspath(tmpfile))
|
225 |
+
|
226 |
+
def test_sandboxing(self):
|
227 |
+
tmpfile = valid_textfile(self.tmpdir)
|
228 |
+
tmpfilename = os.path.split(tmpfile)[-1]
|
229 |
+
|
230 |
+
tmp_path = lambda x: os.path.abspath(self.ds.abspath(x))
|
231 |
+
|
232 |
+
assert_(tmp_path(valid_httpurl()).startswith(self.tmpdir))
|
233 |
+
assert_(tmp_path(invalid_httpurl()).startswith(self.tmpdir))
|
234 |
+
assert_(tmp_path(tmpfile).startswith(self.tmpdir))
|
235 |
+
assert_(tmp_path(tmpfilename).startswith(self.tmpdir))
|
236 |
+
for fn in malicious_files:
|
237 |
+
assert_(tmp_path(http_path+fn).startswith(self.tmpdir))
|
238 |
+
assert_(tmp_path(fn).startswith(self.tmpdir))
|
239 |
+
|
240 |
+
def test_windows_os_sep(self):
|
241 |
+
orig_os_sep = os.sep
|
242 |
+
try:
|
243 |
+
os.sep = '\\'
|
244 |
+
self.test_ValidHTTP()
|
245 |
+
self.test_ValidFile()
|
246 |
+
self.test_InvalidHTTP()
|
247 |
+
self.test_InvalidFile()
|
248 |
+
self.test_sandboxing()
|
249 |
+
finally:
|
250 |
+
os.sep = orig_os_sep
|
251 |
+
|
252 |
+
|
253 |
+
class TestRepositoryAbspath:
|
254 |
+
def setup_method(self):
|
255 |
+
self.tmpdir = os.path.abspath(mkdtemp())
|
256 |
+
self.repos = datasource.Repository(valid_baseurl(), self.tmpdir)
|
257 |
+
|
258 |
+
def teardown_method(self):
|
259 |
+
rmtree(self.tmpdir)
|
260 |
+
del self.repos
|
261 |
+
|
262 |
+
def test_ValidHTTP(self):
|
263 |
+
scheme, netloc, upath, pms, qry, frg = urlparse(valid_httpurl())
|
264 |
+
local_path = os.path.join(self.repos._destpath, netloc,
|
265 |
+
upath.strip(os.sep).strip('/'))
|
266 |
+
filepath = self.repos.abspath(valid_httpfile())
|
267 |
+
assert_equal(local_path, filepath)
|
268 |
+
|
269 |
+
def test_sandboxing(self):
|
270 |
+
tmp_path = lambda x: os.path.abspath(self.repos.abspath(x))
|
271 |
+
assert_(tmp_path(valid_httpfile()).startswith(self.tmpdir))
|
272 |
+
for fn in malicious_files:
|
273 |
+
assert_(tmp_path(http_path+fn).startswith(self.tmpdir))
|
274 |
+
assert_(tmp_path(fn).startswith(self.tmpdir))
|
275 |
+
|
276 |
+
def test_windows_os_sep(self):
|
277 |
+
orig_os_sep = os.sep
|
278 |
+
try:
|
279 |
+
os.sep = '\\'
|
280 |
+
self.test_ValidHTTP()
|
281 |
+
self.test_sandboxing()
|
282 |
+
finally:
|
283 |
+
os.sep = orig_os_sep
|
284 |
+
|
285 |
+
|
286 |
+
class TestRepositoryExists:
|
287 |
+
def setup_method(self):
|
288 |
+
self.tmpdir = mkdtemp()
|
289 |
+
self.repos = datasource.Repository(valid_baseurl(), self.tmpdir)
|
290 |
+
|
291 |
+
def teardown_method(self):
|
292 |
+
rmtree(self.tmpdir)
|
293 |
+
del self.repos
|
294 |
+
|
295 |
+
def test_ValidFile(self):
|
296 |
+
# Create local temp file
|
297 |
+
tmpfile = valid_textfile(self.tmpdir)
|
298 |
+
assert_(self.repos.exists(tmpfile))
|
299 |
+
|
300 |
+
def test_InvalidFile(self):
|
301 |
+
tmpfile = invalid_textfile(self.tmpdir)
|
302 |
+
assert_equal(self.repos.exists(tmpfile), False)
|
303 |
+
|
304 |
+
def test_RemoveHTTPFile(self):
|
305 |
+
assert_(self.repos.exists(valid_httpurl()))
|
306 |
+
|
307 |
+
def test_CachedHTTPFile(self):
|
308 |
+
localfile = valid_httpurl()
|
309 |
+
# Create a locally cached temp file with an URL based
|
310 |
+
# directory structure. This is similar to what Repository.open
|
311 |
+
# would do.
|
312 |
+
scheme, netloc, upath, pms, qry, frg = urlparse(localfile)
|
313 |
+
local_path = os.path.join(self.repos._destpath, netloc)
|
314 |
+
os.mkdir(local_path, 0o0700)
|
315 |
+
tmpfile = valid_textfile(local_path)
|
316 |
+
assert_(self.repos.exists(tmpfile))
|
317 |
+
|
318 |
+
|
319 |
+
class TestOpenFunc:
|
320 |
+
def setup_method(self):
|
321 |
+
self.tmpdir = mkdtemp()
|
322 |
+
|
323 |
+
def teardown_method(self):
|
324 |
+
rmtree(self.tmpdir)
|
325 |
+
|
326 |
+
def test_DataSourceOpen(self):
|
327 |
+
local_file = valid_textfile(self.tmpdir)
|
328 |
+
# Test case where destpath is passed in
|
329 |
+
fp = datasource.open(local_file, destpath=self.tmpdir)
|
330 |
+
assert_(fp)
|
331 |
+
fp.close()
|
332 |
+
# Test case where default destpath is used
|
333 |
+
fp = datasource.open(local_file)
|
334 |
+
assert_(fp)
|
335 |
+
fp.close()
|
336 |
+
|
337 |
+
def test_del_attr_handling():
|
338 |
+
# DataSource __del__ can be called
|
339 |
+
# even if __init__ fails when the
|
340 |
+
# Exception object is caught by the
|
341 |
+
# caller as happens in refguide_check
|
342 |
+
# is_deprecated() function
|
343 |
+
|
344 |
+
ds = datasource.DataSource()
|
345 |
+
# simulate failed __init__ by removing key attribute
|
346 |
+
# produced within __init__ and expected by __del__
|
347 |
+
del ds._istmpdest
|
348 |
+
# should not raise an AttributeError if __del__
|
349 |
+
# gracefully handles failed __init__:
|
350 |
+
ds.__del__()
|
venv/lib/python3.10/site-packages/numpy/lib/tests/test__iotools.py
ADDED
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import time
|
2 |
+
from datetime import date
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
from numpy.testing import (
|
6 |
+
assert_, assert_equal, assert_allclose, assert_raises,
|
7 |
+
)
|
8 |
+
from numpy.lib._iotools import (
|
9 |
+
LineSplitter, NameValidator, StringConverter,
|
10 |
+
has_nested_fields, easy_dtype, flatten_dtype
|
11 |
+
)
|
12 |
+
|
13 |
+
|
14 |
+
class TestLineSplitter:
|
15 |
+
"Tests the LineSplitter class."
|
16 |
+
|
17 |
+
def test_no_delimiter(self):
|
18 |
+
"Test LineSplitter w/o delimiter"
|
19 |
+
strg = " 1 2 3 4 5 # test"
|
20 |
+
test = LineSplitter()(strg)
|
21 |
+
assert_equal(test, ['1', '2', '3', '4', '5'])
|
22 |
+
test = LineSplitter('')(strg)
|
23 |
+
assert_equal(test, ['1', '2', '3', '4', '5'])
|
24 |
+
|
25 |
+
def test_space_delimiter(self):
|
26 |
+
"Test space delimiter"
|
27 |
+
strg = " 1 2 3 4 5 # test"
|
28 |
+
test = LineSplitter(' ')(strg)
|
29 |
+
assert_equal(test, ['1', '2', '3', '4', '', '5'])
|
30 |
+
test = LineSplitter(' ')(strg)
|
31 |
+
assert_equal(test, ['1 2 3 4', '5'])
|
32 |
+
|
33 |
+
def test_tab_delimiter(self):
|
34 |
+
"Test tab delimiter"
|
35 |
+
strg = " 1\t 2\t 3\t 4\t 5 6"
|
36 |
+
test = LineSplitter('\t')(strg)
|
37 |
+
assert_equal(test, ['1', '2', '3', '4', '5 6'])
|
38 |
+
strg = " 1 2\t 3 4\t 5 6"
|
39 |
+
test = LineSplitter('\t')(strg)
|
40 |
+
assert_equal(test, ['1 2', '3 4', '5 6'])
|
41 |
+
|
42 |
+
def test_other_delimiter(self):
|
43 |
+
"Test LineSplitter on delimiter"
|
44 |
+
strg = "1,2,3,4,,5"
|
45 |
+
test = LineSplitter(',')(strg)
|
46 |
+
assert_equal(test, ['1', '2', '3', '4', '', '5'])
|
47 |
+
#
|
48 |
+
strg = " 1,2,3,4,,5 # test"
|
49 |
+
test = LineSplitter(',')(strg)
|
50 |
+
assert_equal(test, ['1', '2', '3', '4', '', '5'])
|
51 |
+
|
52 |
+
# gh-11028 bytes comment/delimiters should get encoded
|
53 |
+
strg = b" 1,2,3,4,,5 % test"
|
54 |
+
test = LineSplitter(delimiter=b',', comments=b'%')(strg)
|
55 |
+
assert_equal(test, ['1', '2', '3', '4', '', '5'])
|
56 |
+
|
57 |
+
def test_constant_fixed_width(self):
|
58 |
+
"Test LineSplitter w/ fixed-width fields"
|
59 |
+
strg = " 1 2 3 4 5 # test"
|
60 |
+
test = LineSplitter(3)(strg)
|
61 |
+
assert_equal(test, ['1', '2', '3', '4', '', '5', ''])
|
62 |
+
#
|
63 |
+
strg = " 1 3 4 5 6# test"
|
64 |
+
test = LineSplitter(20)(strg)
|
65 |
+
assert_equal(test, ['1 3 4 5 6'])
|
66 |
+
#
|
67 |
+
strg = " 1 3 4 5 6# test"
|
68 |
+
test = LineSplitter(30)(strg)
|
69 |
+
assert_equal(test, ['1 3 4 5 6'])
|
70 |
+
|
71 |
+
def test_variable_fixed_width(self):
|
72 |
+
strg = " 1 3 4 5 6# test"
|
73 |
+
test = LineSplitter((3, 6, 6, 3))(strg)
|
74 |
+
assert_equal(test, ['1', '3', '4 5', '6'])
|
75 |
+
#
|
76 |
+
strg = " 1 3 4 5 6# test"
|
77 |
+
test = LineSplitter((6, 6, 9))(strg)
|
78 |
+
assert_equal(test, ['1', '3 4', '5 6'])
|
79 |
+
|
80 |
+
# -----------------------------------------------------------------------------
|
81 |
+
|
82 |
+
|
83 |
+
class TestNameValidator:
|
84 |
+
|
85 |
+
def test_case_sensitivity(self):
|
86 |
+
"Test case sensitivity"
|
87 |
+
names = ['A', 'a', 'b', 'c']
|
88 |
+
test = NameValidator().validate(names)
|
89 |
+
assert_equal(test, ['A', 'a', 'b', 'c'])
|
90 |
+
test = NameValidator(case_sensitive=False).validate(names)
|
91 |
+
assert_equal(test, ['A', 'A_1', 'B', 'C'])
|
92 |
+
test = NameValidator(case_sensitive='upper').validate(names)
|
93 |
+
assert_equal(test, ['A', 'A_1', 'B', 'C'])
|
94 |
+
test = NameValidator(case_sensitive='lower').validate(names)
|
95 |
+
assert_equal(test, ['a', 'a_1', 'b', 'c'])
|
96 |
+
|
97 |
+
# check exceptions
|
98 |
+
assert_raises(ValueError, NameValidator, case_sensitive='foobar')
|
99 |
+
|
100 |
+
def test_excludelist(self):
|
101 |
+
"Test excludelist"
|
102 |
+
names = ['dates', 'data', 'Other Data', 'mask']
|
103 |
+
validator = NameValidator(excludelist=['dates', 'data', 'mask'])
|
104 |
+
test = validator.validate(names)
|
105 |
+
assert_equal(test, ['dates_', 'data_', 'Other_Data', 'mask_'])
|
106 |
+
|
107 |
+
def test_missing_names(self):
|
108 |
+
"Test validate missing names"
|
109 |
+
namelist = ('a', 'b', 'c')
|
110 |
+
validator = NameValidator()
|
111 |
+
assert_equal(validator(namelist), ['a', 'b', 'c'])
|
112 |
+
namelist = ('', 'b', 'c')
|
113 |
+
assert_equal(validator(namelist), ['f0', 'b', 'c'])
|
114 |
+
namelist = ('a', 'b', '')
|
115 |
+
assert_equal(validator(namelist), ['a', 'b', 'f0'])
|
116 |
+
namelist = ('', 'f0', '')
|
117 |
+
assert_equal(validator(namelist), ['f1', 'f0', 'f2'])
|
118 |
+
|
119 |
+
def test_validate_nb_names(self):
|
120 |
+
"Test validate nb names"
|
121 |
+
namelist = ('a', 'b', 'c')
|
122 |
+
validator = NameValidator()
|
123 |
+
assert_equal(validator(namelist, nbfields=1), ('a',))
|
124 |
+
assert_equal(validator(namelist, nbfields=5, defaultfmt="g%i"),
|
125 |
+
['a', 'b', 'c', 'g0', 'g1'])
|
126 |
+
|
127 |
+
def test_validate_wo_names(self):
|
128 |
+
"Test validate no names"
|
129 |
+
namelist = None
|
130 |
+
validator = NameValidator()
|
131 |
+
assert_(validator(namelist) is None)
|
132 |
+
assert_equal(validator(namelist, nbfields=3), ['f0', 'f1', 'f2'])
|
133 |
+
|
134 |
+
# -----------------------------------------------------------------------------
|
135 |
+
|
136 |
+
|
137 |
+
def _bytes_to_date(s):
|
138 |
+
return date(*time.strptime(s, "%Y-%m-%d")[:3])
|
139 |
+
|
140 |
+
|
141 |
+
class TestStringConverter:
|
142 |
+
"Test StringConverter"
|
143 |
+
|
144 |
+
def test_creation(self):
|
145 |
+
"Test creation of a StringConverter"
|
146 |
+
converter = StringConverter(int, -99999)
|
147 |
+
assert_equal(converter._status, 1)
|
148 |
+
assert_equal(converter.default, -99999)
|
149 |
+
|
150 |
+
def test_upgrade(self):
|
151 |
+
"Tests the upgrade method."
|
152 |
+
|
153 |
+
converter = StringConverter()
|
154 |
+
assert_equal(converter._status, 0)
|
155 |
+
|
156 |
+
# test int
|
157 |
+
assert_equal(converter.upgrade('0'), 0)
|
158 |
+
assert_equal(converter._status, 1)
|
159 |
+
|
160 |
+
# On systems where long defaults to 32-bit, the statuses will be
|
161 |
+
# offset by one, so we check for this here.
|
162 |
+
import numpy.core.numeric as nx
|
163 |
+
status_offset = int(nx.dtype(nx.int_).itemsize < nx.dtype(nx.int64).itemsize)
|
164 |
+
|
165 |
+
# test int > 2**32
|
166 |
+
assert_equal(converter.upgrade('17179869184'), 17179869184)
|
167 |
+
assert_equal(converter._status, 1 + status_offset)
|
168 |
+
|
169 |
+
# test float
|
170 |
+
assert_allclose(converter.upgrade('0.'), 0.0)
|
171 |
+
assert_equal(converter._status, 2 + status_offset)
|
172 |
+
|
173 |
+
# test complex
|
174 |
+
assert_equal(converter.upgrade('0j'), complex('0j'))
|
175 |
+
assert_equal(converter._status, 3 + status_offset)
|
176 |
+
|
177 |
+
# test str
|
178 |
+
# note that the longdouble type has been skipped, so the
|
179 |
+
# _status increases by 2. Everything should succeed with
|
180 |
+
# unicode conversion (8).
|
181 |
+
for s in ['a', b'a']:
|
182 |
+
res = converter.upgrade(s)
|
183 |
+
assert_(type(res) is str)
|
184 |
+
assert_equal(res, 'a')
|
185 |
+
assert_equal(converter._status, 8 + status_offset)
|
186 |
+
|
187 |
+
def test_missing(self):
|
188 |
+
"Tests the use of missing values."
|
189 |
+
converter = StringConverter(missing_values=('missing',
|
190 |
+
'missed'))
|
191 |
+
converter.upgrade('0')
|
192 |
+
assert_equal(converter('0'), 0)
|
193 |
+
assert_equal(converter(''), converter.default)
|
194 |
+
assert_equal(converter('missing'), converter.default)
|
195 |
+
assert_equal(converter('missed'), converter.default)
|
196 |
+
try:
|
197 |
+
converter('miss')
|
198 |
+
except ValueError:
|
199 |
+
pass
|
200 |
+
|
201 |
+
def test_upgrademapper(self):
|
202 |
+
"Tests updatemapper"
|
203 |
+
dateparser = _bytes_to_date
|
204 |
+
_original_mapper = StringConverter._mapper[:]
|
205 |
+
try:
|
206 |
+
StringConverter.upgrade_mapper(dateparser, date(2000, 1, 1))
|
207 |
+
convert = StringConverter(dateparser, date(2000, 1, 1))
|
208 |
+
test = convert('2001-01-01')
|
209 |
+
assert_equal(test, date(2001, 1, 1))
|
210 |
+
test = convert('2009-01-01')
|
211 |
+
assert_equal(test, date(2009, 1, 1))
|
212 |
+
test = convert('')
|
213 |
+
assert_equal(test, date(2000, 1, 1))
|
214 |
+
finally:
|
215 |
+
StringConverter._mapper = _original_mapper
|
216 |
+
|
217 |
+
def test_string_to_object(self):
|
218 |
+
"Make sure that string-to-object functions are properly recognized"
|
219 |
+
old_mapper = StringConverter._mapper[:] # copy of list
|
220 |
+
conv = StringConverter(_bytes_to_date)
|
221 |
+
assert_equal(conv._mapper, old_mapper)
|
222 |
+
assert_(hasattr(conv, 'default'))
|
223 |
+
|
224 |
+
def test_keep_default(self):
|
225 |
+
"Make sure we don't lose an explicit default"
|
226 |
+
converter = StringConverter(None, missing_values='',
|
227 |
+
default=-999)
|
228 |
+
converter.upgrade('3.14159265')
|
229 |
+
assert_equal(converter.default, -999)
|
230 |
+
assert_equal(converter.type, np.dtype(float))
|
231 |
+
#
|
232 |
+
converter = StringConverter(
|
233 |
+
None, missing_values='', default=0)
|
234 |
+
converter.upgrade('3.14159265')
|
235 |
+
assert_equal(converter.default, 0)
|
236 |
+
assert_equal(converter.type, np.dtype(float))
|
237 |
+
|
238 |
+
def test_keep_default_zero(self):
|
239 |
+
"Check that we don't lose a default of 0"
|
240 |
+
converter = StringConverter(int, default=0,
|
241 |
+
missing_values="N/A")
|
242 |
+
assert_equal(converter.default, 0)
|
243 |
+
|
244 |
+
def test_keep_missing_values(self):
|
245 |
+
"Check that we're not losing missing values"
|
246 |
+
converter = StringConverter(int, default=0,
|
247 |
+
missing_values="N/A")
|
248 |
+
assert_equal(
|
249 |
+
converter.missing_values, {'', 'N/A'})
|
250 |
+
|
251 |
+
def test_int64_dtype(self):
|
252 |
+
"Check that int64 integer types can be specified"
|
253 |
+
converter = StringConverter(np.int64, default=0)
|
254 |
+
val = "-9223372036854775807"
|
255 |
+
assert_(converter(val) == -9223372036854775807)
|
256 |
+
val = "9223372036854775807"
|
257 |
+
assert_(converter(val) == 9223372036854775807)
|
258 |
+
|
259 |
+
def test_uint64_dtype(self):
|
260 |
+
"Check that uint64 integer types can be specified"
|
261 |
+
converter = StringConverter(np.uint64, default=0)
|
262 |
+
val = "9223372043271415339"
|
263 |
+
assert_(converter(val) == 9223372043271415339)
|
264 |
+
|
265 |
+
|
266 |
+
class TestMiscFunctions:
|
267 |
+
|
268 |
+
def test_has_nested_dtype(self):
|
269 |
+
"Test has_nested_dtype"
|
270 |
+
ndtype = np.dtype(float)
|
271 |
+
assert_equal(has_nested_fields(ndtype), False)
|
272 |
+
ndtype = np.dtype([('A', '|S3'), ('B', float)])
|
273 |
+
assert_equal(has_nested_fields(ndtype), False)
|
274 |
+
ndtype = np.dtype([('A', int), ('B', [('BA', float), ('BB', '|S1')])])
|
275 |
+
assert_equal(has_nested_fields(ndtype), True)
|
276 |
+
|
277 |
+
def test_easy_dtype(self):
|
278 |
+
"Test ndtype on dtypes"
|
279 |
+
# Simple case
|
280 |
+
ndtype = float
|
281 |
+
assert_equal(easy_dtype(ndtype), np.dtype(float))
|
282 |
+
# As string w/o names
|
283 |
+
ndtype = "i4, f8"
|
284 |
+
assert_equal(easy_dtype(ndtype),
|
285 |
+
np.dtype([('f0', "i4"), ('f1', "f8")]))
|
286 |
+
# As string w/o names but different default format
|
287 |
+
assert_equal(easy_dtype(ndtype, defaultfmt="field_%03i"),
|
288 |
+
np.dtype([('field_000', "i4"), ('field_001', "f8")]))
|
289 |
+
# As string w/ names
|
290 |
+
ndtype = "i4, f8"
|
291 |
+
assert_equal(easy_dtype(ndtype, names="a, b"),
|
292 |
+
np.dtype([('a', "i4"), ('b', "f8")]))
|
293 |
+
# As string w/ names (too many)
|
294 |
+
ndtype = "i4, f8"
|
295 |
+
assert_equal(easy_dtype(ndtype, names="a, b, c"),
|
296 |
+
np.dtype([('a', "i4"), ('b', "f8")]))
|
297 |
+
# As string w/ names (not enough)
|
298 |
+
ndtype = "i4, f8"
|
299 |
+
assert_equal(easy_dtype(ndtype, names=", b"),
|
300 |
+
np.dtype([('f0', "i4"), ('b', "f8")]))
|
301 |
+
# ... (with different default format)
|
302 |
+
assert_equal(easy_dtype(ndtype, names="a", defaultfmt="f%02i"),
|
303 |
+
np.dtype([('a', "i4"), ('f00', "f8")]))
|
304 |
+
# As list of tuples w/o names
|
305 |
+
ndtype = [('A', int), ('B', float)]
|
306 |
+
assert_equal(easy_dtype(ndtype), np.dtype([('A', int), ('B', float)]))
|
307 |
+
# As list of tuples w/ names
|
308 |
+
assert_equal(easy_dtype(ndtype, names="a,b"),
|
309 |
+
np.dtype([('a', int), ('b', float)]))
|
310 |
+
# As list of tuples w/ not enough names
|
311 |
+
assert_equal(easy_dtype(ndtype, names="a"),
|
312 |
+
np.dtype([('a', int), ('f0', float)]))
|
313 |
+
# As list of tuples w/ too many names
|
314 |
+
assert_equal(easy_dtype(ndtype, names="a,b,c"),
|
315 |
+
np.dtype([('a', int), ('b', float)]))
|
316 |
+
# As list of types w/o names
|
317 |
+
ndtype = (int, float, float)
|
318 |
+
assert_equal(easy_dtype(ndtype),
|
319 |
+
np.dtype([('f0', int), ('f1', float), ('f2', float)]))
|
320 |
+
# As list of types w names
|
321 |
+
ndtype = (int, float, float)
|
322 |
+
assert_equal(easy_dtype(ndtype, names="a, b, c"),
|
323 |
+
np.dtype([('a', int), ('b', float), ('c', float)]))
|
324 |
+
# As simple dtype w/ names
|
325 |
+
ndtype = np.dtype(float)
|
326 |
+
assert_equal(easy_dtype(ndtype, names="a, b, c"),
|
327 |
+
np.dtype([(_, float) for _ in ('a', 'b', 'c')]))
|
328 |
+
# As simple dtype w/o names (but multiple fields)
|
329 |
+
ndtype = np.dtype(float)
|
330 |
+
assert_equal(
|
331 |
+
easy_dtype(ndtype, names=['', '', ''], defaultfmt="f%02i"),
|
332 |
+
np.dtype([(_, float) for _ in ('f00', 'f01', 'f02')]))
|
333 |
+
|
334 |
+
def test_flatten_dtype(self):
|
335 |
+
"Testing flatten_dtype"
|
336 |
+
# Standard dtype
|
337 |
+
dt = np.dtype([("a", "f8"), ("b", "f8")])
|
338 |
+
dt_flat = flatten_dtype(dt)
|
339 |
+
assert_equal(dt_flat, [float, float])
|
340 |
+
# Recursive dtype
|
341 |
+
dt = np.dtype([("a", [("aa", '|S1'), ("ab", '|S2')]), ("b", int)])
|
342 |
+
dt_flat = flatten_dtype(dt)
|
343 |
+
assert_equal(dt_flat, [np.dtype('|S1'), np.dtype('|S2'), int])
|
344 |
+
# dtype with shaped fields
|
345 |
+
dt = np.dtype([("a", (float, 2)), ("b", (int, 3))])
|
346 |
+
dt_flat = flatten_dtype(dt)
|
347 |
+
assert_equal(dt_flat, [float, int])
|
348 |
+
dt_flat = flatten_dtype(dt, True)
|
349 |
+
assert_equal(dt_flat, [float] * 2 + [int] * 3)
|
350 |
+
# dtype w/ titles
|
351 |
+
dt = np.dtype([(("a", "A"), "f8"), (("b", "B"), "f8")])
|
352 |
+
dt_flat = flatten_dtype(dt)
|
353 |
+
assert_equal(dt_flat, [float, float])
|
venv/lib/python3.10/site-packages/numpy/lib/tests/test_arraysetops.py
ADDED
@@ -0,0 +1,944 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Test functions for 1D array set operations.
|
2 |
+
|
3 |
+
"""
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
from numpy.testing import (assert_array_equal, assert_equal,
|
7 |
+
assert_raises, assert_raises_regex)
|
8 |
+
from numpy.lib.arraysetops import (
|
9 |
+
ediff1d, intersect1d, setxor1d, union1d, setdiff1d, unique, in1d, isin
|
10 |
+
)
|
11 |
+
import pytest
|
12 |
+
|
13 |
+
|
14 |
+
class TestSetOps:
|
15 |
+
|
16 |
+
def test_intersect1d(self):
|
17 |
+
# unique inputs
|
18 |
+
a = np.array([5, 7, 1, 2])
|
19 |
+
b = np.array([2, 4, 3, 1, 5])
|
20 |
+
|
21 |
+
ec = np.array([1, 2, 5])
|
22 |
+
c = intersect1d(a, b, assume_unique=True)
|
23 |
+
assert_array_equal(c, ec)
|
24 |
+
|
25 |
+
# non-unique inputs
|
26 |
+
a = np.array([5, 5, 7, 1, 2])
|
27 |
+
b = np.array([2, 1, 4, 3, 3, 1, 5])
|
28 |
+
|
29 |
+
ed = np.array([1, 2, 5])
|
30 |
+
c = intersect1d(a, b)
|
31 |
+
assert_array_equal(c, ed)
|
32 |
+
assert_array_equal([], intersect1d([], []))
|
33 |
+
|
34 |
+
def test_intersect1d_array_like(self):
|
35 |
+
# See gh-11772
|
36 |
+
class Test:
|
37 |
+
def __array__(self):
|
38 |
+
return np.arange(3)
|
39 |
+
|
40 |
+
a = Test()
|
41 |
+
res = intersect1d(a, a)
|
42 |
+
assert_array_equal(res, a)
|
43 |
+
res = intersect1d([1, 2, 3], [1, 2, 3])
|
44 |
+
assert_array_equal(res, [1, 2, 3])
|
45 |
+
|
46 |
+
def test_intersect1d_indices(self):
|
47 |
+
# unique inputs
|
48 |
+
a = np.array([1, 2, 3, 4])
|
49 |
+
b = np.array([2, 1, 4, 6])
|
50 |
+
c, i1, i2 = intersect1d(a, b, assume_unique=True, return_indices=True)
|
51 |
+
ee = np.array([1, 2, 4])
|
52 |
+
assert_array_equal(c, ee)
|
53 |
+
assert_array_equal(a[i1], ee)
|
54 |
+
assert_array_equal(b[i2], ee)
|
55 |
+
|
56 |
+
# non-unique inputs
|
57 |
+
a = np.array([1, 2, 2, 3, 4, 3, 2])
|
58 |
+
b = np.array([1, 8, 4, 2, 2, 3, 2, 3])
|
59 |
+
c, i1, i2 = intersect1d(a, b, return_indices=True)
|
60 |
+
ef = np.array([1, 2, 3, 4])
|
61 |
+
assert_array_equal(c, ef)
|
62 |
+
assert_array_equal(a[i1], ef)
|
63 |
+
assert_array_equal(b[i2], ef)
|
64 |
+
|
65 |
+
# non1d, unique inputs
|
66 |
+
a = np.array([[2, 4, 5, 6], [7, 8, 1, 15]])
|
67 |
+
b = np.array([[3, 2, 7, 6], [10, 12, 8, 9]])
|
68 |
+
c, i1, i2 = intersect1d(a, b, assume_unique=True, return_indices=True)
|
69 |
+
ui1 = np.unravel_index(i1, a.shape)
|
70 |
+
ui2 = np.unravel_index(i2, b.shape)
|
71 |
+
ea = np.array([2, 6, 7, 8])
|
72 |
+
assert_array_equal(ea, a[ui1])
|
73 |
+
assert_array_equal(ea, b[ui2])
|
74 |
+
|
75 |
+
# non1d, not assumed to be uniqueinputs
|
76 |
+
a = np.array([[2, 4, 5, 6, 6], [4, 7, 8, 7, 2]])
|
77 |
+
b = np.array([[3, 2, 7, 7], [10, 12, 8, 7]])
|
78 |
+
c, i1, i2 = intersect1d(a, b, return_indices=True)
|
79 |
+
ui1 = np.unravel_index(i1, a.shape)
|
80 |
+
ui2 = np.unravel_index(i2, b.shape)
|
81 |
+
ea = np.array([2, 7, 8])
|
82 |
+
assert_array_equal(ea, a[ui1])
|
83 |
+
assert_array_equal(ea, b[ui2])
|
84 |
+
|
85 |
+
def test_setxor1d(self):
|
86 |
+
a = np.array([5, 7, 1, 2])
|
87 |
+
b = np.array([2, 4, 3, 1, 5])
|
88 |
+
|
89 |
+
ec = np.array([3, 4, 7])
|
90 |
+
c = setxor1d(a, b)
|
91 |
+
assert_array_equal(c, ec)
|
92 |
+
|
93 |
+
a = np.array([1, 2, 3])
|
94 |
+
b = np.array([6, 5, 4])
|
95 |
+
|
96 |
+
ec = np.array([1, 2, 3, 4, 5, 6])
|
97 |
+
c = setxor1d(a, b)
|
98 |
+
assert_array_equal(c, ec)
|
99 |
+
|
100 |
+
a = np.array([1, 8, 2, 3])
|
101 |
+
b = np.array([6, 5, 4, 8])
|
102 |
+
|
103 |
+
ec = np.array([1, 2, 3, 4, 5, 6])
|
104 |
+
c = setxor1d(a, b)
|
105 |
+
assert_array_equal(c, ec)
|
106 |
+
|
107 |
+
assert_array_equal([], setxor1d([], []))
|
108 |
+
|
109 |
+
def test_ediff1d(self):
|
110 |
+
zero_elem = np.array([])
|
111 |
+
one_elem = np.array([1])
|
112 |
+
two_elem = np.array([1, 2])
|
113 |
+
|
114 |
+
assert_array_equal([], ediff1d(zero_elem))
|
115 |
+
assert_array_equal([0], ediff1d(zero_elem, to_begin=0))
|
116 |
+
assert_array_equal([0], ediff1d(zero_elem, to_end=0))
|
117 |
+
assert_array_equal([-1, 0], ediff1d(zero_elem, to_begin=-1, to_end=0))
|
118 |
+
assert_array_equal([], ediff1d(one_elem))
|
119 |
+
assert_array_equal([1], ediff1d(two_elem))
|
120 |
+
assert_array_equal([7, 1, 9], ediff1d(two_elem, to_begin=7, to_end=9))
|
121 |
+
assert_array_equal([5, 6, 1, 7, 8],
|
122 |
+
ediff1d(two_elem, to_begin=[5, 6], to_end=[7, 8]))
|
123 |
+
assert_array_equal([1, 9], ediff1d(two_elem, to_end=9))
|
124 |
+
assert_array_equal([1, 7, 8], ediff1d(two_elem, to_end=[7, 8]))
|
125 |
+
assert_array_equal([7, 1], ediff1d(two_elem, to_begin=7))
|
126 |
+
assert_array_equal([5, 6, 1], ediff1d(two_elem, to_begin=[5, 6]))
|
127 |
+
|
128 |
+
@pytest.mark.parametrize("ary, prepend, append, expected", [
|
129 |
+
# should fail because trying to cast
|
130 |
+
# np.nan standard floating point value
|
131 |
+
# into an integer array:
|
132 |
+
(np.array([1, 2, 3], dtype=np.int64),
|
133 |
+
None,
|
134 |
+
np.nan,
|
135 |
+
'to_end'),
|
136 |
+
# should fail because attempting
|
137 |
+
# to downcast to int type:
|
138 |
+
(np.array([1, 2, 3], dtype=np.int64),
|
139 |
+
np.array([5, 7, 2], dtype=np.float32),
|
140 |
+
None,
|
141 |
+
'to_begin'),
|
142 |
+
# should fail because attempting to cast
|
143 |
+
# two special floating point values
|
144 |
+
# to integers (on both sides of ary),
|
145 |
+
# `to_begin` is in the error message as the impl checks this first:
|
146 |
+
(np.array([1., 3., 9.], dtype=np.int8),
|
147 |
+
np.nan,
|
148 |
+
np.nan,
|
149 |
+
'to_begin'),
|
150 |
+
])
|
151 |
+
def test_ediff1d_forbidden_type_casts(self, ary, prepend, append, expected):
|
152 |
+
# verify resolution of gh-11490
|
153 |
+
|
154 |
+
# specifically, raise an appropriate
|
155 |
+
# Exception when attempting to append or
|
156 |
+
# prepend with an incompatible type
|
157 |
+
msg = 'dtype of `{}` must be compatible'.format(expected)
|
158 |
+
with assert_raises_regex(TypeError, msg):
|
159 |
+
ediff1d(ary=ary,
|
160 |
+
to_end=append,
|
161 |
+
to_begin=prepend)
|
162 |
+
|
163 |
+
@pytest.mark.parametrize(
|
164 |
+
"ary,prepend,append,expected",
|
165 |
+
[
|
166 |
+
(np.array([1, 2, 3], dtype=np.int16),
|
167 |
+
2**16, # will be cast to int16 under same kind rule.
|
168 |
+
2**16 + 4,
|
169 |
+
np.array([0, 1, 1, 4], dtype=np.int16)),
|
170 |
+
(np.array([1, 2, 3], dtype=np.float32),
|
171 |
+
np.array([5], dtype=np.float64),
|
172 |
+
None,
|
173 |
+
np.array([5, 1, 1], dtype=np.float32)),
|
174 |
+
(np.array([1, 2, 3], dtype=np.int32),
|
175 |
+
0,
|
176 |
+
0,
|
177 |
+
np.array([0, 1, 1, 0], dtype=np.int32)),
|
178 |
+
(np.array([1, 2, 3], dtype=np.int64),
|
179 |
+
3,
|
180 |
+
-9,
|
181 |
+
np.array([3, 1, 1, -9], dtype=np.int64)),
|
182 |
+
]
|
183 |
+
)
|
184 |
+
def test_ediff1d_scalar_handling(self,
|
185 |
+
ary,
|
186 |
+
prepend,
|
187 |
+
append,
|
188 |
+
expected):
|
189 |
+
# maintain backwards-compatibility
|
190 |
+
# of scalar prepend / append behavior
|
191 |
+
# in ediff1d following fix for gh-11490
|
192 |
+
actual = np.ediff1d(ary=ary,
|
193 |
+
to_end=append,
|
194 |
+
to_begin=prepend)
|
195 |
+
assert_equal(actual, expected)
|
196 |
+
assert actual.dtype == expected.dtype
|
197 |
+
|
198 |
+
@pytest.mark.parametrize("kind", [None, "sort", "table"])
|
199 |
+
def test_isin(self, kind):
|
200 |
+
# the tests for in1d cover most of isin's behavior
|
201 |
+
# if in1d is removed, would need to change those tests to test
|
202 |
+
# isin instead.
|
203 |
+
def _isin_slow(a, b):
|
204 |
+
b = np.asarray(b).flatten().tolist()
|
205 |
+
return a in b
|
206 |
+
isin_slow = np.vectorize(_isin_slow, otypes=[bool], excluded={1})
|
207 |
+
|
208 |
+
def assert_isin_equal(a, b):
|
209 |
+
x = isin(a, b, kind=kind)
|
210 |
+
y = isin_slow(a, b)
|
211 |
+
assert_array_equal(x, y)
|
212 |
+
|
213 |
+
# multidimensional arrays in both arguments
|
214 |
+
a = np.arange(24).reshape([2, 3, 4])
|
215 |
+
b = np.array([[10, 20, 30], [0, 1, 3], [11, 22, 33]])
|
216 |
+
assert_isin_equal(a, b)
|
217 |
+
|
218 |
+
# array-likes as both arguments
|
219 |
+
c = [(9, 8), (7, 6)]
|
220 |
+
d = (9, 7)
|
221 |
+
assert_isin_equal(c, d)
|
222 |
+
|
223 |
+
# zero-d array:
|
224 |
+
f = np.array(3)
|
225 |
+
assert_isin_equal(f, b)
|
226 |
+
assert_isin_equal(a, f)
|
227 |
+
assert_isin_equal(f, f)
|
228 |
+
|
229 |
+
# scalar:
|
230 |
+
assert_isin_equal(5, b)
|
231 |
+
assert_isin_equal(a, 6)
|
232 |
+
assert_isin_equal(5, 6)
|
233 |
+
|
234 |
+
# empty array-like:
|
235 |
+
if kind != "table":
|
236 |
+
# An empty list will become float64,
|
237 |
+
# which is invalid for kind="table"
|
238 |
+
x = []
|
239 |
+
assert_isin_equal(x, b)
|
240 |
+
assert_isin_equal(a, x)
|
241 |
+
assert_isin_equal(x, x)
|
242 |
+
|
243 |
+
# empty array with various types:
|
244 |
+
for dtype in [bool, np.int64, np.float64]:
|
245 |
+
if kind == "table" and dtype == np.float64:
|
246 |
+
continue
|
247 |
+
|
248 |
+
if dtype in {np.int64, np.float64}:
|
249 |
+
ar = np.array([10, 20, 30], dtype=dtype)
|
250 |
+
elif dtype in {bool}:
|
251 |
+
ar = np.array([True, False, False])
|
252 |
+
|
253 |
+
empty_array = np.array([], dtype=dtype)
|
254 |
+
|
255 |
+
assert_isin_equal(empty_array, ar)
|
256 |
+
assert_isin_equal(ar, empty_array)
|
257 |
+
assert_isin_equal(empty_array, empty_array)
|
258 |
+
|
259 |
+
@pytest.mark.parametrize("kind", [None, "sort", "table"])
|
260 |
+
def test_in1d(self, kind):
|
261 |
+
# we use two different sizes for the b array here to test the
|
262 |
+
# two different paths in in1d().
|
263 |
+
for mult in (1, 10):
|
264 |
+
# One check without np.array to make sure lists are handled correct
|
265 |
+
a = [5, 7, 1, 2]
|
266 |
+
b = [2, 4, 3, 1, 5] * mult
|
267 |
+
ec = np.array([True, False, True, True])
|
268 |
+
c = in1d(a, b, assume_unique=True, kind=kind)
|
269 |
+
assert_array_equal(c, ec)
|
270 |
+
|
271 |
+
a[0] = 8
|
272 |
+
ec = np.array([False, False, True, True])
|
273 |
+
c = in1d(a, b, assume_unique=True, kind=kind)
|
274 |
+
assert_array_equal(c, ec)
|
275 |
+
|
276 |
+
a[0], a[3] = 4, 8
|
277 |
+
ec = np.array([True, False, True, False])
|
278 |
+
c = in1d(a, b, assume_unique=True, kind=kind)
|
279 |
+
assert_array_equal(c, ec)
|
280 |
+
|
281 |
+
a = np.array([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5])
|
282 |
+
b = [2, 3, 4] * mult
|
283 |
+
ec = [False, True, False, True, True, True, True, True, True,
|
284 |
+
False, True, False, False, False]
|
285 |
+
c = in1d(a, b, kind=kind)
|
286 |
+
assert_array_equal(c, ec)
|
287 |
+
|
288 |
+
b = b + [5, 5, 4] * mult
|
289 |
+
ec = [True, True, True, True, True, True, True, True, True, True,
|
290 |
+
True, False, True, True]
|
291 |
+
c = in1d(a, b, kind=kind)
|
292 |
+
assert_array_equal(c, ec)
|
293 |
+
|
294 |
+
a = np.array([5, 7, 1, 2])
|
295 |
+
b = np.array([2, 4, 3, 1, 5] * mult)
|
296 |
+
ec = np.array([True, False, True, True])
|
297 |
+
c = in1d(a, b, kind=kind)
|
298 |
+
assert_array_equal(c, ec)
|
299 |
+
|
300 |
+
a = np.array([5, 7, 1, 1, 2])
|
301 |
+
b = np.array([2, 4, 3, 3, 1, 5] * mult)
|
302 |
+
ec = np.array([True, False, True, True, True])
|
303 |
+
c = in1d(a, b, kind=kind)
|
304 |
+
assert_array_equal(c, ec)
|
305 |
+
|
306 |
+
a = np.array([5, 5])
|
307 |
+
b = np.array([2, 2] * mult)
|
308 |
+
ec = np.array([False, False])
|
309 |
+
c = in1d(a, b, kind=kind)
|
310 |
+
assert_array_equal(c, ec)
|
311 |
+
|
312 |
+
a = np.array([5])
|
313 |
+
b = np.array([2])
|
314 |
+
ec = np.array([False])
|
315 |
+
c = in1d(a, b, kind=kind)
|
316 |
+
assert_array_equal(c, ec)
|
317 |
+
|
318 |
+
if kind in {None, "sort"}:
|
319 |
+
assert_array_equal(in1d([], [], kind=kind), [])
|
320 |
+
|
321 |
+
def test_in1d_char_array(self):
|
322 |
+
a = np.array(['a', 'b', 'c', 'd', 'e', 'c', 'e', 'b'])
|
323 |
+
b = np.array(['a', 'c'])
|
324 |
+
|
325 |
+
ec = np.array([True, False, True, False, False, True, False, False])
|
326 |
+
c = in1d(a, b)
|
327 |
+
|
328 |
+
assert_array_equal(c, ec)
|
329 |
+
|
330 |
+
@pytest.mark.parametrize("kind", [None, "sort", "table"])
|
331 |
+
def test_in1d_invert(self, kind):
|
332 |
+
"Test in1d's invert parameter"
|
333 |
+
# We use two different sizes for the b array here to test the
|
334 |
+
# two different paths in in1d().
|
335 |
+
for mult in (1, 10):
|
336 |
+
a = np.array([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5])
|
337 |
+
b = [2, 3, 4] * mult
|
338 |
+
assert_array_equal(np.invert(in1d(a, b, kind=kind)),
|
339 |
+
in1d(a, b, invert=True, kind=kind))
|
340 |
+
|
341 |
+
# float:
|
342 |
+
if kind in {None, "sort"}:
|
343 |
+
for mult in (1, 10):
|
344 |
+
a = np.array([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5],
|
345 |
+
dtype=np.float32)
|
346 |
+
b = [2, 3, 4] * mult
|
347 |
+
b = np.array(b, dtype=np.float32)
|
348 |
+
assert_array_equal(np.invert(in1d(a, b, kind=kind)),
|
349 |
+
in1d(a, b, invert=True, kind=kind))
|
350 |
+
|
351 |
+
@pytest.mark.parametrize("kind", [None, "sort", "table"])
|
352 |
+
def test_in1d_ravel(self, kind):
|
353 |
+
# Test that in1d ravels its input arrays. This is not documented
|
354 |
+
# behavior however. The test is to ensure consistentency.
|
355 |
+
a = np.arange(6).reshape(2, 3)
|
356 |
+
b = np.arange(3, 9).reshape(3, 2)
|
357 |
+
long_b = np.arange(3, 63).reshape(30, 2)
|
358 |
+
ec = np.array([False, False, False, True, True, True])
|
359 |
+
|
360 |
+
assert_array_equal(in1d(a, b, assume_unique=True, kind=kind),
|
361 |
+
ec)
|
362 |
+
assert_array_equal(in1d(a, b, assume_unique=False,
|
363 |
+
kind=kind),
|
364 |
+
ec)
|
365 |
+
assert_array_equal(in1d(a, long_b, assume_unique=True,
|
366 |
+
kind=kind),
|
367 |
+
ec)
|
368 |
+
assert_array_equal(in1d(a, long_b, assume_unique=False,
|
369 |
+
kind=kind),
|
370 |
+
ec)
|
371 |
+
|
372 |
+
def test_in1d_hit_alternate_algorithm(self):
|
373 |
+
"""Hit the standard isin code with integers"""
|
374 |
+
# Need extreme range to hit standard code
|
375 |
+
# This hits it without the use of kind='table'
|
376 |
+
a = np.array([5, 4, 5, 3, 4, 4, 1e9], dtype=np.int64)
|
377 |
+
b = np.array([2, 3, 4, 1e9], dtype=np.int64)
|
378 |
+
expected = np.array([0, 1, 0, 1, 1, 1, 1], dtype=bool)
|
379 |
+
assert_array_equal(expected, in1d(a, b))
|
380 |
+
assert_array_equal(np.invert(expected), in1d(a, b, invert=True))
|
381 |
+
|
382 |
+
a = np.array([5, 7, 1, 2], dtype=np.int64)
|
383 |
+
b = np.array([2, 4, 3, 1, 5, 1e9], dtype=np.int64)
|
384 |
+
ec = np.array([True, False, True, True])
|
385 |
+
c = in1d(a, b, assume_unique=True)
|
386 |
+
assert_array_equal(c, ec)
|
387 |
+
|
388 |
+
@pytest.mark.parametrize("kind", [None, "sort", "table"])
|
389 |
+
def test_in1d_boolean(self, kind):
|
390 |
+
"""Test that in1d works for boolean input"""
|
391 |
+
a = np.array([True, False])
|
392 |
+
b = np.array([False, False, False])
|
393 |
+
expected = np.array([False, True])
|
394 |
+
assert_array_equal(expected,
|
395 |
+
in1d(a, b, kind=kind))
|
396 |
+
assert_array_equal(np.invert(expected),
|
397 |
+
in1d(a, b, invert=True, kind=kind))
|
398 |
+
|
399 |
+
@pytest.mark.parametrize("kind", [None, "sort"])
|
400 |
+
def test_in1d_timedelta(self, kind):
|
401 |
+
"""Test that in1d works for timedelta input"""
|
402 |
+
rstate = np.random.RandomState(0)
|
403 |
+
a = rstate.randint(0, 100, size=10)
|
404 |
+
b = rstate.randint(0, 100, size=10)
|
405 |
+
truth = in1d(a, b)
|
406 |
+
a_timedelta = a.astype("timedelta64[s]")
|
407 |
+
b_timedelta = b.astype("timedelta64[s]")
|
408 |
+
assert_array_equal(truth, in1d(a_timedelta, b_timedelta, kind=kind))
|
409 |
+
|
410 |
+
def test_in1d_table_timedelta_fails(self):
|
411 |
+
a = np.array([0, 1, 2], dtype="timedelta64[s]")
|
412 |
+
b = a
|
413 |
+
# Make sure it raises a value error:
|
414 |
+
with pytest.raises(ValueError):
|
415 |
+
in1d(a, b, kind="table")
|
416 |
+
|
417 |
+
@pytest.mark.parametrize(
|
418 |
+
"dtype1,dtype2",
|
419 |
+
[
|
420 |
+
(np.int8, np.int16),
|
421 |
+
(np.int16, np.int8),
|
422 |
+
(np.uint8, np.uint16),
|
423 |
+
(np.uint16, np.uint8),
|
424 |
+
(np.uint8, np.int16),
|
425 |
+
(np.int16, np.uint8),
|
426 |
+
]
|
427 |
+
)
|
428 |
+
@pytest.mark.parametrize("kind", [None, "sort", "table"])
|
429 |
+
def test_in1d_mixed_dtype(self, dtype1, dtype2, kind):
|
430 |
+
"""Test that in1d works as expected for mixed dtype input."""
|
431 |
+
is_dtype2_signed = np.issubdtype(dtype2, np.signedinteger)
|
432 |
+
ar1 = np.array([0, 0, 1, 1], dtype=dtype1)
|
433 |
+
|
434 |
+
if is_dtype2_signed:
|
435 |
+
ar2 = np.array([-128, 0, 127], dtype=dtype2)
|
436 |
+
else:
|
437 |
+
ar2 = np.array([127, 0, 255], dtype=dtype2)
|
438 |
+
|
439 |
+
expected = np.array([True, True, False, False])
|
440 |
+
|
441 |
+
expect_failure = kind == "table" and any((
|
442 |
+
dtype1 == np.int8 and dtype2 == np.int16,
|
443 |
+
dtype1 == np.int16 and dtype2 == np.int8
|
444 |
+
))
|
445 |
+
|
446 |
+
if expect_failure:
|
447 |
+
with pytest.raises(RuntimeError, match="exceed the maximum"):
|
448 |
+
in1d(ar1, ar2, kind=kind)
|
449 |
+
else:
|
450 |
+
assert_array_equal(in1d(ar1, ar2, kind=kind), expected)
|
451 |
+
|
452 |
+
@pytest.mark.parametrize("kind", [None, "sort", "table"])
|
453 |
+
def test_in1d_mixed_boolean(self, kind):
|
454 |
+
"""Test that in1d works as expected for bool/int input."""
|
455 |
+
for dtype in np.typecodes["AllInteger"]:
|
456 |
+
a = np.array([True, False, False], dtype=bool)
|
457 |
+
b = np.array([0, 0, 0, 0], dtype=dtype)
|
458 |
+
expected = np.array([False, True, True], dtype=bool)
|
459 |
+
assert_array_equal(in1d(a, b, kind=kind), expected)
|
460 |
+
|
461 |
+
a, b = b, a
|
462 |
+
expected = np.array([True, True, True, True], dtype=bool)
|
463 |
+
assert_array_equal(in1d(a, b, kind=kind), expected)
|
464 |
+
|
465 |
+
def test_in1d_first_array_is_object(self):
|
466 |
+
ar1 = [None]
|
467 |
+
ar2 = np.array([1]*10)
|
468 |
+
expected = np.array([False])
|
469 |
+
result = np.in1d(ar1, ar2)
|
470 |
+
assert_array_equal(result, expected)
|
471 |
+
|
472 |
+
def test_in1d_second_array_is_object(self):
|
473 |
+
ar1 = 1
|
474 |
+
ar2 = np.array([None]*10)
|
475 |
+
expected = np.array([False])
|
476 |
+
result = np.in1d(ar1, ar2)
|
477 |
+
assert_array_equal(result, expected)
|
478 |
+
|
479 |
+
def test_in1d_both_arrays_are_object(self):
|
480 |
+
ar1 = [None]
|
481 |
+
ar2 = np.array([None]*10)
|
482 |
+
expected = np.array([True])
|
483 |
+
result = np.in1d(ar1, ar2)
|
484 |
+
assert_array_equal(result, expected)
|
485 |
+
|
486 |
+
def test_in1d_both_arrays_have_structured_dtype(self):
|
487 |
+
# Test arrays of a structured data type containing an integer field
|
488 |
+
# and a field of dtype `object` allowing for arbitrary Python objects
|
489 |
+
dt = np.dtype([('field1', int), ('field2', object)])
|
490 |
+
ar1 = np.array([(1, None)], dtype=dt)
|
491 |
+
ar2 = np.array([(1, None)]*10, dtype=dt)
|
492 |
+
expected = np.array([True])
|
493 |
+
result = np.in1d(ar1, ar2)
|
494 |
+
assert_array_equal(result, expected)
|
495 |
+
|
496 |
+
def test_in1d_with_arrays_containing_tuples(self):
|
497 |
+
ar1 = np.array([(1,), 2], dtype=object)
|
498 |
+
ar2 = np.array([(1,), 2], dtype=object)
|
499 |
+
expected = np.array([True, True])
|
500 |
+
result = np.in1d(ar1, ar2)
|
501 |
+
assert_array_equal(result, expected)
|
502 |
+
result = np.in1d(ar1, ar2, invert=True)
|
503 |
+
assert_array_equal(result, np.invert(expected))
|
504 |
+
|
505 |
+
# An integer is added at the end of the array to make sure
|
506 |
+
# that the array builder will create the array with tuples
|
507 |
+
# and after it's created the integer is removed.
|
508 |
+
# There's a bug in the array constructor that doesn't handle
|
509 |
+
# tuples properly and adding the integer fixes that.
|
510 |
+
ar1 = np.array([(1,), (2, 1), 1], dtype=object)
|
511 |
+
ar1 = ar1[:-1]
|
512 |
+
ar2 = np.array([(1,), (2, 1), 1], dtype=object)
|
513 |
+
ar2 = ar2[:-1]
|
514 |
+
expected = np.array([True, True])
|
515 |
+
result = np.in1d(ar1, ar2)
|
516 |
+
assert_array_equal(result, expected)
|
517 |
+
result = np.in1d(ar1, ar2, invert=True)
|
518 |
+
assert_array_equal(result, np.invert(expected))
|
519 |
+
|
520 |
+
ar1 = np.array([(1,), (2, 3), 1], dtype=object)
|
521 |
+
ar1 = ar1[:-1]
|
522 |
+
ar2 = np.array([(1,), 2], dtype=object)
|
523 |
+
expected = np.array([True, False])
|
524 |
+
result = np.in1d(ar1, ar2)
|
525 |
+
assert_array_equal(result, expected)
|
526 |
+
result = np.in1d(ar1, ar2, invert=True)
|
527 |
+
assert_array_equal(result, np.invert(expected))
|
528 |
+
|
529 |
+
def test_in1d_errors(self):
|
530 |
+
"""Test that in1d raises expected errors."""
|
531 |
+
|
532 |
+
# Error 1: `kind` is not one of 'sort' 'table' or None.
|
533 |
+
ar1 = np.array([1, 2, 3, 4, 5])
|
534 |
+
ar2 = np.array([2, 4, 6, 8, 10])
|
535 |
+
assert_raises(ValueError, in1d, ar1, ar2, kind='quicksort')
|
536 |
+
|
537 |
+
# Error 2: `kind="table"` does not work for non-integral arrays.
|
538 |
+
obj_ar1 = np.array([1, 'a', 3, 'b', 5], dtype=object)
|
539 |
+
obj_ar2 = np.array([1, 'a', 3, 'b', 5], dtype=object)
|
540 |
+
assert_raises(ValueError, in1d, obj_ar1, obj_ar2, kind='table')
|
541 |
+
|
542 |
+
for dtype in [np.int32, np.int64]:
|
543 |
+
ar1 = np.array([-1, 2, 3, 4, 5], dtype=dtype)
|
544 |
+
# The range of this array will overflow:
|
545 |
+
overflow_ar2 = np.array([-1, np.iinfo(dtype).max], dtype=dtype)
|
546 |
+
|
547 |
+
# Error 3: `kind="table"` will trigger a runtime error
|
548 |
+
# if there is an integer overflow expected when computing the
|
549 |
+
# range of ar2
|
550 |
+
assert_raises(
|
551 |
+
RuntimeError,
|
552 |
+
in1d, ar1, overflow_ar2, kind='table'
|
553 |
+
)
|
554 |
+
|
555 |
+
# Non-error: `kind=None` will *not* trigger a runtime error
|
556 |
+
# if there is an integer overflow, it will switch to
|
557 |
+
# the `sort` algorithm.
|
558 |
+
result = np.in1d(ar1, overflow_ar2, kind=None)
|
559 |
+
assert_array_equal(result, [True] + [False] * 4)
|
560 |
+
result = np.in1d(ar1, overflow_ar2, kind='sort')
|
561 |
+
assert_array_equal(result, [True] + [False] * 4)
|
562 |
+
|
563 |
+
def test_union1d(self):
|
564 |
+
a = np.array([5, 4, 7, 1, 2])
|
565 |
+
b = np.array([2, 4, 3, 3, 2, 1, 5])
|
566 |
+
|
567 |
+
ec = np.array([1, 2, 3, 4, 5, 7])
|
568 |
+
c = union1d(a, b)
|
569 |
+
assert_array_equal(c, ec)
|
570 |
+
|
571 |
+
# Tests gh-10340, arguments to union1d should be
|
572 |
+
# flattened if they are not already 1D
|
573 |
+
x = np.array([[0, 1, 2], [3, 4, 5]])
|
574 |
+
y = np.array([0, 1, 2, 3, 4])
|
575 |
+
ez = np.array([0, 1, 2, 3, 4, 5])
|
576 |
+
z = union1d(x, y)
|
577 |
+
assert_array_equal(z, ez)
|
578 |
+
|
579 |
+
assert_array_equal([], union1d([], []))
|
580 |
+
|
581 |
+
def test_setdiff1d(self):
|
582 |
+
a = np.array([6, 5, 4, 7, 1, 2, 7, 4])
|
583 |
+
b = np.array([2, 4, 3, 3, 2, 1, 5])
|
584 |
+
|
585 |
+
ec = np.array([6, 7])
|
586 |
+
c = setdiff1d(a, b)
|
587 |
+
assert_array_equal(c, ec)
|
588 |
+
|
589 |
+
a = np.arange(21)
|
590 |
+
b = np.arange(19)
|
591 |
+
ec = np.array([19, 20])
|
592 |
+
c = setdiff1d(a, b)
|
593 |
+
assert_array_equal(c, ec)
|
594 |
+
|
595 |
+
assert_array_equal([], setdiff1d([], []))
|
596 |
+
a = np.array((), np.uint32)
|
597 |
+
assert_equal(setdiff1d(a, []).dtype, np.uint32)
|
598 |
+
|
599 |
+
def test_setdiff1d_unique(self):
|
600 |
+
a = np.array([3, 2, 1])
|
601 |
+
b = np.array([7, 5, 2])
|
602 |
+
expected = np.array([3, 1])
|
603 |
+
actual = setdiff1d(a, b, assume_unique=True)
|
604 |
+
assert_equal(actual, expected)
|
605 |
+
|
606 |
+
def test_setdiff1d_char_array(self):
|
607 |
+
a = np.array(['a', 'b', 'c'])
|
608 |
+
b = np.array(['a', 'b', 's'])
|
609 |
+
assert_array_equal(setdiff1d(a, b), np.array(['c']))
|
610 |
+
|
611 |
+
def test_manyways(self):
|
612 |
+
a = np.array([5, 7, 1, 2, 8])
|
613 |
+
b = np.array([9, 8, 2, 4, 3, 1, 5])
|
614 |
+
|
615 |
+
c1 = setxor1d(a, b)
|
616 |
+
aux1 = intersect1d(a, b)
|
617 |
+
aux2 = union1d(a, b)
|
618 |
+
c2 = setdiff1d(aux2, aux1)
|
619 |
+
assert_array_equal(c1, c2)
|
620 |
+
|
621 |
+
|
622 |
+
class TestUnique:
|
623 |
+
|
624 |
+
def test_unique_1d(self):
|
625 |
+
|
626 |
+
def check_all(a, b, i1, i2, c, dt):
|
627 |
+
base_msg = 'check {0} failed for type {1}'
|
628 |
+
|
629 |
+
msg = base_msg.format('values', dt)
|
630 |
+
v = unique(a)
|
631 |
+
assert_array_equal(v, b, msg)
|
632 |
+
|
633 |
+
msg = base_msg.format('return_index', dt)
|
634 |
+
v, j = unique(a, True, False, False)
|
635 |
+
assert_array_equal(v, b, msg)
|
636 |
+
assert_array_equal(j, i1, msg)
|
637 |
+
|
638 |
+
msg = base_msg.format('return_inverse', dt)
|
639 |
+
v, j = unique(a, False, True, False)
|
640 |
+
assert_array_equal(v, b, msg)
|
641 |
+
assert_array_equal(j, i2, msg)
|
642 |
+
|
643 |
+
msg = base_msg.format('return_counts', dt)
|
644 |
+
v, j = unique(a, False, False, True)
|
645 |
+
assert_array_equal(v, b, msg)
|
646 |
+
assert_array_equal(j, c, msg)
|
647 |
+
|
648 |
+
msg = base_msg.format('return_index and return_inverse', dt)
|
649 |
+
v, j1, j2 = unique(a, True, True, False)
|
650 |
+
assert_array_equal(v, b, msg)
|
651 |
+
assert_array_equal(j1, i1, msg)
|
652 |
+
assert_array_equal(j2, i2, msg)
|
653 |
+
|
654 |
+
msg = base_msg.format('return_index and return_counts', dt)
|
655 |
+
v, j1, j2 = unique(a, True, False, True)
|
656 |
+
assert_array_equal(v, b, msg)
|
657 |
+
assert_array_equal(j1, i1, msg)
|
658 |
+
assert_array_equal(j2, c, msg)
|
659 |
+
|
660 |
+
msg = base_msg.format('return_inverse and return_counts', dt)
|
661 |
+
v, j1, j2 = unique(a, False, True, True)
|
662 |
+
assert_array_equal(v, b, msg)
|
663 |
+
assert_array_equal(j1, i2, msg)
|
664 |
+
assert_array_equal(j2, c, msg)
|
665 |
+
|
666 |
+
msg = base_msg.format(('return_index, return_inverse '
|
667 |
+
'and return_counts'), dt)
|
668 |
+
v, j1, j2, j3 = unique(a, True, True, True)
|
669 |
+
assert_array_equal(v, b, msg)
|
670 |
+
assert_array_equal(j1, i1, msg)
|
671 |
+
assert_array_equal(j2, i2, msg)
|
672 |
+
assert_array_equal(j3, c, msg)
|
673 |
+
|
674 |
+
a = [5, 7, 1, 2, 1, 5, 7]*10
|
675 |
+
b = [1, 2, 5, 7]
|
676 |
+
i1 = [2, 3, 0, 1]
|
677 |
+
i2 = [2, 3, 0, 1, 0, 2, 3]*10
|
678 |
+
c = np.multiply([2, 1, 2, 2], 10)
|
679 |
+
|
680 |
+
# test for numeric arrays
|
681 |
+
types = []
|
682 |
+
types.extend(np.typecodes['AllInteger'])
|
683 |
+
types.extend(np.typecodes['AllFloat'])
|
684 |
+
types.append('datetime64[D]')
|
685 |
+
types.append('timedelta64[D]')
|
686 |
+
for dt in types:
|
687 |
+
aa = np.array(a, dt)
|
688 |
+
bb = np.array(b, dt)
|
689 |
+
check_all(aa, bb, i1, i2, c, dt)
|
690 |
+
|
691 |
+
# test for object arrays
|
692 |
+
dt = 'O'
|
693 |
+
aa = np.empty(len(a), dt)
|
694 |
+
aa[:] = a
|
695 |
+
bb = np.empty(len(b), dt)
|
696 |
+
bb[:] = b
|
697 |
+
check_all(aa, bb, i1, i2, c, dt)
|
698 |
+
|
699 |
+
# test for structured arrays
|
700 |
+
dt = [('', 'i'), ('', 'i')]
|
701 |
+
aa = np.array(list(zip(a, a)), dt)
|
702 |
+
bb = np.array(list(zip(b, b)), dt)
|
703 |
+
check_all(aa, bb, i1, i2, c, dt)
|
704 |
+
|
705 |
+
# test for ticket #2799
|
706 |
+
aa = [1. + 0.j, 1 - 1.j, 1]
|
707 |
+
assert_array_equal(np.unique(aa), [1. - 1.j, 1. + 0.j])
|
708 |
+
|
709 |
+
# test for ticket #4785
|
710 |
+
a = [(1, 2), (1, 2), (2, 3)]
|
711 |
+
unq = [1, 2, 3]
|
712 |
+
inv = [0, 1, 0, 1, 1, 2]
|
713 |
+
a1 = unique(a)
|
714 |
+
assert_array_equal(a1, unq)
|
715 |
+
a2, a2_inv = unique(a, return_inverse=True)
|
716 |
+
assert_array_equal(a2, unq)
|
717 |
+
assert_array_equal(a2_inv, inv)
|
718 |
+
|
719 |
+
# test for chararrays with return_inverse (gh-5099)
|
720 |
+
a = np.chararray(5)
|
721 |
+
a[...] = ''
|
722 |
+
a2, a2_inv = np.unique(a, return_inverse=True)
|
723 |
+
assert_array_equal(a2_inv, np.zeros(5))
|
724 |
+
|
725 |
+
# test for ticket #9137
|
726 |
+
a = []
|
727 |
+
a1_idx = np.unique(a, return_index=True)[1]
|
728 |
+
a2_inv = np.unique(a, return_inverse=True)[1]
|
729 |
+
a3_idx, a3_inv = np.unique(a, return_index=True,
|
730 |
+
return_inverse=True)[1:]
|
731 |
+
assert_equal(a1_idx.dtype, np.intp)
|
732 |
+
assert_equal(a2_inv.dtype, np.intp)
|
733 |
+
assert_equal(a3_idx.dtype, np.intp)
|
734 |
+
assert_equal(a3_inv.dtype, np.intp)
|
735 |
+
|
736 |
+
# test for ticket 2111 - float
|
737 |
+
a = [2.0, np.nan, 1.0, np.nan]
|
738 |
+
ua = [1.0, 2.0, np.nan]
|
739 |
+
ua_idx = [2, 0, 1]
|
740 |
+
ua_inv = [1, 2, 0, 2]
|
741 |
+
ua_cnt = [1, 1, 2]
|
742 |
+
assert_equal(np.unique(a), ua)
|
743 |
+
assert_equal(np.unique(a, return_index=True), (ua, ua_idx))
|
744 |
+
assert_equal(np.unique(a, return_inverse=True), (ua, ua_inv))
|
745 |
+
assert_equal(np.unique(a, return_counts=True), (ua, ua_cnt))
|
746 |
+
|
747 |
+
# test for ticket 2111 - complex
|
748 |
+
a = [2.0-1j, np.nan, 1.0+1j, complex(0.0, np.nan), complex(1.0, np.nan)]
|
749 |
+
ua = [1.0+1j, 2.0-1j, complex(0.0, np.nan)]
|
750 |
+
ua_idx = [2, 0, 3]
|
751 |
+
ua_inv = [1, 2, 0, 2, 2]
|
752 |
+
ua_cnt = [1, 1, 3]
|
753 |
+
assert_equal(np.unique(a), ua)
|
754 |
+
assert_equal(np.unique(a, return_index=True), (ua, ua_idx))
|
755 |
+
assert_equal(np.unique(a, return_inverse=True), (ua, ua_inv))
|
756 |
+
assert_equal(np.unique(a, return_counts=True), (ua, ua_cnt))
|
757 |
+
|
758 |
+
# test for ticket 2111 - datetime64
|
759 |
+
nat = np.datetime64('nat')
|
760 |
+
a = [np.datetime64('2020-12-26'), nat, np.datetime64('2020-12-24'), nat]
|
761 |
+
ua = [np.datetime64('2020-12-24'), np.datetime64('2020-12-26'), nat]
|
762 |
+
ua_idx = [2, 0, 1]
|
763 |
+
ua_inv = [1, 2, 0, 2]
|
764 |
+
ua_cnt = [1, 1, 2]
|
765 |
+
assert_equal(np.unique(a), ua)
|
766 |
+
assert_equal(np.unique(a, return_index=True), (ua, ua_idx))
|
767 |
+
assert_equal(np.unique(a, return_inverse=True), (ua, ua_inv))
|
768 |
+
assert_equal(np.unique(a, return_counts=True), (ua, ua_cnt))
|
769 |
+
|
770 |
+
# test for ticket 2111 - timedelta
|
771 |
+
nat = np.timedelta64('nat')
|
772 |
+
a = [np.timedelta64(1, 'D'), nat, np.timedelta64(1, 'h'), nat]
|
773 |
+
ua = [np.timedelta64(1, 'h'), np.timedelta64(1, 'D'), nat]
|
774 |
+
ua_idx = [2, 0, 1]
|
775 |
+
ua_inv = [1, 2, 0, 2]
|
776 |
+
ua_cnt = [1, 1, 2]
|
777 |
+
assert_equal(np.unique(a), ua)
|
778 |
+
assert_equal(np.unique(a, return_index=True), (ua, ua_idx))
|
779 |
+
assert_equal(np.unique(a, return_inverse=True), (ua, ua_inv))
|
780 |
+
assert_equal(np.unique(a, return_counts=True), (ua, ua_cnt))
|
781 |
+
|
782 |
+
# test for gh-19300
|
783 |
+
all_nans = [np.nan] * 4
|
784 |
+
ua = [np.nan]
|
785 |
+
ua_idx = [0]
|
786 |
+
ua_inv = [0, 0, 0, 0]
|
787 |
+
ua_cnt = [4]
|
788 |
+
assert_equal(np.unique(all_nans), ua)
|
789 |
+
assert_equal(np.unique(all_nans, return_index=True), (ua, ua_idx))
|
790 |
+
assert_equal(np.unique(all_nans, return_inverse=True), (ua, ua_inv))
|
791 |
+
assert_equal(np.unique(all_nans, return_counts=True), (ua, ua_cnt))
|
792 |
+
|
793 |
+
def test_unique_axis_errors(self):
|
794 |
+
assert_raises(TypeError, self._run_axis_tests, object)
|
795 |
+
assert_raises(TypeError, self._run_axis_tests,
|
796 |
+
[('a', int), ('b', object)])
|
797 |
+
|
798 |
+
assert_raises(np.AxisError, unique, np.arange(10), axis=2)
|
799 |
+
assert_raises(np.AxisError, unique, np.arange(10), axis=-2)
|
800 |
+
|
801 |
+
def test_unique_axis_list(self):
|
802 |
+
msg = "Unique failed on list of lists"
|
803 |
+
inp = [[0, 1, 0], [0, 1, 0]]
|
804 |
+
inp_arr = np.asarray(inp)
|
805 |
+
assert_array_equal(unique(inp, axis=0), unique(inp_arr, axis=0), msg)
|
806 |
+
assert_array_equal(unique(inp, axis=1), unique(inp_arr, axis=1), msg)
|
807 |
+
|
808 |
+
def test_unique_axis(self):
|
809 |
+
types = []
|
810 |
+
types.extend(np.typecodes['AllInteger'])
|
811 |
+
types.extend(np.typecodes['AllFloat'])
|
812 |
+
types.append('datetime64[D]')
|
813 |
+
types.append('timedelta64[D]')
|
814 |
+
types.append([('a', int), ('b', int)])
|
815 |
+
types.append([('a', int), ('b', float)])
|
816 |
+
|
817 |
+
for dtype in types:
|
818 |
+
self._run_axis_tests(dtype)
|
819 |
+
|
820 |
+
msg = 'Non-bitwise-equal booleans test failed'
|
821 |
+
data = np.arange(10, dtype=np.uint8).reshape(-1, 2).view(bool)
|
822 |
+
result = np.array([[False, True], [True, True]], dtype=bool)
|
823 |
+
assert_array_equal(unique(data, axis=0), result, msg)
|
824 |
+
|
825 |
+
msg = 'Negative zero equality test failed'
|
826 |
+
data = np.array([[-0.0, 0.0], [0.0, -0.0], [-0.0, 0.0], [0.0, -0.0]])
|
827 |
+
result = np.array([[-0.0, 0.0]])
|
828 |
+
assert_array_equal(unique(data, axis=0), result, msg)
|
829 |
+
|
830 |
+
@pytest.mark.parametrize("axis", [0, -1])
|
831 |
+
def test_unique_1d_with_axis(self, axis):
|
832 |
+
x = np.array([4, 3, 2, 3, 2, 1, 2, 2])
|
833 |
+
uniq = unique(x, axis=axis)
|
834 |
+
assert_array_equal(uniq, [1, 2, 3, 4])
|
835 |
+
|
836 |
+
def test_unique_axis_zeros(self):
|
837 |
+
# issue 15559
|
838 |
+
single_zero = np.empty(shape=(2, 0), dtype=np.int8)
|
839 |
+
uniq, idx, inv, cnt = unique(single_zero, axis=0, return_index=True,
|
840 |
+
return_inverse=True, return_counts=True)
|
841 |
+
|
842 |
+
# there's 1 element of shape (0,) along axis 0
|
843 |
+
assert_equal(uniq.dtype, single_zero.dtype)
|
844 |
+
assert_array_equal(uniq, np.empty(shape=(1, 0)))
|
845 |
+
assert_array_equal(idx, np.array([0]))
|
846 |
+
assert_array_equal(inv, np.array([0, 0]))
|
847 |
+
assert_array_equal(cnt, np.array([2]))
|
848 |
+
|
849 |
+
# there's 0 elements of shape (2,) along axis 1
|
850 |
+
uniq, idx, inv, cnt = unique(single_zero, axis=1, return_index=True,
|
851 |
+
return_inverse=True, return_counts=True)
|
852 |
+
|
853 |
+
assert_equal(uniq.dtype, single_zero.dtype)
|
854 |
+
assert_array_equal(uniq, np.empty(shape=(2, 0)))
|
855 |
+
assert_array_equal(idx, np.array([]))
|
856 |
+
assert_array_equal(inv, np.array([]))
|
857 |
+
assert_array_equal(cnt, np.array([]))
|
858 |
+
|
859 |
+
# test a "complicated" shape
|
860 |
+
shape = (0, 2, 0, 3, 0, 4, 0)
|
861 |
+
multiple_zeros = np.empty(shape=shape)
|
862 |
+
for axis in range(len(shape)):
|
863 |
+
expected_shape = list(shape)
|
864 |
+
if shape[axis] == 0:
|
865 |
+
expected_shape[axis] = 0
|
866 |
+
else:
|
867 |
+
expected_shape[axis] = 1
|
868 |
+
|
869 |
+
assert_array_equal(unique(multiple_zeros, axis=axis),
|
870 |
+
np.empty(shape=expected_shape))
|
871 |
+
|
872 |
+
def test_unique_masked(self):
|
873 |
+
# issue 8664
|
874 |
+
x = np.array([64, 0, 1, 2, 3, 63, 63, 0, 0, 0, 1, 2, 0, 63, 0],
|
875 |
+
dtype='uint8')
|
876 |
+
y = np.ma.masked_equal(x, 0)
|
877 |
+
|
878 |
+
v = np.unique(y)
|
879 |
+
v2, i, c = np.unique(y, return_index=True, return_counts=True)
|
880 |
+
|
881 |
+
msg = 'Unique returned different results when asked for index'
|
882 |
+
assert_array_equal(v.data, v2.data, msg)
|
883 |
+
assert_array_equal(v.mask, v2.mask, msg)
|
884 |
+
|
885 |
+
def test_unique_sort_order_with_axis(self):
|
886 |
+
# These tests fail if sorting along axis is done by treating subarrays
|
887 |
+
# as unsigned byte strings. See gh-10495.
|
888 |
+
fmt = "sort order incorrect for integer type '%s'"
|
889 |
+
for dt in 'bhilq':
|
890 |
+
a = np.array([[-1], [0]], dt)
|
891 |
+
b = np.unique(a, axis=0)
|
892 |
+
assert_array_equal(a, b, fmt % dt)
|
893 |
+
|
894 |
+
def _run_axis_tests(self, dtype):
|
895 |
+
data = np.array([[0, 1, 0, 0],
|
896 |
+
[1, 0, 0, 0],
|
897 |
+
[0, 1, 0, 0],
|
898 |
+
[1, 0, 0, 0]]).astype(dtype)
|
899 |
+
|
900 |
+
msg = 'Unique with 1d array and axis=0 failed'
|
901 |
+
result = np.array([0, 1])
|
902 |
+
assert_array_equal(unique(data), result.astype(dtype), msg)
|
903 |
+
|
904 |
+
msg = 'Unique with 2d array and axis=0 failed'
|
905 |
+
result = np.array([[0, 1, 0, 0], [1, 0, 0, 0]])
|
906 |
+
assert_array_equal(unique(data, axis=0), result.astype(dtype), msg)
|
907 |
+
|
908 |
+
msg = 'Unique with 2d array and axis=1 failed'
|
909 |
+
result = np.array([[0, 0, 1], [0, 1, 0], [0, 0, 1], [0, 1, 0]])
|
910 |
+
assert_array_equal(unique(data, axis=1), result.astype(dtype), msg)
|
911 |
+
|
912 |
+
msg = 'Unique with 3d array and axis=2 failed'
|
913 |
+
data3d = np.array([[[1, 1],
|
914 |
+
[1, 0]],
|
915 |
+
[[0, 1],
|
916 |
+
[0, 0]]]).astype(dtype)
|
917 |
+
result = np.take(data3d, [1, 0], axis=2)
|
918 |
+
assert_array_equal(unique(data3d, axis=2), result, msg)
|
919 |
+
|
920 |
+
uniq, idx, inv, cnt = unique(data, axis=0, return_index=True,
|
921 |
+
return_inverse=True, return_counts=True)
|
922 |
+
msg = "Unique's return_index=True failed with axis=0"
|
923 |
+
assert_array_equal(data[idx], uniq, msg)
|
924 |
+
msg = "Unique's return_inverse=True failed with axis=0"
|
925 |
+
assert_array_equal(uniq[inv], data)
|
926 |
+
msg = "Unique's return_counts=True failed with axis=0"
|
927 |
+
assert_array_equal(cnt, np.array([2, 2]), msg)
|
928 |
+
|
929 |
+
uniq, idx, inv, cnt = unique(data, axis=1, return_index=True,
|
930 |
+
return_inverse=True, return_counts=True)
|
931 |
+
msg = "Unique's return_index=True failed with axis=1"
|
932 |
+
assert_array_equal(data[:, idx], uniq)
|
933 |
+
msg = "Unique's return_inverse=True failed with axis=1"
|
934 |
+
assert_array_equal(uniq[:, inv], data)
|
935 |
+
msg = "Unique's return_counts=True failed with axis=1"
|
936 |
+
assert_array_equal(cnt, np.array([2, 1, 1]), msg)
|
937 |
+
|
938 |
+
def test_unique_nanequals(self):
|
939 |
+
# issue 20326
|
940 |
+
a = np.array([1, 1, np.nan, np.nan, np.nan])
|
941 |
+
unq = np.unique(a)
|
942 |
+
not_unq = np.unique(a, equal_nan=False)
|
943 |
+
assert_array_equal(unq, np.array([1, np.nan]))
|
944 |
+
assert_array_equal(not_unq, np.array([1, np.nan, np.nan, np.nan]))
|
venv/lib/python3.10/site-packages/numpy/lib/tests/test_arrayterator.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from operator import mul
|
2 |
+
from functools import reduce
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
from numpy.random import randint
|
6 |
+
from numpy.lib import Arrayterator
|
7 |
+
from numpy.testing import assert_
|
8 |
+
|
9 |
+
|
10 |
+
def test():
|
11 |
+
np.random.seed(np.arange(10))
|
12 |
+
|
13 |
+
# Create a random array
|
14 |
+
ndims = randint(5)+1
|
15 |
+
shape = tuple(randint(10)+1 for dim in range(ndims))
|
16 |
+
els = reduce(mul, shape)
|
17 |
+
a = np.arange(els)
|
18 |
+
a.shape = shape
|
19 |
+
|
20 |
+
buf_size = randint(2*els)
|
21 |
+
b = Arrayterator(a, buf_size)
|
22 |
+
|
23 |
+
# Check that each block has at most ``buf_size`` elements
|
24 |
+
for block in b:
|
25 |
+
assert_(len(block.flat) <= (buf_size or els))
|
26 |
+
|
27 |
+
# Check that all elements are iterated correctly
|
28 |
+
assert_(list(b.flat) == list(a.flat))
|
29 |
+
|
30 |
+
# Slice arrayterator
|
31 |
+
start = [randint(dim) for dim in shape]
|
32 |
+
stop = [randint(dim)+1 for dim in shape]
|
33 |
+
step = [randint(dim)+1 for dim in shape]
|
34 |
+
slice_ = tuple(slice(*t) for t in zip(start, stop, step))
|
35 |
+
c = b[slice_]
|
36 |
+
d = a[slice_]
|
37 |
+
|
38 |
+
# Check that each block has at most ``buf_size`` elements
|
39 |
+
for block in c:
|
40 |
+
assert_(len(block.flat) <= (buf_size or els))
|
41 |
+
|
42 |
+
# Check that the arrayterator is sliced correctly
|
43 |
+
assert_(np.all(c.__array__() == d))
|
44 |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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import numpy.ma as ma
|
5 |
+
from numpy.ma.mrecords import MaskedRecords
|
6 |
+
from numpy.ma.testutils import assert_equal
|
7 |
+
from numpy.testing import assert_, assert_raises
|
8 |
+
from numpy.lib.recfunctions import (
|
9 |
+
drop_fields, rename_fields, get_fieldstructure, recursive_fill_fields,
|
10 |
+
find_duplicates, merge_arrays, append_fields, stack_arrays, join_by,
|
11 |
+
repack_fields, unstructured_to_structured, structured_to_unstructured,
|
12 |
+
apply_along_fields, require_fields, assign_fields_by_name)
|
13 |
+
get_fieldspec = np.lib.recfunctions._get_fieldspec
|
14 |
+
get_names = np.lib.recfunctions.get_names
|
15 |
+
get_names_flat = np.lib.recfunctions.get_names_flat
|
16 |
+
zip_descr = np.lib.recfunctions._zip_descr
|
17 |
+
zip_dtype = np.lib.recfunctions._zip_dtype
|
18 |
+
|
19 |
+
|
20 |
+
class TestRecFunctions:
|
21 |
+
# Misc tests
|
22 |
+
|
23 |
+
def setup_method(self):
|
24 |
+
x = np.array([1, 2, ])
|
25 |
+
y = np.array([10, 20, 30])
|
26 |
+
z = np.array([('A', 1.), ('B', 2.)],
|
27 |
+
dtype=[('A', '|S3'), ('B', float)])
|
28 |
+
w = np.array([(1, (2, 3.0)), (4, (5, 6.0))],
|
29 |
+
dtype=[('a', int), ('b', [('ba', float), ('bb', int)])])
|
30 |
+
self.data = (w, x, y, z)
|
31 |
+
|
32 |
+
def test_zip_descr(self):
|
33 |
+
# Test zip_descr
|
34 |
+
(w, x, y, z) = self.data
|
35 |
+
|
36 |
+
# Std array
|
37 |
+
test = zip_descr((x, x), flatten=True)
|
38 |
+
assert_equal(test,
|
39 |
+
np.dtype([('', int), ('', int)]))
|
40 |
+
test = zip_descr((x, x), flatten=False)
|
41 |
+
assert_equal(test,
|
42 |
+
np.dtype([('', int), ('', int)]))
|
43 |
+
|
44 |
+
# Std & flexible-dtype
|
45 |
+
test = zip_descr((x, z), flatten=True)
|
46 |
+
assert_equal(test,
|
47 |
+
np.dtype([('', int), ('A', '|S3'), ('B', float)]))
|
48 |
+
test = zip_descr((x, z), flatten=False)
|
49 |
+
assert_equal(test,
|
50 |
+
np.dtype([('', int),
|
51 |
+
('', [('A', '|S3'), ('B', float)])]))
|
52 |
+
|
53 |
+
# Standard & nested dtype
|
54 |
+
test = zip_descr((x, w), flatten=True)
|
55 |
+
assert_equal(test,
|
56 |
+
np.dtype([('', int),
|
57 |
+
('a', int),
|
58 |
+
('ba', float), ('bb', int)]))
|
59 |
+
test = zip_descr((x, w), flatten=False)
|
60 |
+
assert_equal(test,
|
61 |
+
np.dtype([('', int),
|
62 |
+
('', [('a', int),
|
63 |
+
('b', [('ba', float), ('bb', int)])])]))
|
64 |
+
|
65 |
+
def test_drop_fields(self):
|
66 |
+
# Test drop_fields
|
67 |
+
a = np.array([(1, (2, 3.0)), (4, (5, 6.0))],
|
68 |
+
dtype=[('a', int), ('b', [('ba', float), ('bb', int)])])
|
69 |
+
|
70 |
+
# A basic field
|
71 |
+
test = drop_fields(a, 'a')
|
72 |
+
control = np.array([((2, 3.0),), ((5, 6.0),)],
|
73 |
+
dtype=[('b', [('ba', float), ('bb', int)])])
|
74 |
+
assert_equal(test, control)
|
75 |
+
|
76 |
+
# Another basic field (but nesting two fields)
|
77 |
+
test = drop_fields(a, 'b')
|
78 |
+
control = np.array([(1,), (4,)], dtype=[('a', int)])
|
79 |
+
assert_equal(test, control)
|
80 |
+
|
81 |
+
# A nested sub-field
|
82 |
+
test = drop_fields(a, ['ba', ])
|
83 |
+
control = np.array([(1, (3.0,)), (4, (6.0,))],
|
84 |
+
dtype=[('a', int), ('b', [('bb', int)])])
|
85 |
+
assert_equal(test, control)
|
86 |
+
|
87 |
+
# All the nested sub-field from a field: zap that field
|
88 |
+
test = drop_fields(a, ['ba', 'bb'])
|
89 |
+
control = np.array([(1,), (4,)], dtype=[('a', int)])
|
90 |
+
assert_equal(test, control)
|
91 |
+
|
92 |
+
# dropping all fields results in an array with no fields
|
93 |
+
test = drop_fields(a, ['a', 'b'])
|
94 |
+
control = np.array([(), ()], dtype=[])
|
95 |
+
assert_equal(test, control)
|
96 |
+
|
97 |
+
def test_rename_fields(self):
|
98 |
+
# Test rename fields
|
99 |
+
a = np.array([(1, (2, [3.0, 30.])), (4, (5, [6.0, 60.]))],
|
100 |
+
dtype=[('a', int),
|
101 |
+
('b', [('ba', float), ('bb', (float, 2))])])
|
102 |
+
test = rename_fields(a, {'a': 'A', 'bb': 'BB'})
|
103 |
+
newdtype = [('A', int), ('b', [('ba', float), ('BB', (float, 2))])]
|
104 |
+
control = a.view(newdtype)
|
105 |
+
assert_equal(test.dtype, newdtype)
|
106 |
+
assert_equal(test, control)
|
107 |
+
|
108 |
+
def test_get_names(self):
|
109 |
+
# Test get_names
|
110 |
+
ndtype = np.dtype([('A', '|S3'), ('B', float)])
|
111 |
+
test = get_names(ndtype)
|
112 |
+
assert_equal(test, ('A', 'B'))
|
113 |
+
|
114 |
+
ndtype = np.dtype([('a', int), ('b', [('ba', float), ('bb', int)])])
|
115 |
+
test = get_names(ndtype)
|
116 |
+
assert_equal(test, ('a', ('b', ('ba', 'bb'))))
|
117 |
+
|
118 |
+
ndtype = np.dtype([('a', int), ('b', [])])
|
119 |
+
test = get_names(ndtype)
|
120 |
+
assert_equal(test, ('a', ('b', ())))
|
121 |
+
|
122 |
+
ndtype = np.dtype([])
|
123 |
+
test = get_names(ndtype)
|
124 |
+
assert_equal(test, ())
|
125 |
+
|
126 |
+
def test_get_names_flat(self):
|
127 |
+
# Test get_names_flat
|
128 |
+
ndtype = np.dtype([('A', '|S3'), ('B', float)])
|
129 |
+
test = get_names_flat(ndtype)
|
130 |
+
assert_equal(test, ('A', 'B'))
|
131 |
+
|
132 |
+
ndtype = np.dtype([('a', int), ('b', [('ba', float), ('bb', int)])])
|
133 |
+
test = get_names_flat(ndtype)
|
134 |
+
assert_equal(test, ('a', 'b', 'ba', 'bb'))
|
135 |
+
|
136 |
+
ndtype = np.dtype([('a', int), ('b', [])])
|
137 |
+
test = get_names_flat(ndtype)
|
138 |
+
assert_equal(test, ('a', 'b'))
|
139 |
+
|
140 |
+
ndtype = np.dtype([])
|
141 |
+
test = get_names_flat(ndtype)
|
142 |
+
assert_equal(test, ())
|
143 |
+
|
144 |
+
def test_get_fieldstructure(self):
|
145 |
+
# Test get_fieldstructure
|
146 |
+
|
147 |
+
# No nested fields
|
148 |
+
ndtype = np.dtype([('A', '|S3'), ('B', float)])
|
149 |
+
test = get_fieldstructure(ndtype)
|
150 |
+
assert_equal(test, {'A': [], 'B': []})
|
151 |
+
|
152 |
+
# One 1-nested field
|
153 |
+
ndtype = np.dtype([('A', int), ('B', [('BA', float), ('BB', '|S1')])])
|
154 |
+
test = get_fieldstructure(ndtype)
|
155 |
+
assert_equal(test, {'A': [], 'B': [], 'BA': ['B', ], 'BB': ['B']})
|
156 |
+
|
157 |
+
# One 2-nested fields
|
158 |
+
ndtype = np.dtype([('A', int),
|
159 |
+
('B', [('BA', int),
|
160 |
+
('BB', [('BBA', int), ('BBB', int)])])])
|
161 |
+
test = get_fieldstructure(ndtype)
|
162 |
+
control = {'A': [], 'B': [], 'BA': ['B'], 'BB': ['B'],
|
163 |
+
'BBA': ['B', 'BB'], 'BBB': ['B', 'BB']}
|
164 |
+
assert_equal(test, control)
|
165 |
+
|
166 |
+
# 0 fields
|
167 |
+
ndtype = np.dtype([])
|
168 |
+
test = get_fieldstructure(ndtype)
|
169 |
+
assert_equal(test, {})
|
170 |
+
|
171 |
+
def test_find_duplicates(self):
|
172 |
+
# Test find_duplicates
|
173 |
+
a = ma.array([(2, (2., 'B')), (1, (2., 'B')), (2, (2., 'B')),
|
174 |
+
(1, (1., 'B')), (2, (2., 'B')), (2, (2., 'C'))],
|
175 |
+
mask=[(0, (0, 0)), (0, (0, 0)), (0, (0, 0)),
|
176 |
+
(0, (0, 0)), (1, (0, 0)), (0, (1, 0))],
|
177 |
+
dtype=[('A', int), ('B', [('BA', float), ('BB', '|S1')])])
|
178 |
+
|
179 |
+
test = find_duplicates(a, ignoremask=False, return_index=True)
|
180 |
+
control = [0, 2]
|
181 |
+
assert_equal(sorted(test[-1]), control)
|
182 |
+
assert_equal(test[0], a[test[-1]])
|
183 |
+
|
184 |
+
test = find_duplicates(a, key='A', return_index=True)
|
185 |
+
control = [0, 1, 2, 3, 5]
|
186 |
+
assert_equal(sorted(test[-1]), control)
|
187 |
+
assert_equal(test[0], a[test[-1]])
|
188 |
+
|
189 |
+
test = find_duplicates(a, key='B', return_index=True)
|
190 |
+
control = [0, 1, 2, 4]
|
191 |
+
assert_equal(sorted(test[-1]), control)
|
192 |
+
assert_equal(test[0], a[test[-1]])
|
193 |
+
|
194 |
+
test = find_duplicates(a, key='BA', return_index=True)
|
195 |
+
control = [0, 1, 2, 4]
|
196 |
+
assert_equal(sorted(test[-1]), control)
|
197 |
+
assert_equal(test[0], a[test[-1]])
|
198 |
+
|
199 |
+
test = find_duplicates(a, key='BB', return_index=True)
|
200 |
+
control = [0, 1, 2, 3, 4]
|
201 |
+
assert_equal(sorted(test[-1]), control)
|
202 |
+
assert_equal(test[0], a[test[-1]])
|
203 |
+
|
204 |
+
def test_find_duplicates_ignoremask(self):
|
205 |
+
# Test the ignoremask option of find_duplicates
|
206 |
+
ndtype = [('a', int)]
|
207 |
+
a = ma.array([1, 1, 1, 2, 2, 3, 3],
|
208 |
+
mask=[0, 0, 1, 0, 0, 0, 1]).view(ndtype)
|
209 |
+
test = find_duplicates(a, ignoremask=True, return_index=True)
|
210 |
+
control = [0, 1, 3, 4]
|
211 |
+
assert_equal(sorted(test[-1]), control)
|
212 |
+
assert_equal(test[0], a[test[-1]])
|
213 |
+
|
214 |
+
test = find_duplicates(a, ignoremask=False, return_index=True)
|
215 |
+
control = [0, 1, 2, 3, 4, 6]
|
216 |
+
assert_equal(sorted(test[-1]), control)
|
217 |
+
assert_equal(test[0], a[test[-1]])
|
218 |
+
|
219 |
+
def test_repack_fields(self):
|
220 |
+
dt = np.dtype('u1,f4,i8', align=True)
|
221 |
+
a = np.zeros(2, dtype=dt)
|
222 |
+
|
223 |
+
assert_equal(repack_fields(dt), np.dtype('u1,f4,i8'))
|
224 |
+
assert_equal(repack_fields(a).itemsize, 13)
|
225 |
+
assert_equal(repack_fields(repack_fields(dt), align=True), dt)
|
226 |
+
|
227 |
+
# make sure type is preserved
|
228 |
+
dt = np.dtype((np.record, dt))
|
229 |
+
assert_(repack_fields(dt).type is np.record)
|
230 |
+
|
231 |
+
def test_structured_to_unstructured(self, tmp_path):
|
232 |
+
a = np.zeros(4, dtype=[('a', 'i4'), ('b', 'f4,u2'), ('c', 'f4', 2)])
|
233 |
+
out = structured_to_unstructured(a)
|
234 |
+
assert_equal(out, np.zeros((4,5), dtype='f8'))
|
235 |
+
|
236 |
+
b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)],
|
237 |
+
dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')])
|
238 |
+
out = np.mean(structured_to_unstructured(b[['x', 'z']]), axis=-1)
|
239 |
+
assert_equal(out, np.array([ 3. , 5.5, 9. , 11. ]))
|
240 |
+
out = np.mean(structured_to_unstructured(b[['x']]), axis=-1)
|
241 |
+
assert_equal(out, np.array([ 1. , 4. , 7. , 10. ]))
|
242 |
+
|
243 |
+
c = np.arange(20).reshape((4,5))
|
244 |
+
out = unstructured_to_structured(c, a.dtype)
|
245 |
+
want = np.array([( 0, ( 1., 2), [ 3., 4.]),
|
246 |
+
( 5, ( 6., 7), [ 8., 9.]),
|
247 |
+
(10, (11., 12), [13., 14.]),
|
248 |
+
(15, (16., 17), [18., 19.])],
|
249 |
+
dtype=[('a', 'i4'),
|
250 |
+
('b', [('f0', 'f4'), ('f1', 'u2')]),
|
251 |
+
('c', 'f4', (2,))])
|
252 |
+
assert_equal(out, want)
|
253 |
+
|
254 |
+
d = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)],
|
255 |
+
dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')])
|
256 |
+
assert_equal(apply_along_fields(np.mean, d),
|
257 |
+
np.array([ 8.0/3, 16.0/3, 26.0/3, 11. ]))
|
258 |
+
assert_equal(apply_along_fields(np.mean, d[['x', 'z']]),
|
259 |
+
np.array([ 3. , 5.5, 9. , 11. ]))
|
260 |
+
|
261 |
+
# check that for uniform field dtypes we get a view, not a copy:
|
262 |
+
d = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)],
|
263 |
+
dtype=[('x', 'i4'), ('y', 'i4'), ('z', 'i4')])
|
264 |
+
dd = structured_to_unstructured(d)
|
265 |
+
ddd = unstructured_to_structured(dd, d.dtype)
|
266 |
+
assert_(np.shares_memory(dd, d))
|
267 |
+
assert_(np.shares_memory(ddd, d))
|
268 |
+
|
269 |
+
# check that reversing the order of attributes works
|
270 |
+
dd_attrib_rev = structured_to_unstructured(d[['z', 'x']])
|
271 |
+
assert_equal(dd_attrib_rev, [[5, 1], [7, 4], [11, 7], [12, 10]])
|
272 |
+
assert_(np.shares_memory(dd_attrib_rev, d))
|
273 |
+
|
274 |
+
# including uniform fields with subarrays unpacked
|
275 |
+
d = np.array([(1, [2, 3], [[ 4, 5], [ 6, 7]]),
|
276 |
+
(8, [9, 10], [[11, 12], [13, 14]])],
|
277 |
+
dtype=[('x0', 'i4'), ('x1', ('i4', 2)),
|
278 |
+
('x2', ('i4', (2, 2)))])
|
279 |
+
dd = structured_to_unstructured(d)
|
280 |
+
ddd = unstructured_to_structured(dd, d.dtype)
|
281 |
+
assert_(np.shares_memory(dd, d))
|
282 |
+
assert_(np.shares_memory(ddd, d))
|
283 |
+
|
284 |
+
# check that reversing with sub-arrays works as expected
|
285 |
+
d_rev = d[::-1]
|
286 |
+
dd_rev = structured_to_unstructured(d_rev)
|
287 |
+
assert_equal(dd_rev, [[8, 9, 10, 11, 12, 13, 14],
|
288 |
+
[1, 2, 3, 4, 5, 6, 7]])
|
289 |
+
|
290 |
+
# check that sub-arrays keep the order of their values
|
291 |
+
d_attrib_rev = d[['x2', 'x1', 'x0']]
|
292 |
+
dd_attrib_rev = structured_to_unstructured(d_attrib_rev)
|
293 |
+
assert_equal(dd_attrib_rev, [[4, 5, 6, 7, 2, 3, 1],
|
294 |
+
[11, 12, 13, 14, 9, 10, 8]])
|
295 |
+
|
296 |
+
# with ignored field at the end
|
297 |
+
d = np.array([(1, [2, 3], [[4, 5], [6, 7]], 32),
|
298 |
+
(8, [9, 10], [[11, 12], [13, 14]], 64)],
|
299 |
+
dtype=[('x0', 'i4'), ('x1', ('i4', 2)),
|
300 |
+
('x2', ('i4', (2, 2))), ('ignored', 'u1')])
|
301 |
+
dd = structured_to_unstructured(d[['x0', 'x1', 'x2']])
|
302 |
+
assert_(np.shares_memory(dd, d))
|
303 |
+
assert_equal(dd, [[1, 2, 3, 4, 5, 6, 7],
|
304 |
+
[8, 9, 10, 11, 12, 13, 14]])
|
305 |
+
|
306 |
+
# test that nested fields with identical names don't break anything
|
307 |
+
point = np.dtype([('x', int), ('y', int)])
|
308 |
+
triangle = np.dtype([('a', point), ('b', point), ('c', point)])
|
309 |
+
arr = np.zeros(10, triangle)
|
310 |
+
res = structured_to_unstructured(arr, dtype=int)
|
311 |
+
assert_equal(res, np.zeros((10, 6), dtype=int))
|
312 |
+
|
313 |
+
|
314 |
+
# test nested combinations of subarrays and structured arrays, gh-13333
|
315 |
+
def subarray(dt, shape):
|
316 |
+
return np.dtype((dt, shape))
|
317 |
+
|
318 |
+
def structured(*dts):
|
319 |
+
return np.dtype([('x{}'.format(i), dt) for i, dt in enumerate(dts)])
|
320 |
+
|
321 |
+
def inspect(dt, dtype=None):
|
322 |
+
arr = np.zeros((), dt)
|
323 |
+
ret = structured_to_unstructured(arr, dtype=dtype)
|
324 |
+
backarr = unstructured_to_structured(ret, dt)
|
325 |
+
return ret.shape, ret.dtype, backarr.dtype
|
326 |
+
|
327 |
+
dt = structured(subarray(structured(np.int32, np.int32), 3))
|
328 |
+
assert_equal(inspect(dt), ((6,), np.int32, dt))
|
329 |
+
|
330 |
+
dt = structured(subarray(subarray(np.int32, 2), 2))
|
331 |
+
assert_equal(inspect(dt), ((4,), np.int32, dt))
|
332 |
+
|
333 |
+
dt = structured(np.int32)
|
334 |
+
assert_equal(inspect(dt), ((1,), np.int32, dt))
|
335 |
+
|
336 |
+
dt = structured(np.int32, subarray(subarray(np.int32, 2), 2))
|
337 |
+
assert_equal(inspect(dt), ((5,), np.int32, dt))
|
338 |
+
|
339 |
+
dt = structured()
|
340 |
+
assert_raises(ValueError, structured_to_unstructured, np.zeros(3, dt))
|
341 |
+
|
342 |
+
# these currently don't work, but we may make it work in the future
|
343 |
+
assert_raises(NotImplementedError, structured_to_unstructured,
|
344 |
+
np.zeros(3, dt), dtype=np.int32)
|
345 |
+
assert_raises(NotImplementedError, unstructured_to_structured,
|
346 |
+
np.zeros((3,0), dtype=np.int32))
|
347 |
+
|
348 |
+
# test supported ndarray subclasses
|
349 |
+
d_plain = np.array([(1, 2), (3, 4)], dtype=[('a', 'i4'), ('b', 'i4')])
|
350 |
+
dd_expected = structured_to_unstructured(d_plain, copy=True)
|
351 |
+
|
352 |
+
# recarray
|
353 |
+
d = d_plain.view(np.recarray)
|
354 |
+
|
355 |
+
dd = structured_to_unstructured(d, copy=False)
|
356 |
+
ddd = structured_to_unstructured(d, copy=True)
|
357 |
+
assert_(np.shares_memory(d, dd))
|
358 |
+
assert_(type(dd) is np.recarray)
|
359 |
+
assert_(type(ddd) is np.recarray)
|
360 |
+
assert_equal(dd, dd_expected)
|
361 |
+
assert_equal(ddd, dd_expected)
|
362 |
+
|
363 |
+
# memmap
|
364 |
+
d = np.memmap(tmp_path / 'memmap',
|
365 |
+
mode='w+',
|
366 |
+
dtype=d_plain.dtype,
|
367 |
+
shape=d_plain.shape)
|
368 |
+
d[:] = d_plain
|
369 |
+
dd = structured_to_unstructured(d, copy=False)
|
370 |
+
ddd = structured_to_unstructured(d, copy=True)
|
371 |
+
assert_(np.shares_memory(d, dd))
|
372 |
+
assert_(type(dd) is np.memmap)
|
373 |
+
assert_(type(ddd) is np.memmap)
|
374 |
+
assert_equal(dd, dd_expected)
|
375 |
+
assert_equal(ddd, dd_expected)
|
376 |
+
|
377 |
+
def test_unstructured_to_structured(self):
|
378 |
+
# test if dtype is the args of np.dtype
|
379 |
+
a = np.zeros((20, 2))
|
380 |
+
test_dtype_args = [('x', float), ('y', float)]
|
381 |
+
test_dtype = np.dtype(test_dtype_args)
|
382 |
+
field1 = unstructured_to_structured(a, dtype=test_dtype_args) # now
|
383 |
+
field2 = unstructured_to_structured(a, dtype=test_dtype) # before
|
384 |
+
assert_equal(field1, field2)
|
385 |
+
|
386 |
+
def test_field_assignment_by_name(self):
|
387 |
+
a = np.ones(2, dtype=[('a', 'i4'), ('b', 'f8'), ('c', 'u1')])
|
388 |
+
newdt = [('b', 'f4'), ('c', 'u1')]
|
389 |
+
|
390 |
+
assert_equal(require_fields(a, newdt), np.ones(2, newdt))
|
391 |
+
|
392 |
+
b = np.array([(1,2), (3,4)], dtype=newdt)
|
393 |
+
assign_fields_by_name(a, b, zero_unassigned=False)
|
394 |
+
assert_equal(a, np.array([(1,1,2),(1,3,4)], dtype=a.dtype))
|
395 |
+
assign_fields_by_name(a, b)
|
396 |
+
assert_equal(a, np.array([(0,1,2),(0,3,4)], dtype=a.dtype))
|
397 |
+
|
398 |
+
# test nested fields
|
399 |
+
a = np.ones(2, dtype=[('a', [('b', 'f8'), ('c', 'u1')])])
|
400 |
+
newdt = [('a', [('c', 'u1')])]
|
401 |
+
assert_equal(require_fields(a, newdt), np.ones(2, newdt))
|
402 |
+
b = np.array([((2,),), ((3,),)], dtype=newdt)
|
403 |
+
assign_fields_by_name(a, b, zero_unassigned=False)
|
404 |
+
assert_equal(a, np.array([((1,2),), ((1,3),)], dtype=a.dtype))
|
405 |
+
assign_fields_by_name(a, b)
|
406 |
+
assert_equal(a, np.array([((0,2),), ((0,3),)], dtype=a.dtype))
|
407 |
+
|
408 |
+
# test unstructured code path for 0d arrays
|
409 |
+
a, b = np.array(3), np.array(0)
|
410 |
+
assign_fields_by_name(b, a)
|
411 |
+
assert_equal(b[()], 3)
|
412 |
+
|
413 |
+
|
414 |
+
class TestRecursiveFillFields:
|
415 |
+
# Test recursive_fill_fields.
|
416 |
+
def test_simple_flexible(self):
|
417 |
+
# Test recursive_fill_fields on flexible-array
|
418 |
+
a = np.array([(1, 10.), (2, 20.)], dtype=[('A', int), ('B', float)])
|
419 |
+
b = np.zeros((3,), dtype=a.dtype)
|
420 |
+
test = recursive_fill_fields(a, b)
|
421 |
+
control = np.array([(1, 10.), (2, 20.), (0, 0.)],
|
422 |
+
dtype=[('A', int), ('B', float)])
|
423 |
+
assert_equal(test, control)
|
424 |
+
|
425 |
+
def test_masked_flexible(self):
|
426 |
+
# Test recursive_fill_fields on masked flexible-array
|
427 |
+
a = ma.array([(1, 10.), (2, 20.)], mask=[(0, 1), (1, 0)],
|
428 |
+
dtype=[('A', int), ('B', float)])
|
429 |
+
b = ma.zeros((3,), dtype=a.dtype)
|
430 |
+
test = recursive_fill_fields(a, b)
|
431 |
+
control = ma.array([(1, 10.), (2, 20.), (0, 0.)],
|
432 |
+
mask=[(0, 1), (1, 0), (0, 0)],
|
433 |
+
dtype=[('A', int), ('B', float)])
|
434 |
+
assert_equal(test, control)
|
435 |
+
|
436 |
+
|
437 |
+
class TestMergeArrays:
|
438 |
+
# Test merge_arrays
|
439 |
+
|
440 |
+
def setup_method(self):
|
441 |
+
x = np.array([1, 2, ])
|
442 |
+
y = np.array([10, 20, 30])
|
443 |
+
z = np.array(
|
444 |
+
[('A', 1.), ('B', 2.)], dtype=[('A', '|S3'), ('B', float)])
|
445 |
+
w = np.array(
|
446 |
+
[(1, (2, 3.0, ())), (4, (5, 6.0, ()))],
|
447 |
+
dtype=[('a', int), ('b', [('ba', float), ('bb', int), ('bc', [])])])
|
448 |
+
self.data = (w, x, y, z)
|
449 |
+
|
450 |
+
def test_solo(self):
|
451 |
+
# Test merge_arrays on a single array.
|
452 |
+
(_, x, _, z) = self.data
|
453 |
+
|
454 |
+
test = merge_arrays(x)
|
455 |
+
control = np.array([(1,), (2,)], dtype=[('f0', int)])
|
456 |
+
assert_equal(test, control)
|
457 |
+
test = merge_arrays((x,))
|
458 |
+
assert_equal(test, control)
|
459 |
+
|
460 |
+
test = merge_arrays(z, flatten=False)
|
461 |
+
assert_equal(test, z)
|
462 |
+
test = merge_arrays(z, flatten=True)
|
463 |
+
assert_equal(test, z)
|
464 |
+
|
465 |
+
def test_solo_w_flatten(self):
|
466 |
+
# Test merge_arrays on a single array w & w/o flattening
|
467 |
+
w = self.data[0]
|
468 |
+
test = merge_arrays(w, flatten=False)
|
469 |
+
assert_equal(test, w)
|
470 |
+
|
471 |
+
test = merge_arrays(w, flatten=True)
|
472 |
+
control = np.array([(1, 2, 3.0), (4, 5, 6.0)],
|
473 |
+
dtype=[('a', int), ('ba', float), ('bb', int)])
|
474 |
+
assert_equal(test, control)
|
475 |
+
|
476 |
+
def test_standard(self):
|
477 |
+
# Test standard & standard
|
478 |
+
# Test merge arrays
|
479 |
+
(_, x, y, _) = self.data
|
480 |
+
test = merge_arrays((x, y), usemask=False)
|
481 |
+
control = np.array([(1, 10), (2, 20), (-1, 30)],
|
482 |
+
dtype=[('f0', int), ('f1', int)])
|
483 |
+
assert_equal(test, control)
|
484 |
+
|
485 |
+
test = merge_arrays((x, y), usemask=True)
|
486 |
+
control = ma.array([(1, 10), (2, 20), (-1, 30)],
|
487 |
+
mask=[(0, 0), (0, 0), (1, 0)],
|
488 |
+
dtype=[('f0', int), ('f1', int)])
|
489 |
+
assert_equal(test, control)
|
490 |
+
assert_equal(test.mask, control.mask)
|
491 |
+
|
492 |
+
def test_flatten(self):
|
493 |
+
# Test standard & flexible
|
494 |
+
(_, x, _, z) = self.data
|
495 |
+
test = merge_arrays((x, z), flatten=True)
|
496 |
+
control = np.array([(1, 'A', 1.), (2, 'B', 2.)],
|
497 |
+
dtype=[('f0', int), ('A', '|S3'), ('B', float)])
|
498 |
+
assert_equal(test, control)
|
499 |
+
|
500 |
+
test = merge_arrays((x, z), flatten=False)
|
501 |
+
control = np.array([(1, ('A', 1.)), (2, ('B', 2.))],
|
502 |
+
dtype=[('f0', int),
|
503 |
+
('f1', [('A', '|S3'), ('B', float)])])
|
504 |
+
assert_equal(test, control)
|
505 |
+
|
506 |
+
def test_flatten_wflexible(self):
|
507 |
+
# Test flatten standard & nested
|
508 |
+
(w, x, _, _) = self.data
|
509 |
+
test = merge_arrays((x, w), flatten=True)
|
510 |
+
control = np.array([(1, 1, 2, 3.0), (2, 4, 5, 6.0)],
|
511 |
+
dtype=[('f0', int),
|
512 |
+
('a', int), ('ba', float), ('bb', int)])
|
513 |
+
assert_equal(test, control)
|
514 |
+
|
515 |
+
test = merge_arrays((x, w), flatten=False)
|
516 |
+
controldtype = [('f0', int),
|
517 |
+
('f1', [('a', int),
|
518 |
+
('b', [('ba', float), ('bb', int), ('bc', [])])])]
|
519 |
+
control = np.array([(1., (1, (2, 3.0, ()))), (2, (4, (5, 6.0, ())))],
|
520 |
+
dtype=controldtype)
|
521 |
+
assert_equal(test, control)
|
522 |
+
|
523 |
+
def test_wmasked_arrays(self):
|
524 |
+
# Test merge_arrays masked arrays
|
525 |
+
(_, x, _, _) = self.data
|
526 |
+
mx = ma.array([1, 2, 3], mask=[1, 0, 0])
|
527 |
+
test = merge_arrays((x, mx), usemask=True)
|
528 |
+
control = ma.array([(1, 1), (2, 2), (-1, 3)],
|
529 |
+
mask=[(0, 1), (0, 0), (1, 0)],
|
530 |
+
dtype=[('f0', int), ('f1', int)])
|
531 |
+
assert_equal(test, control)
|
532 |
+
test = merge_arrays((x, mx), usemask=True, asrecarray=True)
|
533 |
+
assert_equal(test, control)
|
534 |
+
assert_(isinstance(test, MaskedRecords))
|
535 |
+
|
536 |
+
def test_w_singlefield(self):
|
537 |
+
# Test single field
|
538 |
+
test = merge_arrays((np.array([1, 2]).view([('a', int)]),
|
539 |
+
np.array([10., 20., 30.])),)
|
540 |
+
control = ma.array([(1, 10.), (2, 20.), (-1, 30.)],
|
541 |
+
mask=[(0, 0), (0, 0), (1, 0)],
|
542 |
+
dtype=[('a', int), ('f1', float)])
|
543 |
+
assert_equal(test, control)
|
544 |
+
|
545 |
+
def test_w_shorter_flex(self):
|
546 |
+
# Test merge_arrays w/ a shorter flexndarray.
|
547 |
+
z = self.data[-1]
|
548 |
+
|
549 |
+
# Fixme, this test looks incomplete and broken
|
550 |
+
#test = merge_arrays((z, np.array([10, 20, 30]).view([('C', int)])))
|
551 |
+
#control = np.array([('A', 1., 10), ('B', 2., 20), ('-1', -1, 20)],
|
552 |
+
# dtype=[('A', '|S3'), ('B', float), ('C', int)])
|
553 |
+
#assert_equal(test, control)
|
554 |
+
|
555 |
+
# Hack to avoid pyflakes warnings about unused variables
|
556 |
+
merge_arrays((z, np.array([10, 20, 30]).view([('C', int)])))
|
557 |
+
np.array([('A', 1., 10), ('B', 2., 20), ('-1', -1, 20)],
|
558 |
+
dtype=[('A', '|S3'), ('B', float), ('C', int)])
|
559 |
+
|
560 |
+
def test_singlerecord(self):
|
561 |
+
(_, x, y, z) = self.data
|
562 |
+
test = merge_arrays((x[0], y[0], z[0]), usemask=False)
|
563 |
+
control = np.array([(1, 10, ('A', 1))],
|
564 |
+
dtype=[('f0', int),
|
565 |
+
('f1', int),
|
566 |
+
('f2', [('A', '|S3'), ('B', float)])])
|
567 |
+
assert_equal(test, control)
|
568 |
+
|
569 |
+
|
570 |
+
class TestAppendFields:
|
571 |
+
# Test append_fields
|
572 |
+
|
573 |
+
def setup_method(self):
|
574 |
+
x = np.array([1, 2, ])
|
575 |
+
y = np.array([10, 20, 30])
|
576 |
+
z = np.array(
|
577 |
+
[('A', 1.), ('B', 2.)], dtype=[('A', '|S3'), ('B', float)])
|
578 |
+
w = np.array([(1, (2, 3.0)), (4, (5, 6.0))],
|
579 |
+
dtype=[('a', int), ('b', [('ba', float), ('bb', int)])])
|
580 |
+
self.data = (w, x, y, z)
|
581 |
+
|
582 |
+
def test_append_single(self):
|
583 |
+
# Test simple case
|
584 |
+
(_, x, _, _) = self.data
|
585 |
+
test = append_fields(x, 'A', data=[10, 20, 30])
|
586 |
+
control = ma.array([(1, 10), (2, 20), (-1, 30)],
|
587 |
+
mask=[(0, 0), (0, 0), (1, 0)],
|
588 |
+
dtype=[('f0', int), ('A', int)],)
|
589 |
+
assert_equal(test, control)
|
590 |
+
|
591 |
+
def test_append_double(self):
|
592 |
+
# Test simple case
|
593 |
+
(_, x, _, _) = self.data
|
594 |
+
test = append_fields(x, ('A', 'B'), data=[[10, 20, 30], [100, 200]])
|
595 |
+
control = ma.array([(1, 10, 100), (2, 20, 200), (-1, 30, -1)],
|
596 |
+
mask=[(0, 0, 0), (0, 0, 0), (1, 0, 1)],
|
597 |
+
dtype=[('f0', int), ('A', int), ('B', int)],)
|
598 |
+
assert_equal(test, control)
|
599 |
+
|
600 |
+
def test_append_on_flex(self):
|
601 |
+
# Test append_fields on flexible type arrays
|
602 |
+
z = self.data[-1]
|
603 |
+
test = append_fields(z, 'C', data=[10, 20, 30])
|
604 |
+
control = ma.array([('A', 1., 10), ('B', 2., 20), (-1, -1., 30)],
|
605 |
+
mask=[(0, 0, 0), (0, 0, 0), (1, 1, 0)],
|
606 |
+
dtype=[('A', '|S3'), ('B', float), ('C', int)],)
|
607 |
+
assert_equal(test, control)
|
608 |
+
|
609 |
+
def test_append_on_nested(self):
|
610 |
+
# Test append_fields on nested fields
|
611 |
+
w = self.data[0]
|
612 |
+
test = append_fields(w, 'C', data=[10, 20, 30])
|
613 |
+
control = ma.array([(1, (2, 3.0), 10),
|
614 |
+
(4, (5, 6.0), 20),
|
615 |
+
(-1, (-1, -1.), 30)],
|
616 |
+
mask=[(
|
617 |
+
0, (0, 0), 0), (0, (0, 0), 0), (1, (1, 1), 0)],
|
618 |
+
dtype=[('a', int),
|
619 |
+
('b', [('ba', float), ('bb', int)]),
|
620 |
+
('C', int)],)
|
621 |
+
assert_equal(test, control)
|
622 |
+
|
623 |
+
|
624 |
+
class TestStackArrays:
|
625 |
+
# Test stack_arrays
|
626 |
+
def setup_method(self):
|
627 |
+
x = np.array([1, 2, ])
|
628 |
+
y = np.array([10, 20, 30])
|
629 |
+
z = np.array(
|
630 |
+
[('A', 1.), ('B', 2.)], dtype=[('A', '|S3'), ('B', float)])
|
631 |
+
w = np.array([(1, (2, 3.0)), (4, (5, 6.0))],
|
632 |
+
dtype=[('a', int), ('b', [('ba', float), ('bb', int)])])
|
633 |
+
self.data = (w, x, y, z)
|
634 |
+
|
635 |
+
def test_solo(self):
|
636 |
+
# Test stack_arrays on single arrays
|
637 |
+
(_, x, _, _) = self.data
|
638 |
+
test = stack_arrays((x,))
|
639 |
+
assert_equal(test, x)
|
640 |
+
assert_(test is x)
|
641 |
+
|
642 |
+
test = stack_arrays(x)
|
643 |
+
assert_equal(test, x)
|
644 |
+
assert_(test is x)
|
645 |
+
|
646 |
+
def test_unnamed_fields(self):
|
647 |
+
# Tests combinations of arrays w/o named fields
|
648 |
+
(_, x, y, _) = self.data
|
649 |
+
|
650 |
+
test = stack_arrays((x, x), usemask=False)
|
651 |
+
control = np.array([1, 2, 1, 2])
|
652 |
+
assert_equal(test, control)
|
653 |
+
|
654 |
+
test = stack_arrays((x, y), usemask=False)
|
655 |
+
control = np.array([1, 2, 10, 20, 30])
|
656 |
+
assert_equal(test, control)
|
657 |
+
|
658 |
+
test = stack_arrays((y, x), usemask=False)
|
659 |
+
control = np.array([10, 20, 30, 1, 2])
|
660 |
+
assert_equal(test, control)
|
661 |
+
|
662 |
+
def test_unnamed_and_named_fields(self):
|
663 |
+
# Test combination of arrays w/ & w/o named fields
|
664 |
+
(_, x, _, z) = self.data
|
665 |
+
|
666 |
+
test = stack_arrays((x, z))
|
667 |
+
control = ma.array([(1, -1, -1), (2, -1, -1),
|
668 |
+
(-1, 'A', 1), (-1, 'B', 2)],
|
669 |
+
mask=[(0, 1, 1), (0, 1, 1),
|
670 |
+
(1, 0, 0), (1, 0, 0)],
|
671 |
+
dtype=[('f0', int), ('A', '|S3'), ('B', float)])
|
672 |
+
assert_equal(test, control)
|
673 |
+
assert_equal(test.mask, control.mask)
|
674 |
+
|
675 |
+
test = stack_arrays((z, x))
|
676 |
+
control = ma.array([('A', 1, -1), ('B', 2, -1),
|
677 |
+
(-1, -1, 1), (-1, -1, 2), ],
|
678 |
+
mask=[(0, 0, 1), (0, 0, 1),
|
679 |
+
(1, 1, 0), (1, 1, 0)],
|
680 |
+
dtype=[('A', '|S3'), ('B', float), ('f2', int)])
|
681 |
+
assert_equal(test, control)
|
682 |
+
assert_equal(test.mask, control.mask)
|
683 |
+
|
684 |
+
test = stack_arrays((z, z, x))
|
685 |
+
control = ma.array([('A', 1, -1), ('B', 2, -1),
|
686 |
+
('A', 1, -1), ('B', 2, -1),
|
687 |
+
(-1, -1, 1), (-1, -1, 2), ],
|
688 |
+
mask=[(0, 0, 1), (0, 0, 1),
|
689 |
+
(0, 0, 1), (0, 0, 1),
|
690 |
+
(1, 1, 0), (1, 1, 0)],
|
691 |
+
dtype=[('A', '|S3'), ('B', float), ('f2', int)])
|
692 |
+
assert_equal(test, control)
|
693 |
+
|
694 |
+
def test_matching_named_fields(self):
|
695 |
+
# Test combination of arrays w/ matching field names
|
696 |
+
(_, x, _, z) = self.data
|
697 |
+
zz = np.array([('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)],
|
698 |
+
dtype=[('A', '|S3'), ('B', float), ('C', float)])
|
699 |
+
test = stack_arrays((z, zz))
|
700 |
+
control = ma.array([('A', 1, -1), ('B', 2, -1),
|
701 |
+
(
|
702 |
+
'a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)],
|
703 |
+
dtype=[('A', '|S3'), ('B', float), ('C', float)],
|
704 |
+
mask=[(0, 0, 1), (0, 0, 1),
|
705 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0)])
|
706 |
+
assert_equal(test, control)
|
707 |
+
assert_equal(test.mask, control.mask)
|
708 |
+
|
709 |
+
test = stack_arrays((z, zz, x))
|
710 |
+
ndtype = [('A', '|S3'), ('B', float), ('C', float), ('f3', int)]
|
711 |
+
control = ma.array([('A', 1, -1, -1), ('B', 2, -1, -1),
|
712 |
+
('a', 10., 100., -1), ('b', 20., 200., -1),
|
713 |
+
('c', 30., 300., -1),
|
714 |
+
(-1, -1, -1, 1), (-1, -1, -1, 2)],
|
715 |
+
dtype=ndtype,
|
716 |
+
mask=[(0, 0, 1, 1), (0, 0, 1, 1),
|
717 |
+
(0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1),
|
718 |
+
(1, 1, 1, 0), (1, 1, 1, 0)])
|
719 |
+
assert_equal(test, control)
|
720 |
+
assert_equal(test.mask, control.mask)
|
721 |
+
|
722 |
+
def test_defaults(self):
|
723 |
+
# Test defaults: no exception raised if keys of defaults are not fields.
|
724 |
+
(_, _, _, z) = self.data
|
725 |
+
zz = np.array([('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)],
|
726 |
+
dtype=[('A', '|S3'), ('B', float), ('C', float)])
|
727 |
+
defaults = {'A': '???', 'B': -999., 'C': -9999., 'D': -99999.}
|
728 |
+
test = stack_arrays((z, zz), defaults=defaults)
|
729 |
+
control = ma.array([('A', 1, -9999.), ('B', 2, -9999.),
|
730 |
+
(
|
731 |
+
'a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)],
|
732 |
+
dtype=[('A', '|S3'), ('B', float), ('C', float)],
|
733 |
+
mask=[(0, 0, 1), (0, 0, 1),
|
734 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0)])
|
735 |
+
assert_equal(test, control)
|
736 |
+
assert_equal(test.data, control.data)
|
737 |
+
assert_equal(test.mask, control.mask)
|
738 |
+
|
739 |
+
def test_autoconversion(self):
|
740 |
+
# Tests autoconversion
|
741 |
+
adtype = [('A', int), ('B', bool), ('C', float)]
|
742 |
+
a = ma.array([(1, 2, 3)], mask=[(0, 1, 0)], dtype=adtype)
|
743 |
+
bdtype = [('A', int), ('B', float), ('C', float)]
|
744 |
+
b = ma.array([(4, 5, 6)], dtype=bdtype)
|
745 |
+
control = ma.array([(1, 2, 3), (4, 5, 6)], mask=[(0, 1, 0), (0, 0, 0)],
|
746 |
+
dtype=bdtype)
|
747 |
+
test = stack_arrays((a, b), autoconvert=True)
|
748 |
+
assert_equal(test, control)
|
749 |
+
assert_equal(test.mask, control.mask)
|
750 |
+
with assert_raises(TypeError):
|
751 |
+
stack_arrays((a, b), autoconvert=False)
|
752 |
+
|
753 |
+
def test_checktitles(self):
|
754 |
+
# Test using titles in the field names
|
755 |
+
adtype = [(('a', 'A'), int), (('b', 'B'), bool), (('c', 'C'), float)]
|
756 |
+
a = ma.array([(1, 2, 3)], mask=[(0, 1, 0)], dtype=adtype)
|
757 |
+
bdtype = [(('a', 'A'), int), (('b', 'B'), bool), (('c', 'C'), float)]
|
758 |
+
b = ma.array([(4, 5, 6)], dtype=bdtype)
|
759 |
+
test = stack_arrays((a, b))
|
760 |
+
control = ma.array([(1, 2, 3), (4, 5, 6)], mask=[(0, 1, 0), (0, 0, 0)],
|
761 |
+
dtype=bdtype)
|
762 |
+
assert_equal(test, control)
|
763 |
+
assert_equal(test.mask, control.mask)
|
764 |
+
|
765 |
+
def test_subdtype(self):
|
766 |
+
z = np.array([
|
767 |
+
('A', 1), ('B', 2)
|
768 |
+
], dtype=[('A', '|S3'), ('B', float, (1,))])
|
769 |
+
zz = np.array([
|
770 |
+
('a', [10.], 100.), ('b', [20.], 200.), ('c', [30.], 300.)
|
771 |
+
], dtype=[('A', '|S3'), ('B', float, (1,)), ('C', float)])
|
772 |
+
|
773 |
+
res = stack_arrays((z, zz))
|
774 |
+
expected = ma.array(
|
775 |
+
data=[
|
776 |
+
(b'A', [1.0], 0),
|
777 |
+
(b'B', [2.0], 0),
|
778 |
+
(b'a', [10.0], 100.0),
|
779 |
+
(b'b', [20.0], 200.0),
|
780 |
+
(b'c', [30.0], 300.0)],
|
781 |
+
mask=[
|
782 |
+
(False, [False], True),
|
783 |
+
(False, [False], True),
|
784 |
+
(False, [False], False),
|
785 |
+
(False, [False], False),
|
786 |
+
(False, [False], False)
|
787 |
+
],
|
788 |
+
dtype=zz.dtype
|
789 |
+
)
|
790 |
+
assert_equal(res.dtype, expected.dtype)
|
791 |
+
assert_equal(res, expected)
|
792 |
+
assert_equal(res.mask, expected.mask)
|
793 |
+
|
794 |
+
|
795 |
+
class TestJoinBy:
|
796 |
+
def setup_method(self):
|
797 |
+
self.a = np.array(list(zip(np.arange(10), np.arange(50, 60),
|
798 |
+
np.arange(100, 110))),
|
799 |
+
dtype=[('a', int), ('b', int), ('c', int)])
|
800 |
+
self.b = np.array(list(zip(np.arange(5, 15), np.arange(65, 75),
|
801 |
+
np.arange(100, 110))),
|
802 |
+
dtype=[('a', int), ('b', int), ('d', int)])
|
803 |
+
|
804 |
+
def test_inner_join(self):
|
805 |
+
# Basic test of join_by
|
806 |
+
a, b = self.a, self.b
|
807 |
+
|
808 |
+
test = join_by('a', a, b, jointype='inner')
|
809 |
+
control = np.array([(5, 55, 65, 105, 100), (6, 56, 66, 106, 101),
|
810 |
+
(7, 57, 67, 107, 102), (8, 58, 68, 108, 103),
|
811 |
+
(9, 59, 69, 109, 104)],
|
812 |
+
dtype=[('a', int), ('b1', int), ('b2', int),
|
813 |
+
('c', int), ('d', int)])
|
814 |
+
assert_equal(test, control)
|
815 |
+
|
816 |
+
def test_join(self):
|
817 |
+
a, b = self.a, self.b
|
818 |
+
|
819 |
+
# Fixme, this test is broken
|
820 |
+
#test = join_by(('a', 'b'), a, b)
|
821 |
+
#control = np.array([(5, 55, 105, 100), (6, 56, 106, 101),
|
822 |
+
# (7, 57, 107, 102), (8, 58, 108, 103),
|
823 |
+
# (9, 59, 109, 104)],
|
824 |
+
# dtype=[('a', int), ('b', int),
|
825 |
+
# ('c', int), ('d', int)])
|
826 |
+
#assert_equal(test, control)
|
827 |
+
|
828 |
+
# Hack to avoid pyflakes unused variable warnings
|
829 |
+
join_by(('a', 'b'), a, b)
|
830 |
+
np.array([(5, 55, 105, 100), (6, 56, 106, 101),
|
831 |
+
(7, 57, 107, 102), (8, 58, 108, 103),
|
832 |
+
(9, 59, 109, 104)],
|
833 |
+
dtype=[('a', int), ('b', int),
|
834 |
+
('c', int), ('d', int)])
|
835 |
+
|
836 |
+
def test_join_subdtype(self):
|
837 |
+
# tests the bug in https://stackoverflow.com/q/44769632/102441
|
838 |
+
foo = np.array([(1,)],
|
839 |
+
dtype=[('key', int)])
|
840 |
+
bar = np.array([(1, np.array([1,2,3]))],
|
841 |
+
dtype=[('key', int), ('value', 'uint16', 3)])
|
842 |
+
res = join_by('key', foo, bar)
|
843 |
+
assert_equal(res, bar.view(ma.MaskedArray))
|
844 |
+
|
845 |
+
def test_outer_join(self):
|
846 |
+
a, b = self.a, self.b
|
847 |
+
|
848 |
+
test = join_by(('a', 'b'), a, b, 'outer')
|
849 |
+
control = ma.array([(0, 50, 100, -1), (1, 51, 101, -1),
|
850 |
+
(2, 52, 102, -1), (3, 53, 103, -1),
|
851 |
+
(4, 54, 104, -1), (5, 55, 105, -1),
|
852 |
+
(5, 65, -1, 100), (6, 56, 106, -1),
|
853 |
+
(6, 66, -1, 101), (7, 57, 107, -1),
|
854 |
+
(7, 67, -1, 102), (8, 58, 108, -1),
|
855 |
+
(8, 68, -1, 103), (9, 59, 109, -1),
|
856 |
+
(9, 69, -1, 104), (10, 70, -1, 105),
|
857 |
+
(11, 71, -1, 106), (12, 72, -1, 107),
|
858 |
+
(13, 73, -1, 108), (14, 74, -1, 109)],
|
859 |
+
mask=[(0, 0, 0, 1), (0, 0, 0, 1),
|
860 |
+
(0, 0, 0, 1), (0, 0, 0, 1),
|
861 |
+
(0, 0, 0, 1), (0, 0, 0, 1),
|
862 |
+
(0, 0, 1, 0), (0, 0, 0, 1),
|
863 |
+
(0, 0, 1, 0), (0, 0, 0, 1),
|
864 |
+
(0, 0, 1, 0), (0, 0, 0, 1),
|
865 |
+
(0, 0, 1, 0), (0, 0, 0, 1),
|
866 |
+
(0, 0, 1, 0), (0, 0, 1, 0),
|
867 |
+
(0, 0, 1, 0), (0, 0, 1, 0),
|
868 |
+
(0, 0, 1, 0), (0, 0, 1, 0)],
|
869 |
+
dtype=[('a', int), ('b', int),
|
870 |
+
('c', int), ('d', int)])
|
871 |
+
assert_equal(test, control)
|
872 |
+
|
873 |
+
def test_leftouter_join(self):
|
874 |
+
a, b = self.a, self.b
|
875 |
+
|
876 |
+
test = join_by(('a', 'b'), a, b, 'leftouter')
|
877 |
+
control = ma.array([(0, 50, 100, -1), (1, 51, 101, -1),
|
878 |
+
(2, 52, 102, -1), (3, 53, 103, -1),
|
879 |
+
(4, 54, 104, -1), (5, 55, 105, -1),
|
880 |
+
(6, 56, 106, -1), (7, 57, 107, -1),
|
881 |
+
(8, 58, 108, -1), (9, 59, 109, -1)],
|
882 |
+
mask=[(0, 0, 0, 1), (0, 0, 0, 1),
|
883 |
+
(0, 0, 0, 1), (0, 0, 0, 1),
|
884 |
+
(0, 0, 0, 1), (0, 0, 0, 1),
|
885 |
+
(0, 0, 0, 1), (0, 0, 0, 1),
|
886 |
+
(0, 0, 0, 1), (0, 0, 0, 1)],
|
887 |
+
dtype=[('a', int), ('b', int), ('c', int), ('d', int)])
|
888 |
+
assert_equal(test, control)
|
889 |
+
|
890 |
+
def test_different_field_order(self):
|
891 |
+
# gh-8940
|
892 |
+
a = np.zeros(3, dtype=[('a', 'i4'), ('b', 'f4'), ('c', 'u1')])
|
893 |
+
b = np.ones(3, dtype=[('c', 'u1'), ('b', 'f4'), ('a', 'i4')])
|
894 |
+
# this should not give a FutureWarning:
|
895 |
+
j = join_by(['c', 'b'], a, b, jointype='inner', usemask=False)
|
896 |
+
assert_equal(j.dtype.names, ['b', 'c', 'a1', 'a2'])
|
897 |
+
|
898 |
+
def test_duplicate_keys(self):
|
899 |
+
a = np.zeros(3, dtype=[('a', 'i4'), ('b', 'f4'), ('c', 'u1')])
|
900 |
+
b = np.ones(3, dtype=[('c', 'u1'), ('b', 'f4'), ('a', 'i4')])
|
901 |
+
assert_raises(ValueError, join_by, ['a', 'b', 'b'], a, b)
|
902 |
+
|
903 |
+
def test_same_name_different_dtypes_key(self):
|
904 |
+
a_dtype = np.dtype([('key', 'S5'), ('value', '<f4')])
|
905 |
+
b_dtype = np.dtype([('key', 'S10'), ('value', '<f4')])
|
906 |
+
expected_dtype = np.dtype([
|
907 |
+
('key', 'S10'), ('value1', '<f4'), ('value2', '<f4')])
|
908 |
+
|
909 |
+
a = np.array([('Sarah', 8.0), ('John', 6.0)], dtype=a_dtype)
|
910 |
+
b = np.array([('Sarah', 10.0), ('John', 7.0)], dtype=b_dtype)
|
911 |
+
res = join_by('key', a, b)
|
912 |
+
|
913 |
+
assert_equal(res.dtype, expected_dtype)
|
914 |
+
|
915 |
+
def test_same_name_different_dtypes(self):
|
916 |
+
# gh-9338
|
917 |
+
a_dtype = np.dtype([('key', 'S10'), ('value', '<f4')])
|
918 |
+
b_dtype = np.dtype([('key', 'S10'), ('value', '<f8')])
|
919 |
+
expected_dtype = np.dtype([
|
920 |
+
('key', '|S10'), ('value1', '<f4'), ('value2', '<f8')])
|
921 |
+
|
922 |
+
a = np.array([('Sarah', 8.0), ('John', 6.0)], dtype=a_dtype)
|
923 |
+
b = np.array([('Sarah', 10.0), ('John', 7.0)], dtype=b_dtype)
|
924 |
+
res = join_by('key', a, b)
|
925 |
+
|
926 |
+
assert_equal(res.dtype, expected_dtype)
|
927 |
+
|
928 |
+
def test_subarray_key(self):
|
929 |
+
a_dtype = np.dtype([('pos', int, 3), ('f', '<f4')])
|
930 |
+
a = np.array([([1, 1, 1], np.pi), ([1, 2, 3], 0.0)], dtype=a_dtype)
|
931 |
+
|
932 |
+
b_dtype = np.dtype([('pos', int, 3), ('g', '<f4')])
|
933 |
+
b = np.array([([1, 1, 1], 3), ([3, 2, 1], 0.0)], dtype=b_dtype)
|
934 |
+
|
935 |
+
expected_dtype = np.dtype([('pos', int, 3), ('f', '<f4'), ('g', '<f4')])
|
936 |
+
expected = np.array([([1, 1, 1], np.pi, 3)], dtype=expected_dtype)
|
937 |
+
|
938 |
+
res = join_by('pos', a, b)
|
939 |
+
assert_equal(res.dtype, expected_dtype)
|
940 |
+
assert_equal(res, expected)
|
941 |
+
|
942 |
+
def test_padded_dtype(self):
|
943 |
+
dt = np.dtype('i1,f4', align=True)
|
944 |
+
dt.names = ('k', 'v')
|
945 |
+
assert_(len(dt.descr), 3) # padding field is inserted
|
946 |
+
|
947 |
+
a = np.array([(1, 3), (3, 2)], dt)
|
948 |
+
b = np.array([(1, 1), (2, 2)], dt)
|
949 |
+
res = join_by('k', a, b)
|
950 |
+
|
951 |
+
# no padding fields remain
|
952 |
+
expected_dtype = np.dtype([
|
953 |
+
('k', 'i1'), ('v1', 'f4'), ('v2', 'f4')
|
954 |
+
])
|
955 |
+
|
956 |
+
assert_equal(res.dtype, expected_dtype)
|
957 |
+
|
958 |
+
|
959 |
+
class TestJoinBy2:
|
960 |
+
@classmethod
|
961 |
+
def setup_method(cls):
|
962 |
+
cls.a = np.array(list(zip(np.arange(10), np.arange(50, 60),
|
963 |
+
np.arange(100, 110))),
|
964 |
+
dtype=[('a', int), ('b', int), ('c', int)])
|
965 |
+
cls.b = np.array(list(zip(np.arange(10), np.arange(65, 75),
|
966 |
+
np.arange(100, 110))),
|
967 |
+
dtype=[('a', int), ('b', int), ('d', int)])
|
968 |
+
|
969 |
+
def test_no_r1postfix(self):
|
970 |
+
# Basic test of join_by no_r1postfix
|
971 |
+
a, b = self.a, self.b
|
972 |
+
|
973 |
+
test = join_by(
|
974 |
+
'a', a, b, r1postfix='', r2postfix='2', jointype='inner')
|
975 |
+
control = np.array([(0, 50, 65, 100, 100), (1, 51, 66, 101, 101),
|
976 |
+
(2, 52, 67, 102, 102), (3, 53, 68, 103, 103),
|
977 |
+
(4, 54, 69, 104, 104), (5, 55, 70, 105, 105),
|
978 |
+
(6, 56, 71, 106, 106), (7, 57, 72, 107, 107),
|
979 |
+
(8, 58, 73, 108, 108), (9, 59, 74, 109, 109)],
|
980 |
+
dtype=[('a', int), ('b', int), ('b2', int),
|
981 |
+
('c', int), ('d', int)])
|
982 |
+
assert_equal(test, control)
|
983 |
+
|
984 |
+
def test_no_postfix(self):
|
985 |
+
assert_raises(ValueError, join_by, 'a', self.a, self.b,
|
986 |
+
r1postfix='', r2postfix='')
|
987 |
+
|
988 |
+
def test_no_r2postfix(self):
|
989 |
+
# Basic test of join_by no_r2postfix
|
990 |
+
a, b = self.a, self.b
|
991 |
+
|
992 |
+
test = join_by(
|
993 |
+
'a', a, b, r1postfix='1', r2postfix='', jointype='inner')
|
994 |
+
control = np.array([(0, 50, 65, 100, 100), (1, 51, 66, 101, 101),
|
995 |
+
(2, 52, 67, 102, 102), (3, 53, 68, 103, 103),
|
996 |
+
(4, 54, 69, 104, 104), (5, 55, 70, 105, 105),
|
997 |
+
(6, 56, 71, 106, 106), (7, 57, 72, 107, 107),
|
998 |
+
(8, 58, 73, 108, 108), (9, 59, 74, 109, 109)],
|
999 |
+
dtype=[('a', int), ('b1', int), ('b', int),
|
1000 |
+
('c', int), ('d', int)])
|
1001 |
+
assert_equal(test, control)
|
1002 |
+
|
1003 |
+
def test_two_keys_two_vars(self):
|
1004 |
+
a = np.array(list(zip(np.tile([10, 11], 5), np.repeat(np.arange(5), 2),
|
1005 |
+
np.arange(50, 60), np.arange(10, 20))),
|
1006 |
+
dtype=[('k', int), ('a', int), ('b', int), ('c', int)])
|
1007 |
+
|
1008 |
+
b = np.array(list(zip(np.tile([10, 11], 5), np.repeat(np.arange(5), 2),
|
1009 |
+
np.arange(65, 75), np.arange(0, 10))),
|
1010 |
+
dtype=[('k', int), ('a', int), ('b', int), ('c', int)])
|
1011 |
+
|
1012 |
+
control = np.array([(10, 0, 50, 65, 10, 0), (11, 0, 51, 66, 11, 1),
|
1013 |
+
(10, 1, 52, 67, 12, 2), (11, 1, 53, 68, 13, 3),
|
1014 |
+
(10, 2, 54, 69, 14, 4), (11, 2, 55, 70, 15, 5),
|
1015 |
+
(10, 3, 56, 71, 16, 6), (11, 3, 57, 72, 17, 7),
|
1016 |
+
(10, 4, 58, 73, 18, 8), (11, 4, 59, 74, 19, 9)],
|
1017 |
+
dtype=[('k', int), ('a', int), ('b1', int),
|
1018 |
+
('b2', int), ('c1', int), ('c2', int)])
|
1019 |
+
test = join_by(
|
1020 |
+
['a', 'k'], a, b, r1postfix='1', r2postfix='2', jointype='inner')
|
1021 |
+
assert_equal(test.dtype, control.dtype)
|
1022 |
+
assert_equal(test, control)
|
1023 |
+
|
1024 |
+
class TestAppendFieldsObj:
|
1025 |
+
"""
|
1026 |
+
Test append_fields with arrays containing objects
|
1027 |
+
"""
|
1028 |
+
# https://github.com/numpy/numpy/issues/2346
|
1029 |
+
|
1030 |
+
def setup_method(self):
|
1031 |
+
from datetime import date
|
1032 |
+
self.data = dict(obj=date(2000, 1, 1))
|
1033 |
+
|
1034 |
+
def test_append_to_objects(self):
|
1035 |
+
"Test append_fields when the base array contains objects"
|
1036 |
+
obj = self.data['obj']
|
1037 |
+
x = np.array([(obj, 1.), (obj, 2.)],
|
1038 |
+
dtype=[('A', object), ('B', float)])
|
1039 |
+
y = np.array([10, 20], dtype=int)
|
1040 |
+
test = append_fields(x, 'C', data=y, usemask=False)
|
1041 |
+
control = np.array([(obj, 1.0, 10), (obj, 2.0, 20)],
|
1042 |
+
dtype=[('A', object), ('B', float), ('C', int)])
|
1043 |
+
assert_equal(test, control)
|
venv/lib/python3.10/site-packages/numpy/lib/tests/test_stride_tricks.py
ADDED
@@ -0,0 +1,645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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from numpy.core._rational_tests import rational
|
3 |
+
from numpy.testing import (
|
4 |
+
assert_equal, assert_array_equal, assert_raises, assert_,
|
5 |
+
assert_raises_regex, assert_warns,
|
6 |
+
)
|
7 |
+
from numpy.lib.stride_tricks import (
|
8 |
+
as_strided, broadcast_arrays, _broadcast_shape, broadcast_to,
|
9 |
+
broadcast_shapes, sliding_window_view,
|
10 |
+
)
|
11 |
+
import pytest
|
12 |
+
|
13 |
+
|
14 |
+
def assert_shapes_correct(input_shapes, expected_shape):
|
15 |
+
# Broadcast a list of arrays with the given input shapes and check the
|
16 |
+
# common output shape.
|
17 |
+
|
18 |
+
inarrays = [np.zeros(s) for s in input_shapes]
|
19 |
+
outarrays = broadcast_arrays(*inarrays)
|
20 |
+
outshapes = [a.shape for a in outarrays]
|
21 |
+
expected = [expected_shape] * len(inarrays)
|
22 |
+
assert_equal(outshapes, expected)
|
23 |
+
|
24 |
+
|
25 |
+
def assert_incompatible_shapes_raise(input_shapes):
|
26 |
+
# Broadcast a list of arrays with the given (incompatible) input shapes
|
27 |
+
# and check that they raise a ValueError.
|
28 |
+
|
29 |
+
inarrays = [np.zeros(s) for s in input_shapes]
|
30 |
+
assert_raises(ValueError, broadcast_arrays, *inarrays)
|
31 |
+
|
32 |
+
|
33 |
+
def assert_same_as_ufunc(shape0, shape1, transposed=False, flipped=False):
|
34 |
+
# Broadcast two shapes against each other and check that the data layout
|
35 |
+
# is the same as if a ufunc did the broadcasting.
|
36 |
+
|
37 |
+
x0 = np.zeros(shape0, dtype=int)
|
38 |
+
# Note that multiply.reduce's identity element is 1.0, so when shape1==(),
|
39 |
+
# this gives the desired n==1.
|
40 |
+
n = int(np.multiply.reduce(shape1))
|
41 |
+
x1 = np.arange(n).reshape(shape1)
|
42 |
+
if transposed:
|
43 |
+
x0 = x0.T
|
44 |
+
x1 = x1.T
|
45 |
+
if flipped:
|
46 |
+
x0 = x0[::-1]
|
47 |
+
x1 = x1[::-1]
|
48 |
+
# Use the add ufunc to do the broadcasting. Since we're adding 0s to x1, the
|
49 |
+
# result should be exactly the same as the broadcasted view of x1.
|
50 |
+
y = x0 + x1
|
51 |
+
b0, b1 = broadcast_arrays(x0, x1)
|
52 |
+
assert_array_equal(y, b1)
|
53 |
+
|
54 |
+
|
55 |
+
def test_same():
|
56 |
+
x = np.arange(10)
|
57 |
+
y = np.arange(10)
|
58 |
+
bx, by = broadcast_arrays(x, y)
|
59 |
+
assert_array_equal(x, bx)
|
60 |
+
assert_array_equal(y, by)
|
61 |
+
|
62 |
+
def test_broadcast_kwargs():
|
63 |
+
# ensure that a TypeError is appropriately raised when
|
64 |
+
# np.broadcast_arrays() is called with any keyword
|
65 |
+
# argument other than 'subok'
|
66 |
+
x = np.arange(10)
|
67 |
+
y = np.arange(10)
|
68 |
+
|
69 |
+
with assert_raises_regex(TypeError, 'got an unexpected keyword'):
|
70 |
+
broadcast_arrays(x, y, dtype='float64')
|
71 |
+
|
72 |
+
|
73 |
+
def test_one_off():
|
74 |
+
x = np.array([[1, 2, 3]])
|
75 |
+
y = np.array([[1], [2], [3]])
|
76 |
+
bx, by = broadcast_arrays(x, y)
|
77 |
+
bx0 = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
|
78 |
+
by0 = bx0.T
|
79 |
+
assert_array_equal(bx0, bx)
|
80 |
+
assert_array_equal(by0, by)
|
81 |
+
|
82 |
+
|
83 |
+
def test_same_input_shapes():
|
84 |
+
# Check that the final shape is just the input shape.
|
85 |
+
|
86 |
+
data = [
|
87 |
+
(),
|
88 |
+
(1,),
|
89 |
+
(3,),
|
90 |
+
(0, 1),
|
91 |
+
(0, 3),
|
92 |
+
(1, 0),
|
93 |
+
(3, 0),
|
94 |
+
(1, 3),
|
95 |
+
(3, 1),
|
96 |
+
(3, 3),
|
97 |
+
]
|
98 |
+
for shape in data:
|
99 |
+
input_shapes = [shape]
|
100 |
+
# Single input.
|
101 |
+
assert_shapes_correct(input_shapes, shape)
|
102 |
+
# Double input.
|
103 |
+
input_shapes2 = [shape, shape]
|
104 |
+
assert_shapes_correct(input_shapes2, shape)
|
105 |
+
# Triple input.
|
106 |
+
input_shapes3 = [shape, shape, shape]
|
107 |
+
assert_shapes_correct(input_shapes3, shape)
|
108 |
+
|
109 |
+
|
110 |
+
def test_two_compatible_by_ones_input_shapes():
|
111 |
+
# Check that two different input shapes of the same length, but some have
|
112 |
+
# ones, broadcast to the correct shape.
|
113 |
+
|
114 |
+
data = [
|
115 |
+
[[(1,), (3,)], (3,)],
|
116 |
+
[[(1, 3), (3, 3)], (3, 3)],
|
117 |
+
[[(3, 1), (3, 3)], (3, 3)],
|
118 |
+
[[(1, 3), (3, 1)], (3, 3)],
|
119 |
+
[[(1, 1), (3, 3)], (3, 3)],
|
120 |
+
[[(1, 1), (1, 3)], (1, 3)],
|
121 |
+
[[(1, 1), (3, 1)], (3, 1)],
|
122 |
+
[[(1, 0), (0, 0)], (0, 0)],
|
123 |
+
[[(0, 1), (0, 0)], (0, 0)],
|
124 |
+
[[(1, 0), (0, 1)], (0, 0)],
|
125 |
+
[[(1, 1), (0, 0)], (0, 0)],
|
126 |
+
[[(1, 1), (1, 0)], (1, 0)],
|
127 |
+
[[(1, 1), (0, 1)], (0, 1)],
|
128 |
+
]
|
129 |
+
for input_shapes, expected_shape in data:
|
130 |
+
assert_shapes_correct(input_shapes, expected_shape)
|
131 |
+
# Reverse the input shapes since broadcasting should be symmetric.
|
132 |
+
assert_shapes_correct(input_shapes[::-1], expected_shape)
|
133 |
+
|
134 |
+
|
135 |
+
def test_two_compatible_by_prepending_ones_input_shapes():
|
136 |
+
# Check that two different input shapes (of different lengths) broadcast
|
137 |
+
# to the correct shape.
|
138 |
+
|
139 |
+
data = [
|
140 |
+
[[(), (3,)], (3,)],
|
141 |
+
[[(3,), (3, 3)], (3, 3)],
|
142 |
+
[[(3,), (3, 1)], (3, 3)],
|
143 |
+
[[(1,), (3, 3)], (3, 3)],
|
144 |
+
[[(), (3, 3)], (3, 3)],
|
145 |
+
[[(1, 1), (3,)], (1, 3)],
|
146 |
+
[[(1,), (3, 1)], (3, 1)],
|
147 |
+
[[(1,), (1, 3)], (1, 3)],
|
148 |
+
[[(), (1, 3)], (1, 3)],
|
149 |
+
[[(), (3, 1)], (3, 1)],
|
150 |
+
[[(), (0,)], (0,)],
|
151 |
+
[[(0,), (0, 0)], (0, 0)],
|
152 |
+
[[(0,), (0, 1)], (0, 0)],
|
153 |
+
[[(1,), (0, 0)], (0, 0)],
|
154 |
+
[[(), (0, 0)], (0, 0)],
|
155 |
+
[[(1, 1), (0,)], (1, 0)],
|
156 |
+
[[(1,), (0, 1)], (0, 1)],
|
157 |
+
[[(1,), (1, 0)], (1, 0)],
|
158 |
+
[[(), (1, 0)], (1, 0)],
|
159 |
+
[[(), (0, 1)], (0, 1)],
|
160 |
+
]
|
161 |
+
for input_shapes, expected_shape in data:
|
162 |
+
assert_shapes_correct(input_shapes, expected_shape)
|
163 |
+
# Reverse the input shapes since broadcasting should be symmetric.
|
164 |
+
assert_shapes_correct(input_shapes[::-1], expected_shape)
|
165 |
+
|
166 |
+
|
167 |
+
def test_incompatible_shapes_raise_valueerror():
|
168 |
+
# Check that a ValueError is raised for incompatible shapes.
|
169 |
+
|
170 |
+
data = [
|
171 |
+
[(3,), (4,)],
|
172 |
+
[(2, 3), (2,)],
|
173 |
+
[(3,), (3,), (4,)],
|
174 |
+
[(1, 3, 4), (2, 3, 3)],
|
175 |
+
]
|
176 |
+
for input_shapes in data:
|
177 |
+
assert_incompatible_shapes_raise(input_shapes)
|
178 |
+
# Reverse the input shapes since broadcasting should be symmetric.
|
179 |
+
assert_incompatible_shapes_raise(input_shapes[::-1])
|
180 |
+
|
181 |
+
|
182 |
+
def test_same_as_ufunc():
|
183 |
+
# Check that the data layout is the same as if a ufunc did the operation.
|
184 |
+
|
185 |
+
data = [
|
186 |
+
[[(1,), (3,)], (3,)],
|
187 |
+
[[(1, 3), (3, 3)], (3, 3)],
|
188 |
+
[[(3, 1), (3, 3)], (3, 3)],
|
189 |
+
[[(1, 3), (3, 1)], (3, 3)],
|
190 |
+
[[(1, 1), (3, 3)], (3, 3)],
|
191 |
+
[[(1, 1), (1, 3)], (1, 3)],
|
192 |
+
[[(1, 1), (3, 1)], (3, 1)],
|
193 |
+
[[(1, 0), (0, 0)], (0, 0)],
|
194 |
+
[[(0, 1), (0, 0)], (0, 0)],
|
195 |
+
[[(1, 0), (0, 1)], (0, 0)],
|
196 |
+
[[(1, 1), (0, 0)], (0, 0)],
|
197 |
+
[[(1, 1), (1, 0)], (1, 0)],
|
198 |
+
[[(1, 1), (0, 1)], (0, 1)],
|
199 |
+
[[(), (3,)], (3,)],
|
200 |
+
[[(3,), (3, 3)], (3, 3)],
|
201 |
+
[[(3,), (3, 1)], (3, 3)],
|
202 |
+
[[(1,), (3, 3)], (3, 3)],
|
203 |
+
[[(), (3, 3)], (3, 3)],
|
204 |
+
[[(1, 1), (3,)], (1, 3)],
|
205 |
+
[[(1,), (3, 1)], (3, 1)],
|
206 |
+
[[(1,), (1, 3)], (1, 3)],
|
207 |
+
[[(), (1, 3)], (1, 3)],
|
208 |
+
[[(), (3, 1)], (3, 1)],
|
209 |
+
[[(), (0,)], (0,)],
|
210 |
+
[[(0,), (0, 0)], (0, 0)],
|
211 |
+
[[(0,), (0, 1)], (0, 0)],
|
212 |
+
[[(1,), (0, 0)], (0, 0)],
|
213 |
+
[[(), (0, 0)], (0, 0)],
|
214 |
+
[[(1, 1), (0,)], (1, 0)],
|
215 |
+
[[(1,), (0, 1)], (0, 1)],
|
216 |
+
[[(1,), (1, 0)], (1, 0)],
|
217 |
+
[[(), (1, 0)], (1, 0)],
|
218 |
+
[[(), (0, 1)], (0, 1)],
|
219 |
+
]
|
220 |
+
for input_shapes, expected_shape in data:
|
221 |
+
assert_same_as_ufunc(input_shapes[0], input_shapes[1],
|
222 |
+
"Shapes: %s %s" % (input_shapes[0], input_shapes[1]))
|
223 |
+
# Reverse the input shapes since broadcasting should be symmetric.
|
224 |
+
assert_same_as_ufunc(input_shapes[1], input_shapes[0])
|
225 |
+
# Try them transposed, too.
|
226 |
+
assert_same_as_ufunc(input_shapes[0], input_shapes[1], True)
|
227 |
+
# ... and flipped for non-rank-0 inputs in order to test negative
|
228 |
+
# strides.
|
229 |
+
if () not in input_shapes:
|
230 |
+
assert_same_as_ufunc(input_shapes[0], input_shapes[1], False, True)
|
231 |
+
assert_same_as_ufunc(input_shapes[0], input_shapes[1], True, True)
|
232 |
+
|
233 |
+
|
234 |
+
def test_broadcast_to_succeeds():
|
235 |
+
data = [
|
236 |
+
[np.array(0), (0,), np.array(0)],
|
237 |
+
[np.array(0), (1,), np.zeros(1)],
|
238 |
+
[np.array(0), (3,), np.zeros(3)],
|
239 |
+
[np.ones(1), (1,), np.ones(1)],
|
240 |
+
[np.ones(1), (2,), np.ones(2)],
|
241 |
+
[np.ones(1), (1, 2, 3), np.ones((1, 2, 3))],
|
242 |
+
[np.arange(3), (3,), np.arange(3)],
|
243 |
+
[np.arange(3), (1, 3), np.arange(3).reshape(1, -1)],
|
244 |
+
[np.arange(3), (2, 3), np.array([[0, 1, 2], [0, 1, 2]])],
|
245 |
+
# test if shape is not a tuple
|
246 |
+
[np.ones(0), 0, np.ones(0)],
|
247 |
+
[np.ones(1), 1, np.ones(1)],
|
248 |
+
[np.ones(1), 2, np.ones(2)],
|
249 |
+
# these cases with size 0 are strange, but they reproduce the behavior
|
250 |
+
# of broadcasting with ufuncs (see test_same_as_ufunc above)
|
251 |
+
[np.ones(1), (0,), np.ones(0)],
|
252 |
+
[np.ones((1, 2)), (0, 2), np.ones((0, 2))],
|
253 |
+
[np.ones((2, 1)), (2, 0), np.ones((2, 0))],
|
254 |
+
]
|
255 |
+
for input_array, shape, expected in data:
|
256 |
+
actual = broadcast_to(input_array, shape)
|
257 |
+
assert_array_equal(expected, actual)
|
258 |
+
|
259 |
+
|
260 |
+
def test_broadcast_to_raises():
|
261 |
+
data = [
|
262 |
+
[(0,), ()],
|
263 |
+
[(1,), ()],
|
264 |
+
[(3,), ()],
|
265 |
+
[(3,), (1,)],
|
266 |
+
[(3,), (2,)],
|
267 |
+
[(3,), (4,)],
|
268 |
+
[(1, 2), (2, 1)],
|
269 |
+
[(1, 1), (1,)],
|
270 |
+
[(1,), -1],
|
271 |
+
[(1,), (-1,)],
|
272 |
+
[(1, 2), (-1, 2)],
|
273 |
+
]
|
274 |
+
for orig_shape, target_shape in data:
|
275 |
+
arr = np.zeros(orig_shape)
|
276 |
+
assert_raises(ValueError, lambda: broadcast_to(arr, target_shape))
|
277 |
+
|
278 |
+
|
279 |
+
def test_broadcast_shape():
|
280 |
+
# tests internal _broadcast_shape
|
281 |
+
# _broadcast_shape is already exercised indirectly by broadcast_arrays
|
282 |
+
# _broadcast_shape is also exercised by the public broadcast_shapes function
|
283 |
+
assert_equal(_broadcast_shape(), ())
|
284 |
+
assert_equal(_broadcast_shape([1, 2]), (2,))
|
285 |
+
assert_equal(_broadcast_shape(np.ones((1, 1))), (1, 1))
|
286 |
+
assert_equal(_broadcast_shape(np.ones((1, 1)), np.ones((3, 4))), (3, 4))
|
287 |
+
assert_equal(_broadcast_shape(*([np.ones((1, 2))] * 32)), (1, 2))
|
288 |
+
assert_equal(_broadcast_shape(*([np.ones((1, 2))] * 100)), (1, 2))
|
289 |
+
|
290 |
+
# regression tests for gh-5862
|
291 |
+
assert_equal(_broadcast_shape(*([np.ones(2)] * 32 + [1])), (2,))
|
292 |
+
bad_args = [np.ones(2)] * 32 + [np.ones(3)] * 32
|
293 |
+
assert_raises(ValueError, lambda: _broadcast_shape(*bad_args))
|
294 |
+
|
295 |
+
|
296 |
+
def test_broadcast_shapes_succeeds():
|
297 |
+
# tests public broadcast_shapes
|
298 |
+
data = [
|
299 |
+
[[], ()],
|
300 |
+
[[()], ()],
|
301 |
+
[[(7,)], (7,)],
|
302 |
+
[[(1, 2), (2,)], (1, 2)],
|
303 |
+
[[(1, 1)], (1, 1)],
|
304 |
+
[[(1, 1), (3, 4)], (3, 4)],
|
305 |
+
[[(6, 7), (5, 6, 1), (7,), (5, 1, 7)], (5, 6, 7)],
|
306 |
+
[[(5, 6, 1)], (5, 6, 1)],
|
307 |
+
[[(1, 3), (3, 1)], (3, 3)],
|
308 |
+
[[(1, 0), (0, 0)], (0, 0)],
|
309 |
+
[[(0, 1), (0, 0)], (0, 0)],
|
310 |
+
[[(1, 0), (0, 1)], (0, 0)],
|
311 |
+
[[(1, 1), (0, 0)], (0, 0)],
|
312 |
+
[[(1, 1), (1, 0)], (1, 0)],
|
313 |
+
[[(1, 1), (0, 1)], (0, 1)],
|
314 |
+
[[(), (0,)], (0,)],
|
315 |
+
[[(0,), (0, 0)], (0, 0)],
|
316 |
+
[[(0,), (0, 1)], (0, 0)],
|
317 |
+
[[(1,), (0, 0)], (0, 0)],
|
318 |
+
[[(), (0, 0)], (0, 0)],
|
319 |
+
[[(1, 1), (0,)], (1, 0)],
|
320 |
+
[[(1,), (0, 1)], (0, 1)],
|
321 |
+
[[(1,), (1, 0)], (1, 0)],
|
322 |
+
[[(), (1, 0)], (1, 0)],
|
323 |
+
[[(), (0, 1)], (0, 1)],
|
324 |
+
[[(1,), (3,)], (3,)],
|
325 |
+
[[2, (3, 2)], (3, 2)],
|
326 |
+
]
|
327 |
+
for input_shapes, target_shape in data:
|
328 |
+
assert_equal(broadcast_shapes(*input_shapes), target_shape)
|
329 |
+
|
330 |
+
assert_equal(broadcast_shapes(*([(1, 2)] * 32)), (1, 2))
|
331 |
+
assert_equal(broadcast_shapes(*([(1, 2)] * 100)), (1, 2))
|
332 |
+
|
333 |
+
# regression tests for gh-5862
|
334 |
+
assert_equal(broadcast_shapes(*([(2,)] * 32)), (2,))
|
335 |
+
|
336 |
+
|
337 |
+
def test_broadcast_shapes_raises():
|
338 |
+
# tests public broadcast_shapes
|
339 |
+
data = [
|
340 |
+
[(3,), (4,)],
|
341 |
+
[(2, 3), (2,)],
|
342 |
+
[(3,), (3,), (4,)],
|
343 |
+
[(1, 3, 4), (2, 3, 3)],
|
344 |
+
[(1, 2), (3,1), (3,2), (10, 5)],
|
345 |
+
[2, (2, 3)],
|
346 |
+
]
|
347 |
+
for input_shapes in data:
|
348 |
+
assert_raises(ValueError, lambda: broadcast_shapes(*input_shapes))
|
349 |
+
|
350 |
+
bad_args = [(2,)] * 32 + [(3,)] * 32
|
351 |
+
assert_raises(ValueError, lambda: broadcast_shapes(*bad_args))
|
352 |
+
|
353 |
+
|
354 |
+
def test_as_strided():
|
355 |
+
a = np.array([None])
|
356 |
+
a_view = as_strided(a)
|
357 |
+
expected = np.array([None])
|
358 |
+
assert_array_equal(a_view, np.array([None]))
|
359 |
+
|
360 |
+
a = np.array([1, 2, 3, 4])
|
361 |
+
a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,))
|
362 |
+
expected = np.array([1, 3])
|
363 |
+
assert_array_equal(a_view, expected)
|
364 |
+
|
365 |
+
a = np.array([1, 2, 3, 4])
|
366 |
+
a_view = as_strided(a, shape=(3, 4), strides=(0, 1 * a.itemsize))
|
367 |
+
expected = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])
|
368 |
+
assert_array_equal(a_view, expected)
|
369 |
+
|
370 |
+
# Regression test for gh-5081
|
371 |
+
dt = np.dtype([('num', 'i4'), ('obj', 'O')])
|
372 |
+
a = np.empty((4,), dtype=dt)
|
373 |
+
a['num'] = np.arange(1, 5)
|
374 |
+
a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize))
|
375 |
+
expected_num = [[1, 2, 3, 4]] * 3
|
376 |
+
expected_obj = [[None]*4]*3
|
377 |
+
assert_equal(a_view.dtype, dt)
|
378 |
+
assert_array_equal(expected_num, a_view['num'])
|
379 |
+
assert_array_equal(expected_obj, a_view['obj'])
|
380 |
+
|
381 |
+
# Make sure that void types without fields are kept unchanged
|
382 |
+
a = np.empty((4,), dtype='V4')
|
383 |
+
a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize))
|
384 |
+
assert_equal(a.dtype, a_view.dtype)
|
385 |
+
|
386 |
+
# Make sure that the only type that could fail is properly handled
|
387 |
+
dt = np.dtype({'names': [''], 'formats': ['V4']})
|
388 |
+
a = np.empty((4,), dtype=dt)
|
389 |
+
a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize))
|
390 |
+
assert_equal(a.dtype, a_view.dtype)
|
391 |
+
|
392 |
+
# Custom dtypes should not be lost (gh-9161)
|
393 |
+
r = [rational(i) for i in range(4)]
|
394 |
+
a = np.array(r, dtype=rational)
|
395 |
+
a_view = as_strided(a, shape=(3, 4), strides=(0, a.itemsize))
|
396 |
+
assert_equal(a.dtype, a_view.dtype)
|
397 |
+
assert_array_equal([r] * 3, a_view)
|
398 |
+
|
399 |
+
|
400 |
+
class TestSlidingWindowView:
|
401 |
+
def test_1d(self):
|
402 |
+
arr = np.arange(5)
|
403 |
+
arr_view = sliding_window_view(arr, 2)
|
404 |
+
expected = np.array([[0, 1],
|
405 |
+
[1, 2],
|
406 |
+
[2, 3],
|
407 |
+
[3, 4]])
|
408 |
+
assert_array_equal(arr_view, expected)
|
409 |
+
|
410 |
+
def test_2d(self):
|
411 |
+
i, j = np.ogrid[:3, :4]
|
412 |
+
arr = 10*i + j
|
413 |
+
shape = (2, 2)
|
414 |
+
arr_view = sliding_window_view(arr, shape)
|
415 |
+
expected = np.array([[[[0, 1], [10, 11]],
|
416 |
+
[[1, 2], [11, 12]],
|
417 |
+
[[2, 3], [12, 13]]],
|
418 |
+
[[[10, 11], [20, 21]],
|
419 |
+
[[11, 12], [21, 22]],
|
420 |
+
[[12, 13], [22, 23]]]])
|
421 |
+
assert_array_equal(arr_view, expected)
|
422 |
+
|
423 |
+
def test_2d_with_axis(self):
|
424 |
+
i, j = np.ogrid[:3, :4]
|
425 |
+
arr = 10*i + j
|
426 |
+
arr_view = sliding_window_view(arr, 3, 0)
|
427 |
+
expected = np.array([[[0, 10, 20],
|
428 |
+
[1, 11, 21],
|
429 |
+
[2, 12, 22],
|
430 |
+
[3, 13, 23]]])
|
431 |
+
assert_array_equal(arr_view, expected)
|
432 |
+
|
433 |
+
def test_2d_repeated_axis(self):
|
434 |
+
i, j = np.ogrid[:3, :4]
|
435 |
+
arr = 10*i + j
|
436 |
+
arr_view = sliding_window_view(arr, (2, 3), (1, 1))
|
437 |
+
expected = np.array([[[[0, 1, 2],
|
438 |
+
[1, 2, 3]]],
|
439 |
+
[[[10, 11, 12],
|
440 |
+
[11, 12, 13]]],
|
441 |
+
[[[20, 21, 22],
|
442 |
+
[21, 22, 23]]]])
|
443 |
+
assert_array_equal(arr_view, expected)
|
444 |
+
|
445 |
+
def test_2d_without_axis(self):
|
446 |
+
i, j = np.ogrid[:4, :4]
|
447 |
+
arr = 10*i + j
|
448 |
+
shape = (2, 3)
|
449 |
+
arr_view = sliding_window_view(arr, shape)
|
450 |
+
expected = np.array([[[[0, 1, 2], [10, 11, 12]],
|
451 |
+
[[1, 2, 3], [11, 12, 13]]],
|
452 |
+
[[[10, 11, 12], [20, 21, 22]],
|
453 |
+
[[11, 12, 13], [21, 22, 23]]],
|
454 |
+
[[[20, 21, 22], [30, 31, 32]],
|
455 |
+
[[21, 22, 23], [31, 32, 33]]]])
|
456 |
+
assert_array_equal(arr_view, expected)
|
457 |
+
|
458 |
+
def test_errors(self):
|
459 |
+
i, j = np.ogrid[:4, :4]
|
460 |
+
arr = 10*i + j
|
461 |
+
with pytest.raises(ValueError, match='cannot contain negative values'):
|
462 |
+
sliding_window_view(arr, (-1, 3))
|
463 |
+
with pytest.raises(
|
464 |
+
ValueError,
|
465 |
+
match='must provide window_shape for all dimensions of `x`'):
|
466 |
+
sliding_window_view(arr, (1,))
|
467 |
+
with pytest.raises(
|
468 |
+
ValueError,
|
469 |
+
match='Must provide matching length window_shape and axis'):
|
470 |
+
sliding_window_view(arr, (1, 3, 4), axis=(0, 1))
|
471 |
+
with pytest.raises(
|
472 |
+
ValueError,
|
473 |
+
match='window shape cannot be larger than input array'):
|
474 |
+
sliding_window_view(arr, (5, 5))
|
475 |
+
|
476 |
+
def test_writeable(self):
|
477 |
+
arr = np.arange(5)
|
478 |
+
view = sliding_window_view(arr, 2, writeable=False)
|
479 |
+
assert_(not view.flags.writeable)
|
480 |
+
with pytest.raises(
|
481 |
+
ValueError,
|
482 |
+
match='assignment destination is read-only'):
|
483 |
+
view[0, 0] = 3
|
484 |
+
view = sliding_window_view(arr, 2, writeable=True)
|
485 |
+
assert_(view.flags.writeable)
|
486 |
+
view[0, 1] = 3
|
487 |
+
assert_array_equal(arr, np.array([0, 3, 2, 3, 4]))
|
488 |
+
|
489 |
+
def test_subok(self):
|
490 |
+
class MyArray(np.ndarray):
|
491 |
+
pass
|
492 |
+
|
493 |
+
arr = np.arange(5).view(MyArray)
|
494 |
+
assert_(not isinstance(sliding_window_view(arr, 2,
|
495 |
+
subok=False),
|
496 |
+
MyArray))
|
497 |
+
assert_(isinstance(sliding_window_view(arr, 2, subok=True), MyArray))
|
498 |
+
# Default behavior
|
499 |
+
assert_(not isinstance(sliding_window_view(arr, 2), MyArray))
|
500 |
+
|
501 |
+
|
502 |
+
def as_strided_writeable():
|
503 |
+
arr = np.ones(10)
|
504 |
+
view = as_strided(arr, writeable=False)
|
505 |
+
assert_(not view.flags.writeable)
|
506 |
+
|
507 |
+
# Check that writeable also is fine:
|
508 |
+
view = as_strided(arr, writeable=True)
|
509 |
+
assert_(view.flags.writeable)
|
510 |
+
view[...] = 3
|
511 |
+
assert_array_equal(arr, np.full_like(arr, 3))
|
512 |
+
|
513 |
+
# Test that things do not break down for readonly:
|
514 |
+
arr.flags.writeable = False
|
515 |
+
view = as_strided(arr, writeable=False)
|
516 |
+
view = as_strided(arr, writeable=True)
|
517 |
+
assert_(not view.flags.writeable)
|
518 |
+
|
519 |
+
|
520 |
+
class VerySimpleSubClass(np.ndarray):
|
521 |
+
def __new__(cls, *args, **kwargs):
|
522 |
+
return np.array(*args, subok=True, **kwargs).view(cls)
|
523 |
+
|
524 |
+
|
525 |
+
class SimpleSubClass(VerySimpleSubClass):
|
526 |
+
def __new__(cls, *args, **kwargs):
|
527 |
+
self = np.array(*args, subok=True, **kwargs).view(cls)
|
528 |
+
self.info = 'simple'
|
529 |
+
return self
|
530 |
+
|
531 |
+
def __array_finalize__(self, obj):
|
532 |
+
self.info = getattr(obj, 'info', '') + ' finalized'
|
533 |
+
|
534 |
+
|
535 |
+
def test_subclasses():
|
536 |
+
# test that subclass is preserved only if subok=True
|
537 |
+
a = VerySimpleSubClass([1, 2, 3, 4])
|
538 |
+
assert_(type(a) is VerySimpleSubClass)
|
539 |
+
a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,))
|
540 |
+
assert_(type(a_view) is np.ndarray)
|
541 |
+
a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,), subok=True)
|
542 |
+
assert_(type(a_view) is VerySimpleSubClass)
|
543 |
+
# test that if a subclass has __array_finalize__, it is used
|
544 |
+
a = SimpleSubClass([1, 2, 3, 4])
|
545 |
+
a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,), subok=True)
|
546 |
+
assert_(type(a_view) is SimpleSubClass)
|
547 |
+
assert_(a_view.info == 'simple finalized')
|
548 |
+
|
549 |
+
# similar tests for broadcast_arrays
|
550 |
+
b = np.arange(len(a)).reshape(-1, 1)
|
551 |
+
a_view, b_view = broadcast_arrays(a, b)
|
552 |
+
assert_(type(a_view) is np.ndarray)
|
553 |
+
assert_(type(b_view) is np.ndarray)
|
554 |
+
assert_(a_view.shape == b_view.shape)
|
555 |
+
a_view, b_view = broadcast_arrays(a, b, subok=True)
|
556 |
+
assert_(type(a_view) is SimpleSubClass)
|
557 |
+
assert_(a_view.info == 'simple finalized')
|
558 |
+
assert_(type(b_view) is np.ndarray)
|
559 |
+
assert_(a_view.shape == b_view.shape)
|
560 |
+
|
561 |
+
# and for broadcast_to
|
562 |
+
shape = (2, 4)
|
563 |
+
a_view = broadcast_to(a, shape)
|
564 |
+
assert_(type(a_view) is np.ndarray)
|
565 |
+
assert_(a_view.shape == shape)
|
566 |
+
a_view = broadcast_to(a, shape, subok=True)
|
567 |
+
assert_(type(a_view) is SimpleSubClass)
|
568 |
+
assert_(a_view.info == 'simple finalized')
|
569 |
+
assert_(a_view.shape == shape)
|
570 |
+
|
571 |
+
|
572 |
+
def test_writeable():
|
573 |
+
# broadcast_to should return a readonly array
|
574 |
+
original = np.array([1, 2, 3])
|
575 |
+
result = broadcast_to(original, (2, 3))
|
576 |
+
assert_equal(result.flags.writeable, False)
|
577 |
+
assert_raises(ValueError, result.__setitem__, slice(None), 0)
|
578 |
+
|
579 |
+
# but the result of broadcast_arrays needs to be writeable, to
|
580 |
+
# preserve backwards compatibility
|
581 |
+
for is_broadcast, results in [(False, broadcast_arrays(original,)),
|
582 |
+
(True, broadcast_arrays(0, original))]:
|
583 |
+
for result in results:
|
584 |
+
# This will change to False in a future version
|
585 |
+
if is_broadcast:
|
586 |
+
with assert_warns(FutureWarning):
|
587 |
+
assert_equal(result.flags.writeable, True)
|
588 |
+
with assert_warns(DeprecationWarning):
|
589 |
+
result[:] = 0
|
590 |
+
# Warning not emitted, writing to the array resets it
|
591 |
+
assert_equal(result.flags.writeable, True)
|
592 |
+
else:
|
593 |
+
# No warning:
|
594 |
+
assert_equal(result.flags.writeable, True)
|
595 |
+
|
596 |
+
for results in [broadcast_arrays(original),
|
597 |
+
broadcast_arrays(0, original)]:
|
598 |
+
for result in results:
|
599 |
+
# resets the warn_on_write DeprecationWarning
|
600 |
+
result.flags.writeable = True
|
601 |
+
# check: no warning emitted
|
602 |
+
assert_equal(result.flags.writeable, True)
|
603 |
+
result[:] = 0
|
604 |
+
|
605 |
+
# keep readonly input readonly
|
606 |
+
original.flags.writeable = False
|
607 |
+
_, result = broadcast_arrays(0, original)
|
608 |
+
assert_equal(result.flags.writeable, False)
|
609 |
+
|
610 |
+
# regression test for GH6491
|
611 |
+
shape = (2,)
|
612 |
+
strides = [0]
|
613 |
+
tricky_array = as_strided(np.array(0), shape, strides)
|
614 |
+
other = np.zeros((1,))
|
615 |
+
first, second = broadcast_arrays(tricky_array, other)
|
616 |
+
assert_(first.shape == second.shape)
|
617 |
+
|
618 |
+
|
619 |
+
def test_writeable_memoryview():
|
620 |
+
# The result of broadcast_arrays exports as a non-writeable memoryview
|
621 |
+
# because otherwise there is no good way to opt in to the new behaviour
|
622 |
+
# (i.e. you would need to set writeable to False explicitly).
|
623 |
+
# See gh-13929.
|
624 |
+
original = np.array([1, 2, 3])
|
625 |
+
|
626 |
+
for is_broadcast, results in [(False, broadcast_arrays(original,)),
|
627 |
+
(True, broadcast_arrays(0, original))]:
|
628 |
+
for result in results:
|
629 |
+
# This will change to False in a future version
|
630 |
+
if is_broadcast:
|
631 |
+
# memoryview(result, writable=True) will give warning but cannot
|
632 |
+
# be tested using the python API.
|
633 |
+
assert memoryview(result).readonly
|
634 |
+
else:
|
635 |
+
assert not memoryview(result).readonly
|
636 |
+
|
637 |
+
|
638 |
+
def test_reference_types():
|
639 |
+
input_array = np.array('a', dtype=object)
|
640 |
+
expected = np.array(['a'] * 3, dtype=object)
|
641 |
+
actual = broadcast_to(input_array, (3,))
|
642 |
+
assert_array_equal(expected, actual)
|
643 |
+
|
644 |
+
actual, _ = broadcast_arrays(input_array, np.ones(3))
|
645 |
+
assert_array_equal(expected, actual)
|
venv/lib/python3.10/site-packages/numpy/lib/tests/test_twodim_base.py
ADDED
@@ -0,0 +1,541 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Test functions for matrix module
|
2 |
+
|
3 |
+
"""
|
4 |
+
from numpy.testing import (
|
5 |
+
assert_equal, assert_array_equal, assert_array_max_ulp,
|
6 |
+
assert_array_almost_equal, assert_raises, assert_
|
7 |
+
)
|
8 |
+
from numpy import (
|
9 |
+
arange, add, fliplr, flipud, zeros, ones, eye, array, diag, histogram2d,
|
10 |
+
tri, mask_indices, triu_indices, triu_indices_from, tril_indices,
|
11 |
+
tril_indices_from, vander,
|
12 |
+
)
|
13 |
+
import numpy as np
|
14 |
+
|
15 |
+
import pytest
|
16 |
+
|
17 |
+
|
18 |
+
def get_mat(n):
|
19 |
+
data = arange(n)
|
20 |
+
data = add.outer(data, data)
|
21 |
+
return data
|
22 |
+
|
23 |
+
|
24 |
+
class TestEye:
|
25 |
+
def test_basic(self):
|
26 |
+
assert_equal(eye(4),
|
27 |
+
array([[1, 0, 0, 0],
|
28 |
+
[0, 1, 0, 0],
|
29 |
+
[0, 0, 1, 0],
|
30 |
+
[0, 0, 0, 1]]))
|
31 |
+
|
32 |
+
assert_equal(eye(4, dtype='f'),
|
33 |
+
array([[1, 0, 0, 0],
|
34 |
+
[0, 1, 0, 0],
|
35 |
+
[0, 0, 1, 0],
|
36 |
+
[0, 0, 0, 1]], 'f'))
|
37 |
+
|
38 |
+
assert_equal(eye(3) == 1,
|
39 |
+
eye(3, dtype=bool))
|
40 |
+
|
41 |
+
def test_uint64(self):
|
42 |
+
# Regression test for gh-9982
|
43 |
+
assert_equal(eye(np.uint64(2), dtype=int), array([[1, 0], [0, 1]]))
|
44 |
+
assert_equal(eye(np.uint64(2), M=np.uint64(4), k=np.uint64(1)),
|
45 |
+
array([[0, 1, 0, 0], [0, 0, 1, 0]]))
|
46 |
+
|
47 |
+
def test_diag(self):
|
48 |
+
assert_equal(eye(4, k=1),
|
49 |
+
array([[0, 1, 0, 0],
|
50 |
+
[0, 0, 1, 0],
|
51 |
+
[0, 0, 0, 1],
|
52 |
+
[0, 0, 0, 0]]))
|
53 |
+
|
54 |
+
assert_equal(eye(4, k=-1),
|
55 |
+
array([[0, 0, 0, 0],
|
56 |
+
[1, 0, 0, 0],
|
57 |
+
[0, 1, 0, 0],
|
58 |
+
[0, 0, 1, 0]]))
|
59 |
+
|
60 |
+
def test_2d(self):
|
61 |
+
assert_equal(eye(4, 3),
|
62 |
+
array([[1, 0, 0],
|
63 |
+
[0, 1, 0],
|
64 |
+
[0, 0, 1],
|
65 |
+
[0, 0, 0]]))
|
66 |
+
|
67 |
+
assert_equal(eye(3, 4),
|
68 |
+
array([[1, 0, 0, 0],
|
69 |
+
[0, 1, 0, 0],
|
70 |
+
[0, 0, 1, 0]]))
|
71 |
+
|
72 |
+
def test_diag2d(self):
|
73 |
+
assert_equal(eye(3, 4, k=2),
|
74 |
+
array([[0, 0, 1, 0],
|
75 |
+
[0, 0, 0, 1],
|
76 |
+
[0, 0, 0, 0]]))
|
77 |
+
|
78 |
+
assert_equal(eye(4, 3, k=-2),
|
79 |
+
array([[0, 0, 0],
|
80 |
+
[0, 0, 0],
|
81 |
+
[1, 0, 0],
|
82 |
+
[0, 1, 0]]))
|
83 |
+
|
84 |
+
def test_eye_bounds(self):
|
85 |
+
assert_equal(eye(2, 2, 1), [[0, 1], [0, 0]])
|
86 |
+
assert_equal(eye(2, 2, -1), [[0, 0], [1, 0]])
|
87 |
+
assert_equal(eye(2, 2, 2), [[0, 0], [0, 0]])
|
88 |
+
assert_equal(eye(2, 2, -2), [[0, 0], [0, 0]])
|
89 |
+
assert_equal(eye(3, 2, 2), [[0, 0], [0, 0], [0, 0]])
|
90 |
+
assert_equal(eye(3, 2, 1), [[0, 1], [0, 0], [0, 0]])
|
91 |
+
assert_equal(eye(3, 2, -1), [[0, 0], [1, 0], [0, 1]])
|
92 |
+
assert_equal(eye(3, 2, -2), [[0, 0], [0, 0], [1, 0]])
|
93 |
+
assert_equal(eye(3, 2, -3), [[0, 0], [0, 0], [0, 0]])
|
94 |
+
|
95 |
+
def test_strings(self):
|
96 |
+
assert_equal(eye(2, 2, dtype='S3'),
|
97 |
+
[[b'1', b''], [b'', b'1']])
|
98 |
+
|
99 |
+
def test_bool(self):
|
100 |
+
assert_equal(eye(2, 2, dtype=bool), [[True, False], [False, True]])
|
101 |
+
|
102 |
+
def test_order(self):
|
103 |
+
mat_c = eye(4, 3, k=-1)
|
104 |
+
mat_f = eye(4, 3, k=-1, order='F')
|
105 |
+
assert_equal(mat_c, mat_f)
|
106 |
+
assert mat_c.flags.c_contiguous
|
107 |
+
assert not mat_c.flags.f_contiguous
|
108 |
+
assert not mat_f.flags.c_contiguous
|
109 |
+
assert mat_f.flags.f_contiguous
|
110 |
+
|
111 |
+
|
112 |
+
class TestDiag:
|
113 |
+
def test_vector(self):
|
114 |
+
vals = (100 * arange(5)).astype('l')
|
115 |
+
b = zeros((5, 5))
|
116 |
+
for k in range(5):
|
117 |
+
b[k, k] = vals[k]
|
118 |
+
assert_equal(diag(vals), b)
|
119 |
+
b = zeros((7, 7))
|
120 |
+
c = b.copy()
|
121 |
+
for k in range(5):
|
122 |
+
b[k, k + 2] = vals[k]
|
123 |
+
c[k + 2, k] = vals[k]
|
124 |
+
assert_equal(diag(vals, k=2), b)
|
125 |
+
assert_equal(diag(vals, k=-2), c)
|
126 |
+
|
127 |
+
def test_matrix(self, vals=None):
|
128 |
+
if vals is None:
|
129 |
+
vals = (100 * get_mat(5) + 1).astype('l')
|
130 |
+
b = zeros((5,))
|
131 |
+
for k in range(5):
|
132 |
+
b[k] = vals[k, k]
|
133 |
+
assert_equal(diag(vals), b)
|
134 |
+
b = b * 0
|
135 |
+
for k in range(3):
|
136 |
+
b[k] = vals[k, k + 2]
|
137 |
+
assert_equal(diag(vals, 2), b[:3])
|
138 |
+
for k in range(3):
|
139 |
+
b[k] = vals[k + 2, k]
|
140 |
+
assert_equal(diag(vals, -2), b[:3])
|
141 |
+
|
142 |
+
def test_fortran_order(self):
|
143 |
+
vals = array((100 * get_mat(5) + 1), order='F', dtype='l')
|
144 |
+
self.test_matrix(vals)
|
145 |
+
|
146 |
+
def test_diag_bounds(self):
|
147 |
+
A = [[1, 2], [3, 4], [5, 6]]
|
148 |
+
assert_equal(diag(A, k=2), [])
|
149 |
+
assert_equal(diag(A, k=1), [2])
|
150 |
+
assert_equal(diag(A, k=0), [1, 4])
|
151 |
+
assert_equal(diag(A, k=-1), [3, 6])
|
152 |
+
assert_equal(diag(A, k=-2), [5])
|
153 |
+
assert_equal(diag(A, k=-3), [])
|
154 |
+
|
155 |
+
def test_failure(self):
|
156 |
+
assert_raises(ValueError, diag, [[[1]]])
|
157 |
+
|
158 |
+
|
159 |
+
class TestFliplr:
|
160 |
+
def test_basic(self):
|
161 |
+
assert_raises(ValueError, fliplr, ones(4))
|
162 |
+
a = get_mat(4)
|
163 |
+
b = a[:, ::-1]
|
164 |
+
assert_equal(fliplr(a), b)
|
165 |
+
a = [[0, 1, 2],
|
166 |
+
[3, 4, 5]]
|
167 |
+
b = [[2, 1, 0],
|
168 |
+
[5, 4, 3]]
|
169 |
+
assert_equal(fliplr(a), b)
|
170 |
+
|
171 |
+
|
172 |
+
class TestFlipud:
|
173 |
+
def test_basic(self):
|
174 |
+
a = get_mat(4)
|
175 |
+
b = a[::-1, :]
|
176 |
+
assert_equal(flipud(a), b)
|
177 |
+
a = [[0, 1, 2],
|
178 |
+
[3, 4, 5]]
|
179 |
+
b = [[3, 4, 5],
|
180 |
+
[0, 1, 2]]
|
181 |
+
assert_equal(flipud(a), b)
|
182 |
+
|
183 |
+
|
184 |
+
class TestHistogram2d:
|
185 |
+
def test_simple(self):
|
186 |
+
x = array(
|
187 |
+
[0.41702200, 0.72032449, 1.1437481e-4, 0.302332573, 0.146755891])
|
188 |
+
y = array(
|
189 |
+
[0.09233859, 0.18626021, 0.34556073, 0.39676747, 0.53881673])
|
190 |
+
xedges = np.linspace(0, 1, 10)
|
191 |
+
yedges = np.linspace(0, 1, 10)
|
192 |
+
H = histogram2d(x, y, (xedges, yedges))[0]
|
193 |
+
answer = array(
|
194 |
+
[[0, 0, 0, 1, 0, 0, 0, 0, 0],
|
195 |
+
[0, 0, 0, 0, 0, 0, 1, 0, 0],
|
196 |
+
[0, 0, 0, 0, 0, 0, 0, 0, 0],
|
197 |
+
[1, 0, 1, 0, 0, 0, 0, 0, 0],
|
198 |
+
[0, 1, 0, 0, 0, 0, 0, 0, 0],
|
199 |
+
[0, 0, 0, 0, 0, 0, 0, 0, 0],
|
200 |
+
[0, 0, 0, 0, 0, 0, 0, 0, 0],
|
201 |
+
[0, 0, 0, 0, 0, 0, 0, 0, 0],
|
202 |
+
[0, 0, 0, 0, 0, 0, 0, 0, 0]])
|
203 |
+
assert_array_equal(H.T, answer)
|
204 |
+
H = histogram2d(x, y, xedges)[0]
|
205 |
+
assert_array_equal(H.T, answer)
|
206 |
+
H, xedges, yedges = histogram2d(list(range(10)), list(range(10)))
|
207 |
+
assert_array_equal(H, eye(10, 10))
|
208 |
+
assert_array_equal(xedges, np.linspace(0, 9, 11))
|
209 |
+
assert_array_equal(yedges, np.linspace(0, 9, 11))
|
210 |
+
|
211 |
+
def test_asym(self):
|
212 |
+
x = array([1, 1, 2, 3, 4, 4, 4, 5])
|
213 |
+
y = array([1, 3, 2, 0, 1, 2, 3, 4])
|
214 |
+
H, xed, yed = histogram2d(
|
215 |
+
x, y, (6, 5), range=[[0, 6], [0, 5]], density=True)
|
216 |
+
answer = array(
|
217 |
+
[[0., 0, 0, 0, 0],
|
218 |
+
[0, 1, 0, 1, 0],
|
219 |
+
[0, 0, 1, 0, 0],
|
220 |
+
[1, 0, 0, 0, 0],
|
221 |
+
[0, 1, 1, 1, 0],
|
222 |
+
[0, 0, 0, 0, 1]])
|
223 |
+
assert_array_almost_equal(H, answer/8., 3)
|
224 |
+
assert_array_equal(xed, np.linspace(0, 6, 7))
|
225 |
+
assert_array_equal(yed, np.linspace(0, 5, 6))
|
226 |
+
|
227 |
+
def test_density(self):
|
228 |
+
x = array([1, 2, 3, 1, 2, 3, 1, 2, 3])
|
229 |
+
y = array([1, 1, 1, 2, 2, 2, 3, 3, 3])
|
230 |
+
H, xed, yed = histogram2d(
|
231 |
+
x, y, [[1, 2, 3, 5], [1, 2, 3, 5]], density=True)
|
232 |
+
answer = array([[1, 1, .5],
|
233 |
+
[1, 1, .5],
|
234 |
+
[.5, .5, .25]])/9.
|
235 |
+
assert_array_almost_equal(H, answer, 3)
|
236 |
+
|
237 |
+
def test_all_outliers(self):
|
238 |
+
r = np.random.rand(100) + 1. + 1e6 # histogramdd rounds by decimal=6
|
239 |
+
H, xed, yed = histogram2d(r, r, (4, 5), range=([0, 1], [0, 1]))
|
240 |
+
assert_array_equal(H, 0)
|
241 |
+
|
242 |
+
def test_empty(self):
|
243 |
+
a, edge1, edge2 = histogram2d([], [], bins=([0, 1], [0, 1]))
|
244 |
+
assert_array_max_ulp(a, array([[0.]]))
|
245 |
+
|
246 |
+
a, edge1, edge2 = histogram2d([], [], bins=4)
|
247 |
+
assert_array_max_ulp(a, np.zeros((4, 4)))
|
248 |
+
|
249 |
+
def test_binparameter_combination(self):
|
250 |
+
x = array(
|
251 |
+
[0, 0.09207008, 0.64575234, 0.12875982, 0.47390599,
|
252 |
+
0.59944483, 1])
|
253 |
+
y = array(
|
254 |
+
[0, 0.14344267, 0.48988575, 0.30558665, 0.44700682,
|
255 |
+
0.15886423, 1])
|
256 |
+
edges = (0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1)
|
257 |
+
H, xe, ye = histogram2d(x, y, (edges, 4))
|
258 |
+
answer = array(
|
259 |
+
[[2., 0., 0., 0.],
|
260 |
+
[0., 1., 0., 0.],
|
261 |
+
[0., 0., 0., 0.],
|
262 |
+
[0., 0., 0., 0.],
|
263 |
+
[0., 1., 0., 0.],
|
264 |
+
[1., 0., 0., 0.],
|
265 |
+
[0., 1., 0., 0.],
|
266 |
+
[0., 0., 0., 0.],
|
267 |
+
[0., 0., 0., 0.],
|
268 |
+
[0., 0., 0., 1.]])
|
269 |
+
assert_array_equal(H, answer)
|
270 |
+
assert_array_equal(ye, array([0., 0.25, 0.5, 0.75, 1]))
|
271 |
+
H, xe, ye = histogram2d(x, y, (4, edges))
|
272 |
+
answer = array(
|
273 |
+
[[1., 1., 0., 1., 0., 0., 0., 0., 0., 0.],
|
274 |
+
[0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
|
275 |
+
[0., 1., 0., 0., 1., 0., 0., 0., 0., 0.],
|
276 |
+
[0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]])
|
277 |
+
assert_array_equal(H, answer)
|
278 |
+
assert_array_equal(xe, array([0., 0.25, 0.5, 0.75, 1]))
|
279 |
+
|
280 |
+
def test_dispatch(self):
|
281 |
+
class ShouldDispatch:
|
282 |
+
def __array_function__(self, function, types, args, kwargs):
|
283 |
+
return types, args, kwargs
|
284 |
+
|
285 |
+
xy = [1, 2]
|
286 |
+
s_d = ShouldDispatch()
|
287 |
+
r = histogram2d(s_d, xy)
|
288 |
+
# Cannot use assert_equal since that dispatches...
|
289 |
+
assert_(r == ((ShouldDispatch,), (s_d, xy), {}))
|
290 |
+
r = histogram2d(xy, s_d)
|
291 |
+
assert_(r == ((ShouldDispatch,), (xy, s_d), {}))
|
292 |
+
r = histogram2d(xy, xy, bins=s_d)
|
293 |
+
assert_(r, ((ShouldDispatch,), (xy, xy), dict(bins=s_d)))
|
294 |
+
r = histogram2d(xy, xy, bins=[s_d, 5])
|
295 |
+
assert_(r, ((ShouldDispatch,), (xy, xy), dict(bins=[s_d, 5])))
|
296 |
+
assert_raises(Exception, histogram2d, xy, xy, bins=[s_d])
|
297 |
+
r = histogram2d(xy, xy, weights=s_d)
|
298 |
+
assert_(r, ((ShouldDispatch,), (xy, xy), dict(weights=s_d)))
|
299 |
+
|
300 |
+
@pytest.mark.parametrize(("x_len", "y_len"), [(10, 11), (20, 19)])
|
301 |
+
def test_bad_length(self, x_len, y_len):
|
302 |
+
x, y = np.ones(x_len), np.ones(y_len)
|
303 |
+
with pytest.raises(ValueError,
|
304 |
+
match='x and y must have the same length.'):
|
305 |
+
histogram2d(x, y)
|
306 |
+
|
307 |
+
|
308 |
+
class TestTri:
|
309 |
+
def test_dtype(self):
|
310 |
+
out = array([[1, 0, 0],
|
311 |
+
[1, 1, 0],
|
312 |
+
[1, 1, 1]])
|
313 |
+
assert_array_equal(tri(3), out)
|
314 |
+
assert_array_equal(tri(3, dtype=bool), out.astype(bool))
|
315 |
+
|
316 |
+
|
317 |
+
def test_tril_triu_ndim2():
|
318 |
+
for dtype in np.typecodes['AllFloat'] + np.typecodes['AllInteger']:
|
319 |
+
a = np.ones((2, 2), dtype=dtype)
|
320 |
+
b = np.tril(a)
|
321 |
+
c = np.triu(a)
|
322 |
+
assert_array_equal(b, [[1, 0], [1, 1]])
|
323 |
+
assert_array_equal(c, b.T)
|
324 |
+
# should return the same dtype as the original array
|
325 |
+
assert_equal(b.dtype, a.dtype)
|
326 |
+
assert_equal(c.dtype, a.dtype)
|
327 |
+
|
328 |
+
|
329 |
+
def test_tril_triu_ndim3():
|
330 |
+
for dtype in np.typecodes['AllFloat'] + np.typecodes['AllInteger']:
|
331 |
+
a = np.array([
|
332 |
+
[[1, 1], [1, 1]],
|
333 |
+
[[1, 1], [1, 0]],
|
334 |
+
[[1, 1], [0, 0]],
|
335 |
+
], dtype=dtype)
|
336 |
+
a_tril_desired = np.array([
|
337 |
+
[[1, 0], [1, 1]],
|
338 |
+
[[1, 0], [1, 0]],
|
339 |
+
[[1, 0], [0, 0]],
|
340 |
+
], dtype=dtype)
|
341 |
+
a_triu_desired = np.array([
|
342 |
+
[[1, 1], [0, 1]],
|
343 |
+
[[1, 1], [0, 0]],
|
344 |
+
[[1, 1], [0, 0]],
|
345 |
+
], dtype=dtype)
|
346 |
+
a_triu_observed = np.triu(a)
|
347 |
+
a_tril_observed = np.tril(a)
|
348 |
+
assert_array_equal(a_triu_observed, a_triu_desired)
|
349 |
+
assert_array_equal(a_tril_observed, a_tril_desired)
|
350 |
+
assert_equal(a_triu_observed.dtype, a.dtype)
|
351 |
+
assert_equal(a_tril_observed.dtype, a.dtype)
|
352 |
+
|
353 |
+
|
354 |
+
def test_tril_triu_with_inf():
|
355 |
+
# Issue 4859
|
356 |
+
arr = np.array([[1, 1, np.inf],
|
357 |
+
[1, 1, 1],
|
358 |
+
[np.inf, 1, 1]])
|
359 |
+
out_tril = np.array([[1, 0, 0],
|
360 |
+
[1, 1, 0],
|
361 |
+
[np.inf, 1, 1]])
|
362 |
+
out_triu = out_tril.T
|
363 |
+
assert_array_equal(np.triu(arr), out_triu)
|
364 |
+
assert_array_equal(np.tril(arr), out_tril)
|
365 |
+
|
366 |
+
|
367 |
+
def test_tril_triu_dtype():
|
368 |
+
# Issue 4916
|
369 |
+
# tril and triu should return the same dtype as input
|
370 |
+
for c in np.typecodes['All']:
|
371 |
+
if c == 'V':
|
372 |
+
continue
|
373 |
+
arr = np.zeros((3, 3), dtype=c)
|
374 |
+
assert_equal(np.triu(arr).dtype, arr.dtype)
|
375 |
+
assert_equal(np.tril(arr).dtype, arr.dtype)
|
376 |
+
|
377 |
+
# check special cases
|
378 |
+
arr = np.array([['2001-01-01T12:00', '2002-02-03T13:56'],
|
379 |
+
['2004-01-01T12:00', '2003-01-03T13:45']],
|
380 |
+
dtype='datetime64')
|
381 |
+
assert_equal(np.triu(arr).dtype, arr.dtype)
|
382 |
+
assert_equal(np.tril(arr).dtype, arr.dtype)
|
383 |
+
|
384 |
+
arr = np.zeros((3, 3), dtype='f4,f4')
|
385 |
+
assert_equal(np.triu(arr).dtype, arr.dtype)
|
386 |
+
assert_equal(np.tril(arr).dtype, arr.dtype)
|
387 |
+
|
388 |
+
|
389 |
+
def test_mask_indices():
|
390 |
+
# simple test without offset
|
391 |
+
iu = mask_indices(3, np.triu)
|
392 |
+
a = np.arange(9).reshape(3, 3)
|
393 |
+
assert_array_equal(a[iu], array([0, 1, 2, 4, 5, 8]))
|
394 |
+
# Now with an offset
|
395 |
+
iu1 = mask_indices(3, np.triu, 1)
|
396 |
+
assert_array_equal(a[iu1], array([1, 2, 5]))
|
397 |
+
|
398 |
+
|
399 |
+
def test_tril_indices():
|
400 |
+
# indices without and with offset
|
401 |
+
il1 = tril_indices(4)
|
402 |
+
il2 = tril_indices(4, k=2)
|
403 |
+
il3 = tril_indices(4, m=5)
|
404 |
+
il4 = tril_indices(4, k=2, m=5)
|
405 |
+
|
406 |
+
a = np.array([[1, 2, 3, 4],
|
407 |
+
[5, 6, 7, 8],
|
408 |
+
[9, 10, 11, 12],
|
409 |
+
[13, 14, 15, 16]])
|
410 |
+
b = np.arange(1, 21).reshape(4, 5)
|
411 |
+
|
412 |
+
# indexing:
|
413 |
+
assert_array_equal(a[il1],
|
414 |
+
array([1, 5, 6, 9, 10, 11, 13, 14, 15, 16]))
|
415 |
+
assert_array_equal(b[il3],
|
416 |
+
array([1, 6, 7, 11, 12, 13, 16, 17, 18, 19]))
|
417 |
+
|
418 |
+
# And for assigning values:
|
419 |
+
a[il1] = -1
|
420 |
+
assert_array_equal(a,
|
421 |
+
array([[-1, 2, 3, 4],
|
422 |
+
[-1, -1, 7, 8],
|
423 |
+
[-1, -1, -1, 12],
|
424 |
+
[-1, -1, -1, -1]]))
|
425 |
+
b[il3] = -1
|
426 |
+
assert_array_equal(b,
|
427 |
+
array([[-1, 2, 3, 4, 5],
|
428 |
+
[-1, -1, 8, 9, 10],
|
429 |
+
[-1, -1, -1, 14, 15],
|
430 |
+
[-1, -1, -1, -1, 20]]))
|
431 |
+
# These cover almost the whole array (two diagonals right of the main one):
|
432 |
+
a[il2] = -10
|
433 |
+
assert_array_equal(a,
|
434 |
+
array([[-10, -10, -10, 4],
|
435 |
+
[-10, -10, -10, -10],
|
436 |
+
[-10, -10, -10, -10],
|
437 |
+
[-10, -10, -10, -10]]))
|
438 |
+
b[il4] = -10
|
439 |
+
assert_array_equal(b,
|
440 |
+
array([[-10, -10, -10, 4, 5],
|
441 |
+
[-10, -10, -10, -10, 10],
|
442 |
+
[-10, -10, -10, -10, -10],
|
443 |
+
[-10, -10, -10, -10, -10]]))
|
444 |
+
|
445 |
+
|
446 |
+
class TestTriuIndices:
|
447 |
+
def test_triu_indices(self):
|
448 |
+
iu1 = triu_indices(4)
|
449 |
+
iu2 = triu_indices(4, k=2)
|
450 |
+
iu3 = triu_indices(4, m=5)
|
451 |
+
iu4 = triu_indices(4, k=2, m=5)
|
452 |
+
|
453 |
+
a = np.array([[1, 2, 3, 4],
|
454 |
+
[5, 6, 7, 8],
|
455 |
+
[9, 10, 11, 12],
|
456 |
+
[13, 14, 15, 16]])
|
457 |
+
b = np.arange(1, 21).reshape(4, 5)
|
458 |
+
|
459 |
+
# Both for indexing:
|
460 |
+
assert_array_equal(a[iu1],
|
461 |
+
array([1, 2, 3, 4, 6, 7, 8, 11, 12, 16]))
|
462 |
+
assert_array_equal(b[iu3],
|
463 |
+
array([1, 2, 3, 4, 5, 7, 8, 9,
|
464 |
+
10, 13, 14, 15, 19, 20]))
|
465 |
+
|
466 |
+
# And for assigning values:
|
467 |
+
a[iu1] = -1
|
468 |
+
assert_array_equal(a,
|
469 |
+
array([[-1, -1, -1, -1],
|
470 |
+
[5, -1, -1, -1],
|
471 |
+
[9, 10, -1, -1],
|
472 |
+
[13, 14, 15, -1]]))
|
473 |
+
b[iu3] = -1
|
474 |
+
assert_array_equal(b,
|
475 |
+
array([[-1, -1, -1, -1, -1],
|
476 |
+
[6, -1, -1, -1, -1],
|
477 |
+
[11, 12, -1, -1, -1],
|
478 |
+
[16, 17, 18, -1, -1]]))
|
479 |
+
|
480 |
+
# These cover almost the whole array (two diagonals right of the
|
481 |
+
# main one):
|
482 |
+
a[iu2] = -10
|
483 |
+
assert_array_equal(a,
|
484 |
+
array([[-1, -1, -10, -10],
|
485 |
+
[5, -1, -1, -10],
|
486 |
+
[9, 10, -1, -1],
|
487 |
+
[13, 14, 15, -1]]))
|
488 |
+
b[iu4] = -10
|
489 |
+
assert_array_equal(b,
|
490 |
+
array([[-1, -1, -10, -10, -10],
|
491 |
+
[6, -1, -1, -10, -10],
|
492 |
+
[11, 12, -1, -1, -10],
|
493 |
+
[16, 17, 18, -1, -1]]))
|
494 |
+
|
495 |
+
|
496 |
+
class TestTrilIndicesFrom:
|
497 |
+
def test_exceptions(self):
|
498 |
+
assert_raises(ValueError, tril_indices_from, np.ones((2,)))
|
499 |
+
assert_raises(ValueError, tril_indices_from, np.ones((2, 2, 2)))
|
500 |
+
# assert_raises(ValueError, tril_indices_from, np.ones((2, 3)))
|
501 |
+
|
502 |
+
|
503 |
+
class TestTriuIndicesFrom:
|
504 |
+
def test_exceptions(self):
|
505 |
+
assert_raises(ValueError, triu_indices_from, np.ones((2,)))
|
506 |
+
assert_raises(ValueError, triu_indices_from, np.ones((2, 2, 2)))
|
507 |
+
# assert_raises(ValueError, triu_indices_from, np.ones((2, 3)))
|
508 |
+
|
509 |
+
|
510 |
+
class TestVander:
|
511 |
+
def test_basic(self):
|
512 |
+
c = np.array([0, 1, -2, 3])
|
513 |
+
v = vander(c)
|
514 |
+
powers = np.array([[0, 0, 0, 0, 1],
|
515 |
+
[1, 1, 1, 1, 1],
|
516 |
+
[16, -8, 4, -2, 1],
|
517 |
+
[81, 27, 9, 3, 1]])
|
518 |
+
# Check default value of N:
|
519 |
+
assert_array_equal(v, powers[:, 1:])
|
520 |
+
# Check a range of N values, including 0 and 5 (greater than default)
|
521 |
+
m = powers.shape[1]
|
522 |
+
for n in range(6):
|
523 |
+
v = vander(c, N=n)
|
524 |
+
assert_array_equal(v, powers[:, m-n:m])
|
525 |
+
|
526 |
+
def test_dtypes(self):
|
527 |
+
c = array([11, -12, 13], dtype=np.int8)
|
528 |
+
v = vander(c)
|
529 |
+
expected = np.array([[121, 11, 1],
|
530 |
+
[144, -12, 1],
|
531 |
+
[169, 13, 1]])
|
532 |
+
assert_array_equal(v, expected)
|
533 |
+
|
534 |
+
c = array([1.0+1j, 1.0-1j])
|
535 |
+
v = vander(c, N=3)
|
536 |
+
expected = np.array([[2j, 1+1j, 1],
|
537 |
+
[-2j, 1-1j, 1]])
|
538 |
+
# The data is floating point, but the values are small integers,
|
539 |
+
# so assert_array_equal *should* be safe here (rather than, say,
|
540 |
+
# assert_array_almost_equal).
|
541 |
+
assert_array_equal(v, expected)
|
venv/lib/python3.10/site-packages/numpy/lib/tests/test_type_check.py
ADDED
@@ -0,0 +1,478 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from numpy.testing import (
|
3 |
+
assert_, assert_equal, assert_array_equal, assert_raises
|
4 |
+
)
|
5 |
+
from numpy.lib.type_check import (
|
6 |
+
common_type, mintypecode, isreal, iscomplex, isposinf, isneginf,
|
7 |
+
nan_to_num, isrealobj, iscomplexobj, asfarray, real_if_close
|
8 |
+
)
|
9 |
+
|
10 |
+
|
11 |
+
def assert_all(x):
|
12 |
+
assert_(np.all(x), x)
|
13 |
+
|
14 |
+
|
15 |
+
class TestCommonType:
|
16 |
+
def test_basic(self):
|
17 |
+
ai32 = np.array([[1, 2], [3, 4]], dtype=np.int32)
|
18 |
+
af16 = np.array([[1, 2], [3, 4]], dtype=np.float16)
|
19 |
+
af32 = np.array([[1, 2], [3, 4]], dtype=np.float32)
|
20 |
+
af64 = np.array([[1, 2], [3, 4]], dtype=np.float64)
|
21 |
+
acs = np.array([[1+5j, 2+6j], [3+7j, 4+8j]], dtype=np.csingle)
|
22 |
+
acd = np.array([[1+5j, 2+6j], [3+7j, 4+8j]], dtype=np.cdouble)
|
23 |
+
assert_(common_type(ai32) == np.float64)
|
24 |
+
assert_(common_type(af16) == np.float16)
|
25 |
+
assert_(common_type(af32) == np.float32)
|
26 |
+
assert_(common_type(af64) == np.float64)
|
27 |
+
assert_(common_type(acs) == np.csingle)
|
28 |
+
assert_(common_type(acd) == np.cdouble)
|
29 |
+
|
30 |
+
|
31 |
+
class TestMintypecode:
|
32 |
+
|
33 |
+
def test_default_1(self):
|
34 |
+
for itype in '1bcsuwil':
|
35 |
+
assert_equal(mintypecode(itype), 'd')
|
36 |
+
assert_equal(mintypecode('f'), 'f')
|
37 |
+
assert_equal(mintypecode('d'), 'd')
|
38 |
+
assert_equal(mintypecode('F'), 'F')
|
39 |
+
assert_equal(mintypecode('D'), 'D')
|
40 |
+
|
41 |
+
def test_default_2(self):
|
42 |
+
for itype in '1bcsuwil':
|
43 |
+
assert_equal(mintypecode(itype+'f'), 'f')
|
44 |
+
assert_equal(mintypecode(itype+'d'), 'd')
|
45 |
+
assert_equal(mintypecode(itype+'F'), 'F')
|
46 |
+
assert_equal(mintypecode(itype+'D'), 'D')
|
47 |
+
assert_equal(mintypecode('ff'), 'f')
|
48 |
+
assert_equal(mintypecode('fd'), 'd')
|
49 |
+
assert_equal(mintypecode('fF'), 'F')
|
50 |
+
assert_equal(mintypecode('fD'), 'D')
|
51 |
+
assert_equal(mintypecode('df'), 'd')
|
52 |
+
assert_equal(mintypecode('dd'), 'd')
|
53 |
+
#assert_equal(mintypecode('dF',savespace=1),'F')
|
54 |
+
assert_equal(mintypecode('dF'), 'D')
|
55 |
+
assert_equal(mintypecode('dD'), 'D')
|
56 |
+
assert_equal(mintypecode('Ff'), 'F')
|
57 |
+
#assert_equal(mintypecode('Fd',savespace=1),'F')
|
58 |
+
assert_equal(mintypecode('Fd'), 'D')
|
59 |
+
assert_equal(mintypecode('FF'), 'F')
|
60 |
+
assert_equal(mintypecode('FD'), 'D')
|
61 |
+
assert_equal(mintypecode('Df'), 'D')
|
62 |
+
assert_equal(mintypecode('Dd'), 'D')
|
63 |
+
assert_equal(mintypecode('DF'), 'D')
|
64 |
+
assert_equal(mintypecode('DD'), 'D')
|
65 |
+
|
66 |
+
def test_default_3(self):
|
67 |
+
assert_equal(mintypecode('fdF'), 'D')
|
68 |
+
#assert_equal(mintypecode('fdF',savespace=1),'F')
|
69 |
+
assert_equal(mintypecode('fdD'), 'D')
|
70 |
+
assert_equal(mintypecode('fFD'), 'D')
|
71 |
+
assert_equal(mintypecode('dFD'), 'D')
|
72 |
+
|
73 |
+
assert_equal(mintypecode('ifd'), 'd')
|
74 |
+
assert_equal(mintypecode('ifF'), 'F')
|
75 |
+
assert_equal(mintypecode('ifD'), 'D')
|
76 |
+
assert_equal(mintypecode('idF'), 'D')
|
77 |
+
#assert_equal(mintypecode('idF',savespace=1),'F')
|
78 |
+
assert_equal(mintypecode('idD'), 'D')
|
79 |
+
|
80 |
+
|
81 |
+
class TestIsscalar:
|
82 |
+
|
83 |
+
def test_basic(self):
|
84 |
+
assert_(np.isscalar(3))
|
85 |
+
assert_(not np.isscalar([3]))
|
86 |
+
assert_(not np.isscalar((3,)))
|
87 |
+
assert_(np.isscalar(3j))
|
88 |
+
assert_(np.isscalar(4.0))
|
89 |
+
|
90 |
+
|
91 |
+
class TestReal:
|
92 |
+
|
93 |
+
def test_real(self):
|
94 |
+
y = np.random.rand(10,)
|
95 |
+
assert_array_equal(y, np.real(y))
|
96 |
+
|
97 |
+
y = np.array(1)
|
98 |
+
out = np.real(y)
|
99 |
+
assert_array_equal(y, out)
|
100 |
+
assert_(isinstance(out, np.ndarray))
|
101 |
+
|
102 |
+
y = 1
|
103 |
+
out = np.real(y)
|
104 |
+
assert_equal(y, out)
|
105 |
+
assert_(not isinstance(out, np.ndarray))
|
106 |
+
|
107 |
+
def test_cmplx(self):
|
108 |
+
y = np.random.rand(10,)+1j*np.random.rand(10,)
|
109 |
+
assert_array_equal(y.real, np.real(y))
|
110 |
+
|
111 |
+
y = np.array(1 + 1j)
|
112 |
+
out = np.real(y)
|
113 |
+
assert_array_equal(y.real, out)
|
114 |
+
assert_(isinstance(out, np.ndarray))
|
115 |
+
|
116 |
+
y = 1 + 1j
|
117 |
+
out = np.real(y)
|
118 |
+
assert_equal(1.0, out)
|
119 |
+
assert_(not isinstance(out, np.ndarray))
|
120 |
+
|
121 |
+
|
122 |
+
class TestImag:
|
123 |
+
|
124 |
+
def test_real(self):
|
125 |
+
y = np.random.rand(10,)
|
126 |
+
assert_array_equal(0, np.imag(y))
|
127 |
+
|
128 |
+
y = np.array(1)
|
129 |
+
out = np.imag(y)
|
130 |
+
assert_array_equal(0, out)
|
131 |
+
assert_(isinstance(out, np.ndarray))
|
132 |
+
|
133 |
+
y = 1
|
134 |
+
out = np.imag(y)
|
135 |
+
assert_equal(0, out)
|
136 |
+
assert_(not isinstance(out, np.ndarray))
|
137 |
+
|
138 |
+
def test_cmplx(self):
|
139 |
+
y = np.random.rand(10,)+1j*np.random.rand(10,)
|
140 |
+
assert_array_equal(y.imag, np.imag(y))
|
141 |
+
|
142 |
+
y = np.array(1 + 1j)
|
143 |
+
out = np.imag(y)
|
144 |
+
assert_array_equal(y.imag, out)
|
145 |
+
assert_(isinstance(out, np.ndarray))
|
146 |
+
|
147 |
+
y = 1 + 1j
|
148 |
+
out = np.imag(y)
|
149 |
+
assert_equal(1.0, out)
|
150 |
+
assert_(not isinstance(out, np.ndarray))
|
151 |
+
|
152 |
+
|
153 |
+
class TestIscomplex:
|
154 |
+
|
155 |
+
def test_fail(self):
|
156 |
+
z = np.array([-1, 0, 1])
|
157 |
+
res = iscomplex(z)
|
158 |
+
assert_(not np.any(res, axis=0))
|
159 |
+
|
160 |
+
def test_pass(self):
|
161 |
+
z = np.array([-1j, 1, 0])
|
162 |
+
res = iscomplex(z)
|
163 |
+
assert_array_equal(res, [1, 0, 0])
|
164 |
+
|
165 |
+
|
166 |
+
class TestIsreal:
|
167 |
+
|
168 |
+
def test_pass(self):
|
169 |
+
z = np.array([-1, 0, 1j])
|
170 |
+
res = isreal(z)
|
171 |
+
assert_array_equal(res, [1, 1, 0])
|
172 |
+
|
173 |
+
def test_fail(self):
|
174 |
+
z = np.array([-1j, 1, 0])
|
175 |
+
res = isreal(z)
|
176 |
+
assert_array_equal(res, [0, 1, 1])
|
177 |
+
|
178 |
+
|
179 |
+
class TestIscomplexobj:
|
180 |
+
|
181 |
+
def test_basic(self):
|
182 |
+
z = np.array([-1, 0, 1])
|
183 |
+
assert_(not iscomplexobj(z))
|
184 |
+
z = np.array([-1j, 0, -1])
|
185 |
+
assert_(iscomplexobj(z))
|
186 |
+
|
187 |
+
def test_scalar(self):
|
188 |
+
assert_(not iscomplexobj(1.0))
|
189 |
+
assert_(iscomplexobj(1+0j))
|
190 |
+
|
191 |
+
def test_list(self):
|
192 |
+
assert_(iscomplexobj([3, 1+0j, True]))
|
193 |
+
assert_(not iscomplexobj([3, 1, True]))
|
194 |
+
|
195 |
+
def test_duck(self):
|
196 |
+
class DummyComplexArray:
|
197 |
+
@property
|
198 |
+
def dtype(self):
|
199 |
+
return np.dtype(complex)
|
200 |
+
dummy = DummyComplexArray()
|
201 |
+
assert_(iscomplexobj(dummy))
|
202 |
+
|
203 |
+
def test_pandas_duck(self):
|
204 |
+
# This tests a custom np.dtype duck-typed class, such as used by pandas
|
205 |
+
# (pandas.core.dtypes)
|
206 |
+
class PdComplex(np.complex128):
|
207 |
+
pass
|
208 |
+
class PdDtype:
|
209 |
+
name = 'category'
|
210 |
+
names = None
|
211 |
+
type = PdComplex
|
212 |
+
kind = 'c'
|
213 |
+
str = '<c16'
|
214 |
+
base = np.dtype('complex128')
|
215 |
+
class DummyPd:
|
216 |
+
@property
|
217 |
+
def dtype(self):
|
218 |
+
return PdDtype
|
219 |
+
dummy = DummyPd()
|
220 |
+
assert_(iscomplexobj(dummy))
|
221 |
+
|
222 |
+
def test_custom_dtype_duck(self):
|
223 |
+
class MyArray(list):
|
224 |
+
@property
|
225 |
+
def dtype(self):
|
226 |
+
return complex
|
227 |
+
|
228 |
+
a = MyArray([1+0j, 2+0j, 3+0j])
|
229 |
+
assert_(iscomplexobj(a))
|
230 |
+
|
231 |
+
|
232 |
+
class TestIsrealobj:
|
233 |
+
def test_basic(self):
|
234 |
+
z = np.array([-1, 0, 1])
|
235 |
+
assert_(isrealobj(z))
|
236 |
+
z = np.array([-1j, 0, -1])
|
237 |
+
assert_(not isrealobj(z))
|
238 |
+
|
239 |
+
|
240 |
+
class TestIsnan:
|
241 |
+
|
242 |
+
def test_goodvalues(self):
|
243 |
+
z = np.array((-1., 0., 1.))
|
244 |
+
res = np.isnan(z) == 0
|
245 |
+
assert_all(np.all(res, axis=0))
|
246 |
+
|
247 |
+
def test_posinf(self):
|
248 |
+
with np.errstate(divide='ignore'):
|
249 |
+
assert_all(np.isnan(np.array((1.,))/0.) == 0)
|
250 |
+
|
251 |
+
def test_neginf(self):
|
252 |
+
with np.errstate(divide='ignore'):
|
253 |
+
assert_all(np.isnan(np.array((-1.,))/0.) == 0)
|
254 |
+
|
255 |
+
def test_ind(self):
|
256 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
257 |
+
assert_all(np.isnan(np.array((0.,))/0.) == 1)
|
258 |
+
|
259 |
+
def test_integer(self):
|
260 |
+
assert_all(np.isnan(1) == 0)
|
261 |
+
|
262 |
+
def test_complex(self):
|
263 |
+
assert_all(np.isnan(1+1j) == 0)
|
264 |
+
|
265 |
+
def test_complex1(self):
|
266 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
267 |
+
assert_all(np.isnan(np.array(0+0j)/0.) == 1)
|
268 |
+
|
269 |
+
|
270 |
+
class TestIsfinite:
|
271 |
+
# Fixme, wrong place, isfinite now ufunc
|
272 |
+
|
273 |
+
def test_goodvalues(self):
|
274 |
+
z = np.array((-1., 0., 1.))
|
275 |
+
res = np.isfinite(z) == 1
|
276 |
+
assert_all(np.all(res, axis=0))
|
277 |
+
|
278 |
+
def test_posinf(self):
|
279 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
280 |
+
assert_all(np.isfinite(np.array((1.,))/0.) == 0)
|
281 |
+
|
282 |
+
def test_neginf(self):
|
283 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
284 |
+
assert_all(np.isfinite(np.array((-1.,))/0.) == 0)
|
285 |
+
|
286 |
+
def test_ind(self):
|
287 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
288 |
+
assert_all(np.isfinite(np.array((0.,))/0.) == 0)
|
289 |
+
|
290 |
+
def test_integer(self):
|
291 |
+
assert_all(np.isfinite(1) == 1)
|
292 |
+
|
293 |
+
def test_complex(self):
|
294 |
+
assert_all(np.isfinite(1+1j) == 1)
|
295 |
+
|
296 |
+
def test_complex1(self):
|
297 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
298 |
+
assert_all(np.isfinite(np.array(1+1j)/0.) == 0)
|
299 |
+
|
300 |
+
|
301 |
+
class TestIsinf:
|
302 |
+
# Fixme, wrong place, isinf now ufunc
|
303 |
+
|
304 |
+
def test_goodvalues(self):
|
305 |
+
z = np.array((-1., 0., 1.))
|
306 |
+
res = np.isinf(z) == 0
|
307 |
+
assert_all(np.all(res, axis=0))
|
308 |
+
|
309 |
+
def test_posinf(self):
|
310 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
311 |
+
assert_all(np.isinf(np.array((1.,))/0.) == 1)
|
312 |
+
|
313 |
+
def test_posinf_scalar(self):
|
314 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
315 |
+
assert_all(np.isinf(np.array(1.,)/0.) == 1)
|
316 |
+
|
317 |
+
def test_neginf(self):
|
318 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
319 |
+
assert_all(np.isinf(np.array((-1.,))/0.) == 1)
|
320 |
+
|
321 |
+
def test_neginf_scalar(self):
|
322 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
323 |
+
assert_all(np.isinf(np.array(-1.)/0.) == 1)
|
324 |
+
|
325 |
+
def test_ind(self):
|
326 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
327 |
+
assert_all(np.isinf(np.array((0.,))/0.) == 0)
|
328 |
+
|
329 |
+
|
330 |
+
class TestIsposinf:
|
331 |
+
|
332 |
+
def test_generic(self):
|
333 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
334 |
+
vals = isposinf(np.array((-1., 0, 1))/0.)
|
335 |
+
assert_(vals[0] == 0)
|
336 |
+
assert_(vals[1] == 0)
|
337 |
+
assert_(vals[2] == 1)
|
338 |
+
|
339 |
+
|
340 |
+
class TestIsneginf:
|
341 |
+
|
342 |
+
def test_generic(self):
|
343 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
344 |
+
vals = isneginf(np.array((-1., 0, 1))/0.)
|
345 |
+
assert_(vals[0] == 1)
|
346 |
+
assert_(vals[1] == 0)
|
347 |
+
assert_(vals[2] == 0)
|
348 |
+
|
349 |
+
|
350 |
+
class TestNanToNum:
|
351 |
+
|
352 |
+
def test_generic(self):
|
353 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
354 |
+
vals = nan_to_num(np.array((-1., 0, 1))/0.)
|
355 |
+
assert_all(vals[0] < -1e10) and assert_all(np.isfinite(vals[0]))
|
356 |
+
assert_(vals[1] == 0)
|
357 |
+
assert_all(vals[2] > 1e10) and assert_all(np.isfinite(vals[2]))
|
358 |
+
assert_equal(type(vals), np.ndarray)
|
359 |
+
|
360 |
+
# perform the same tests but with nan, posinf and neginf keywords
|
361 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
362 |
+
vals = nan_to_num(np.array((-1., 0, 1))/0.,
|
363 |
+
nan=10, posinf=20, neginf=30)
|
364 |
+
assert_equal(vals, [30, 10, 20])
|
365 |
+
assert_all(np.isfinite(vals[[0, 2]]))
|
366 |
+
assert_equal(type(vals), np.ndarray)
|
367 |
+
|
368 |
+
# perform the same test but in-place
|
369 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
370 |
+
vals = np.array((-1., 0, 1))/0.
|
371 |
+
result = nan_to_num(vals, copy=False)
|
372 |
+
|
373 |
+
assert_(result is vals)
|
374 |
+
assert_all(vals[0] < -1e10) and assert_all(np.isfinite(vals[0]))
|
375 |
+
assert_(vals[1] == 0)
|
376 |
+
assert_all(vals[2] > 1e10) and assert_all(np.isfinite(vals[2]))
|
377 |
+
assert_equal(type(vals), np.ndarray)
|
378 |
+
|
379 |
+
# perform the same test but in-place
|
380 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
381 |
+
vals = np.array((-1., 0, 1))/0.
|
382 |
+
result = nan_to_num(vals, copy=False, nan=10, posinf=20, neginf=30)
|
383 |
+
|
384 |
+
assert_(result is vals)
|
385 |
+
assert_equal(vals, [30, 10, 20])
|
386 |
+
assert_all(np.isfinite(vals[[0, 2]]))
|
387 |
+
assert_equal(type(vals), np.ndarray)
|
388 |
+
|
389 |
+
def test_array(self):
|
390 |
+
vals = nan_to_num([1])
|
391 |
+
assert_array_equal(vals, np.array([1], int))
|
392 |
+
assert_equal(type(vals), np.ndarray)
|
393 |
+
vals = nan_to_num([1], nan=10, posinf=20, neginf=30)
|
394 |
+
assert_array_equal(vals, np.array([1], int))
|
395 |
+
assert_equal(type(vals), np.ndarray)
|
396 |
+
|
397 |
+
def test_integer(self):
|
398 |
+
vals = nan_to_num(1)
|
399 |
+
assert_all(vals == 1)
|
400 |
+
assert_equal(type(vals), np.int_)
|
401 |
+
vals = nan_to_num(1, nan=10, posinf=20, neginf=30)
|
402 |
+
assert_all(vals == 1)
|
403 |
+
assert_equal(type(vals), np.int_)
|
404 |
+
|
405 |
+
def test_float(self):
|
406 |
+
vals = nan_to_num(1.0)
|
407 |
+
assert_all(vals == 1.0)
|
408 |
+
assert_equal(type(vals), np.float_)
|
409 |
+
vals = nan_to_num(1.1, nan=10, posinf=20, neginf=30)
|
410 |
+
assert_all(vals == 1.1)
|
411 |
+
assert_equal(type(vals), np.float_)
|
412 |
+
|
413 |
+
def test_complex_good(self):
|
414 |
+
vals = nan_to_num(1+1j)
|
415 |
+
assert_all(vals == 1+1j)
|
416 |
+
assert_equal(type(vals), np.complex_)
|
417 |
+
vals = nan_to_num(1+1j, nan=10, posinf=20, neginf=30)
|
418 |
+
assert_all(vals == 1+1j)
|
419 |
+
assert_equal(type(vals), np.complex_)
|
420 |
+
|
421 |
+
def test_complex_bad(self):
|
422 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
423 |
+
v = 1 + 1j
|
424 |
+
v += np.array(0+1.j)/0.
|
425 |
+
vals = nan_to_num(v)
|
426 |
+
# !! This is actually (unexpectedly) zero
|
427 |
+
assert_all(np.isfinite(vals))
|
428 |
+
assert_equal(type(vals), np.complex_)
|
429 |
+
|
430 |
+
def test_complex_bad2(self):
|
431 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
432 |
+
v = 1 + 1j
|
433 |
+
v += np.array(-1+1.j)/0.
|
434 |
+
vals = nan_to_num(v)
|
435 |
+
assert_all(np.isfinite(vals))
|
436 |
+
assert_equal(type(vals), np.complex_)
|
437 |
+
# Fixme
|
438 |
+
#assert_all(vals.imag > 1e10) and assert_all(np.isfinite(vals))
|
439 |
+
# !! This is actually (unexpectedly) positive
|
440 |
+
# !! inf. Comment out for now, and see if it
|
441 |
+
# !! changes
|
442 |
+
#assert_all(vals.real < -1e10) and assert_all(np.isfinite(vals))
|
443 |
+
|
444 |
+
def test_do_not_rewrite_previous_keyword(self):
|
445 |
+
# This is done to test that when, for instance, nan=np.inf then these
|
446 |
+
# values are not rewritten by posinf keyword to the posinf value.
|
447 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
448 |
+
vals = nan_to_num(np.array((-1., 0, 1))/0., nan=np.inf, posinf=999)
|
449 |
+
assert_all(np.isfinite(vals[[0, 2]]))
|
450 |
+
assert_all(vals[0] < -1e10)
|
451 |
+
assert_equal(vals[[1, 2]], [np.inf, 999])
|
452 |
+
assert_equal(type(vals), np.ndarray)
|
453 |
+
|
454 |
+
|
455 |
+
class TestRealIfClose:
|
456 |
+
|
457 |
+
def test_basic(self):
|
458 |
+
a = np.random.rand(10)
|
459 |
+
b = real_if_close(a+1e-15j)
|
460 |
+
assert_all(isrealobj(b))
|
461 |
+
assert_array_equal(a, b)
|
462 |
+
b = real_if_close(a+1e-7j)
|
463 |
+
assert_all(iscomplexobj(b))
|
464 |
+
b = real_if_close(a+1e-7j, tol=1e-6)
|
465 |
+
assert_all(isrealobj(b))
|
466 |
+
|
467 |
+
|
468 |
+
class TestArrayConversion:
|
469 |
+
|
470 |
+
def test_asfarray(self):
|
471 |
+
a = asfarray(np.array([1, 2, 3]))
|
472 |
+
assert_equal(a.__class__, np.ndarray)
|
473 |
+
assert_(np.issubdtype(a.dtype, np.floating))
|
474 |
+
|
475 |
+
# previously this would infer dtypes from arrays, unlike every single
|
476 |
+
# other numpy function
|
477 |
+
assert_raises(TypeError,
|
478 |
+
asfarray, np.array([1, 2, 3]), dtype=np.array(1.0))
|
venv/lib/python3.10/site-packages/numpy/polynomial/__init__.py
ADDED
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
A sub-package for efficiently dealing with polynomials.
|
3 |
+
|
4 |
+
Within the documentation for this sub-package, a "finite power series,"
|
5 |
+
i.e., a polynomial (also referred to simply as a "series") is represented
|
6 |
+
by a 1-D numpy array of the polynomial's coefficients, ordered from lowest
|
7 |
+
order term to highest. For example, array([1,2,3]) represents
|
8 |
+
``P_0 + 2*P_1 + 3*P_2``, where P_n is the n-th order basis polynomial
|
9 |
+
applicable to the specific module in question, e.g., `polynomial` (which
|
10 |
+
"wraps" the "standard" basis) or `chebyshev`. For optimal performance,
|
11 |
+
all operations on polynomials, including evaluation at an argument, are
|
12 |
+
implemented as operations on the coefficients. Additional (module-specific)
|
13 |
+
information can be found in the docstring for the module of interest.
|
14 |
+
|
15 |
+
This package provides *convenience classes* for each of six different kinds
|
16 |
+
of polynomials:
|
17 |
+
|
18 |
+
======================== ================
|
19 |
+
**Name** **Provides**
|
20 |
+
======================== ================
|
21 |
+
`~polynomial.Polynomial` Power series
|
22 |
+
`~chebyshev.Chebyshev` Chebyshev series
|
23 |
+
`~legendre.Legendre` Legendre series
|
24 |
+
`~laguerre.Laguerre` Laguerre series
|
25 |
+
`~hermite.Hermite` Hermite series
|
26 |
+
`~hermite_e.HermiteE` HermiteE series
|
27 |
+
======================== ================
|
28 |
+
|
29 |
+
These *convenience classes* provide a consistent interface for creating,
|
30 |
+
manipulating, and fitting data with polynomials of different bases.
|
31 |
+
The convenience classes are the preferred interface for the `~numpy.polynomial`
|
32 |
+
package, and are available from the ``numpy.polynomial`` namespace.
|
33 |
+
This eliminates the need to navigate to the corresponding submodules, e.g.
|
34 |
+
``np.polynomial.Polynomial`` or ``np.polynomial.Chebyshev`` instead of
|
35 |
+
``np.polynomial.polynomial.Polynomial`` or
|
36 |
+
``np.polynomial.chebyshev.Chebyshev``, respectively.
|
37 |
+
The classes provide a more consistent and concise interface than the
|
38 |
+
type-specific functions defined in the submodules for each type of polynomial.
|
39 |
+
For example, to fit a Chebyshev polynomial with degree ``1`` to data given
|
40 |
+
by arrays ``xdata`` and ``ydata``, the
|
41 |
+
`~chebyshev.Chebyshev.fit` class method::
|
42 |
+
|
43 |
+
>>> from numpy.polynomial import Chebyshev
|
44 |
+
>>> c = Chebyshev.fit(xdata, ydata, deg=1)
|
45 |
+
|
46 |
+
is preferred over the `chebyshev.chebfit` function from the
|
47 |
+
``np.polynomial.chebyshev`` module::
|
48 |
+
|
49 |
+
>>> from numpy.polynomial.chebyshev import chebfit
|
50 |
+
>>> c = chebfit(xdata, ydata, deg=1)
|
51 |
+
|
52 |
+
See :doc:`routines.polynomials.classes` for more details.
|
53 |
+
|
54 |
+
Convenience Classes
|
55 |
+
===================
|
56 |
+
|
57 |
+
The following lists the various constants and methods common to all of
|
58 |
+
the classes representing the various kinds of polynomials. In the following,
|
59 |
+
the term ``Poly`` represents any one of the convenience classes (e.g.
|
60 |
+
`~polynomial.Polynomial`, `~chebyshev.Chebyshev`, `~hermite.Hermite`, etc.)
|
61 |
+
while the lowercase ``p`` represents an **instance** of a polynomial class.
|
62 |
+
|
63 |
+
Constants
|
64 |
+
---------
|
65 |
+
|
66 |
+
- ``Poly.domain`` -- Default domain
|
67 |
+
- ``Poly.window`` -- Default window
|
68 |
+
- ``Poly.basis_name`` -- String used to represent the basis
|
69 |
+
- ``Poly.maxpower`` -- Maximum value ``n`` such that ``p**n`` is allowed
|
70 |
+
- ``Poly.nickname`` -- String used in printing
|
71 |
+
|
72 |
+
Creation
|
73 |
+
--------
|
74 |
+
|
75 |
+
Methods for creating polynomial instances.
|
76 |
+
|
77 |
+
- ``Poly.basis(degree)`` -- Basis polynomial of given degree
|
78 |
+
- ``Poly.identity()`` -- ``p`` where ``p(x) = x`` for all ``x``
|
79 |
+
- ``Poly.fit(x, y, deg)`` -- ``p`` of degree ``deg`` with coefficients
|
80 |
+
determined by the least-squares fit to the data ``x``, ``y``
|
81 |
+
- ``Poly.fromroots(roots)`` -- ``p`` with specified roots
|
82 |
+
- ``p.copy()`` -- Create a copy of ``p``
|
83 |
+
|
84 |
+
Conversion
|
85 |
+
----------
|
86 |
+
|
87 |
+
Methods for converting a polynomial instance of one kind to another.
|
88 |
+
|
89 |
+
- ``p.cast(Poly)`` -- Convert ``p`` to instance of kind ``Poly``
|
90 |
+
- ``p.convert(Poly)`` -- Convert ``p`` to instance of kind ``Poly`` or map
|
91 |
+
between ``domain`` and ``window``
|
92 |
+
|
93 |
+
Calculus
|
94 |
+
--------
|
95 |
+
- ``p.deriv()`` -- Take the derivative of ``p``
|
96 |
+
- ``p.integ()`` -- Integrate ``p``
|
97 |
+
|
98 |
+
Validation
|
99 |
+
----------
|
100 |
+
- ``Poly.has_samecoef(p1, p2)`` -- Check if coefficients match
|
101 |
+
- ``Poly.has_samedomain(p1, p2)`` -- Check if domains match
|
102 |
+
- ``Poly.has_sametype(p1, p2)`` -- Check if types match
|
103 |
+
- ``Poly.has_samewindow(p1, p2)`` -- Check if windows match
|
104 |
+
|
105 |
+
Misc
|
106 |
+
----
|
107 |
+
- ``p.linspace()`` -- Return ``x, p(x)`` at equally-spaced points in ``domain``
|
108 |
+
- ``p.mapparms()`` -- Return the parameters for the linear mapping between
|
109 |
+
``domain`` and ``window``.
|
110 |
+
- ``p.roots()`` -- Return the roots of `p`.
|
111 |
+
- ``p.trim()`` -- Remove trailing coefficients.
|
112 |
+
- ``p.cutdeg(degree)`` -- Truncate p to given degree
|
113 |
+
- ``p.truncate(size)`` -- Truncate p to given size
|
114 |
+
|
115 |
+
"""
|
116 |
+
from .polynomial import Polynomial
|
117 |
+
from .chebyshev import Chebyshev
|
118 |
+
from .legendre import Legendre
|
119 |
+
from .hermite import Hermite
|
120 |
+
from .hermite_e import HermiteE
|
121 |
+
from .laguerre import Laguerre
|
122 |
+
|
123 |
+
__all__ = [
|
124 |
+
"set_default_printstyle",
|
125 |
+
"polynomial", "Polynomial",
|
126 |
+
"chebyshev", "Chebyshev",
|
127 |
+
"legendre", "Legendre",
|
128 |
+
"hermite", "Hermite",
|
129 |
+
"hermite_e", "HermiteE",
|
130 |
+
"laguerre", "Laguerre",
|
131 |
+
]
|
132 |
+
|
133 |
+
|
134 |
+
def set_default_printstyle(style):
|
135 |
+
"""
|
136 |
+
Set the default format for the string representation of polynomials.
|
137 |
+
|
138 |
+
Values for ``style`` must be valid inputs to ``__format__``, i.e. 'ascii'
|
139 |
+
or 'unicode'.
|
140 |
+
|
141 |
+
Parameters
|
142 |
+
----------
|
143 |
+
style : str
|
144 |
+
Format string for default printing style. Must be either 'ascii' or
|
145 |
+
'unicode'.
|
146 |
+
|
147 |
+
Notes
|
148 |
+
-----
|
149 |
+
The default format depends on the platform: 'unicode' is used on
|
150 |
+
Unix-based systems and 'ascii' on Windows. This determination is based on
|
151 |
+
default font support for the unicode superscript and subscript ranges.
|
152 |
+
|
153 |
+
Examples
|
154 |
+
--------
|
155 |
+
>>> p = np.polynomial.Polynomial([1, 2, 3])
|
156 |
+
>>> c = np.polynomial.Chebyshev([1, 2, 3])
|
157 |
+
>>> np.polynomial.set_default_printstyle('unicode')
|
158 |
+
>>> print(p)
|
159 |
+
1.0 + 2.0·x + 3.0·x²
|
160 |
+
>>> print(c)
|
161 |
+
1.0 + 2.0·T₁(x) + 3.0·T₂(x)
|
162 |
+
>>> np.polynomial.set_default_printstyle('ascii')
|
163 |
+
>>> print(p)
|
164 |
+
1.0 + 2.0 x + 3.0 x**2
|
165 |
+
>>> print(c)
|
166 |
+
1.0 + 2.0 T_1(x) + 3.0 T_2(x)
|
167 |
+
>>> # Formatting supersedes all class/package-level defaults
|
168 |
+
>>> print(f"{p:unicode}")
|
169 |
+
1.0 + 2.0·x + 3.0·x²
|
170 |
+
"""
|
171 |
+
if style not in ('unicode', 'ascii'):
|
172 |
+
raise ValueError(
|
173 |
+
f"Unsupported format string '{style}'. Valid options are 'ascii' "
|
174 |
+
f"and 'unicode'"
|
175 |
+
)
|
176 |
+
_use_unicode = True
|
177 |
+
if style == 'ascii':
|
178 |
+
_use_unicode = False
|
179 |
+
from ._polybase import ABCPolyBase
|
180 |
+
ABCPolyBase._use_unicode = _use_unicode
|
181 |
+
|
182 |
+
|
183 |
+
from numpy._pytesttester import PytestTester
|
184 |
+
test = PytestTester(__name__)
|
185 |
+
del PytestTester
|
venv/lib/python3.10/site-packages/numpy/polynomial/__init__.pyi
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from numpy._pytesttester import PytestTester
|
2 |
+
|
3 |
+
from numpy.polynomial import (
|
4 |
+
chebyshev as chebyshev,
|
5 |
+
hermite as hermite,
|
6 |
+
hermite_e as hermite_e,
|
7 |
+
laguerre as laguerre,
|
8 |
+
legendre as legendre,
|
9 |
+
polynomial as polynomial,
|
10 |
+
)
|
11 |
+
from numpy.polynomial.chebyshev import Chebyshev as Chebyshev
|
12 |
+
from numpy.polynomial.hermite import Hermite as Hermite
|
13 |
+
from numpy.polynomial.hermite_e import HermiteE as HermiteE
|
14 |
+
from numpy.polynomial.laguerre import Laguerre as Laguerre
|
15 |
+
from numpy.polynomial.legendre import Legendre as Legendre
|
16 |
+
from numpy.polynomial.polynomial import Polynomial as Polynomial
|
17 |
+
|
18 |
+
__all__: list[str]
|
19 |
+
__path__: list[str]
|
20 |
+
test: PytestTester
|
21 |
+
|
22 |
+
def set_default_printstyle(style): ...
|
venv/lib/python3.10/site-packages/numpy/polynomial/_polybase.py
ADDED
@@ -0,0 +1,1206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Abstract base class for the various polynomial Classes.
|
3 |
+
|
4 |
+
The ABCPolyBase class provides the methods needed to implement the common API
|
5 |
+
for the various polynomial classes. It operates as a mixin, but uses the
|
6 |
+
abc module from the stdlib, hence it is only available for Python >= 2.6.
|
7 |
+
|
8 |
+
"""
|
9 |
+
import os
|
10 |
+
import abc
|
11 |
+
import numbers
|
12 |
+
|
13 |
+
import numpy as np
|
14 |
+
from . import polyutils as pu
|
15 |
+
|
16 |
+
__all__ = ['ABCPolyBase']
|
17 |
+
|
18 |
+
class ABCPolyBase(abc.ABC):
|
19 |
+
"""An abstract base class for immutable series classes.
|
20 |
+
|
21 |
+
ABCPolyBase provides the standard Python numerical methods
|
22 |
+
'+', '-', '*', '//', '%', 'divmod', '**', and '()' along with the
|
23 |
+
methods listed below.
|
24 |
+
|
25 |
+
.. versionadded:: 1.9.0
|
26 |
+
|
27 |
+
Parameters
|
28 |
+
----------
|
29 |
+
coef : array_like
|
30 |
+
Series coefficients in order of increasing degree, i.e.,
|
31 |
+
``(1, 2, 3)`` gives ``1*P_0(x) + 2*P_1(x) + 3*P_2(x)``, where
|
32 |
+
``P_i`` is the basis polynomials of degree ``i``.
|
33 |
+
domain : (2,) array_like, optional
|
34 |
+
Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
|
35 |
+
to the interval ``[window[0], window[1]]`` by shifting and scaling.
|
36 |
+
The default value is the derived class domain.
|
37 |
+
window : (2,) array_like, optional
|
38 |
+
Window, see domain for its use. The default value is the
|
39 |
+
derived class window.
|
40 |
+
symbol : str, optional
|
41 |
+
Symbol used to represent the independent variable in string
|
42 |
+
representations of the polynomial expression, e.g. for printing.
|
43 |
+
The symbol must be a valid Python identifier. Default value is 'x'.
|
44 |
+
|
45 |
+
.. versionadded:: 1.24
|
46 |
+
|
47 |
+
Attributes
|
48 |
+
----------
|
49 |
+
coef : (N,) ndarray
|
50 |
+
Series coefficients in order of increasing degree.
|
51 |
+
domain : (2,) ndarray
|
52 |
+
Domain that is mapped to window.
|
53 |
+
window : (2,) ndarray
|
54 |
+
Window that domain is mapped to.
|
55 |
+
symbol : str
|
56 |
+
Symbol representing the independent variable.
|
57 |
+
|
58 |
+
Class Attributes
|
59 |
+
----------------
|
60 |
+
maxpower : int
|
61 |
+
Maximum power allowed, i.e., the largest number ``n`` such that
|
62 |
+
``p(x)**n`` is allowed. This is to limit runaway polynomial size.
|
63 |
+
domain : (2,) ndarray
|
64 |
+
Default domain of the class.
|
65 |
+
window : (2,) ndarray
|
66 |
+
Default window of the class.
|
67 |
+
|
68 |
+
"""
|
69 |
+
|
70 |
+
# Not hashable
|
71 |
+
__hash__ = None
|
72 |
+
|
73 |
+
# Opt out of numpy ufuncs and Python ops with ndarray subclasses.
|
74 |
+
__array_ufunc__ = None
|
75 |
+
|
76 |
+
# Limit runaway size. T_n^m has degree n*m
|
77 |
+
maxpower = 100
|
78 |
+
|
79 |
+
# Unicode character mappings for improved __str__
|
80 |
+
_superscript_mapping = str.maketrans({
|
81 |
+
"0": "⁰",
|
82 |
+
"1": "¹",
|
83 |
+
"2": "²",
|
84 |
+
"3": "³",
|
85 |
+
"4": "⁴",
|
86 |
+
"5": "⁵",
|
87 |
+
"6": "⁶",
|
88 |
+
"7": "⁷",
|
89 |
+
"8": "⁸",
|
90 |
+
"9": "⁹"
|
91 |
+
})
|
92 |
+
_subscript_mapping = str.maketrans({
|
93 |
+
"0": "₀",
|
94 |
+
"1": "₁",
|
95 |
+
"2": "₂",
|
96 |
+
"3": "₃",
|
97 |
+
"4": "₄",
|
98 |
+
"5": "₅",
|
99 |
+
"6": "₆",
|
100 |
+
"7": "₇",
|
101 |
+
"8": "₈",
|
102 |
+
"9": "₉"
|
103 |
+
})
|
104 |
+
# Some fonts don't support full unicode character ranges necessary for
|
105 |
+
# the full set of superscripts and subscripts, including common/default
|
106 |
+
# fonts in Windows shells/terminals. Therefore, default to ascii-only
|
107 |
+
# printing on windows.
|
108 |
+
_use_unicode = not os.name == 'nt'
|
109 |
+
|
110 |
+
@property
|
111 |
+
def symbol(self):
|
112 |
+
return self._symbol
|
113 |
+
|
114 |
+
@property
|
115 |
+
@abc.abstractmethod
|
116 |
+
def domain(self):
|
117 |
+
pass
|
118 |
+
|
119 |
+
@property
|
120 |
+
@abc.abstractmethod
|
121 |
+
def window(self):
|
122 |
+
pass
|
123 |
+
|
124 |
+
@property
|
125 |
+
@abc.abstractmethod
|
126 |
+
def basis_name(self):
|
127 |
+
pass
|
128 |
+
|
129 |
+
@staticmethod
|
130 |
+
@abc.abstractmethod
|
131 |
+
def _add(c1, c2):
|
132 |
+
pass
|
133 |
+
|
134 |
+
@staticmethod
|
135 |
+
@abc.abstractmethod
|
136 |
+
def _sub(c1, c2):
|
137 |
+
pass
|
138 |
+
|
139 |
+
@staticmethod
|
140 |
+
@abc.abstractmethod
|
141 |
+
def _mul(c1, c2):
|
142 |
+
pass
|
143 |
+
|
144 |
+
@staticmethod
|
145 |
+
@abc.abstractmethod
|
146 |
+
def _div(c1, c2):
|
147 |
+
pass
|
148 |
+
|
149 |
+
@staticmethod
|
150 |
+
@abc.abstractmethod
|
151 |
+
def _pow(c, pow, maxpower=None):
|
152 |
+
pass
|
153 |
+
|
154 |
+
@staticmethod
|
155 |
+
@abc.abstractmethod
|
156 |
+
def _val(x, c):
|
157 |
+
pass
|
158 |
+
|
159 |
+
@staticmethod
|
160 |
+
@abc.abstractmethod
|
161 |
+
def _int(c, m, k, lbnd, scl):
|
162 |
+
pass
|
163 |
+
|
164 |
+
@staticmethod
|
165 |
+
@abc.abstractmethod
|
166 |
+
def _der(c, m, scl):
|
167 |
+
pass
|
168 |
+
|
169 |
+
@staticmethod
|
170 |
+
@abc.abstractmethod
|
171 |
+
def _fit(x, y, deg, rcond, full):
|
172 |
+
pass
|
173 |
+
|
174 |
+
@staticmethod
|
175 |
+
@abc.abstractmethod
|
176 |
+
def _line(off, scl):
|
177 |
+
pass
|
178 |
+
|
179 |
+
@staticmethod
|
180 |
+
@abc.abstractmethod
|
181 |
+
def _roots(c):
|
182 |
+
pass
|
183 |
+
|
184 |
+
@staticmethod
|
185 |
+
@abc.abstractmethod
|
186 |
+
def _fromroots(r):
|
187 |
+
pass
|
188 |
+
|
189 |
+
def has_samecoef(self, other):
|
190 |
+
"""Check if coefficients match.
|
191 |
+
|
192 |
+
.. versionadded:: 1.6.0
|
193 |
+
|
194 |
+
Parameters
|
195 |
+
----------
|
196 |
+
other : class instance
|
197 |
+
The other class must have the ``coef`` attribute.
|
198 |
+
|
199 |
+
Returns
|
200 |
+
-------
|
201 |
+
bool : boolean
|
202 |
+
True if the coefficients are the same, False otherwise.
|
203 |
+
|
204 |
+
"""
|
205 |
+
if len(self.coef) != len(other.coef):
|
206 |
+
return False
|
207 |
+
elif not np.all(self.coef == other.coef):
|
208 |
+
return False
|
209 |
+
else:
|
210 |
+
return True
|
211 |
+
|
212 |
+
def has_samedomain(self, other):
|
213 |
+
"""Check if domains match.
|
214 |
+
|
215 |
+
.. versionadded:: 1.6.0
|
216 |
+
|
217 |
+
Parameters
|
218 |
+
----------
|
219 |
+
other : class instance
|
220 |
+
The other class must have the ``domain`` attribute.
|
221 |
+
|
222 |
+
Returns
|
223 |
+
-------
|
224 |
+
bool : boolean
|
225 |
+
True if the domains are the same, False otherwise.
|
226 |
+
|
227 |
+
"""
|
228 |
+
return np.all(self.domain == other.domain)
|
229 |
+
|
230 |
+
def has_samewindow(self, other):
|
231 |
+
"""Check if windows match.
|
232 |
+
|
233 |
+
.. versionadded:: 1.6.0
|
234 |
+
|
235 |
+
Parameters
|
236 |
+
----------
|
237 |
+
other : class instance
|
238 |
+
The other class must have the ``window`` attribute.
|
239 |
+
|
240 |
+
Returns
|
241 |
+
-------
|
242 |
+
bool : boolean
|
243 |
+
True if the windows are the same, False otherwise.
|
244 |
+
|
245 |
+
"""
|
246 |
+
return np.all(self.window == other.window)
|
247 |
+
|
248 |
+
def has_sametype(self, other):
|
249 |
+
"""Check if types match.
|
250 |
+
|
251 |
+
.. versionadded:: 1.7.0
|
252 |
+
|
253 |
+
Parameters
|
254 |
+
----------
|
255 |
+
other : object
|
256 |
+
Class instance.
|
257 |
+
|
258 |
+
Returns
|
259 |
+
-------
|
260 |
+
bool : boolean
|
261 |
+
True if other is same class as self
|
262 |
+
|
263 |
+
"""
|
264 |
+
return isinstance(other, self.__class__)
|
265 |
+
|
266 |
+
def _get_coefficients(self, other):
|
267 |
+
"""Interpret other as polynomial coefficients.
|
268 |
+
|
269 |
+
The `other` argument is checked to see if it is of the same
|
270 |
+
class as self with identical domain and window. If so,
|
271 |
+
return its coefficients, otherwise return `other`.
|
272 |
+
|
273 |
+
.. versionadded:: 1.9.0
|
274 |
+
|
275 |
+
Parameters
|
276 |
+
----------
|
277 |
+
other : anything
|
278 |
+
Object to be checked.
|
279 |
+
|
280 |
+
Returns
|
281 |
+
-------
|
282 |
+
coef
|
283 |
+
The coefficients of`other` if it is a compatible instance,
|
284 |
+
of ABCPolyBase, otherwise `other`.
|
285 |
+
|
286 |
+
Raises
|
287 |
+
------
|
288 |
+
TypeError
|
289 |
+
When `other` is an incompatible instance of ABCPolyBase.
|
290 |
+
|
291 |
+
"""
|
292 |
+
if isinstance(other, ABCPolyBase):
|
293 |
+
if not isinstance(other, self.__class__):
|
294 |
+
raise TypeError("Polynomial types differ")
|
295 |
+
elif not np.all(self.domain == other.domain):
|
296 |
+
raise TypeError("Domains differ")
|
297 |
+
elif not np.all(self.window == other.window):
|
298 |
+
raise TypeError("Windows differ")
|
299 |
+
elif self.symbol != other.symbol:
|
300 |
+
raise ValueError("Polynomial symbols differ")
|
301 |
+
return other.coef
|
302 |
+
return other
|
303 |
+
|
304 |
+
def __init__(self, coef, domain=None, window=None, symbol='x'):
|
305 |
+
[coef] = pu.as_series([coef], trim=False)
|
306 |
+
self.coef = coef
|
307 |
+
|
308 |
+
if domain is not None:
|
309 |
+
[domain] = pu.as_series([domain], trim=False)
|
310 |
+
if len(domain) != 2:
|
311 |
+
raise ValueError("Domain has wrong number of elements.")
|
312 |
+
self.domain = domain
|
313 |
+
|
314 |
+
if window is not None:
|
315 |
+
[window] = pu.as_series([window], trim=False)
|
316 |
+
if len(window) != 2:
|
317 |
+
raise ValueError("Window has wrong number of elements.")
|
318 |
+
self.window = window
|
319 |
+
|
320 |
+
# Validation for symbol
|
321 |
+
try:
|
322 |
+
if not symbol.isidentifier():
|
323 |
+
raise ValueError(
|
324 |
+
"Symbol string must be a valid Python identifier"
|
325 |
+
)
|
326 |
+
# If a user passes in something other than a string, the above
|
327 |
+
# results in an AttributeError. Catch this and raise a more
|
328 |
+
# informative exception
|
329 |
+
except AttributeError:
|
330 |
+
raise TypeError("Symbol must be a non-empty string")
|
331 |
+
|
332 |
+
self._symbol = symbol
|
333 |
+
|
334 |
+
def __repr__(self):
|
335 |
+
coef = repr(self.coef)[6:-1]
|
336 |
+
domain = repr(self.domain)[6:-1]
|
337 |
+
window = repr(self.window)[6:-1]
|
338 |
+
name = self.__class__.__name__
|
339 |
+
return (f"{name}({coef}, domain={domain}, window={window}, "
|
340 |
+
f"symbol='{self.symbol}')")
|
341 |
+
|
342 |
+
def __format__(self, fmt_str):
|
343 |
+
if fmt_str == '':
|
344 |
+
return self.__str__()
|
345 |
+
if fmt_str not in ('ascii', 'unicode'):
|
346 |
+
raise ValueError(
|
347 |
+
f"Unsupported format string '{fmt_str}' passed to "
|
348 |
+
f"{self.__class__}.__format__. Valid options are "
|
349 |
+
f"'ascii' and 'unicode'"
|
350 |
+
)
|
351 |
+
if fmt_str == 'ascii':
|
352 |
+
return self._generate_string(self._str_term_ascii)
|
353 |
+
return self._generate_string(self._str_term_unicode)
|
354 |
+
|
355 |
+
def __str__(self):
|
356 |
+
if self._use_unicode:
|
357 |
+
return self._generate_string(self._str_term_unicode)
|
358 |
+
return self._generate_string(self._str_term_ascii)
|
359 |
+
|
360 |
+
def _generate_string(self, term_method):
|
361 |
+
"""
|
362 |
+
Generate the full string representation of the polynomial, using
|
363 |
+
``term_method`` to generate each polynomial term.
|
364 |
+
"""
|
365 |
+
# Get configuration for line breaks
|
366 |
+
linewidth = np.get_printoptions().get('linewidth', 75)
|
367 |
+
if linewidth < 1:
|
368 |
+
linewidth = 1
|
369 |
+
out = pu.format_float(self.coef[0])
|
370 |
+
for i, coef in enumerate(self.coef[1:]):
|
371 |
+
out += " "
|
372 |
+
power = str(i + 1)
|
373 |
+
# Polynomial coefficient
|
374 |
+
# The coefficient array can be an object array with elements that
|
375 |
+
# will raise a TypeError with >= 0 (e.g. strings or Python
|
376 |
+
# complex). In this case, represent the coefficient as-is.
|
377 |
+
try:
|
378 |
+
if coef >= 0:
|
379 |
+
next_term = f"+ " + pu.format_float(coef, parens=True)
|
380 |
+
else:
|
381 |
+
next_term = f"- " + pu.format_float(-coef, parens=True)
|
382 |
+
except TypeError:
|
383 |
+
next_term = f"+ {coef}"
|
384 |
+
# Polynomial term
|
385 |
+
next_term += term_method(power, self.symbol)
|
386 |
+
# Length of the current line with next term added
|
387 |
+
line_len = len(out.split('\n')[-1]) + len(next_term)
|
388 |
+
# If not the last term in the polynomial, it will be two
|
389 |
+
# characters longer due to the +/- with the next term
|
390 |
+
if i < len(self.coef[1:]) - 1:
|
391 |
+
line_len += 2
|
392 |
+
# Handle linebreaking
|
393 |
+
if line_len >= linewidth:
|
394 |
+
next_term = next_term.replace(" ", "\n", 1)
|
395 |
+
out += next_term
|
396 |
+
return out
|
397 |
+
|
398 |
+
@classmethod
|
399 |
+
def _str_term_unicode(cls, i, arg_str):
|
400 |
+
"""
|
401 |
+
String representation of single polynomial term using unicode
|
402 |
+
characters for superscripts and subscripts.
|
403 |
+
"""
|
404 |
+
if cls.basis_name is None:
|
405 |
+
raise NotImplementedError(
|
406 |
+
"Subclasses must define either a basis_name, or override "
|
407 |
+
"_str_term_unicode(cls, i, arg_str)"
|
408 |
+
)
|
409 |
+
return (f"·{cls.basis_name}{i.translate(cls._subscript_mapping)}"
|
410 |
+
f"({arg_str})")
|
411 |
+
|
412 |
+
@classmethod
|
413 |
+
def _str_term_ascii(cls, i, arg_str):
|
414 |
+
"""
|
415 |
+
String representation of a single polynomial term using ** and _ to
|
416 |
+
represent superscripts and subscripts, respectively.
|
417 |
+
"""
|
418 |
+
if cls.basis_name is None:
|
419 |
+
raise NotImplementedError(
|
420 |
+
"Subclasses must define either a basis_name, or override "
|
421 |
+
"_str_term_ascii(cls, i, arg_str)"
|
422 |
+
)
|
423 |
+
return f" {cls.basis_name}_{i}({arg_str})"
|
424 |
+
|
425 |
+
@classmethod
|
426 |
+
def _repr_latex_term(cls, i, arg_str, needs_parens):
|
427 |
+
if cls.basis_name is None:
|
428 |
+
raise NotImplementedError(
|
429 |
+
"Subclasses must define either a basis name, or override "
|
430 |
+
"_repr_latex_term(i, arg_str, needs_parens)")
|
431 |
+
# since we always add parens, we don't care if the expression needs them
|
432 |
+
return f"{{{cls.basis_name}}}_{{{i}}}({arg_str})"
|
433 |
+
|
434 |
+
@staticmethod
|
435 |
+
def _repr_latex_scalar(x, parens=False):
|
436 |
+
# TODO: we're stuck with disabling math formatting until we handle
|
437 |
+
# exponents in this function
|
438 |
+
return r'\text{{{}}}'.format(pu.format_float(x, parens=parens))
|
439 |
+
|
440 |
+
def _repr_latex_(self):
|
441 |
+
# get the scaled argument string to the basis functions
|
442 |
+
off, scale = self.mapparms()
|
443 |
+
if off == 0 and scale == 1:
|
444 |
+
term = self.symbol
|
445 |
+
needs_parens = False
|
446 |
+
elif scale == 1:
|
447 |
+
term = f"{self._repr_latex_scalar(off)} + {self.symbol}"
|
448 |
+
needs_parens = True
|
449 |
+
elif off == 0:
|
450 |
+
term = f"{self._repr_latex_scalar(scale)}{self.symbol}"
|
451 |
+
needs_parens = True
|
452 |
+
else:
|
453 |
+
term = (
|
454 |
+
f"{self._repr_latex_scalar(off)} + "
|
455 |
+
f"{self._repr_latex_scalar(scale)}{self.symbol}"
|
456 |
+
)
|
457 |
+
needs_parens = True
|
458 |
+
|
459 |
+
mute = r"\color{{LightGray}}{{{}}}".format
|
460 |
+
|
461 |
+
parts = []
|
462 |
+
for i, c in enumerate(self.coef):
|
463 |
+
# prevent duplication of + and - signs
|
464 |
+
if i == 0:
|
465 |
+
coef_str = f"{self._repr_latex_scalar(c)}"
|
466 |
+
elif not isinstance(c, numbers.Real):
|
467 |
+
coef_str = f" + ({self._repr_latex_scalar(c)})"
|
468 |
+
elif not np.signbit(c):
|
469 |
+
coef_str = f" + {self._repr_latex_scalar(c, parens=True)}"
|
470 |
+
else:
|
471 |
+
coef_str = f" - {self._repr_latex_scalar(-c, parens=True)}"
|
472 |
+
|
473 |
+
# produce the string for the term
|
474 |
+
term_str = self._repr_latex_term(i, term, needs_parens)
|
475 |
+
if term_str == '1':
|
476 |
+
part = coef_str
|
477 |
+
else:
|
478 |
+
part = rf"{coef_str}\,{term_str}"
|
479 |
+
|
480 |
+
if c == 0:
|
481 |
+
part = mute(part)
|
482 |
+
|
483 |
+
parts.append(part)
|
484 |
+
|
485 |
+
if parts:
|
486 |
+
body = ''.join(parts)
|
487 |
+
else:
|
488 |
+
# in case somehow there are no coefficients at all
|
489 |
+
body = '0'
|
490 |
+
|
491 |
+
return rf"${self.symbol} \mapsto {body}$"
|
492 |
+
|
493 |
+
|
494 |
+
|
495 |
+
# Pickle and copy
|
496 |
+
|
497 |
+
def __getstate__(self):
|
498 |
+
ret = self.__dict__.copy()
|
499 |
+
ret['coef'] = self.coef.copy()
|
500 |
+
ret['domain'] = self.domain.copy()
|
501 |
+
ret['window'] = self.window.copy()
|
502 |
+
ret['symbol'] = self.symbol
|
503 |
+
return ret
|
504 |
+
|
505 |
+
def __setstate__(self, dict):
|
506 |
+
self.__dict__ = dict
|
507 |
+
|
508 |
+
# Call
|
509 |
+
|
510 |
+
def __call__(self, arg):
|
511 |
+
off, scl = pu.mapparms(self.domain, self.window)
|
512 |
+
arg = off + scl*arg
|
513 |
+
return self._val(arg, self.coef)
|
514 |
+
|
515 |
+
def __iter__(self):
|
516 |
+
return iter(self.coef)
|
517 |
+
|
518 |
+
def __len__(self):
|
519 |
+
return len(self.coef)
|
520 |
+
|
521 |
+
# Numeric properties.
|
522 |
+
|
523 |
+
def __neg__(self):
|
524 |
+
return self.__class__(
|
525 |
+
-self.coef, self.domain, self.window, self.symbol
|
526 |
+
)
|
527 |
+
|
528 |
+
def __pos__(self):
|
529 |
+
return self
|
530 |
+
|
531 |
+
def __add__(self, other):
|
532 |
+
othercoef = self._get_coefficients(other)
|
533 |
+
try:
|
534 |
+
coef = self._add(self.coef, othercoef)
|
535 |
+
except Exception:
|
536 |
+
return NotImplemented
|
537 |
+
return self.__class__(coef, self.domain, self.window, self.symbol)
|
538 |
+
|
539 |
+
def __sub__(self, other):
|
540 |
+
othercoef = self._get_coefficients(other)
|
541 |
+
try:
|
542 |
+
coef = self._sub(self.coef, othercoef)
|
543 |
+
except Exception:
|
544 |
+
return NotImplemented
|
545 |
+
return self.__class__(coef, self.domain, self.window, self.symbol)
|
546 |
+
|
547 |
+
def __mul__(self, other):
|
548 |
+
othercoef = self._get_coefficients(other)
|
549 |
+
try:
|
550 |
+
coef = self._mul(self.coef, othercoef)
|
551 |
+
except Exception:
|
552 |
+
return NotImplemented
|
553 |
+
return self.__class__(coef, self.domain, self.window, self.symbol)
|
554 |
+
|
555 |
+
def __truediv__(self, other):
|
556 |
+
# there is no true divide if the rhs is not a Number, although it
|
557 |
+
# could return the first n elements of an infinite series.
|
558 |
+
# It is hard to see where n would come from, though.
|
559 |
+
if not isinstance(other, numbers.Number) or isinstance(other, bool):
|
560 |
+
raise TypeError(
|
561 |
+
f"unsupported types for true division: "
|
562 |
+
f"'{type(self)}', '{type(other)}'"
|
563 |
+
)
|
564 |
+
return self.__floordiv__(other)
|
565 |
+
|
566 |
+
def __floordiv__(self, other):
|
567 |
+
res = self.__divmod__(other)
|
568 |
+
if res is NotImplemented:
|
569 |
+
return res
|
570 |
+
return res[0]
|
571 |
+
|
572 |
+
def __mod__(self, other):
|
573 |
+
res = self.__divmod__(other)
|
574 |
+
if res is NotImplemented:
|
575 |
+
return res
|
576 |
+
return res[1]
|
577 |
+
|
578 |
+
def __divmod__(self, other):
|
579 |
+
othercoef = self._get_coefficients(other)
|
580 |
+
try:
|
581 |
+
quo, rem = self._div(self.coef, othercoef)
|
582 |
+
except ZeroDivisionError:
|
583 |
+
raise
|
584 |
+
except Exception:
|
585 |
+
return NotImplemented
|
586 |
+
quo = self.__class__(quo, self.domain, self.window, self.symbol)
|
587 |
+
rem = self.__class__(rem, self.domain, self.window, self.symbol)
|
588 |
+
return quo, rem
|
589 |
+
|
590 |
+
def __pow__(self, other):
|
591 |
+
coef = self._pow(self.coef, other, maxpower=self.maxpower)
|
592 |
+
res = self.__class__(coef, self.domain, self.window, self.symbol)
|
593 |
+
return res
|
594 |
+
|
595 |
+
def __radd__(self, other):
|
596 |
+
try:
|
597 |
+
coef = self._add(other, self.coef)
|
598 |
+
except Exception:
|
599 |
+
return NotImplemented
|
600 |
+
return self.__class__(coef, self.domain, self.window, self.symbol)
|
601 |
+
|
602 |
+
def __rsub__(self, other):
|
603 |
+
try:
|
604 |
+
coef = self._sub(other, self.coef)
|
605 |
+
except Exception:
|
606 |
+
return NotImplemented
|
607 |
+
return self.__class__(coef, self.domain, self.window, self.symbol)
|
608 |
+
|
609 |
+
def __rmul__(self, other):
|
610 |
+
try:
|
611 |
+
coef = self._mul(other, self.coef)
|
612 |
+
except Exception:
|
613 |
+
return NotImplemented
|
614 |
+
return self.__class__(coef, self.domain, self.window, self.symbol)
|
615 |
+
|
616 |
+
def __rdiv__(self, other):
|
617 |
+
# set to __floordiv__ /.
|
618 |
+
return self.__rfloordiv__(other)
|
619 |
+
|
620 |
+
def __rtruediv__(self, other):
|
621 |
+
# An instance of ABCPolyBase is not considered a
|
622 |
+
# Number.
|
623 |
+
return NotImplemented
|
624 |
+
|
625 |
+
def __rfloordiv__(self, other):
|
626 |
+
res = self.__rdivmod__(other)
|
627 |
+
if res is NotImplemented:
|
628 |
+
return res
|
629 |
+
return res[0]
|
630 |
+
|
631 |
+
def __rmod__(self, other):
|
632 |
+
res = self.__rdivmod__(other)
|
633 |
+
if res is NotImplemented:
|
634 |
+
return res
|
635 |
+
return res[1]
|
636 |
+
|
637 |
+
def __rdivmod__(self, other):
|
638 |
+
try:
|
639 |
+
quo, rem = self._div(other, self.coef)
|
640 |
+
except ZeroDivisionError:
|
641 |
+
raise
|
642 |
+
except Exception:
|
643 |
+
return NotImplemented
|
644 |
+
quo = self.__class__(quo, self.domain, self.window, self.symbol)
|
645 |
+
rem = self.__class__(rem, self.domain, self.window, self.symbol)
|
646 |
+
return quo, rem
|
647 |
+
|
648 |
+
def __eq__(self, other):
|
649 |
+
res = (isinstance(other, self.__class__) and
|
650 |
+
np.all(self.domain == other.domain) and
|
651 |
+
np.all(self.window == other.window) and
|
652 |
+
(self.coef.shape == other.coef.shape) and
|
653 |
+
np.all(self.coef == other.coef) and
|
654 |
+
(self.symbol == other.symbol))
|
655 |
+
return res
|
656 |
+
|
657 |
+
def __ne__(self, other):
|
658 |
+
return not self.__eq__(other)
|
659 |
+
|
660 |
+
#
|
661 |
+
# Extra methods.
|
662 |
+
#
|
663 |
+
|
664 |
+
def copy(self):
|
665 |
+
"""Return a copy.
|
666 |
+
|
667 |
+
Returns
|
668 |
+
-------
|
669 |
+
new_series : series
|
670 |
+
Copy of self.
|
671 |
+
|
672 |
+
"""
|
673 |
+
return self.__class__(self.coef, self.domain, self.window, self.symbol)
|
674 |
+
|
675 |
+
def degree(self):
|
676 |
+
"""The degree of the series.
|
677 |
+
|
678 |
+
.. versionadded:: 1.5.0
|
679 |
+
|
680 |
+
Returns
|
681 |
+
-------
|
682 |
+
degree : int
|
683 |
+
Degree of the series, one less than the number of coefficients.
|
684 |
+
|
685 |
+
Examples
|
686 |
+
--------
|
687 |
+
|
688 |
+
Create a polynomial object for ``1 + 7*x + 4*x**2``:
|
689 |
+
|
690 |
+
>>> poly = np.polynomial.Polynomial([1, 7, 4])
|
691 |
+
>>> print(poly)
|
692 |
+
1.0 + 7.0·x + 4.0·x²
|
693 |
+
>>> poly.degree()
|
694 |
+
2
|
695 |
+
|
696 |
+
Note that this method does not check for non-zero coefficients.
|
697 |
+
You must trim the polynomial to remove any trailing zeroes:
|
698 |
+
|
699 |
+
>>> poly = np.polynomial.Polynomial([1, 7, 0])
|
700 |
+
>>> print(poly)
|
701 |
+
1.0 + 7.0·x + 0.0·x²
|
702 |
+
>>> poly.degree()
|
703 |
+
2
|
704 |
+
>>> poly.trim().degree()
|
705 |
+
1
|
706 |
+
|
707 |
+
"""
|
708 |
+
return len(self) - 1
|
709 |
+
|
710 |
+
def cutdeg(self, deg):
|
711 |
+
"""Truncate series to the given degree.
|
712 |
+
|
713 |
+
Reduce the degree of the series to `deg` by discarding the
|
714 |
+
high order terms. If `deg` is greater than the current degree a
|
715 |
+
copy of the current series is returned. This can be useful in least
|
716 |
+
squares where the coefficients of the high degree terms may be very
|
717 |
+
small.
|
718 |
+
|
719 |
+
.. versionadded:: 1.5.0
|
720 |
+
|
721 |
+
Parameters
|
722 |
+
----------
|
723 |
+
deg : non-negative int
|
724 |
+
The series is reduced to degree `deg` by discarding the high
|
725 |
+
order terms. The value of `deg` must be a non-negative integer.
|
726 |
+
|
727 |
+
Returns
|
728 |
+
-------
|
729 |
+
new_series : series
|
730 |
+
New instance of series with reduced degree.
|
731 |
+
|
732 |
+
"""
|
733 |
+
return self.truncate(deg + 1)
|
734 |
+
|
735 |
+
def trim(self, tol=0):
|
736 |
+
"""Remove trailing coefficients
|
737 |
+
|
738 |
+
Remove trailing coefficients until a coefficient is reached whose
|
739 |
+
absolute value greater than `tol` or the beginning of the series is
|
740 |
+
reached. If all the coefficients would be removed the series is set
|
741 |
+
to ``[0]``. A new series instance is returned with the new
|
742 |
+
coefficients. The current instance remains unchanged.
|
743 |
+
|
744 |
+
Parameters
|
745 |
+
----------
|
746 |
+
tol : non-negative number.
|
747 |
+
All trailing coefficients less than `tol` will be removed.
|
748 |
+
|
749 |
+
Returns
|
750 |
+
-------
|
751 |
+
new_series : series
|
752 |
+
New instance of series with trimmed coefficients.
|
753 |
+
|
754 |
+
"""
|
755 |
+
coef = pu.trimcoef(self.coef, tol)
|
756 |
+
return self.__class__(coef, self.domain, self.window, self.symbol)
|
757 |
+
|
758 |
+
def truncate(self, size):
|
759 |
+
"""Truncate series to length `size`.
|
760 |
+
|
761 |
+
Reduce the series to length `size` by discarding the high
|
762 |
+
degree terms. The value of `size` must be a positive integer. This
|
763 |
+
can be useful in least squares where the coefficients of the
|
764 |
+
high degree terms may be very small.
|
765 |
+
|
766 |
+
Parameters
|
767 |
+
----------
|
768 |
+
size : positive int
|
769 |
+
The series is reduced to length `size` by discarding the high
|
770 |
+
degree terms. The value of `size` must be a positive integer.
|
771 |
+
|
772 |
+
Returns
|
773 |
+
-------
|
774 |
+
new_series : series
|
775 |
+
New instance of series with truncated coefficients.
|
776 |
+
|
777 |
+
"""
|
778 |
+
isize = int(size)
|
779 |
+
if isize != size or isize < 1:
|
780 |
+
raise ValueError("size must be a positive integer")
|
781 |
+
if isize >= len(self.coef):
|
782 |
+
coef = self.coef
|
783 |
+
else:
|
784 |
+
coef = self.coef[:isize]
|
785 |
+
return self.__class__(coef, self.domain, self.window, self.symbol)
|
786 |
+
|
787 |
+
def convert(self, domain=None, kind=None, window=None):
|
788 |
+
"""Convert series to a different kind and/or domain and/or window.
|
789 |
+
|
790 |
+
Parameters
|
791 |
+
----------
|
792 |
+
domain : array_like, optional
|
793 |
+
The domain of the converted series. If the value is None,
|
794 |
+
the default domain of `kind` is used.
|
795 |
+
kind : class, optional
|
796 |
+
The polynomial series type class to which the current instance
|
797 |
+
should be converted. If kind is None, then the class of the
|
798 |
+
current instance is used.
|
799 |
+
window : array_like, optional
|
800 |
+
The window of the converted series. If the value is None,
|
801 |
+
the default window of `kind` is used.
|
802 |
+
|
803 |
+
Returns
|
804 |
+
-------
|
805 |
+
new_series : series
|
806 |
+
The returned class can be of different type than the current
|
807 |
+
instance and/or have a different domain and/or different
|
808 |
+
window.
|
809 |
+
|
810 |
+
Notes
|
811 |
+
-----
|
812 |
+
Conversion between domains and class types can result in
|
813 |
+
numerically ill defined series.
|
814 |
+
|
815 |
+
"""
|
816 |
+
if kind is None:
|
817 |
+
kind = self.__class__
|
818 |
+
if domain is None:
|
819 |
+
domain = kind.domain
|
820 |
+
if window is None:
|
821 |
+
window = kind.window
|
822 |
+
return self(kind.identity(domain, window=window, symbol=self.symbol))
|
823 |
+
|
824 |
+
def mapparms(self):
|
825 |
+
"""Return the mapping parameters.
|
826 |
+
|
827 |
+
The returned values define a linear map ``off + scl*x`` that is
|
828 |
+
applied to the input arguments before the series is evaluated. The
|
829 |
+
map depends on the ``domain`` and ``window``; if the current
|
830 |
+
``domain`` is equal to the ``window`` the resulting map is the
|
831 |
+
identity. If the coefficients of the series instance are to be
|
832 |
+
used by themselves outside this class, then the linear function
|
833 |
+
must be substituted for the ``x`` in the standard representation of
|
834 |
+
the base polynomials.
|
835 |
+
|
836 |
+
Returns
|
837 |
+
-------
|
838 |
+
off, scl : float or complex
|
839 |
+
The mapping function is defined by ``off + scl*x``.
|
840 |
+
|
841 |
+
Notes
|
842 |
+
-----
|
843 |
+
If the current domain is the interval ``[l1, r1]`` and the window
|
844 |
+
is ``[l2, r2]``, then the linear mapping function ``L`` is
|
845 |
+
defined by the equations::
|
846 |
+
|
847 |
+
L(l1) = l2
|
848 |
+
L(r1) = r2
|
849 |
+
|
850 |
+
"""
|
851 |
+
return pu.mapparms(self.domain, self.window)
|
852 |
+
|
853 |
+
def integ(self, m=1, k=[], lbnd=None):
|
854 |
+
"""Integrate.
|
855 |
+
|
856 |
+
Return a series instance that is the definite integral of the
|
857 |
+
current series.
|
858 |
+
|
859 |
+
Parameters
|
860 |
+
----------
|
861 |
+
m : non-negative int
|
862 |
+
The number of integrations to perform.
|
863 |
+
k : array_like
|
864 |
+
Integration constants. The first constant is applied to the
|
865 |
+
first integration, the second to the second, and so on. The
|
866 |
+
list of values must less than or equal to `m` in length and any
|
867 |
+
missing values are set to zero.
|
868 |
+
lbnd : Scalar
|
869 |
+
The lower bound of the definite integral.
|
870 |
+
|
871 |
+
Returns
|
872 |
+
-------
|
873 |
+
new_series : series
|
874 |
+
A new series representing the integral. The domain is the same
|
875 |
+
as the domain of the integrated series.
|
876 |
+
|
877 |
+
"""
|
878 |
+
off, scl = self.mapparms()
|
879 |
+
if lbnd is None:
|
880 |
+
lbnd = 0
|
881 |
+
else:
|
882 |
+
lbnd = off + scl*lbnd
|
883 |
+
coef = self._int(self.coef, m, k, lbnd, 1./scl)
|
884 |
+
return self.__class__(coef, self.domain, self.window, self.symbol)
|
885 |
+
|
886 |
+
def deriv(self, m=1):
|
887 |
+
"""Differentiate.
|
888 |
+
|
889 |
+
Return a series instance of that is the derivative of the current
|
890 |
+
series.
|
891 |
+
|
892 |
+
Parameters
|
893 |
+
----------
|
894 |
+
m : non-negative int
|
895 |
+
Find the derivative of order `m`.
|
896 |
+
|
897 |
+
Returns
|
898 |
+
-------
|
899 |
+
new_series : series
|
900 |
+
A new series representing the derivative. The domain is the same
|
901 |
+
as the domain of the differentiated series.
|
902 |
+
|
903 |
+
"""
|
904 |
+
off, scl = self.mapparms()
|
905 |
+
coef = self._der(self.coef, m, scl)
|
906 |
+
return self.__class__(coef, self.domain, self.window, self.symbol)
|
907 |
+
|
908 |
+
def roots(self):
|
909 |
+
"""Return the roots of the series polynomial.
|
910 |
+
|
911 |
+
Compute the roots for the series. Note that the accuracy of the
|
912 |
+
roots decreases the further outside the `domain` they lie.
|
913 |
+
|
914 |
+
Returns
|
915 |
+
-------
|
916 |
+
roots : ndarray
|
917 |
+
Array containing the roots of the series.
|
918 |
+
|
919 |
+
"""
|
920 |
+
roots = self._roots(self.coef)
|
921 |
+
return pu.mapdomain(roots, self.window, self.domain)
|
922 |
+
|
923 |
+
def linspace(self, n=100, domain=None):
|
924 |
+
"""Return x, y values at equally spaced points in domain.
|
925 |
+
|
926 |
+
Returns the x, y values at `n` linearly spaced points across the
|
927 |
+
domain. Here y is the value of the polynomial at the points x. By
|
928 |
+
default the domain is the same as that of the series instance.
|
929 |
+
This method is intended mostly as a plotting aid.
|
930 |
+
|
931 |
+
.. versionadded:: 1.5.0
|
932 |
+
|
933 |
+
Parameters
|
934 |
+
----------
|
935 |
+
n : int, optional
|
936 |
+
Number of point pairs to return. The default value is 100.
|
937 |
+
domain : {None, array_like}, optional
|
938 |
+
If not None, the specified domain is used instead of that of
|
939 |
+
the calling instance. It should be of the form ``[beg,end]``.
|
940 |
+
The default is None which case the class domain is used.
|
941 |
+
|
942 |
+
Returns
|
943 |
+
-------
|
944 |
+
x, y : ndarray
|
945 |
+
x is equal to linspace(self.domain[0], self.domain[1], n) and
|
946 |
+
y is the series evaluated at element of x.
|
947 |
+
|
948 |
+
"""
|
949 |
+
if domain is None:
|
950 |
+
domain = self.domain
|
951 |
+
x = np.linspace(domain[0], domain[1], n)
|
952 |
+
y = self(x)
|
953 |
+
return x, y
|
954 |
+
|
955 |
+
@classmethod
|
956 |
+
def fit(cls, x, y, deg, domain=None, rcond=None, full=False, w=None,
|
957 |
+
window=None, symbol='x'):
|
958 |
+
"""Least squares fit to data.
|
959 |
+
|
960 |
+
Return a series instance that is the least squares fit to the data
|
961 |
+
`y` sampled at `x`. The domain of the returned instance can be
|
962 |
+
specified and this will often result in a superior fit with less
|
963 |
+
chance of ill conditioning.
|
964 |
+
|
965 |
+
Parameters
|
966 |
+
----------
|
967 |
+
x : array_like, shape (M,)
|
968 |
+
x-coordinates of the M sample points ``(x[i], y[i])``.
|
969 |
+
y : array_like, shape (M,)
|
970 |
+
y-coordinates of the M sample points ``(x[i], y[i])``.
|
971 |
+
deg : int or 1-D array_like
|
972 |
+
Degree(s) of the fitting polynomials. If `deg` is a single integer
|
973 |
+
all terms up to and including the `deg`'th term are included in the
|
974 |
+
fit. For NumPy versions >= 1.11.0 a list of integers specifying the
|
975 |
+
degrees of the terms to include may be used instead.
|
976 |
+
domain : {None, [beg, end], []}, optional
|
977 |
+
Domain to use for the returned series. If ``None``,
|
978 |
+
then a minimal domain that covers the points `x` is chosen. If
|
979 |
+
``[]`` the class domain is used. The default value was the
|
980 |
+
class domain in NumPy 1.4 and ``None`` in later versions.
|
981 |
+
The ``[]`` option was added in numpy 1.5.0.
|
982 |
+
rcond : float, optional
|
983 |
+
Relative condition number of the fit. Singular values smaller
|
984 |
+
than this relative to the largest singular value will be
|
985 |
+
ignored. The default value is len(x)*eps, where eps is the
|
986 |
+
relative precision of the float type, about 2e-16 in most
|
987 |
+
cases.
|
988 |
+
full : bool, optional
|
989 |
+
Switch determining nature of return value. When it is False
|
990 |
+
(the default) just the coefficients are returned, when True
|
991 |
+
diagnostic information from the singular value decomposition is
|
992 |
+
also returned.
|
993 |
+
w : array_like, shape (M,), optional
|
994 |
+
Weights. If not None, the weight ``w[i]`` applies to the unsquared
|
995 |
+
residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are
|
996 |
+
chosen so that the errors of the products ``w[i]*y[i]`` all have
|
997 |
+
the same variance. When using inverse-variance weighting, use
|
998 |
+
``w[i] = 1/sigma(y[i])``. The default value is None.
|
999 |
+
|
1000 |
+
.. versionadded:: 1.5.0
|
1001 |
+
window : {[beg, end]}, optional
|
1002 |
+
Window to use for the returned series. The default
|
1003 |
+
value is the default class domain
|
1004 |
+
|
1005 |
+
.. versionadded:: 1.6.0
|
1006 |
+
symbol : str, optional
|
1007 |
+
Symbol representing the independent variable. Default is 'x'.
|
1008 |
+
|
1009 |
+
Returns
|
1010 |
+
-------
|
1011 |
+
new_series : series
|
1012 |
+
A series that represents the least squares fit to the data and
|
1013 |
+
has the domain and window specified in the call. If the
|
1014 |
+
coefficients for the unscaled and unshifted basis polynomials are
|
1015 |
+
of interest, do ``new_series.convert().coef``.
|
1016 |
+
|
1017 |
+
[resid, rank, sv, rcond] : list
|
1018 |
+
These values are only returned if ``full == True``
|
1019 |
+
|
1020 |
+
- resid -- sum of squared residuals of the least squares fit
|
1021 |
+
- rank -- the numerical rank of the scaled Vandermonde matrix
|
1022 |
+
- sv -- singular values of the scaled Vandermonde matrix
|
1023 |
+
- rcond -- value of `rcond`.
|
1024 |
+
|
1025 |
+
For more details, see `linalg.lstsq`.
|
1026 |
+
|
1027 |
+
"""
|
1028 |
+
if domain is None:
|
1029 |
+
domain = pu.getdomain(x)
|
1030 |
+
elif type(domain) is list and len(domain) == 0:
|
1031 |
+
domain = cls.domain
|
1032 |
+
|
1033 |
+
if window is None:
|
1034 |
+
window = cls.window
|
1035 |
+
|
1036 |
+
xnew = pu.mapdomain(x, domain, window)
|
1037 |
+
res = cls._fit(xnew, y, deg, w=w, rcond=rcond, full=full)
|
1038 |
+
if full:
|
1039 |
+
[coef, status] = res
|
1040 |
+
return (
|
1041 |
+
cls(coef, domain=domain, window=window, symbol=symbol), status
|
1042 |
+
)
|
1043 |
+
else:
|
1044 |
+
coef = res
|
1045 |
+
return cls(coef, domain=domain, window=window, symbol=symbol)
|
1046 |
+
|
1047 |
+
@classmethod
|
1048 |
+
def fromroots(cls, roots, domain=[], window=None, symbol='x'):
|
1049 |
+
"""Return series instance that has the specified roots.
|
1050 |
+
|
1051 |
+
Returns a series representing the product
|
1052 |
+
``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a
|
1053 |
+
list of roots.
|
1054 |
+
|
1055 |
+
Parameters
|
1056 |
+
----------
|
1057 |
+
roots : array_like
|
1058 |
+
List of roots.
|
1059 |
+
domain : {[], None, array_like}, optional
|
1060 |
+
Domain for the resulting series. If None the domain is the
|
1061 |
+
interval from the smallest root to the largest. If [] the
|
1062 |
+
domain is the class domain. The default is [].
|
1063 |
+
window : {None, array_like}, optional
|
1064 |
+
Window for the returned series. If None the class window is
|
1065 |
+
used. The default is None.
|
1066 |
+
symbol : str, optional
|
1067 |
+
Symbol representing the independent variable. Default is 'x'.
|
1068 |
+
|
1069 |
+
Returns
|
1070 |
+
-------
|
1071 |
+
new_series : series
|
1072 |
+
Series with the specified roots.
|
1073 |
+
|
1074 |
+
"""
|
1075 |
+
[roots] = pu.as_series([roots], trim=False)
|
1076 |
+
if domain is None:
|
1077 |
+
domain = pu.getdomain(roots)
|
1078 |
+
elif type(domain) is list and len(domain) == 0:
|
1079 |
+
domain = cls.domain
|
1080 |
+
|
1081 |
+
if window is None:
|
1082 |
+
window = cls.window
|
1083 |
+
|
1084 |
+
deg = len(roots)
|
1085 |
+
off, scl = pu.mapparms(domain, window)
|
1086 |
+
rnew = off + scl*roots
|
1087 |
+
coef = cls._fromroots(rnew) / scl**deg
|
1088 |
+
return cls(coef, domain=domain, window=window, symbol=symbol)
|
1089 |
+
|
1090 |
+
@classmethod
|
1091 |
+
def identity(cls, domain=None, window=None, symbol='x'):
|
1092 |
+
"""Identity function.
|
1093 |
+
|
1094 |
+
If ``p`` is the returned series, then ``p(x) == x`` for all
|
1095 |
+
values of x.
|
1096 |
+
|
1097 |
+
Parameters
|
1098 |
+
----------
|
1099 |
+
domain : {None, array_like}, optional
|
1100 |
+
If given, the array must be of the form ``[beg, end]``, where
|
1101 |
+
``beg`` and ``end`` are the endpoints of the domain. If None is
|
1102 |
+
given then the class domain is used. The default is None.
|
1103 |
+
window : {None, array_like}, optional
|
1104 |
+
If given, the resulting array must be if the form
|
1105 |
+
``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
|
1106 |
+
the window. If None is given then the class window is used. The
|
1107 |
+
default is None.
|
1108 |
+
symbol : str, optional
|
1109 |
+
Symbol representing the independent variable. Default is 'x'.
|
1110 |
+
|
1111 |
+
Returns
|
1112 |
+
-------
|
1113 |
+
new_series : series
|
1114 |
+
Series of representing the identity.
|
1115 |
+
|
1116 |
+
"""
|
1117 |
+
if domain is None:
|
1118 |
+
domain = cls.domain
|
1119 |
+
if window is None:
|
1120 |
+
window = cls.window
|
1121 |
+
off, scl = pu.mapparms(window, domain)
|
1122 |
+
coef = cls._line(off, scl)
|
1123 |
+
return cls(coef, domain, window, symbol)
|
1124 |
+
|
1125 |
+
@classmethod
|
1126 |
+
def basis(cls, deg, domain=None, window=None, symbol='x'):
|
1127 |
+
"""Series basis polynomial of degree `deg`.
|
1128 |
+
|
1129 |
+
Returns the series representing the basis polynomial of degree `deg`.
|
1130 |
+
|
1131 |
+
.. versionadded:: 1.7.0
|
1132 |
+
|
1133 |
+
Parameters
|
1134 |
+
----------
|
1135 |
+
deg : int
|
1136 |
+
Degree of the basis polynomial for the series. Must be >= 0.
|
1137 |
+
domain : {None, array_like}, optional
|
1138 |
+
If given, the array must be of the form ``[beg, end]``, where
|
1139 |
+
``beg`` and ``end`` are the endpoints of the domain. If None is
|
1140 |
+
given then the class domain is used. The default is None.
|
1141 |
+
window : {None, array_like}, optional
|
1142 |
+
If given, the resulting array must be if the form
|
1143 |
+
``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
|
1144 |
+
the window. If None is given then the class window is used. The
|
1145 |
+
default is None.
|
1146 |
+
symbol : str, optional
|
1147 |
+
Symbol representing the independent variable. Default is 'x'.
|
1148 |
+
|
1149 |
+
Returns
|
1150 |
+
-------
|
1151 |
+
new_series : series
|
1152 |
+
A series with the coefficient of the `deg` term set to one and
|
1153 |
+
all others zero.
|
1154 |
+
|
1155 |
+
"""
|
1156 |
+
if domain is None:
|
1157 |
+
domain = cls.domain
|
1158 |
+
if window is None:
|
1159 |
+
window = cls.window
|
1160 |
+
ideg = int(deg)
|
1161 |
+
|
1162 |
+
if ideg != deg or ideg < 0:
|
1163 |
+
raise ValueError("deg must be non-negative integer")
|
1164 |
+
return cls([0]*ideg + [1], domain, window, symbol)
|
1165 |
+
|
1166 |
+
@classmethod
|
1167 |
+
def cast(cls, series, domain=None, window=None):
|
1168 |
+
"""Convert series to series of this class.
|
1169 |
+
|
1170 |
+
The `series` is expected to be an instance of some polynomial
|
1171 |
+
series of one of the types supported by by the numpy.polynomial
|
1172 |
+
module, but could be some other class that supports the convert
|
1173 |
+
method.
|
1174 |
+
|
1175 |
+
.. versionadded:: 1.7.0
|
1176 |
+
|
1177 |
+
Parameters
|
1178 |
+
----------
|
1179 |
+
series : series
|
1180 |
+
The series instance to be converted.
|
1181 |
+
domain : {None, array_like}, optional
|
1182 |
+
If given, the array must be of the form ``[beg, end]``, where
|
1183 |
+
``beg`` and ``end`` are the endpoints of the domain. If None is
|
1184 |
+
given then the class domain is used. The default is None.
|
1185 |
+
window : {None, array_like}, optional
|
1186 |
+
If given, the resulting array must be if the form
|
1187 |
+
``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
|
1188 |
+
the window. If None is given then the class window is used. The
|
1189 |
+
default is None.
|
1190 |
+
|
1191 |
+
Returns
|
1192 |
+
-------
|
1193 |
+
new_series : series
|
1194 |
+
A series of the same kind as the calling class and equal to
|
1195 |
+
`series` when evaluated.
|
1196 |
+
|
1197 |
+
See Also
|
1198 |
+
--------
|
1199 |
+
convert : similar instance method
|
1200 |
+
|
1201 |
+
"""
|
1202 |
+
if domain is None:
|
1203 |
+
domain = cls.domain
|
1204 |
+
if window is None:
|
1205 |
+
window = cls.window
|
1206 |
+
return series.convert(domain, cls, window)
|
venv/lib/python3.10/site-packages/numpy/polynomial/_polybase.pyi
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import abc
|
2 |
+
from typing import Any, ClassVar
|
3 |
+
|
4 |
+
__all__: list[str]
|
5 |
+
|
6 |
+
class ABCPolyBase(abc.ABC):
|
7 |
+
__hash__: ClassVar[None] # type: ignore[assignment]
|
8 |
+
__array_ufunc__: ClassVar[None]
|
9 |
+
maxpower: ClassVar[int]
|
10 |
+
coef: Any
|
11 |
+
@property
|
12 |
+
def symbol(self) -> str: ...
|
13 |
+
@property
|
14 |
+
@abc.abstractmethod
|
15 |
+
def domain(self): ...
|
16 |
+
@property
|
17 |
+
@abc.abstractmethod
|
18 |
+
def window(self): ...
|
19 |
+
@property
|
20 |
+
@abc.abstractmethod
|
21 |
+
def basis_name(self): ...
|
22 |
+
def has_samecoef(self, other): ...
|
23 |
+
def has_samedomain(self, other): ...
|
24 |
+
def has_samewindow(self, other): ...
|
25 |
+
def has_sametype(self, other): ...
|
26 |
+
def __init__(self, coef, domain=..., window=..., symbol: str = ...) -> None: ...
|
27 |
+
def __format__(self, fmt_str): ...
|
28 |
+
def __call__(self, arg): ...
|
29 |
+
def __iter__(self): ...
|
30 |
+
def __len__(self): ...
|
31 |
+
def __neg__(self): ...
|
32 |
+
def __pos__(self): ...
|
33 |
+
def __add__(self, other): ...
|
34 |
+
def __sub__(self, other): ...
|
35 |
+
def __mul__(self, other): ...
|
36 |
+
def __truediv__(self, other): ...
|
37 |
+
def __floordiv__(self, other): ...
|
38 |
+
def __mod__(self, other): ...
|
39 |
+
def __divmod__(self, other): ...
|
40 |
+
def __pow__(self, other): ...
|
41 |
+
def __radd__(self, other): ...
|
42 |
+
def __rsub__(self, other): ...
|
43 |
+
def __rmul__(self, other): ...
|
44 |
+
def __rdiv__(self, other): ...
|
45 |
+
def __rtruediv__(self, other): ...
|
46 |
+
def __rfloordiv__(self, other): ...
|
47 |
+
def __rmod__(self, other): ...
|
48 |
+
def __rdivmod__(self, other): ...
|
49 |
+
def __eq__(self, other): ...
|
50 |
+
def __ne__(self, other): ...
|
51 |
+
def copy(self): ...
|
52 |
+
def degree(self): ...
|
53 |
+
def cutdeg(self, deg): ...
|
54 |
+
def trim(self, tol=...): ...
|
55 |
+
def truncate(self, size): ...
|
56 |
+
def convert(self, domain=..., kind=..., window=...): ...
|
57 |
+
def mapparms(self): ...
|
58 |
+
def integ(self, m=..., k = ..., lbnd=...): ...
|
59 |
+
def deriv(self, m=...): ...
|
60 |
+
def roots(self): ...
|
61 |
+
def linspace(self, n=..., domain=...): ...
|
62 |
+
@classmethod
|
63 |
+
def fit(cls, x, y, deg, domain=..., rcond=..., full=..., w=..., window=...): ...
|
64 |
+
@classmethod
|
65 |
+
def fromroots(cls, roots, domain = ..., window=...): ...
|
66 |
+
@classmethod
|
67 |
+
def identity(cls, domain=..., window=...): ...
|
68 |
+
@classmethod
|
69 |
+
def basis(cls, deg, domain=..., window=...): ...
|
70 |
+
@classmethod
|
71 |
+
def cast(cls, series, domain=..., window=...): ...
|
venv/lib/python3.10/site-packages/numpy/polynomial/chebyshev.py
ADDED
@@ -0,0 +1,2082 @@
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
====================================================
|
3 |
+
Chebyshev Series (:mod:`numpy.polynomial.chebyshev`)
|
4 |
+
====================================================
|
5 |
+
|
6 |
+
This module provides a number of objects (mostly functions) useful for
|
7 |
+
dealing with Chebyshev series, including a `Chebyshev` class that
|
8 |
+
encapsulates the usual arithmetic operations. (General information
|
9 |
+
on how this module represents and works with such polynomials is in the
|
10 |
+
docstring for its "parent" sub-package, `numpy.polynomial`).
|
11 |
+
|
12 |
+
Classes
|
13 |
+
-------
|
14 |
+
|
15 |
+
.. autosummary::
|
16 |
+
:toctree: generated/
|
17 |
+
|
18 |
+
Chebyshev
|
19 |
+
|
20 |
+
|
21 |
+
Constants
|
22 |
+
---------
|
23 |
+
|
24 |
+
.. autosummary::
|
25 |
+
:toctree: generated/
|
26 |
+
|
27 |
+
chebdomain
|
28 |
+
chebzero
|
29 |
+
chebone
|
30 |
+
chebx
|
31 |
+
|
32 |
+
Arithmetic
|
33 |
+
----------
|
34 |
+
|
35 |
+
.. autosummary::
|
36 |
+
:toctree: generated/
|
37 |
+
|
38 |
+
chebadd
|
39 |
+
chebsub
|
40 |
+
chebmulx
|
41 |
+
chebmul
|
42 |
+
chebdiv
|
43 |
+
chebpow
|
44 |
+
chebval
|
45 |
+
chebval2d
|
46 |
+
chebval3d
|
47 |
+
chebgrid2d
|
48 |
+
chebgrid3d
|
49 |
+
|
50 |
+
Calculus
|
51 |
+
--------
|
52 |
+
|
53 |
+
.. autosummary::
|
54 |
+
:toctree: generated/
|
55 |
+
|
56 |
+
chebder
|
57 |
+
chebint
|
58 |
+
|
59 |
+
Misc Functions
|
60 |
+
--------------
|
61 |
+
|
62 |
+
.. autosummary::
|
63 |
+
:toctree: generated/
|
64 |
+
|
65 |
+
chebfromroots
|
66 |
+
chebroots
|
67 |
+
chebvander
|
68 |
+
chebvander2d
|
69 |
+
chebvander3d
|
70 |
+
chebgauss
|
71 |
+
chebweight
|
72 |
+
chebcompanion
|
73 |
+
chebfit
|
74 |
+
chebpts1
|
75 |
+
chebpts2
|
76 |
+
chebtrim
|
77 |
+
chebline
|
78 |
+
cheb2poly
|
79 |
+
poly2cheb
|
80 |
+
chebinterpolate
|
81 |
+
|
82 |
+
See also
|
83 |
+
--------
|
84 |
+
`numpy.polynomial`
|
85 |
+
|
86 |
+
Notes
|
87 |
+
-----
|
88 |
+
The implementations of multiplication, division, integration, and
|
89 |
+
differentiation use the algebraic identities [1]_:
|
90 |
+
|
91 |
+
.. math::
|
92 |
+
T_n(x) = \\frac{z^n + z^{-n}}{2} \\\\
|
93 |
+
z\\frac{dx}{dz} = \\frac{z - z^{-1}}{2}.
|
94 |
+
|
95 |
+
where
|
96 |
+
|
97 |
+
.. math:: x = \\frac{z + z^{-1}}{2}.
|
98 |
+
|
99 |
+
These identities allow a Chebyshev series to be expressed as a finite,
|
100 |
+
symmetric Laurent series. In this module, this sort of Laurent series
|
101 |
+
is referred to as a "z-series."
|
102 |
+
|
103 |
+
References
|
104 |
+
----------
|
105 |
+
.. [1] A. T. Benjamin, et al., "Combinatorial Trigonometry with Chebyshev
|
106 |
+
Polynomials," *Journal of Statistical Planning and Inference 14*, 2008
|
107 |
+
(https://web.archive.org/web/20080221202153/https://www.math.hmc.edu/~benjamin/papers/CombTrig.pdf, pg. 4)
|
108 |
+
|
109 |
+
"""
|
110 |
+
import numpy as np
|
111 |
+
import numpy.linalg as la
|
112 |
+
from numpy.core.multiarray import normalize_axis_index
|
113 |
+
|
114 |
+
from . import polyutils as pu
|
115 |
+
from ._polybase import ABCPolyBase
|
116 |
+
|
117 |
+
__all__ = [
|
118 |
+
'chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', 'chebadd',
|
119 |
+
'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebpow', 'chebval',
|
120 |
+
'chebder', 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots',
|
121 |
+
'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'chebpts1',
|
122 |
+
'chebpts2', 'Chebyshev', 'chebval2d', 'chebval3d', 'chebgrid2d',
|
123 |
+
'chebgrid3d', 'chebvander2d', 'chebvander3d', 'chebcompanion',
|
124 |
+
'chebgauss', 'chebweight', 'chebinterpolate']
|
125 |
+
|
126 |
+
chebtrim = pu.trimcoef
|
127 |
+
|
128 |
+
#
|
129 |
+
# A collection of functions for manipulating z-series. These are private
|
130 |
+
# functions and do minimal error checking.
|
131 |
+
#
|
132 |
+
|
133 |
+
def _cseries_to_zseries(c):
|
134 |
+
"""Convert Chebyshev series to z-series.
|
135 |
+
|
136 |
+
Convert a Chebyshev series to the equivalent z-series. The result is
|
137 |
+
never an empty array. The dtype of the return is the same as that of
|
138 |
+
the input. No checks are run on the arguments as this routine is for
|
139 |
+
internal use.
|
140 |
+
|
141 |
+
Parameters
|
142 |
+
----------
|
143 |
+
c : 1-D ndarray
|
144 |
+
Chebyshev coefficients, ordered from low to high
|
145 |
+
|
146 |
+
Returns
|
147 |
+
-------
|
148 |
+
zs : 1-D ndarray
|
149 |
+
Odd length symmetric z-series, ordered from low to high.
|
150 |
+
|
151 |
+
"""
|
152 |
+
n = c.size
|
153 |
+
zs = np.zeros(2*n-1, dtype=c.dtype)
|
154 |
+
zs[n-1:] = c/2
|
155 |
+
return zs + zs[::-1]
|
156 |
+
|
157 |
+
|
158 |
+
def _zseries_to_cseries(zs):
|
159 |
+
"""Convert z-series to a Chebyshev series.
|
160 |
+
|
161 |
+
Convert a z series to the equivalent Chebyshev series. The result is
|
162 |
+
never an empty array. The dtype of the return is the same as that of
|
163 |
+
the input. No checks are run on the arguments as this routine is for
|
164 |
+
internal use.
|
165 |
+
|
166 |
+
Parameters
|
167 |
+
----------
|
168 |
+
zs : 1-D ndarray
|
169 |
+
Odd length symmetric z-series, ordered from low to high.
|
170 |
+
|
171 |
+
Returns
|
172 |
+
-------
|
173 |
+
c : 1-D ndarray
|
174 |
+
Chebyshev coefficients, ordered from low to high.
|
175 |
+
|
176 |
+
"""
|
177 |
+
n = (zs.size + 1)//2
|
178 |
+
c = zs[n-1:].copy()
|
179 |
+
c[1:n] *= 2
|
180 |
+
return c
|
181 |
+
|
182 |
+
|
183 |
+
def _zseries_mul(z1, z2):
|
184 |
+
"""Multiply two z-series.
|
185 |
+
|
186 |
+
Multiply two z-series to produce a z-series.
|
187 |
+
|
188 |
+
Parameters
|
189 |
+
----------
|
190 |
+
z1, z2 : 1-D ndarray
|
191 |
+
The arrays must be 1-D but this is not checked.
|
192 |
+
|
193 |
+
Returns
|
194 |
+
-------
|
195 |
+
product : 1-D ndarray
|
196 |
+
The product z-series.
|
197 |
+
|
198 |
+
Notes
|
199 |
+
-----
|
200 |
+
This is simply convolution. If symmetric/anti-symmetric z-series are
|
201 |
+
denoted by S/A then the following rules apply:
|
202 |
+
|
203 |
+
S*S, A*A -> S
|
204 |
+
S*A, A*S -> A
|
205 |
+
|
206 |
+
"""
|
207 |
+
return np.convolve(z1, z2)
|
208 |
+
|
209 |
+
|
210 |
+
def _zseries_div(z1, z2):
|
211 |
+
"""Divide the first z-series by the second.
|
212 |
+
|
213 |
+
Divide `z1` by `z2` and return the quotient and remainder as z-series.
|
214 |
+
Warning: this implementation only applies when both z1 and z2 have the
|
215 |
+
same symmetry, which is sufficient for present purposes.
|
216 |
+
|
217 |
+
Parameters
|
218 |
+
----------
|
219 |
+
z1, z2 : 1-D ndarray
|
220 |
+
The arrays must be 1-D and have the same symmetry, but this is not
|
221 |
+
checked.
|
222 |
+
|
223 |
+
Returns
|
224 |
+
-------
|
225 |
+
|
226 |
+
(quotient, remainder) : 1-D ndarrays
|
227 |
+
Quotient and remainder as z-series.
|
228 |
+
|
229 |
+
Notes
|
230 |
+
-----
|
231 |
+
This is not the same as polynomial division on account of the desired form
|
232 |
+
of the remainder. If symmetric/anti-symmetric z-series are denoted by S/A
|
233 |
+
then the following rules apply:
|
234 |
+
|
235 |
+
S/S -> S,S
|
236 |
+
A/A -> S,A
|
237 |
+
|
238 |
+
The restriction to types of the same symmetry could be fixed but seems like
|
239 |
+
unneeded generality. There is no natural form for the remainder in the case
|
240 |
+
where there is no symmetry.
|
241 |
+
|
242 |
+
"""
|
243 |
+
z1 = z1.copy()
|
244 |
+
z2 = z2.copy()
|
245 |
+
lc1 = len(z1)
|
246 |
+
lc2 = len(z2)
|
247 |
+
if lc2 == 1:
|
248 |
+
z1 /= z2
|
249 |
+
return z1, z1[:1]*0
|
250 |
+
elif lc1 < lc2:
|
251 |
+
return z1[:1]*0, z1
|
252 |
+
else:
|
253 |
+
dlen = lc1 - lc2
|
254 |
+
scl = z2[0]
|
255 |
+
z2 /= scl
|
256 |
+
quo = np.empty(dlen + 1, dtype=z1.dtype)
|
257 |
+
i = 0
|
258 |
+
j = dlen
|
259 |
+
while i < j:
|
260 |
+
r = z1[i]
|
261 |
+
quo[i] = z1[i]
|
262 |
+
quo[dlen - i] = r
|
263 |
+
tmp = r*z2
|
264 |
+
z1[i:i+lc2] -= tmp
|
265 |
+
z1[j:j+lc2] -= tmp
|
266 |
+
i += 1
|
267 |
+
j -= 1
|
268 |
+
r = z1[i]
|
269 |
+
quo[i] = r
|
270 |
+
tmp = r*z2
|
271 |
+
z1[i:i+lc2] -= tmp
|
272 |
+
quo /= scl
|
273 |
+
rem = z1[i+1:i-1+lc2].copy()
|
274 |
+
return quo, rem
|
275 |
+
|
276 |
+
|
277 |
+
def _zseries_der(zs):
|
278 |
+
"""Differentiate a z-series.
|
279 |
+
|
280 |
+
The derivative is with respect to x, not z. This is achieved using the
|
281 |
+
chain rule and the value of dx/dz given in the module notes.
|
282 |
+
|
283 |
+
Parameters
|
284 |
+
----------
|
285 |
+
zs : z-series
|
286 |
+
The z-series to differentiate.
|
287 |
+
|
288 |
+
Returns
|
289 |
+
-------
|
290 |
+
derivative : z-series
|
291 |
+
The derivative
|
292 |
+
|
293 |
+
Notes
|
294 |
+
-----
|
295 |
+
The zseries for x (ns) has been multiplied by two in order to avoid
|
296 |
+
using floats that are incompatible with Decimal and likely other
|
297 |
+
specialized scalar types. This scaling has been compensated by
|
298 |
+
multiplying the value of zs by two also so that the two cancels in the
|
299 |
+
division.
|
300 |
+
|
301 |
+
"""
|
302 |
+
n = len(zs)//2
|
303 |
+
ns = np.array([-1, 0, 1], dtype=zs.dtype)
|
304 |
+
zs *= np.arange(-n, n+1)*2
|
305 |
+
d, r = _zseries_div(zs, ns)
|
306 |
+
return d
|
307 |
+
|
308 |
+
|
309 |
+
def _zseries_int(zs):
|
310 |
+
"""Integrate a z-series.
|
311 |
+
|
312 |
+
The integral is with respect to x, not z. This is achieved by a change
|
313 |
+
of variable using dx/dz given in the module notes.
|
314 |
+
|
315 |
+
Parameters
|
316 |
+
----------
|
317 |
+
zs : z-series
|
318 |
+
The z-series to integrate
|
319 |
+
|
320 |
+
Returns
|
321 |
+
-------
|
322 |
+
integral : z-series
|
323 |
+
The indefinite integral
|
324 |
+
|
325 |
+
Notes
|
326 |
+
-----
|
327 |
+
The zseries for x (ns) has been multiplied by two in order to avoid
|
328 |
+
using floats that are incompatible with Decimal and likely other
|
329 |
+
specialized scalar types. This scaling has been compensated by
|
330 |
+
dividing the resulting zs by two.
|
331 |
+
|
332 |
+
"""
|
333 |
+
n = 1 + len(zs)//2
|
334 |
+
ns = np.array([-1, 0, 1], dtype=zs.dtype)
|
335 |
+
zs = _zseries_mul(zs, ns)
|
336 |
+
div = np.arange(-n, n+1)*2
|
337 |
+
zs[:n] /= div[:n]
|
338 |
+
zs[n+1:] /= div[n+1:]
|
339 |
+
zs[n] = 0
|
340 |
+
return zs
|
341 |
+
|
342 |
+
#
|
343 |
+
# Chebyshev series functions
|
344 |
+
#
|
345 |
+
|
346 |
+
|
347 |
+
def poly2cheb(pol):
|
348 |
+
"""
|
349 |
+
Convert a polynomial to a Chebyshev series.
|
350 |
+
|
351 |
+
Convert an array representing the coefficients of a polynomial (relative
|
352 |
+
to the "standard" basis) ordered from lowest degree to highest, to an
|
353 |
+
array of the coefficients of the equivalent Chebyshev series, ordered
|
354 |
+
from lowest to highest degree.
|
355 |
+
|
356 |
+
Parameters
|
357 |
+
----------
|
358 |
+
pol : array_like
|
359 |
+
1-D array containing the polynomial coefficients
|
360 |
+
|
361 |
+
Returns
|
362 |
+
-------
|
363 |
+
c : ndarray
|
364 |
+
1-D array containing the coefficients of the equivalent Chebyshev
|
365 |
+
series.
|
366 |
+
|
367 |
+
See Also
|
368 |
+
--------
|
369 |
+
cheb2poly
|
370 |
+
|
371 |
+
Notes
|
372 |
+
-----
|
373 |
+
The easy way to do conversions between polynomial basis sets
|
374 |
+
is to use the convert method of a class instance.
|
375 |
+
|
376 |
+
Examples
|
377 |
+
--------
|
378 |
+
>>> from numpy import polynomial as P
|
379 |
+
>>> p = P.Polynomial(range(4))
|
380 |
+
>>> p
|
381 |
+
Polynomial([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1])
|
382 |
+
>>> c = p.convert(kind=P.Chebyshev)
|
383 |
+
>>> c
|
384 |
+
Chebyshev([1. , 3.25, 1. , 0.75], domain=[-1., 1.], window=[-1., 1.])
|
385 |
+
>>> P.chebyshev.poly2cheb(range(4))
|
386 |
+
array([1. , 3.25, 1. , 0.75])
|
387 |
+
|
388 |
+
"""
|
389 |
+
[pol] = pu.as_series([pol])
|
390 |
+
deg = len(pol) - 1
|
391 |
+
res = 0
|
392 |
+
for i in range(deg, -1, -1):
|
393 |
+
res = chebadd(chebmulx(res), pol[i])
|
394 |
+
return res
|
395 |
+
|
396 |
+
|
397 |
+
def cheb2poly(c):
|
398 |
+
"""
|
399 |
+
Convert a Chebyshev series to a polynomial.
|
400 |
+
|
401 |
+
Convert an array representing the coefficients of a Chebyshev series,
|
402 |
+
ordered from lowest degree to highest, to an array of the coefficients
|
403 |
+
of the equivalent polynomial (relative to the "standard" basis) ordered
|
404 |
+
from lowest to highest degree.
|
405 |
+
|
406 |
+
Parameters
|
407 |
+
----------
|
408 |
+
c : array_like
|
409 |
+
1-D array containing the Chebyshev series coefficients, ordered
|
410 |
+
from lowest order term to highest.
|
411 |
+
|
412 |
+
Returns
|
413 |
+
-------
|
414 |
+
pol : ndarray
|
415 |
+
1-D array containing the coefficients of the equivalent polynomial
|
416 |
+
(relative to the "standard" basis) ordered from lowest order term
|
417 |
+
to highest.
|
418 |
+
|
419 |
+
See Also
|
420 |
+
--------
|
421 |
+
poly2cheb
|
422 |
+
|
423 |
+
Notes
|
424 |
+
-----
|
425 |
+
The easy way to do conversions between polynomial basis sets
|
426 |
+
is to use the convert method of a class instance.
|
427 |
+
|
428 |
+
Examples
|
429 |
+
--------
|
430 |
+
>>> from numpy import polynomial as P
|
431 |
+
>>> c = P.Chebyshev(range(4))
|
432 |
+
>>> c
|
433 |
+
Chebyshev([0., 1., 2., 3.], domain=[-1, 1], window=[-1, 1])
|
434 |
+
>>> p = c.convert(kind=P.Polynomial)
|
435 |
+
>>> p
|
436 |
+
Polynomial([-2., -8., 4., 12.], domain=[-1., 1.], window=[-1., 1.])
|
437 |
+
>>> P.chebyshev.cheb2poly(range(4))
|
438 |
+
array([-2., -8., 4., 12.])
|
439 |
+
|
440 |
+
"""
|
441 |
+
from .polynomial import polyadd, polysub, polymulx
|
442 |
+
|
443 |
+
[c] = pu.as_series([c])
|
444 |
+
n = len(c)
|
445 |
+
if n < 3:
|
446 |
+
return c
|
447 |
+
else:
|
448 |
+
c0 = c[-2]
|
449 |
+
c1 = c[-1]
|
450 |
+
# i is the current degree of c1
|
451 |
+
for i in range(n - 1, 1, -1):
|
452 |
+
tmp = c0
|
453 |
+
c0 = polysub(c[i - 2], c1)
|
454 |
+
c1 = polyadd(tmp, polymulx(c1)*2)
|
455 |
+
return polyadd(c0, polymulx(c1))
|
456 |
+
|
457 |
+
|
458 |
+
#
|
459 |
+
# These are constant arrays are of integer type so as to be compatible
|
460 |
+
# with the widest range of other types, such as Decimal.
|
461 |
+
#
|
462 |
+
|
463 |
+
# Chebyshev default domain.
|
464 |
+
chebdomain = np.array([-1, 1])
|
465 |
+
|
466 |
+
# Chebyshev coefficients representing zero.
|
467 |
+
chebzero = np.array([0])
|
468 |
+
|
469 |
+
# Chebyshev coefficients representing one.
|
470 |
+
chebone = np.array([1])
|
471 |
+
|
472 |
+
# Chebyshev coefficients representing the identity x.
|
473 |
+
chebx = np.array([0, 1])
|
474 |
+
|
475 |
+
|
476 |
+
def chebline(off, scl):
|
477 |
+
"""
|
478 |
+
Chebyshev series whose graph is a straight line.
|
479 |
+
|
480 |
+
Parameters
|
481 |
+
----------
|
482 |
+
off, scl : scalars
|
483 |
+
The specified line is given by ``off + scl*x``.
|
484 |
+
|
485 |
+
Returns
|
486 |
+
-------
|
487 |
+
y : ndarray
|
488 |
+
This module's representation of the Chebyshev series for
|
489 |
+
``off + scl*x``.
|
490 |
+
|
491 |
+
See Also
|
492 |
+
--------
|
493 |
+
numpy.polynomial.polynomial.polyline
|
494 |
+
numpy.polynomial.legendre.legline
|
495 |
+
numpy.polynomial.laguerre.lagline
|
496 |
+
numpy.polynomial.hermite.hermline
|
497 |
+
numpy.polynomial.hermite_e.hermeline
|
498 |
+
|
499 |
+
Examples
|
500 |
+
--------
|
501 |
+
>>> import numpy.polynomial.chebyshev as C
|
502 |
+
>>> C.chebline(3,2)
|
503 |
+
array([3, 2])
|
504 |
+
>>> C.chebval(-3, C.chebline(3,2)) # should be -3
|
505 |
+
-3.0
|
506 |
+
|
507 |
+
"""
|
508 |
+
if scl != 0:
|
509 |
+
return np.array([off, scl])
|
510 |
+
else:
|
511 |
+
return np.array([off])
|
512 |
+
|
513 |
+
|
514 |
+
def chebfromroots(roots):
|
515 |
+
"""
|
516 |
+
Generate a Chebyshev series with given roots.
|
517 |
+
|
518 |
+
The function returns the coefficients of the polynomial
|
519 |
+
|
520 |
+
.. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),
|
521 |
+
|
522 |
+
in Chebyshev form, where the `r_n` are the roots specified in `roots`.
|
523 |
+
If a zero has multiplicity n, then it must appear in `roots` n times.
|
524 |
+
For instance, if 2 is a root of multiplicity three and 3 is a root of
|
525 |
+
multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The
|
526 |
+
roots can appear in any order.
|
527 |
+
|
528 |
+
If the returned coefficients are `c`, then
|
529 |
+
|
530 |
+
.. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x)
|
531 |
+
|
532 |
+
The coefficient of the last term is not generally 1 for monic
|
533 |
+
polynomials in Chebyshev form.
|
534 |
+
|
535 |
+
Parameters
|
536 |
+
----------
|
537 |
+
roots : array_like
|
538 |
+
Sequence containing the roots.
|
539 |
+
|
540 |
+
Returns
|
541 |
+
-------
|
542 |
+
out : ndarray
|
543 |
+
1-D array of coefficients. If all roots are real then `out` is a
|
544 |
+
real array, if some of the roots are complex, then `out` is complex
|
545 |
+
even if all the coefficients in the result are real (see Examples
|
546 |
+
below).
|
547 |
+
|
548 |
+
See Also
|
549 |
+
--------
|
550 |
+
numpy.polynomial.polynomial.polyfromroots
|
551 |
+
numpy.polynomial.legendre.legfromroots
|
552 |
+
numpy.polynomial.laguerre.lagfromroots
|
553 |
+
numpy.polynomial.hermite.hermfromroots
|
554 |
+
numpy.polynomial.hermite_e.hermefromroots
|
555 |
+
|
556 |
+
Examples
|
557 |
+
--------
|
558 |
+
>>> import numpy.polynomial.chebyshev as C
|
559 |
+
>>> C.chebfromroots((-1,0,1)) # x^3 - x relative to the standard basis
|
560 |
+
array([ 0. , -0.25, 0. , 0.25])
|
561 |
+
>>> j = complex(0,1)
|
562 |
+
>>> C.chebfromroots((-j,j)) # x^2 + 1 relative to the standard basis
|
563 |
+
array([1.5+0.j, 0. +0.j, 0.5+0.j])
|
564 |
+
|
565 |
+
"""
|
566 |
+
return pu._fromroots(chebline, chebmul, roots)
|
567 |
+
|
568 |
+
|
569 |
+
def chebadd(c1, c2):
|
570 |
+
"""
|
571 |
+
Add one Chebyshev series to another.
|
572 |
+
|
573 |
+
Returns the sum of two Chebyshev series `c1` + `c2`. The arguments
|
574 |
+
are sequences of coefficients ordered from lowest order term to
|
575 |
+
highest, i.e., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
|
576 |
+
|
577 |
+
Parameters
|
578 |
+
----------
|
579 |
+
c1, c2 : array_like
|
580 |
+
1-D arrays of Chebyshev series coefficients ordered from low to
|
581 |
+
high.
|
582 |
+
|
583 |
+
Returns
|
584 |
+
-------
|
585 |
+
out : ndarray
|
586 |
+
Array representing the Chebyshev series of their sum.
|
587 |
+
|
588 |
+
See Also
|
589 |
+
--------
|
590 |
+
chebsub, chebmulx, chebmul, chebdiv, chebpow
|
591 |
+
|
592 |
+
Notes
|
593 |
+
-----
|
594 |
+
Unlike multiplication, division, etc., the sum of two Chebyshev series
|
595 |
+
is a Chebyshev series (without having to "reproject" the result onto
|
596 |
+
the basis set) so addition, just like that of "standard" polynomials,
|
597 |
+
is simply "component-wise."
|
598 |
+
|
599 |
+
Examples
|
600 |
+
--------
|
601 |
+
>>> from numpy.polynomial import chebyshev as C
|
602 |
+
>>> c1 = (1,2,3)
|
603 |
+
>>> c2 = (3,2,1)
|
604 |
+
>>> C.chebadd(c1,c2)
|
605 |
+
array([4., 4., 4.])
|
606 |
+
|
607 |
+
"""
|
608 |
+
return pu._add(c1, c2)
|
609 |
+
|
610 |
+
|
611 |
+
def chebsub(c1, c2):
|
612 |
+
"""
|
613 |
+
Subtract one Chebyshev series from another.
|
614 |
+
|
615 |
+
Returns the difference of two Chebyshev series `c1` - `c2`. The
|
616 |
+
sequences of coefficients are from lowest order term to highest, i.e.,
|
617 |
+
[1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
|
618 |
+
|
619 |
+
Parameters
|
620 |
+
----------
|
621 |
+
c1, c2 : array_like
|
622 |
+
1-D arrays of Chebyshev series coefficients ordered from low to
|
623 |
+
high.
|
624 |
+
|
625 |
+
Returns
|
626 |
+
-------
|
627 |
+
out : ndarray
|
628 |
+
Of Chebyshev series coefficients representing their difference.
|
629 |
+
|
630 |
+
See Also
|
631 |
+
--------
|
632 |
+
chebadd, chebmulx, chebmul, chebdiv, chebpow
|
633 |
+
|
634 |
+
Notes
|
635 |
+
-----
|
636 |
+
Unlike multiplication, division, etc., the difference of two Chebyshev
|
637 |
+
series is a Chebyshev series (without having to "reproject" the result
|
638 |
+
onto the basis set) so subtraction, just like that of "standard"
|
639 |
+
polynomials, is simply "component-wise."
|
640 |
+
|
641 |
+
Examples
|
642 |
+
--------
|
643 |
+
>>> from numpy.polynomial import chebyshev as C
|
644 |
+
>>> c1 = (1,2,3)
|
645 |
+
>>> c2 = (3,2,1)
|
646 |
+
>>> C.chebsub(c1,c2)
|
647 |
+
array([-2., 0., 2.])
|
648 |
+
>>> C.chebsub(c2,c1) # -C.chebsub(c1,c2)
|
649 |
+
array([ 2., 0., -2.])
|
650 |
+
|
651 |
+
"""
|
652 |
+
return pu._sub(c1, c2)
|
653 |
+
|
654 |
+
|
655 |
+
def chebmulx(c):
|
656 |
+
"""Multiply a Chebyshev series by x.
|
657 |
+
|
658 |
+
Multiply the polynomial `c` by x, where x is the independent
|
659 |
+
variable.
|
660 |
+
|
661 |
+
|
662 |
+
Parameters
|
663 |
+
----------
|
664 |
+
c : array_like
|
665 |
+
1-D array of Chebyshev series coefficients ordered from low to
|
666 |
+
high.
|
667 |
+
|
668 |
+
Returns
|
669 |
+
-------
|
670 |
+
out : ndarray
|
671 |
+
Array representing the result of the multiplication.
|
672 |
+
|
673 |
+
Notes
|
674 |
+
-----
|
675 |
+
|
676 |
+
.. versionadded:: 1.5.0
|
677 |
+
|
678 |
+
Examples
|
679 |
+
--------
|
680 |
+
>>> from numpy.polynomial import chebyshev as C
|
681 |
+
>>> C.chebmulx([1,2,3])
|
682 |
+
array([1. , 2.5, 1. , 1.5])
|
683 |
+
|
684 |
+
"""
|
685 |
+
# c is a trimmed copy
|
686 |
+
[c] = pu.as_series([c])
|
687 |
+
# The zero series needs special treatment
|
688 |
+
if len(c) == 1 and c[0] == 0:
|
689 |
+
return c
|
690 |
+
|
691 |
+
prd = np.empty(len(c) + 1, dtype=c.dtype)
|
692 |
+
prd[0] = c[0]*0
|
693 |
+
prd[1] = c[0]
|
694 |
+
if len(c) > 1:
|
695 |
+
tmp = c[1:]/2
|
696 |
+
prd[2:] = tmp
|
697 |
+
prd[0:-2] += tmp
|
698 |
+
return prd
|
699 |
+
|
700 |
+
|
701 |
+
def chebmul(c1, c2):
|
702 |
+
"""
|
703 |
+
Multiply one Chebyshev series by another.
|
704 |
+
|
705 |
+
Returns the product of two Chebyshev series `c1` * `c2`. The arguments
|
706 |
+
are sequences of coefficients, from lowest order "term" to highest,
|
707 |
+
e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.
|
708 |
+
|
709 |
+
Parameters
|
710 |
+
----------
|
711 |
+
c1, c2 : array_like
|
712 |
+
1-D arrays of Chebyshev series coefficients ordered from low to
|
713 |
+
high.
|
714 |
+
|
715 |
+
Returns
|
716 |
+
-------
|
717 |
+
out : ndarray
|
718 |
+
Of Chebyshev series coefficients representing their product.
|
719 |
+
|
720 |
+
See Also
|
721 |
+
--------
|
722 |
+
chebadd, chebsub, chebmulx, chebdiv, chebpow
|
723 |
+
|
724 |
+
Notes
|
725 |
+
-----
|
726 |
+
In general, the (polynomial) product of two C-series results in terms
|
727 |
+
that are not in the Chebyshev polynomial basis set. Thus, to express
|
728 |
+
the product as a C-series, it is typically necessary to "reproject"
|
729 |
+
the product onto said basis set, which typically produces
|
730 |
+
"unintuitive live" (but correct) results; see Examples section below.
|
731 |
+
|
732 |
+
Examples
|
733 |
+
--------
|
734 |
+
>>> from numpy.polynomial import chebyshev as C
|
735 |
+
>>> c1 = (1,2,3)
|
736 |
+
>>> c2 = (3,2,1)
|
737 |
+
>>> C.chebmul(c1,c2) # multiplication requires "reprojection"
|
738 |
+
array([ 6.5, 12. , 12. , 4. , 1.5])
|
739 |
+
|
740 |
+
"""
|
741 |
+
# c1, c2 are trimmed copies
|
742 |
+
[c1, c2] = pu.as_series([c1, c2])
|
743 |
+
z1 = _cseries_to_zseries(c1)
|
744 |
+
z2 = _cseries_to_zseries(c2)
|
745 |
+
prd = _zseries_mul(z1, z2)
|
746 |
+
ret = _zseries_to_cseries(prd)
|
747 |
+
return pu.trimseq(ret)
|
748 |
+
|
749 |
+
|
750 |
+
def chebdiv(c1, c2):
|
751 |
+
"""
|
752 |
+
Divide one Chebyshev series by another.
|
753 |
+
|
754 |
+
Returns the quotient-with-remainder of two Chebyshev series
|
755 |
+
`c1` / `c2`. The arguments are sequences of coefficients from lowest
|
756 |
+
order "term" to highest, e.g., [1,2,3] represents the series
|
757 |
+
``T_0 + 2*T_1 + 3*T_2``.
|
758 |
+
|
759 |
+
Parameters
|
760 |
+
----------
|
761 |
+
c1, c2 : array_like
|
762 |
+
1-D arrays of Chebyshev series coefficients ordered from low to
|
763 |
+
high.
|
764 |
+
|
765 |
+
Returns
|
766 |
+
-------
|
767 |
+
[quo, rem] : ndarrays
|
768 |
+
Of Chebyshev series coefficients representing the quotient and
|
769 |
+
remainder.
|
770 |
+
|
771 |
+
See Also
|
772 |
+
--------
|
773 |
+
chebadd, chebsub, chebmulx, chebmul, chebpow
|
774 |
+
|
775 |
+
Notes
|
776 |
+
-----
|
777 |
+
In general, the (polynomial) division of one C-series by another
|
778 |
+
results in quotient and remainder terms that are not in the Chebyshev
|
779 |
+
polynomial basis set. Thus, to express these results as C-series, it
|
780 |
+
is typically necessary to "reproject" the results onto said basis
|
781 |
+
set, which typically produces "unintuitive" (but correct) results;
|
782 |
+
see Examples section below.
|
783 |
+
|
784 |
+
Examples
|
785 |
+
--------
|
786 |
+
>>> from numpy.polynomial import chebyshev as C
|
787 |
+
>>> c1 = (1,2,3)
|
788 |
+
>>> c2 = (3,2,1)
|
789 |
+
>>> C.chebdiv(c1,c2) # quotient "intuitive," remainder not
|
790 |
+
(array([3.]), array([-8., -4.]))
|
791 |
+
>>> c2 = (0,1,2,3)
|
792 |
+
>>> C.chebdiv(c2,c1) # neither "intuitive"
|
793 |
+
(array([0., 2.]), array([-2., -4.]))
|
794 |
+
|
795 |
+
"""
|
796 |
+
# c1, c2 are trimmed copies
|
797 |
+
[c1, c2] = pu.as_series([c1, c2])
|
798 |
+
if c2[-1] == 0:
|
799 |
+
raise ZeroDivisionError()
|
800 |
+
|
801 |
+
# note: this is more efficient than `pu._div(chebmul, c1, c2)`
|
802 |
+
lc1 = len(c1)
|
803 |
+
lc2 = len(c2)
|
804 |
+
if lc1 < lc2:
|
805 |
+
return c1[:1]*0, c1
|
806 |
+
elif lc2 == 1:
|
807 |
+
return c1/c2[-1], c1[:1]*0
|
808 |
+
else:
|
809 |
+
z1 = _cseries_to_zseries(c1)
|
810 |
+
z2 = _cseries_to_zseries(c2)
|
811 |
+
quo, rem = _zseries_div(z1, z2)
|
812 |
+
quo = pu.trimseq(_zseries_to_cseries(quo))
|
813 |
+
rem = pu.trimseq(_zseries_to_cseries(rem))
|
814 |
+
return quo, rem
|
815 |
+
|
816 |
+
|
817 |
+
def chebpow(c, pow, maxpower=16):
|
818 |
+
"""Raise a Chebyshev series to a power.
|
819 |
+
|
820 |
+
Returns the Chebyshev series `c` raised to the power `pow`. The
|
821 |
+
argument `c` is a sequence of coefficients ordered from low to high.
|
822 |
+
i.e., [1,2,3] is the series ``T_0 + 2*T_1 + 3*T_2.``
|
823 |
+
|
824 |
+
Parameters
|
825 |
+
----------
|
826 |
+
c : array_like
|
827 |
+
1-D array of Chebyshev series coefficients ordered from low to
|
828 |
+
high.
|
829 |
+
pow : integer
|
830 |
+
Power to which the series will be raised
|
831 |
+
maxpower : integer, optional
|
832 |
+
Maximum power allowed. This is mainly to limit growth of the series
|
833 |
+
to unmanageable size. Default is 16
|
834 |
+
|
835 |
+
Returns
|
836 |
+
-------
|
837 |
+
coef : ndarray
|
838 |
+
Chebyshev series of power.
|
839 |
+
|
840 |
+
See Also
|
841 |
+
--------
|
842 |
+
chebadd, chebsub, chebmulx, chebmul, chebdiv
|
843 |
+
|
844 |
+
Examples
|
845 |
+
--------
|
846 |
+
>>> from numpy.polynomial import chebyshev as C
|
847 |
+
>>> C.chebpow([1, 2, 3, 4], 2)
|
848 |
+
array([15.5, 22. , 16. , ..., 12.5, 12. , 8. ])
|
849 |
+
|
850 |
+
"""
|
851 |
+
# note: this is more efficient than `pu._pow(chebmul, c1, c2)`, as it
|
852 |
+
# avoids converting between z and c series repeatedly
|
853 |
+
|
854 |
+
# c is a trimmed copy
|
855 |
+
[c] = pu.as_series([c])
|
856 |
+
power = int(pow)
|
857 |
+
if power != pow or power < 0:
|
858 |
+
raise ValueError("Power must be a non-negative integer.")
|
859 |
+
elif maxpower is not None and power > maxpower:
|
860 |
+
raise ValueError("Power is too large")
|
861 |
+
elif power == 0:
|
862 |
+
return np.array([1], dtype=c.dtype)
|
863 |
+
elif power == 1:
|
864 |
+
return c
|
865 |
+
else:
|
866 |
+
# This can be made more efficient by using powers of two
|
867 |
+
# in the usual way.
|
868 |
+
zs = _cseries_to_zseries(c)
|
869 |
+
prd = zs
|
870 |
+
for i in range(2, power + 1):
|
871 |
+
prd = np.convolve(prd, zs)
|
872 |
+
return _zseries_to_cseries(prd)
|
873 |
+
|
874 |
+
|
875 |
+
def chebder(c, m=1, scl=1, axis=0):
|
876 |
+
"""
|
877 |
+
Differentiate a Chebyshev series.
|
878 |
+
|
879 |
+
Returns the Chebyshev series coefficients `c` differentiated `m` times
|
880 |
+
along `axis`. At each iteration the result is multiplied by `scl` (the
|
881 |
+
scaling factor is for use in a linear change of variable). The argument
|
882 |
+
`c` is an array of coefficients from low to high degree along each
|
883 |
+
axis, e.g., [1,2,3] represents the series ``1*T_0 + 2*T_1 + 3*T_2``
|
884 |
+
while [[1,2],[1,2]] represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) +
|
885 |
+
2*T_0(x)*T_1(y) + 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is
|
886 |
+
``y``.
|
887 |
+
|
888 |
+
Parameters
|
889 |
+
----------
|
890 |
+
c : array_like
|
891 |
+
Array of Chebyshev series coefficients. If c is multidimensional
|
892 |
+
the different axis correspond to different variables with the
|
893 |
+
degree in each axis given by the corresponding index.
|
894 |
+
m : int, optional
|
895 |
+
Number of derivatives taken, must be non-negative. (Default: 1)
|
896 |
+
scl : scalar, optional
|
897 |
+
Each differentiation is multiplied by `scl`. The end result is
|
898 |
+
multiplication by ``scl**m``. This is for use in a linear change of
|
899 |
+
variable. (Default: 1)
|
900 |
+
axis : int, optional
|
901 |
+
Axis over which the derivative is taken. (Default: 0).
|
902 |
+
|
903 |
+
.. versionadded:: 1.7.0
|
904 |
+
|
905 |
+
Returns
|
906 |
+
-------
|
907 |
+
der : ndarray
|
908 |
+
Chebyshev series of the derivative.
|
909 |
+
|
910 |
+
See Also
|
911 |
+
--------
|
912 |
+
chebint
|
913 |
+
|
914 |
+
Notes
|
915 |
+
-----
|
916 |
+
In general, the result of differentiating a C-series needs to be
|
917 |
+
"reprojected" onto the C-series basis set. Thus, typically, the
|
918 |
+
result of this function is "unintuitive," albeit correct; see Examples
|
919 |
+
section below.
|
920 |
+
|
921 |
+
Examples
|
922 |
+
--------
|
923 |
+
>>> from numpy.polynomial import chebyshev as C
|
924 |
+
>>> c = (1,2,3,4)
|
925 |
+
>>> C.chebder(c)
|
926 |
+
array([14., 12., 24.])
|
927 |
+
>>> C.chebder(c,3)
|
928 |
+
array([96.])
|
929 |
+
>>> C.chebder(c,scl=-1)
|
930 |
+
array([-14., -12., -24.])
|
931 |
+
>>> C.chebder(c,2,-1)
|
932 |
+
array([12., 96.])
|
933 |
+
|
934 |
+
"""
|
935 |
+
c = np.array(c, ndmin=1, copy=True)
|
936 |
+
if c.dtype.char in '?bBhHiIlLqQpP':
|
937 |
+
c = c.astype(np.double)
|
938 |
+
cnt = pu._deprecate_as_int(m, "the order of derivation")
|
939 |
+
iaxis = pu._deprecate_as_int(axis, "the axis")
|
940 |
+
if cnt < 0:
|
941 |
+
raise ValueError("The order of derivation must be non-negative")
|
942 |
+
iaxis = normalize_axis_index(iaxis, c.ndim)
|
943 |
+
|
944 |
+
if cnt == 0:
|
945 |
+
return c
|
946 |
+
|
947 |
+
c = np.moveaxis(c, iaxis, 0)
|
948 |
+
n = len(c)
|
949 |
+
if cnt >= n:
|
950 |
+
c = c[:1]*0
|
951 |
+
else:
|
952 |
+
for i in range(cnt):
|
953 |
+
n = n - 1
|
954 |
+
c *= scl
|
955 |
+
der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
|
956 |
+
for j in range(n, 2, -1):
|
957 |
+
der[j - 1] = (2*j)*c[j]
|
958 |
+
c[j - 2] += (j*c[j])/(j - 2)
|
959 |
+
if n > 1:
|
960 |
+
der[1] = 4*c[2]
|
961 |
+
der[0] = c[1]
|
962 |
+
c = der
|
963 |
+
c = np.moveaxis(c, 0, iaxis)
|
964 |
+
return c
|
965 |
+
|
966 |
+
|
967 |
+
def chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
|
968 |
+
"""
|
969 |
+
Integrate a Chebyshev series.
|
970 |
+
|
971 |
+
Returns the Chebyshev series coefficients `c` integrated `m` times from
|
972 |
+
`lbnd` along `axis`. At each iteration the resulting series is
|
973 |
+
**multiplied** by `scl` and an integration constant, `k`, is added.
|
974 |
+
The scaling factor is for use in a linear change of variable. ("Buyer
|
975 |
+
beware": note that, depending on what one is doing, one may want `scl`
|
976 |
+
to be the reciprocal of what one might expect; for more information,
|
977 |
+
see the Notes section below.) The argument `c` is an array of
|
978 |
+
coefficients from low to high degree along each axis, e.g., [1,2,3]
|
979 |
+
represents the series ``T_0 + 2*T_1 + 3*T_2`` while [[1,2],[1,2]]
|
980 |
+
represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) +
|
981 |
+
2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
|
982 |
+
|
983 |
+
Parameters
|
984 |
+
----------
|
985 |
+
c : array_like
|
986 |
+
Array of Chebyshev series coefficients. If c is multidimensional
|
987 |
+
the different axis correspond to different variables with the
|
988 |
+
degree in each axis given by the corresponding index.
|
989 |
+
m : int, optional
|
990 |
+
Order of integration, must be positive. (Default: 1)
|
991 |
+
k : {[], list, scalar}, optional
|
992 |
+
Integration constant(s). The value of the first integral at zero
|
993 |
+
is the first value in the list, the value of the second integral
|
994 |
+
at zero is the second value, etc. If ``k == []`` (the default),
|
995 |
+
all constants are set to zero. If ``m == 1``, a single scalar can
|
996 |
+
be given instead of a list.
|
997 |
+
lbnd : scalar, optional
|
998 |
+
The lower bound of the integral. (Default: 0)
|
999 |
+
scl : scalar, optional
|
1000 |
+
Following each integration the result is *multiplied* by `scl`
|
1001 |
+
before the integration constant is added. (Default: 1)
|
1002 |
+
axis : int, optional
|
1003 |
+
Axis over which the integral is taken. (Default: 0).
|
1004 |
+
|
1005 |
+
.. versionadded:: 1.7.0
|
1006 |
+
|
1007 |
+
Returns
|
1008 |
+
-------
|
1009 |
+
S : ndarray
|
1010 |
+
C-series coefficients of the integral.
|
1011 |
+
|
1012 |
+
Raises
|
1013 |
+
------
|
1014 |
+
ValueError
|
1015 |
+
If ``m < 1``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
|
1016 |
+
``np.ndim(scl) != 0``.
|
1017 |
+
|
1018 |
+
See Also
|
1019 |
+
--------
|
1020 |
+
chebder
|
1021 |
+
|
1022 |
+
Notes
|
1023 |
+
-----
|
1024 |
+
Note that the result of each integration is *multiplied* by `scl`.
|
1025 |
+
Why is this important to note? Say one is making a linear change of
|
1026 |
+
variable :math:`u = ax + b` in an integral relative to `x`. Then
|
1027 |
+
:math:`dx = du/a`, so one will need to set `scl` equal to
|
1028 |
+
:math:`1/a`- perhaps not what one would have first thought.
|
1029 |
+
|
1030 |
+
Also note that, in general, the result of integrating a C-series needs
|
1031 |
+
to be "reprojected" onto the C-series basis set. Thus, typically,
|
1032 |
+
the result of this function is "unintuitive," albeit correct; see
|
1033 |
+
Examples section below.
|
1034 |
+
|
1035 |
+
Examples
|
1036 |
+
--------
|
1037 |
+
>>> from numpy.polynomial import chebyshev as C
|
1038 |
+
>>> c = (1,2,3)
|
1039 |
+
>>> C.chebint(c)
|
1040 |
+
array([ 0.5, -0.5, 0.5, 0.5])
|
1041 |
+
>>> C.chebint(c,3)
|
1042 |
+
array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667, # may vary
|
1043 |
+
0.00625 ])
|
1044 |
+
>>> C.chebint(c, k=3)
|
1045 |
+
array([ 3.5, -0.5, 0.5, 0.5])
|
1046 |
+
>>> C.chebint(c,lbnd=-2)
|
1047 |
+
array([ 8.5, -0.5, 0.5, 0.5])
|
1048 |
+
>>> C.chebint(c,scl=-2)
|
1049 |
+
array([-1., 1., -1., -1.])
|
1050 |
+
|
1051 |
+
"""
|
1052 |
+
c = np.array(c, ndmin=1, copy=True)
|
1053 |
+
if c.dtype.char in '?bBhHiIlLqQpP':
|
1054 |
+
c = c.astype(np.double)
|
1055 |
+
if not np.iterable(k):
|
1056 |
+
k = [k]
|
1057 |
+
cnt = pu._deprecate_as_int(m, "the order of integration")
|
1058 |
+
iaxis = pu._deprecate_as_int(axis, "the axis")
|
1059 |
+
if cnt < 0:
|
1060 |
+
raise ValueError("The order of integration must be non-negative")
|
1061 |
+
if len(k) > cnt:
|
1062 |
+
raise ValueError("Too many integration constants")
|
1063 |
+
if np.ndim(lbnd) != 0:
|
1064 |
+
raise ValueError("lbnd must be a scalar.")
|
1065 |
+
if np.ndim(scl) != 0:
|
1066 |
+
raise ValueError("scl must be a scalar.")
|
1067 |
+
iaxis = normalize_axis_index(iaxis, c.ndim)
|
1068 |
+
|
1069 |
+
if cnt == 0:
|
1070 |
+
return c
|
1071 |
+
|
1072 |
+
c = np.moveaxis(c, iaxis, 0)
|
1073 |
+
k = list(k) + [0]*(cnt - len(k))
|
1074 |
+
for i in range(cnt):
|
1075 |
+
n = len(c)
|
1076 |
+
c *= scl
|
1077 |
+
if n == 1 and np.all(c[0] == 0):
|
1078 |
+
c[0] += k[i]
|
1079 |
+
else:
|
1080 |
+
tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
|
1081 |
+
tmp[0] = c[0]*0
|
1082 |
+
tmp[1] = c[0]
|
1083 |
+
if n > 1:
|
1084 |
+
tmp[2] = c[1]/4
|
1085 |
+
for j in range(2, n):
|
1086 |
+
tmp[j + 1] = c[j]/(2*(j + 1))
|
1087 |
+
tmp[j - 1] -= c[j]/(2*(j - 1))
|
1088 |
+
tmp[0] += k[i] - chebval(lbnd, tmp)
|
1089 |
+
c = tmp
|
1090 |
+
c = np.moveaxis(c, 0, iaxis)
|
1091 |
+
return c
|
1092 |
+
|
1093 |
+
|
1094 |
+
def chebval(x, c, tensor=True):
|
1095 |
+
"""
|
1096 |
+
Evaluate a Chebyshev series at points x.
|
1097 |
+
|
1098 |
+
If `c` is of length `n + 1`, this function returns the value:
|
1099 |
+
|
1100 |
+
.. math:: p(x) = c_0 * T_0(x) + c_1 * T_1(x) + ... + c_n * T_n(x)
|
1101 |
+
|
1102 |
+
The parameter `x` is converted to an array only if it is a tuple or a
|
1103 |
+
list, otherwise it is treated as a scalar. In either case, either `x`
|
1104 |
+
or its elements must support multiplication and addition both with
|
1105 |
+
themselves and with the elements of `c`.
|
1106 |
+
|
1107 |
+
If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If
|
1108 |
+
`c` is multidimensional, then the shape of the result depends on the
|
1109 |
+
value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
|
1110 |
+
x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
|
1111 |
+
scalars have shape (,).
|
1112 |
+
|
1113 |
+
Trailing zeros in the coefficients will be used in the evaluation, so
|
1114 |
+
they should be avoided if efficiency is a concern.
|
1115 |
+
|
1116 |
+
Parameters
|
1117 |
+
----------
|
1118 |
+
x : array_like, compatible object
|
1119 |
+
If `x` is a list or tuple, it is converted to an ndarray, otherwise
|
1120 |
+
it is left unchanged and treated as a scalar. In either case, `x`
|
1121 |
+
or its elements must support addition and multiplication with
|
1122 |
+
themselves and with the elements of `c`.
|
1123 |
+
c : array_like
|
1124 |
+
Array of coefficients ordered so that the coefficients for terms of
|
1125 |
+
degree n are contained in c[n]. If `c` is multidimensional the
|
1126 |
+
remaining indices enumerate multiple polynomials. In the two
|
1127 |
+
dimensional case the coefficients may be thought of as stored in
|
1128 |
+
the columns of `c`.
|
1129 |
+
tensor : boolean, optional
|
1130 |
+
If True, the shape of the coefficient array is extended with ones
|
1131 |
+
on the right, one for each dimension of `x`. Scalars have dimension 0
|
1132 |
+
for this action. The result is that every column of coefficients in
|
1133 |
+
`c` is evaluated for every element of `x`. If False, `x` is broadcast
|
1134 |
+
over the columns of `c` for the evaluation. This keyword is useful
|
1135 |
+
when `c` is multidimensional. The default value is True.
|
1136 |
+
|
1137 |
+
.. versionadded:: 1.7.0
|
1138 |
+
|
1139 |
+
Returns
|
1140 |
+
-------
|
1141 |
+
values : ndarray, algebra_like
|
1142 |
+
The shape of the return value is described above.
|
1143 |
+
|
1144 |
+
See Also
|
1145 |
+
--------
|
1146 |
+
chebval2d, chebgrid2d, chebval3d, chebgrid3d
|
1147 |
+
|
1148 |
+
Notes
|
1149 |
+
-----
|
1150 |
+
The evaluation uses Clenshaw recursion, aka synthetic division.
|
1151 |
+
|
1152 |
+
"""
|
1153 |
+
c = np.array(c, ndmin=1, copy=True)
|
1154 |
+
if c.dtype.char in '?bBhHiIlLqQpP':
|
1155 |
+
c = c.astype(np.double)
|
1156 |
+
if isinstance(x, (tuple, list)):
|
1157 |
+
x = np.asarray(x)
|
1158 |
+
if isinstance(x, np.ndarray) and tensor:
|
1159 |
+
c = c.reshape(c.shape + (1,)*x.ndim)
|
1160 |
+
|
1161 |
+
if len(c) == 1:
|
1162 |
+
c0 = c[0]
|
1163 |
+
c1 = 0
|
1164 |
+
elif len(c) == 2:
|
1165 |
+
c0 = c[0]
|
1166 |
+
c1 = c[1]
|
1167 |
+
else:
|
1168 |
+
x2 = 2*x
|
1169 |
+
c0 = c[-2]
|
1170 |
+
c1 = c[-1]
|
1171 |
+
for i in range(3, len(c) + 1):
|
1172 |
+
tmp = c0
|
1173 |
+
c0 = c[-i] - c1
|
1174 |
+
c1 = tmp + c1*x2
|
1175 |
+
return c0 + c1*x
|
1176 |
+
|
1177 |
+
|
1178 |
+
def chebval2d(x, y, c):
|
1179 |
+
"""
|
1180 |
+
Evaluate a 2-D Chebyshev series at points (x, y).
|
1181 |
+
|
1182 |
+
This function returns the values:
|
1183 |
+
|
1184 |
+
.. math:: p(x,y) = \\sum_{i,j} c_{i,j} * T_i(x) * T_j(y)
|
1185 |
+
|
1186 |
+
The parameters `x` and `y` are converted to arrays only if they are
|
1187 |
+
tuples or a lists, otherwise they are treated as a scalars and they
|
1188 |
+
must have the same shape after conversion. In either case, either `x`
|
1189 |
+
and `y` or their elements must support multiplication and addition both
|
1190 |
+
with themselves and with the elements of `c`.
|
1191 |
+
|
1192 |
+
If `c` is a 1-D array a one is implicitly appended to its shape to make
|
1193 |
+
it 2-D. The shape of the result will be c.shape[2:] + x.shape.
|
1194 |
+
|
1195 |
+
Parameters
|
1196 |
+
----------
|
1197 |
+
x, y : array_like, compatible objects
|
1198 |
+
The two dimensional series is evaluated at the points `(x, y)`,
|
1199 |
+
where `x` and `y` must have the same shape. If `x` or `y` is a list
|
1200 |
+
or tuple, it is first converted to an ndarray, otherwise it is left
|
1201 |
+
unchanged and if it isn't an ndarray it is treated as a scalar.
|
1202 |
+
c : array_like
|
1203 |
+
Array of coefficients ordered so that the coefficient of the term
|
1204 |
+
of multi-degree i,j is contained in ``c[i,j]``. If `c` has
|
1205 |
+
dimension greater than 2 the remaining indices enumerate multiple
|
1206 |
+
sets of coefficients.
|
1207 |
+
|
1208 |
+
Returns
|
1209 |
+
-------
|
1210 |
+
values : ndarray, compatible object
|
1211 |
+
The values of the two dimensional Chebyshev series at points formed
|
1212 |
+
from pairs of corresponding values from `x` and `y`.
|
1213 |
+
|
1214 |
+
See Also
|
1215 |
+
--------
|
1216 |
+
chebval, chebgrid2d, chebval3d, chebgrid3d
|
1217 |
+
|
1218 |
+
Notes
|
1219 |
+
-----
|
1220 |
+
|
1221 |
+
.. versionadded:: 1.7.0
|
1222 |
+
|
1223 |
+
"""
|
1224 |
+
return pu._valnd(chebval, c, x, y)
|
1225 |
+
|
1226 |
+
|
1227 |
+
def chebgrid2d(x, y, c):
|
1228 |
+
"""
|
1229 |
+
Evaluate a 2-D Chebyshev series on the Cartesian product of x and y.
|
1230 |
+
|
1231 |
+
This function returns the values:
|
1232 |
+
|
1233 |
+
.. math:: p(a,b) = \\sum_{i,j} c_{i,j} * T_i(a) * T_j(b),
|
1234 |
+
|
1235 |
+
where the points `(a, b)` consist of all pairs formed by taking
|
1236 |
+
`a` from `x` and `b` from `y`. The resulting points form a grid with
|
1237 |
+
`x` in the first dimension and `y` in the second.
|
1238 |
+
|
1239 |
+
The parameters `x` and `y` are converted to arrays only if they are
|
1240 |
+
tuples or a lists, otherwise they are treated as a scalars. In either
|
1241 |
+
case, either `x` and `y` or their elements must support multiplication
|
1242 |
+
and addition both with themselves and with the elements of `c`.
|
1243 |
+
|
1244 |
+
If `c` has fewer than two dimensions, ones are implicitly appended to
|
1245 |
+
its shape to make it 2-D. The shape of the result will be c.shape[2:] +
|
1246 |
+
x.shape + y.shape.
|
1247 |
+
|
1248 |
+
Parameters
|
1249 |
+
----------
|
1250 |
+
x, y : array_like, compatible objects
|
1251 |
+
The two dimensional series is evaluated at the points in the
|
1252 |
+
Cartesian product of `x` and `y`. If `x` or `y` is a list or
|
1253 |
+
tuple, it is first converted to an ndarray, otherwise it is left
|
1254 |
+
unchanged and, if it isn't an ndarray, it is treated as a scalar.
|
1255 |
+
c : array_like
|
1256 |
+
Array of coefficients ordered so that the coefficient of the term of
|
1257 |
+
multi-degree i,j is contained in `c[i,j]`. If `c` has dimension
|
1258 |
+
greater than two the remaining indices enumerate multiple sets of
|
1259 |
+
coefficients.
|
1260 |
+
|
1261 |
+
Returns
|
1262 |
+
-------
|
1263 |
+
values : ndarray, compatible object
|
1264 |
+
The values of the two dimensional Chebyshev series at points in the
|
1265 |
+
Cartesian product of `x` and `y`.
|
1266 |
+
|
1267 |
+
See Also
|
1268 |
+
--------
|
1269 |
+
chebval, chebval2d, chebval3d, chebgrid3d
|
1270 |
+
|
1271 |
+
Notes
|
1272 |
+
-----
|
1273 |
+
|
1274 |
+
.. versionadded:: 1.7.0
|
1275 |
+
|
1276 |
+
"""
|
1277 |
+
return pu._gridnd(chebval, c, x, y)
|
1278 |
+
|
1279 |
+
|
1280 |
+
def chebval3d(x, y, z, c):
|
1281 |
+
"""
|
1282 |
+
Evaluate a 3-D Chebyshev series at points (x, y, z).
|
1283 |
+
|
1284 |
+
This function returns the values:
|
1285 |
+
|
1286 |
+
.. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * T_i(x) * T_j(y) * T_k(z)
|
1287 |
+
|
1288 |
+
The parameters `x`, `y`, and `z` are converted to arrays only if
|
1289 |
+
they are tuples or a lists, otherwise they are treated as a scalars and
|
1290 |
+
they must have the same shape after conversion. In either case, either
|
1291 |
+
`x`, `y`, and `z` or their elements must support multiplication and
|
1292 |
+
addition both with themselves and with the elements of `c`.
|
1293 |
+
|
1294 |
+
If `c` has fewer than 3 dimensions, ones are implicitly appended to its
|
1295 |
+
shape to make it 3-D. The shape of the result will be c.shape[3:] +
|
1296 |
+
x.shape.
|
1297 |
+
|
1298 |
+
Parameters
|
1299 |
+
----------
|
1300 |
+
x, y, z : array_like, compatible object
|
1301 |
+
The three dimensional series is evaluated at the points
|
1302 |
+
`(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If
|
1303 |
+
any of `x`, `y`, or `z` is a list or tuple, it is first converted
|
1304 |
+
to an ndarray, otherwise it is left unchanged and if it isn't an
|
1305 |
+
ndarray it is treated as a scalar.
|
1306 |
+
c : array_like
|
1307 |
+
Array of coefficients ordered so that the coefficient of the term of
|
1308 |
+
multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension
|
1309 |
+
greater than 3 the remaining indices enumerate multiple sets of
|
1310 |
+
coefficients.
|
1311 |
+
|
1312 |
+
Returns
|
1313 |
+
-------
|
1314 |
+
values : ndarray, compatible object
|
1315 |
+
The values of the multidimensional polynomial on points formed with
|
1316 |
+
triples of corresponding values from `x`, `y`, and `z`.
|
1317 |
+
|
1318 |
+
See Also
|
1319 |
+
--------
|
1320 |
+
chebval, chebval2d, chebgrid2d, chebgrid3d
|
1321 |
+
|
1322 |
+
Notes
|
1323 |
+
-----
|
1324 |
+
|
1325 |
+
.. versionadded:: 1.7.0
|
1326 |
+
|
1327 |
+
"""
|
1328 |
+
return pu._valnd(chebval, c, x, y, z)
|
1329 |
+
|
1330 |
+
|
1331 |
+
def chebgrid3d(x, y, z, c):
|
1332 |
+
"""
|
1333 |
+
Evaluate a 3-D Chebyshev series on the Cartesian product of x, y, and z.
|
1334 |
+
|
1335 |
+
This function returns the values:
|
1336 |
+
|
1337 |
+
.. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * T_i(a) * T_j(b) * T_k(c)
|
1338 |
+
|
1339 |
+
where the points `(a, b, c)` consist of all triples formed by taking
|
1340 |
+
`a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
|
1341 |
+
a grid with `x` in the first dimension, `y` in the second, and `z` in
|
1342 |
+
the third.
|
1343 |
+
|
1344 |
+
The parameters `x`, `y`, and `z` are converted to arrays only if they
|
1345 |
+
are tuples or a lists, otherwise they are treated as a scalars. In
|
1346 |
+
either case, either `x`, `y`, and `z` or their elements must support
|
1347 |
+
multiplication and addition both with themselves and with the elements
|
1348 |
+
of `c`.
|
1349 |
+
|
1350 |
+
If `c` has fewer than three dimensions, ones are implicitly appended to
|
1351 |
+
its shape to make it 3-D. The shape of the result will be c.shape[3:] +
|
1352 |
+
x.shape + y.shape + z.shape.
|
1353 |
+
|
1354 |
+
Parameters
|
1355 |
+
----------
|
1356 |
+
x, y, z : array_like, compatible objects
|
1357 |
+
The three dimensional series is evaluated at the points in the
|
1358 |
+
Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a
|
1359 |
+
list or tuple, it is first converted to an ndarray, otherwise it is
|
1360 |
+
left unchanged and, if it isn't an ndarray, it is treated as a
|
1361 |
+
scalar.
|
1362 |
+
c : array_like
|
1363 |
+
Array of coefficients ordered so that the coefficients for terms of
|
1364 |
+
degree i,j are contained in ``c[i,j]``. If `c` has dimension
|
1365 |
+
greater than two the remaining indices enumerate multiple sets of
|
1366 |
+
coefficients.
|
1367 |
+
|
1368 |
+
Returns
|
1369 |
+
-------
|
1370 |
+
values : ndarray, compatible object
|
1371 |
+
The values of the two dimensional polynomial at points in the Cartesian
|
1372 |
+
product of `x` and `y`.
|
1373 |
+
|
1374 |
+
See Also
|
1375 |
+
--------
|
1376 |
+
chebval, chebval2d, chebgrid2d, chebval3d
|
1377 |
+
|
1378 |
+
Notes
|
1379 |
+
-----
|
1380 |
+
|
1381 |
+
.. versionadded:: 1.7.0
|
1382 |
+
|
1383 |
+
"""
|
1384 |
+
return pu._gridnd(chebval, c, x, y, z)
|
1385 |
+
|
1386 |
+
|
1387 |
+
def chebvander(x, deg):
|
1388 |
+
"""Pseudo-Vandermonde matrix of given degree.
|
1389 |
+
|
1390 |
+
Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
|
1391 |
+
`x`. The pseudo-Vandermonde matrix is defined by
|
1392 |
+
|
1393 |
+
.. math:: V[..., i] = T_i(x),
|
1394 |
+
|
1395 |
+
where `0 <= i <= deg`. The leading indices of `V` index the elements of
|
1396 |
+
`x` and the last index is the degree of the Chebyshev polynomial.
|
1397 |
+
|
1398 |
+
If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
|
1399 |
+
matrix ``V = chebvander(x, n)``, then ``np.dot(V, c)`` and
|
1400 |
+
``chebval(x, c)`` are the same up to roundoff. This equivalence is
|
1401 |
+
useful both for least squares fitting and for the evaluation of a large
|
1402 |
+
number of Chebyshev series of the same degree and sample points.
|
1403 |
+
|
1404 |
+
Parameters
|
1405 |
+
----------
|
1406 |
+
x : array_like
|
1407 |
+
Array of points. The dtype is converted to float64 or complex128
|
1408 |
+
depending on whether any of the elements are complex. If `x` is
|
1409 |
+
scalar it is converted to a 1-D array.
|
1410 |
+
deg : int
|
1411 |
+
Degree of the resulting matrix.
|
1412 |
+
|
1413 |
+
Returns
|
1414 |
+
-------
|
1415 |
+
vander : ndarray
|
1416 |
+
The pseudo Vandermonde matrix. The shape of the returned matrix is
|
1417 |
+
``x.shape + (deg + 1,)``, where The last index is the degree of the
|
1418 |
+
corresponding Chebyshev polynomial. The dtype will be the same as
|
1419 |
+
the converted `x`.
|
1420 |
+
|
1421 |
+
"""
|
1422 |
+
ideg = pu._deprecate_as_int(deg, "deg")
|
1423 |
+
if ideg < 0:
|
1424 |
+
raise ValueError("deg must be non-negative")
|
1425 |
+
|
1426 |
+
x = np.array(x, copy=False, ndmin=1) + 0.0
|
1427 |
+
dims = (ideg + 1,) + x.shape
|
1428 |
+
dtyp = x.dtype
|
1429 |
+
v = np.empty(dims, dtype=dtyp)
|
1430 |
+
# Use forward recursion to generate the entries.
|
1431 |
+
v[0] = x*0 + 1
|
1432 |
+
if ideg > 0:
|
1433 |
+
x2 = 2*x
|
1434 |
+
v[1] = x
|
1435 |
+
for i in range(2, ideg + 1):
|
1436 |
+
v[i] = v[i-1]*x2 - v[i-2]
|
1437 |
+
return np.moveaxis(v, 0, -1)
|
1438 |
+
|
1439 |
+
|
1440 |
+
def chebvander2d(x, y, deg):
|
1441 |
+
"""Pseudo-Vandermonde matrix of given degrees.
|
1442 |
+
|
1443 |
+
Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
|
1444 |
+
points `(x, y)`. The pseudo-Vandermonde matrix is defined by
|
1445 |
+
|
1446 |
+
.. math:: V[..., (deg[1] + 1)*i + j] = T_i(x) * T_j(y),
|
1447 |
+
|
1448 |
+
where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
|
1449 |
+
`V` index the points `(x, y)` and the last index encodes the degrees of
|
1450 |
+
the Chebyshev polynomials.
|
1451 |
+
|
1452 |
+
If ``V = chebvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
|
1453 |
+
correspond to the elements of a 2-D coefficient array `c` of shape
|
1454 |
+
(xdeg + 1, ydeg + 1) in the order
|
1455 |
+
|
1456 |
+
.. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
|
1457 |
+
|
1458 |
+
and ``np.dot(V, c.flat)`` and ``chebval2d(x, y, c)`` will be the same
|
1459 |
+
up to roundoff. This equivalence is useful both for least squares
|
1460 |
+
fitting and for the evaluation of a large number of 2-D Chebyshev
|
1461 |
+
series of the same degrees and sample points.
|
1462 |
+
|
1463 |
+
Parameters
|
1464 |
+
----------
|
1465 |
+
x, y : array_like
|
1466 |
+
Arrays of point coordinates, all of the same shape. The dtypes
|
1467 |
+
will be converted to either float64 or complex128 depending on
|
1468 |
+
whether any of the elements are complex. Scalars are converted to
|
1469 |
+
1-D arrays.
|
1470 |
+
deg : list of ints
|
1471 |
+
List of maximum degrees of the form [x_deg, y_deg].
|
1472 |
+
|
1473 |
+
Returns
|
1474 |
+
-------
|
1475 |
+
vander2d : ndarray
|
1476 |
+
The shape of the returned matrix is ``x.shape + (order,)``, where
|
1477 |
+
:math:`order = (deg[0]+1)*(deg[1]+1)`. The dtype will be the same
|
1478 |
+
as the converted `x` and `y`.
|
1479 |
+
|
1480 |
+
See Also
|
1481 |
+
--------
|
1482 |
+
chebvander, chebvander3d, chebval2d, chebval3d
|
1483 |
+
|
1484 |
+
Notes
|
1485 |
+
-----
|
1486 |
+
|
1487 |
+
.. versionadded:: 1.7.0
|
1488 |
+
|
1489 |
+
"""
|
1490 |
+
return pu._vander_nd_flat((chebvander, chebvander), (x, y), deg)
|
1491 |
+
|
1492 |
+
|
1493 |
+
def chebvander3d(x, y, z, deg):
|
1494 |
+
"""Pseudo-Vandermonde matrix of given degrees.
|
1495 |
+
|
1496 |
+
Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
|
1497 |
+
points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,
|
1498 |
+
then The pseudo-Vandermonde matrix is defined by
|
1499 |
+
|
1500 |
+
.. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = T_i(x)*T_j(y)*T_k(z),
|
1501 |
+
|
1502 |
+
where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading
|
1503 |
+
indices of `V` index the points `(x, y, z)` and the last index encodes
|
1504 |
+
the degrees of the Chebyshev polynomials.
|
1505 |
+
|
1506 |
+
If ``V = chebvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns
|
1507 |
+
of `V` correspond to the elements of a 3-D coefficient array `c` of
|
1508 |
+
shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order
|
1509 |
+
|
1510 |
+
.. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...
|
1511 |
+
|
1512 |
+
and ``np.dot(V, c.flat)`` and ``chebval3d(x, y, z, c)`` will be the
|
1513 |
+
same up to roundoff. This equivalence is useful both for least squares
|
1514 |
+
fitting and for the evaluation of a large number of 3-D Chebyshev
|
1515 |
+
series of the same degrees and sample points.
|
1516 |
+
|
1517 |
+
Parameters
|
1518 |
+
----------
|
1519 |
+
x, y, z : array_like
|
1520 |
+
Arrays of point coordinates, all of the same shape. The dtypes will
|
1521 |
+
be converted to either float64 or complex128 depending on whether
|
1522 |
+
any of the elements are complex. Scalars are converted to 1-D
|
1523 |
+
arrays.
|
1524 |
+
deg : list of ints
|
1525 |
+
List of maximum degrees of the form [x_deg, y_deg, z_deg].
|
1526 |
+
|
1527 |
+
Returns
|
1528 |
+
-------
|
1529 |
+
vander3d : ndarray
|
1530 |
+
The shape of the returned matrix is ``x.shape + (order,)``, where
|
1531 |
+
:math:`order = (deg[0]+1)*(deg[1]+1)*(deg[2]+1)`. The dtype will
|
1532 |
+
be the same as the converted `x`, `y`, and `z`.
|
1533 |
+
|
1534 |
+
See Also
|
1535 |
+
--------
|
1536 |
+
chebvander, chebvander3d, chebval2d, chebval3d
|
1537 |
+
|
1538 |
+
Notes
|
1539 |
+
-----
|
1540 |
+
|
1541 |
+
.. versionadded:: 1.7.0
|
1542 |
+
|
1543 |
+
"""
|
1544 |
+
return pu._vander_nd_flat((chebvander, chebvander, chebvander), (x, y, z), deg)
|
1545 |
+
|
1546 |
+
|
1547 |
+
def chebfit(x, y, deg, rcond=None, full=False, w=None):
|
1548 |
+
"""
|
1549 |
+
Least squares fit of Chebyshev series to data.
|
1550 |
+
|
1551 |
+
Return the coefficients of a Chebyshev series of degree `deg` that is the
|
1552 |
+
least squares fit to the data values `y` given at points `x`. If `y` is
|
1553 |
+
1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple
|
1554 |
+
fits are done, one for each column of `y`, and the resulting
|
1555 |
+
coefficients are stored in the corresponding columns of a 2-D return.
|
1556 |
+
The fitted polynomial(s) are in the form
|
1557 |
+
|
1558 |
+
.. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x),
|
1559 |
+
|
1560 |
+
where `n` is `deg`.
|
1561 |
+
|
1562 |
+
Parameters
|
1563 |
+
----------
|
1564 |
+
x : array_like, shape (M,)
|
1565 |
+
x-coordinates of the M sample points ``(x[i], y[i])``.
|
1566 |
+
y : array_like, shape (M,) or (M, K)
|
1567 |
+
y-coordinates of the sample points. Several data sets of sample
|
1568 |
+
points sharing the same x-coordinates can be fitted at once by
|
1569 |
+
passing in a 2D-array that contains one dataset per column.
|
1570 |
+
deg : int or 1-D array_like
|
1571 |
+
Degree(s) of the fitting polynomials. If `deg` is a single integer,
|
1572 |
+
all terms up to and including the `deg`'th term are included in the
|
1573 |
+
fit. For NumPy versions >= 1.11.0 a list of integers specifying the
|
1574 |
+
degrees of the terms to include may be used instead.
|
1575 |
+
rcond : float, optional
|
1576 |
+
Relative condition number of the fit. Singular values smaller than
|
1577 |
+
this relative to the largest singular value will be ignored. The
|
1578 |
+
default value is len(x)*eps, where eps is the relative precision of
|
1579 |
+
the float type, about 2e-16 in most cases.
|
1580 |
+
full : bool, optional
|
1581 |
+
Switch determining nature of return value. When it is False (the
|
1582 |
+
default) just the coefficients are returned, when True diagnostic
|
1583 |
+
information from the singular value decomposition is also returned.
|
1584 |
+
w : array_like, shape (`M`,), optional
|
1585 |
+
Weights. If not None, the weight ``w[i]`` applies to the unsquared
|
1586 |
+
residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are
|
1587 |
+
chosen so that the errors of the products ``w[i]*y[i]`` all have the
|
1588 |
+
same variance. When using inverse-variance weighting, use
|
1589 |
+
``w[i] = 1/sigma(y[i])``. The default value is None.
|
1590 |
+
|
1591 |
+
.. versionadded:: 1.5.0
|
1592 |
+
|
1593 |
+
Returns
|
1594 |
+
-------
|
1595 |
+
coef : ndarray, shape (M,) or (M, K)
|
1596 |
+
Chebyshev coefficients ordered from low to high. If `y` was 2-D,
|
1597 |
+
the coefficients for the data in column k of `y` are in column
|
1598 |
+
`k`.
|
1599 |
+
|
1600 |
+
[residuals, rank, singular_values, rcond] : list
|
1601 |
+
These values are only returned if ``full == True``
|
1602 |
+
|
1603 |
+
- residuals -- sum of squared residuals of the least squares fit
|
1604 |
+
- rank -- the numerical rank of the scaled Vandermonde matrix
|
1605 |
+
- singular_values -- singular values of the scaled Vandermonde matrix
|
1606 |
+
- rcond -- value of `rcond`.
|
1607 |
+
|
1608 |
+
For more details, see `numpy.linalg.lstsq`.
|
1609 |
+
|
1610 |
+
Warns
|
1611 |
+
-----
|
1612 |
+
RankWarning
|
1613 |
+
The rank of the coefficient matrix in the least-squares fit is
|
1614 |
+
deficient. The warning is only raised if ``full == False``. The
|
1615 |
+
warnings can be turned off by
|
1616 |
+
|
1617 |
+
>>> import warnings
|
1618 |
+
>>> warnings.simplefilter('ignore', np.RankWarning)
|
1619 |
+
|
1620 |
+
See Also
|
1621 |
+
--------
|
1622 |
+
numpy.polynomial.polynomial.polyfit
|
1623 |
+
numpy.polynomial.legendre.legfit
|
1624 |
+
numpy.polynomial.laguerre.lagfit
|
1625 |
+
numpy.polynomial.hermite.hermfit
|
1626 |
+
numpy.polynomial.hermite_e.hermefit
|
1627 |
+
chebval : Evaluates a Chebyshev series.
|
1628 |
+
chebvander : Vandermonde matrix of Chebyshev series.
|
1629 |
+
chebweight : Chebyshev weight function.
|
1630 |
+
numpy.linalg.lstsq : Computes a least-squares fit from the matrix.
|
1631 |
+
scipy.interpolate.UnivariateSpline : Computes spline fits.
|
1632 |
+
|
1633 |
+
Notes
|
1634 |
+
-----
|
1635 |
+
The solution is the coefficients of the Chebyshev series `p` that
|
1636 |
+
minimizes the sum of the weighted squared errors
|
1637 |
+
|
1638 |
+
.. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
|
1639 |
+
|
1640 |
+
where :math:`w_j` are the weights. This problem is solved by setting up
|
1641 |
+
as the (typically) overdetermined matrix equation
|
1642 |
+
|
1643 |
+
.. math:: V(x) * c = w * y,
|
1644 |
+
|
1645 |
+
where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the
|
1646 |
+
coefficients to be solved for, `w` are the weights, and `y` are the
|
1647 |
+
observed values. This equation is then solved using the singular value
|
1648 |
+
decomposition of `V`.
|
1649 |
+
|
1650 |
+
If some of the singular values of `V` are so small that they are
|
1651 |
+
neglected, then a `RankWarning` will be issued. This means that the
|
1652 |
+
coefficient values may be poorly determined. Using a lower order fit
|
1653 |
+
will usually get rid of the warning. The `rcond` parameter can also be
|
1654 |
+
set to a value smaller than its default, but the resulting fit may be
|
1655 |
+
spurious and have large contributions from roundoff error.
|
1656 |
+
|
1657 |
+
Fits using Chebyshev series are usually better conditioned than fits
|
1658 |
+
using power series, but much can depend on the distribution of the
|
1659 |
+
sample points and the smoothness of the data. If the quality of the fit
|
1660 |
+
is inadequate splines may be a good alternative.
|
1661 |
+
|
1662 |
+
References
|
1663 |
+
----------
|
1664 |
+
.. [1] Wikipedia, "Curve fitting",
|
1665 |
+
https://en.wikipedia.org/wiki/Curve_fitting
|
1666 |
+
|
1667 |
+
Examples
|
1668 |
+
--------
|
1669 |
+
|
1670 |
+
"""
|
1671 |
+
return pu._fit(chebvander, x, y, deg, rcond, full, w)
|
1672 |
+
|
1673 |
+
|
1674 |
+
def chebcompanion(c):
|
1675 |
+
"""Return the scaled companion matrix of c.
|
1676 |
+
|
1677 |
+
The basis polynomials are scaled so that the companion matrix is
|
1678 |
+
symmetric when `c` is a Chebyshev basis polynomial. This provides
|
1679 |
+
better eigenvalue estimates than the unscaled case and for basis
|
1680 |
+
polynomials the eigenvalues are guaranteed to be real if
|
1681 |
+
`numpy.linalg.eigvalsh` is used to obtain them.
|
1682 |
+
|
1683 |
+
Parameters
|
1684 |
+
----------
|
1685 |
+
c : array_like
|
1686 |
+
1-D array of Chebyshev series coefficients ordered from low to high
|
1687 |
+
degree.
|
1688 |
+
|
1689 |
+
Returns
|
1690 |
+
-------
|
1691 |
+
mat : ndarray
|
1692 |
+
Scaled companion matrix of dimensions (deg, deg).
|
1693 |
+
|
1694 |
+
Notes
|
1695 |
+
-----
|
1696 |
+
|
1697 |
+
.. versionadded:: 1.7.0
|
1698 |
+
|
1699 |
+
"""
|
1700 |
+
# c is a trimmed copy
|
1701 |
+
[c] = pu.as_series([c])
|
1702 |
+
if len(c) < 2:
|
1703 |
+
raise ValueError('Series must have maximum degree of at least 1.')
|
1704 |
+
if len(c) == 2:
|
1705 |
+
return np.array([[-c[0]/c[1]]])
|
1706 |
+
|
1707 |
+
n = len(c) - 1
|
1708 |
+
mat = np.zeros((n, n), dtype=c.dtype)
|
1709 |
+
scl = np.array([1.] + [np.sqrt(.5)]*(n-1))
|
1710 |
+
top = mat.reshape(-1)[1::n+1]
|
1711 |
+
bot = mat.reshape(-1)[n::n+1]
|
1712 |
+
top[0] = np.sqrt(.5)
|
1713 |
+
top[1:] = 1/2
|
1714 |
+
bot[...] = top
|
1715 |
+
mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])*.5
|
1716 |
+
return mat
|
1717 |
+
|
1718 |
+
|
1719 |
+
def chebroots(c):
|
1720 |
+
"""
|
1721 |
+
Compute the roots of a Chebyshev series.
|
1722 |
+
|
1723 |
+
Return the roots (a.k.a. "zeros") of the polynomial
|
1724 |
+
|
1725 |
+
.. math:: p(x) = \\sum_i c[i] * T_i(x).
|
1726 |
+
|
1727 |
+
Parameters
|
1728 |
+
----------
|
1729 |
+
c : 1-D array_like
|
1730 |
+
1-D array of coefficients.
|
1731 |
+
|
1732 |
+
Returns
|
1733 |
+
-------
|
1734 |
+
out : ndarray
|
1735 |
+
Array of the roots of the series. If all the roots are real,
|
1736 |
+
then `out` is also real, otherwise it is complex.
|
1737 |
+
|
1738 |
+
See Also
|
1739 |
+
--------
|
1740 |
+
numpy.polynomial.polynomial.polyroots
|
1741 |
+
numpy.polynomial.legendre.legroots
|
1742 |
+
numpy.polynomial.laguerre.lagroots
|
1743 |
+
numpy.polynomial.hermite.hermroots
|
1744 |
+
numpy.polynomial.hermite_e.hermeroots
|
1745 |
+
|
1746 |
+
Notes
|
1747 |
+
-----
|
1748 |
+
The root estimates are obtained as the eigenvalues of the companion
|
1749 |
+
matrix, Roots far from the origin of the complex plane may have large
|
1750 |
+
errors due to the numerical instability of the series for such
|
1751 |
+
values. Roots with multiplicity greater than 1 will also show larger
|
1752 |
+
errors as the value of the series near such points is relatively
|
1753 |
+
insensitive to errors in the roots. Isolated roots near the origin can
|
1754 |
+
be improved by a few iterations of Newton's method.
|
1755 |
+
|
1756 |
+
The Chebyshev series basis polynomials aren't powers of `x` so the
|
1757 |
+
results of this function may seem unintuitive.
|
1758 |
+
|
1759 |
+
Examples
|
1760 |
+
--------
|
1761 |
+
>>> import numpy.polynomial.chebyshev as cheb
|
1762 |
+
>>> cheb.chebroots((-1, 1,-1, 1)) # T3 - T2 + T1 - T0 has real roots
|
1763 |
+
array([ -5.00000000e-01, 2.60860684e-17, 1.00000000e+00]) # may vary
|
1764 |
+
|
1765 |
+
"""
|
1766 |
+
# c is a trimmed copy
|
1767 |
+
[c] = pu.as_series([c])
|
1768 |
+
if len(c) < 2:
|
1769 |
+
return np.array([], dtype=c.dtype)
|
1770 |
+
if len(c) == 2:
|
1771 |
+
return np.array([-c[0]/c[1]])
|
1772 |
+
|
1773 |
+
# rotated companion matrix reduces error
|
1774 |
+
m = chebcompanion(c)[::-1,::-1]
|
1775 |
+
r = la.eigvals(m)
|
1776 |
+
r.sort()
|
1777 |
+
return r
|
1778 |
+
|
1779 |
+
|
1780 |
+
def chebinterpolate(func, deg, args=()):
|
1781 |
+
"""Interpolate a function at the Chebyshev points of the first kind.
|
1782 |
+
|
1783 |
+
Returns the Chebyshev series that interpolates `func` at the Chebyshev
|
1784 |
+
points of the first kind in the interval [-1, 1]. The interpolating
|
1785 |
+
series tends to a minmax approximation to `func` with increasing `deg`
|
1786 |
+
if the function is continuous in the interval.
|
1787 |
+
|
1788 |
+
.. versionadded:: 1.14.0
|
1789 |
+
|
1790 |
+
Parameters
|
1791 |
+
----------
|
1792 |
+
func : function
|
1793 |
+
The function to be approximated. It must be a function of a single
|
1794 |
+
variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are
|
1795 |
+
extra arguments passed in the `args` parameter.
|
1796 |
+
deg : int
|
1797 |
+
Degree of the interpolating polynomial
|
1798 |
+
args : tuple, optional
|
1799 |
+
Extra arguments to be used in the function call. Default is no extra
|
1800 |
+
arguments.
|
1801 |
+
|
1802 |
+
Returns
|
1803 |
+
-------
|
1804 |
+
coef : ndarray, shape (deg + 1,)
|
1805 |
+
Chebyshev coefficients of the interpolating series ordered from low to
|
1806 |
+
high.
|
1807 |
+
|
1808 |
+
Examples
|
1809 |
+
--------
|
1810 |
+
>>> import numpy.polynomial.chebyshev as C
|
1811 |
+
>>> C.chebfromfunction(lambda x: np.tanh(x) + 0.5, 8)
|
1812 |
+
array([ 5.00000000e-01, 8.11675684e-01, -9.86864911e-17,
|
1813 |
+
-5.42457905e-02, -2.71387850e-16, 4.51658839e-03,
|
1814 |
+
2.46716228e-17, -3.79694221e-04, -3.26899002e-16])
|
1815 |
+
|
1816 |
+
Notes
|
1817 |
+
-----
|
1818 |
+
|
1819 |
+
The Chebyshev polynomials used in the interpolation are orthogonal when
|
1820 |
+
sampled at the Chebyshev points of the first kind. If it is desired to
|
1821 |
+
constrain some of the coefficients they can simply be set to the desired
|
1822 |
+
value after the interpolation, no new interpolation or fit is needed. This
|
1823 |
+
is especially useful if it is known apriori that some of coefficients are
|
1824 |
+
zero. For instance, if the function is even then the coefficients of the
|
1825 |
+
terms of odd degree in the result can be set to zero.
|
1826 |
+
|
1827 |
+
"""
|
1828 |
+
deg = np.asarray(deg)
|
1829 |
+
|
1830 |
+
# check arguments.
|
1831 |
+
if deg.ndim > 0 or deg.dtype.kind not in 'iu' or deg.size == 0:
|
1832 |
+
raise TypeError("deg must be an int")
|
1833 |
+
if deg < 0:
|
1834 |
+
raise ValueError("expected deg >= 0")
|
1835 |
+
|
1836 |
+
order = deg + 1
|
1837 |
+
xcheb = chebpts1(order)
|
1838 |
+
yfunc = func(xcheb, *args)
|
1839 |
+
m = chebvander(xcheb, deg)
|
1840 |
+
c = np.dot(m.T, yfunc)
|
1841 |
+
c[0] /= order
|
1842 |
+
c[1:] /= 0.5*order
|
1843 |
+
|
1844 |
+
return c
|
1845 |
+
|
1846 |
+
|
1847 |
+
def chebgauss(deg):
|
1848 |
+
"""
|
1849 |
+
Gauss-Chebyshev quadrature.
|
1850 |
+
|
1851 |
+
Computes the sample points and weights for Gauss-Chebyshev quadrature.
|
1852 |
+
These sample points and weights will correctly integrate polynomials of
|
1853 |
+
degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with
|
1854 |
+
the weight function :math:`f(x) = 1/\\sqrt{1 - x^2}`.
|
1855 |
+
|
1856 |
+
Parameters
|
1857 |
+
----------
|
1858 |
+
deg : int
|
1859 |
+
Number of sample points and weights. It must be >= 1.
|
1860 |
+
|
1861 |
+
Returns
|
1862 |
+
-------
|
1863 |
+
x : ndarray
|
1864 |
+
1-D ndarray containing the sample points.
|
1865 |
+
y : ndarray
|
1866 |
+
1-D ndarray containing the weights.
|
1867 |
+
|
1868 |
+
Notes
|
1869 |
+
-----
|
1870 |
+
|
1871 |
+
.. versionadded:: 1.7.0
|
1872 |
+
|
1873 |
+
The results have only been tested up to degree 100, higher degrees may
|
1874 |
+
be problematic. For Gauss-Chebyshev there are closed form solutions for
|
1875 |
+
the sample points and weights. If n = `deg`, then
|
1876 |
+
|
1877 |
+
.. math:: x_i = \\cos(\\pi (2 i - 1) / (2 n))
|
1878 |
+
|
1879 |
+
.. math:: w_i = \\pi / n
|
1880 |
+
|
1881 |
+
"""
|
1882 |
+
ideg = pu._deprecate_as_int(deg, "deg")
|
1883 |
+
if ideg <= 0:
|
1884 |
+
raise ValueError("deg must be a positive integer")
|
1885 |
+
|
1886 |
+
x = np.cos(np.pi * np.arange(1, 2*ideg, 2) / (2.0*ideg))
|
1887 |
+
w = np.ones(ideg)*(np.pi/ideg)
|
1888 |
+
|
1889 |
+
return x, w
|
1890 |
+
|
1891 |
+
|
1892 |
+
def chebweight(x):
|
1893 |
+
"""
|
1894 |
+
The weight function of the Chebyshev polynomials.
|
1895 |
+
|
1896 |
+
The weight function is :math:`1/\\sqrt{1 - x^2}` and the interval of
|
1897 |
+
integration is :math:`[-1, 1]`. The Chebyshev polynomials are
|
1898 |
+
orthogonal, but not normalized, with respect to this weight function.
|
1899 |
+
|
1900 |
+
Parameters
|
1901 |
+
----------
|
1902 |
+
x : array_like
|
1903 |
+
Values at which the weight function will be computed.
|
1904 |
+
|
1905 |
+
Returns
|
1906 |
+
-------
|
1907 |
+
w : ndarray
|
1908 |
+
The weight function at `x`.
|
1909 |
+
|
1910 |
+
Notes
|
1911 |
+
-----
|
1912 |
+
|
1913 |
+
.. versionadded:: 1.7.0
|
1914 |
+
|
1915 |
+
"""
|
1916 |
+
w = 1./(np.sqrt(1. + x) * np.sqrt(1. - x))
|
1917 |
+
return w
|
1918 |
+
|
1919 |
+
|
1920 |
+
def chebpts1(npts):
|
1921 |
+
"""
|
1922 |
+
Chebyshev points of the first kind.
|
1923 |
+
|
1924 |
+
The Chebyshev points of the first kind are the points ``cos(x)``,
|
1925 |
+
where ``x = [pi*(k + .5)/npts for k in range(npts)]``.
|
1926 |
+
|
1927 |
+
Parameters
|
1928 |
+
----------
|
1929 |
+
npts : int
|
1930 |
+
Number of sample points desired.
|
1931 |
+
|
1932 |
+
Returns
|
1933 |
+
-------
|
1934 |
+
pts : ndarray
|
1935 |
+
The Chebyshev points of the first kind.
|
1936 |
+
|
1937 |
+
See Also
|
1938 |
+
--------
|
1939 |
+
chebpts2
|
1940 |
+
|
1941 |
+
Notes
|
1942 |
+
-----
|
1943 |
+
|
1944 |
+
.. versionadded:: 1.5.0
|
1945 |
+
|
1946 |
+
"""
|
1947 |
+
_npts = int(npts)
|
1948 |
+
if _npts != npts:
|
1949 |
+
raise ValueError("npts must be integer")
|
1950 |
+
if _npts < 1:
|
1951 |
+
raise ValueError("npts must be >= 1")
|
1952 |
+
|
1953 |
+
x = 0.5 * np.pi / _npts * np.arange(-_npts+1, _npts+1, 2)
|
1954 |
+
return np.sin(x)
|
1955 |
+
|
1956 |
+
|
1957 |
+
def chebpts2(npts):
|
1958 |
+
"""
|
1959 |
+
Chebyshev points of the second kind.
|
1960 |
+
|
1961 |
+
The Chebyshev points of the second kind are the points ``cos(x)``,
|
1962 |
+
where ``x = [pi*k/(npts - 1) for k in range(npts)]`` sorted in ascending
|
1963 |
+
order.
|
1964 |
+
|
1965 |
+
Parameters
|
1966 |
+
----------
|
1967 |
+
npts : int
|
1968 |
+
Number of sample points desired.
|
1969 |
+
|
1970 |
+
Returns
|
1971 |
+
-------
|
1972 |
+
pts : ndarray
|
1973 |
+
The Chebyshev points of the second kind.
|
1974 |
+
|
1975 |
+
Notes
|
1976 |
+
-----
|
1977 |
+
|
1978 |
+
.. versionadded:: 1.5.0
|
1979 |
+
|
1980 |
+
"""
|
1981 |
+
_npts = int(npts)
|
1982 |
+
if _npts != npts:
|
1983 |
+
raise ValueError("npts must be integer")
|
1984 |
+
if _npts < 2:
|
1985 |
+
raise ValueError("npts must be >= 2")
|
1986 |
+
|
1987 |
+
x = np.linspace(-np.pi, 0, _npts)
|
1988 |
+
return np.cos(x)
|
1989 |
+
|
1990 |
+
|
1991 |
+
#
|
1992 |
+
# Chebyshev series class
|
1993 |
+
#
|
1994 |
+
|
1995 |
+
class Chebyshev(ABCPolyBase):
|
1996 |
+
"""A Chebyshev series class.
|
1997 |
+
|
1998 |
+
The Chebyshev class provides the standard Python numerical methods
|
1999 |
+
'+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
|
2000 |
+
methods listed below.
|
2001 |
+
|
2002 |
+
Parameters
|
2003 |
+
----------
|
2004 |
+
coef : array_like
|
2005 |
+
Chebyshev coefficients in order of increasing degree, i.e.,
|
2006 |
+
``(1, 2, 3)`` gives ``1*T_0(x) + 2*T_1(x) + 3*T_2(x)``.
|
2007 |
+
domain : (2,) array_like, optional
|
2008 |
+
Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
|
2009 |
+
to the interval ``[window[0], window[1]]`` by shifting and scaling.
|
2010 |
+
The default value is [-1, 1].
|
2011 |
+
window : (2,) array_like, optional
|
2012 |
+
Window, see `domain` for its use. The default value is [-1, 1].
|
2013 |
+
|
2014 |
+
.. versionadded:: 1.6.0
|
2015 |
+
symbol : str, optional
|
2016 |
+
Symbol used to represent the independent variable in string
|
2017 |
+
representations of the polynomial expression, e.g. for printing.
|
2018 |
+
The symbol must be a valid Python identifier. Default value is 'x'.
|
2019 |
+
|
2020 |
+
.. versionadded:: 1.24
|
2021 |
+
|
2022 |
+
"""
|
2023 |
+
# Virtual Functions
|
2024 |
+
_add = staticmethod(chebadd)
|
2025 |
+
_sub = staticmethod(chebsub)
|
2026 |
+
_mul = staticmethod(chebmul)
|
2027 |
+
_div = staticmethod(chebdiv)
|
2028 |
+
_pow = staticmethod(chebpow)
|
2029 |
+
_val = staticmethod(chebval)
|
2030 |
+
_int = staticmethod(chebint)
|
2031 |
+
_der = staticmethod(chebder)
|
2032 |
+
_fit = staticmethod(chebfit)
|
2033 |
+
_line = staticmethod(chebline)
|
2034 |
+
_roots = staticmethod(chebroots)
|
2035 |
+
_fromroots = staticmethod(chebfromroots)
|
2036 |
+
|
2037 |
+
@classmethod
|
2038 |
+
def interpolate(cls, func, deg, domain=None, args=()):
|
2039 |
+
"""Interpolate a function at the Chebyshev points of the first kind.
|
2040 |
+
|
2041 |
+
Returns the series that interpolates `func` at the Chebyshev points of
|
2042 |
+
the first kind scaled and shifted to the `domain`. The resulting series
|
2043 |
+
tends to a minmax approximation of `func` when the function is
|
2044 |
+
continuous in the domain.
|
2045 |
+
|
2046 |
+
.. versionadded:: 1.14.0
|
2047 |
+
|
2048 |
+
Parameters
|
2049 |
+
----------
|
2050 |
+
func : function
|
2051 |
+
The function to be interpolated. It must be a function of a single
|
2052 |
+
variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are
|
2053 |
+
extra arguments passed in the `args` parameter.
|
2054 |
+
deg : int
|
2055 |
+
Degree of the interpolating polynomial.
|
2056 |
+
domain : {None, [beg, end]}, optional
|
2057 |
+
Domain over which `func` is interpolated. The default is None, in
|
2058 |
+
which case the domain is [-1, 1].
|
2059 |
+
args : tuple, optional
|
2060 |
+
Extra arguments to be used in the function call. Default is no
|
2061 |
+
extra arguments.
|
2062 |
+
|
2063 |
+
Returns
|
2064 |
+
-------
|
2065 |
+
polynomial : Chebyshev instance
|
2066 |
+
Interpolating Chebyshev instance.
|
2067 |
+
|
2068 |
+
Notes
|
2069 |
+
-----
|
2070 |
+
See `numpy.polynomial.chebfromfunction` for more details.
|
2071 |
+
|
2072 |
+
"""
|
2073 |
+
if domain is None:
|
2074 |
+
domain = cls.domain
|
2075 |
+
xfunc = lambda x: func(pu.mapdomain(x, cls.window, domain), *args)
|
2076 |
+
coef = chebinterpolate(xfunc, deg)
|
2077 |
+
return cls(coef, domain=domain)
|
2078 |
+
|
2079 |
+
# Virtual properties
|
2080 |
+
domain = np.array(chebdomain)
|
2081 |
+
window = np.array(chebdomain)
|
2082 |
+
basis_name = 'T'
|
venv/lib/python3.10/site-packages/numpy/polynomial/chebyshev.pyi
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any
|
2 |
+
|
3 |
+
from numpy import ndarray, dtype, int_
|
4 |
+
from numpy.polynomial._polybase import ABCPolyBase
|
5 |
+
from numpy.polynomial.polyutils import trimcoef
|
6 |
+
|
7 |
+
__all__: list[str]
|
8 |
+
|
9 |
+
chebtrim = trimcoef
|
10 |
+
|
11 |
+
def poly2cheb(pol): ...
|
12 |
+
def cheb2poly(c): ...
|
13 |
+
|
14 |
+
chebdomain: ndarray[Any, dtype[int_]]
|
15 |
+
chebzero: ndarray[Any, dtype[int_]]
|
16 |
+
chebone: ndarray[Any, dtype[int_]]
|
17 |
+
chebx: ndarray[Any, dtype[int_]]
|
18 |
+
|
19 |
+
def chebline(off, scl): ...
|
20 |
+
def chebfromroots(roots): ...
|
21 |
+
def chebadd(c1, c2): ...
|
22 |
+
def chebsub(c1, c2): ...
|
23 |
+
def chebmulx(c): ...
|
24 |
+
def chebmul(c1, c2): ...
|
25 |
+
def chebdiv(c1, c2): ...
|
26 |
+
def chebpow(c, pow, maxpower=...): ...
|
27 |
+
def chebder(c, m=..., scl=..., axis=...): ...
|
28 |
+
def chebint(c, m=..., k = ..., lbnd=..., scl=..., axis=...): ...
|
29 |
+
def chebval(x, c, tensor=...): ...
|
30 |
+
def chebval2d(x, y, c): ...
|
31 |
+
def chebgrid2d(x, y, c): ...
|
32 |
+
def chebval3d(x, y, z, c): ...
|
33 |
+
def chebgrid3d(x, y, z, c): ...
|
34 |
+
def chebvander(x, deg): ...
|
35 |
+
def chebvander2d(x, y, deg): ...
|
36 |
+
def chebvander3d(x, y, z, deg): ...
|
37 |
+
def chebfit(x, y, deg, rcond=..., full=..., w=...): ...
|
38 |
+
def chebcompanion(c): ...
|
39 |
+
def chebroots(c): ...
|
40 |
+
def chebinterpolate(func, deg, args = ...): ...
|
41 |
+
def chebgauss(deg): ...
|
42 |
+
def chebweight(x): ...
|
43 |
+
def chebpts1(npts): ...
|
44 |
+
def chebpts2(npts): ...
|
45 |
+
|
46 |
+
class Chebyshev(ABCPolyBase):
|
47 |
+
@classmethod
|
48 |
+
def interpolate(cls, func, deg, domain=..., args = ...): ...
|
49 |
+
domain: Any
|
50 |
+
window: Any
|
51 |
+
basis_name: Any
|