Created starter files for the project.

This commit is contained in:
Batuhan Berk Başoğlu 2020-10-02 21:26:03 -04:00
commit 73f0c0db42
1992 changed files with 769897 additions and 0 deletions

View file

@ -0,0 +1,74 @@
"""Provide class for testing in French locale
"""
import sys
import locale
import pytest
__ALL__ = ['CommaDecimalPointLocale']
def find_comma_decimal_point_locale():
"""See if platform has a decimal point as comma locale.
Find a locale that uses a comma instead of a period as the
decimal point.
Returns
-------
old_locale: str
Locale when the function was called.
new_locale: {str, None)
First French locale found, None if none found.
"""
if sys.platform == 'win32':
locales = ['FRENCH']
else:
locales = ['fr_FR', 'fr_FR.UTF-8', 'fi_FI', 'fi_FI.UTF-8']
old_locale = locale.getlocale(locale.LC_NUMERIC)
new_locale = None
try:
for loc in locales:
try:
locale.setlocale(locale.LC_NUMERIC, loc)
new_locale = loc
break
except locale.Error:
pass
finally:
locale.setlocale(locale.LC_NUMERIC, locale=old_locale)
return old_locale, new_locale
class CommaDecimalPointLocale:
"""Sets LC_NUMERIC to a locale with comma as decimal point.
Classes derived from this class have setup and teardown methods that run
tests with locale.LC_NUMERIC set to a locale where commas (',') are used as
the decimal point instead of periods ('.'). On exit the locale is restored
to the initial locale. It also serves as context manager with the same
effect. If no such locale is available, the test is skipped.
.. versionadded:: 1.15.0
"""
(cur_locale, tst_locale) = find_comma_decimal_point_locale()
def setup(self):
if self.tst_locale is None:
pytest.skip("No French locale available")
locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)
def teardown(self):
locale.setlocale(locale.LC_NUMERIC, locale=self.cur_locale)
def __enter__(self):
if self.tst_locale is None:
pytest.skip("No French locale available")
locale.setlocale(locale.LC_NUMERIC, locale=self.tst_locale)
def __exit__(self, type, value, traceback):
locale.setlocale(locale.LC_NUMERIC, locale=self.cur_locale)

View file

@ -0,0 +1,15 @@
Steps to validate transcendental functions:
1) Add a file 'umath-validation-set-<ufuncname>', where ufuncname is name of
the function in NumPy you want to validate
2) The file should contain 4 columns: dtype,input,expected output,ulperror
a. dtype: one of np.float16, np.float32, np.float64
b. input: floating point input to ufunc in hex. Example: 0x414570a4
represents 12.340000152587890625
c. expected output: floating point output for the corresponding input in hex.
This should be computed using a high(er) precision library and then rounded to
same format as the input.
d. ulperror: expected maximum ulp error of the function. This
should be same across all rows of the same dtype. Otherwise, the function is
tested for the maximum ulp error among all entries of that dtype.
3) Add file umath-validation-set-<ufuncname> to the test file test_umath_accuracy.py
which will then validate your ufunc.

View file

@ -0,0 +1,665 @@
dtype,input,output,ulperrortol
## +ve denormals ##
np.float32,0x004b4716,0x3f800000,2
np.float32,0x007b2490,0x3f800000,2
np.float32,0x007c99fa,0x3f800000,2
np.float32,0x00734a0c,0x3f800000,2
np.float32,0x0070de24,0x3f800000,2
np.float32,0x007fffff,0x3f800000,2
np.float32,0x00000001,0x3f800000,2
## -ve denormals ##
np.float32,0x80495d65,0x3f800000,2
np.float32,0x806894f6,0x3f800000,2
np.float32,0x80555a76,0x3f800000,2
np.float32,0x804e1fb8,0x3f800000,2
np.float32,0x80687de9,0x3f800000,2
np.float32,0x807fffff,0x3f800000,2
np.float32,0x80000001,0x3f800000,2
## +/-0.0f, +/-FLT_MIN +/-FLT_MAX ##
np.float32,0x00000000,0x3f800000,2
np.float32,0x80000000,0x3f800000,2
np.float32,0x00800000,0x3f800000,2
np.float32,0x80800000,0x3f800000,2
## 1.00f + 0x00000001 ##
np.float32,0x3f800000,0x3f0a5140,2
np.float32,0x3f800001,0x3f0a513f,2
np.float32,0x3f800002,0x3f0a513d,2
np.float32,0xc090a8b0,0xbe4332ce,2
np.float32,0x41ce3184,0x3f4d1de1,2
np.float32,0xc1d85848,0xbeaa8980,2
np.float32,0x402b8820,0xbf653aa3,2
np.float32,0x42b4e454,0xbf4a338b,2
np.float32,0x42a67a60,0x3c58202e,2
np.float32,0x41d92388,0xbed987c7,2
np.float32,0x422dd66c,0x3f5dcab3,2
np.float32,0xc28f5be6,0xbf5688d8,2
np.float32,0x41ab2674,0xbf53aa3b,2
np.float32,0x3f490fdb,0x3f3504f3,2
np.float32,0xbf490fdb,0x3f3504f3,2
np.float32,0x3fc90fdb,0xb33bbd2e,2
np.float32,0xbfc90fdb,0xb33bbd2e,2
np.float32,0x40490fdb,0xbf800000,2
np.float32,0xc0490fdb,0xbf800000,2
np.float32,0x3fc90fdb,0xb33bbd2e,2
np.float32,0xbfc90fdb,0xb33bbd2e,2
np.float32,0x40490fdb,0xbf800000,2
np.float32,0xc0490fdb,0xbf800000,2
np.float32,0x40c90fdb,0x3f800000,2
np.float32,0xc0c90fdb,0x3f800000,2
np.float32,0x4016cbe4,0xbf3504f3,2
np.float32,0xc016cbe4,0xbf3504f3,2
np.float32,0x4096cbe4,0x324cde2e,2
np.float32,0xc096cbe4,0x324cde2e,2
np.float32,0x4116cbe4,0xbf800000,2
np.float32,0xc116cbe4,0xbf800000,2
np.float32,0x40490fdb,0xbf800000,2
np.float32,0xc0490fdb,0xbf800000,2
np.float32,0x40c90fdb,0x3f800000,2
np.float32,0xc0c90fdb,0x3f800000,2
np.float32,0x41490fdb,0x3f800000,2
np.float32,0xc1490fdb,0x3f800000,2
np.float32,0x407b53d2,0xbf3504f1,2
np.float32,0xc07b53d2,0xbf3504f1,2
np.float32,0x40fb53d2,0xb4b5563d,2
np.float32,0xc0fb53d2,0xb4b5563d,2
np.float32,0x417b53d2,0xbf800000,2
np.float32,0xc17b53d2,0xbf800000,2
np.float32,0x4096cbe4,0x324cde2e,2
np.float32,0xc096cbe4,0x324cde2e,2
np.float32,0x4116cbe4,0xbf800000,2
np.float32,0xc116cbe4,0xbf800000,2
np.float32,0x4196cbe4,0x3f800000,2
np.float32,0xc196cbe4,0x3f800000,2
np.float32,0x40afede0,0x3f3504f7,2
np.float32,0xc0afede0,0x3f3504f7,2
np.float32,0x412fede0,0x353222c4,2
np.float32,0xc12fede0,0x353222c4,2
np.float32,0x41afede0,0xbf800000,2
np.float32,0xc1afede0,0xbf800000,2
np.float32,0x40c90fdb,0x3f800000,2
np.float32,0xc0c90fdb,0x3f800000,2
np.float32,0x41490fdb,0x3f800000,2
np.float32,0xc1490fdb,0x3f800000,2
np.float32,0x41c90fdb,0x3f800000,2
np.float32,0xc1c90fdb,0x3f800000,2
np.float32,0x40e231d6,0x3f3504f3,2
np.float32,0xc0e231d6,0x3f3504f3,2
np.float32,0x416231d6,0xb319a6a2,2
np.float32,0xc16231d6,0xb319a6a2,2
np.float32,0x41e231d6,0xbf800000,2
np.float32,0xc1e231d6,0xbf800000,2
np.float32,0x40fb53d2,0xb4b5563d,2
np.float32,0xc0fb53d2,0xb4b5563d,2
np.float32,0x417b53d2,0xbf800000,2
np.float32,0xc17b53d2,0xbf800000,2
np.float32,0x41fb53d2,0x3f800000,2
np.float32,0xc1fb53d2,0x3f800000,2
np.float32,0x410a3ae7,0xbf3504fb,2
np.float32,0xc10a3ae7,0xbf3504fb,2
np.float32,0x418a3ae7,0x35b08908,2
np.float32,0xc18a3ae7,0x35b08908,2
np.float32,0x420a3ae7,0xbf800000,2
np.float32,0xc20a3ae7,0xbf800000,2
np.float32,0x4116cbe4,0xbf800000,2
np.float32,0xc116cbe4,0xbf800000,2
np.float32,0x4196cbe4,0x3f800000,2
np.float32,0xc196cbe4,0x3f800000,2
np.float32,0x4216cbe4,0x3f800000,2
np.float32,0xc216cbe4,0x3f800000,2
np.float32,0x41235ce2,0xbf3504ef,2
np.float32,0xc1235ce2,0xbf3504ef,2
np.float32,0x41a35ce2,0xb53889b6,2
np.float32,0xc1a35ce2,0xb53889b6,2
np.float32,0x42235ce2,0xbf800000,2
np.float32,0xc2235ce2,0xbf800000,2
np.float32,0x412fede0,0x353222c4,2
np.float32,0xc12fede0,0x353222c4,2
np.float32,0x41afede0,0xbf800000,2
np.float32,0xc1afede0,0xbf800000,2
np.float32,0x422fede0,0x3f800000,2
np.float32,0xc22fede0,0x3f800000,2
np.float32,0x413c7edd,0x3f3504f4,2
np.float32,0xc13c7edd,0x3f3504f4,2
np.float32,0x41bc7edd,0x33800add,2
np.float32,0xc1bc7edd,0x33800add,2
np.float32,0x423c7edd,0xbf800000,2
np.float32,0xc23c7edd,0xbf800000,2
np.float32,0x41490fdb,0x3f800000,2
np.float32,0xc1490fdb,0x3f800000,2
np.float32,0x41c90fdb,0x3f800000,2
np.float32,0xc1c90fdb,0x3f800000,2
np.float32,0x42490fdb,0x3f800000,2
np.float32,0xc2490fdb,0x3f800000,2
np.float32,0x4155a0d9,0x3f3504eb,2
np.float32,0xc155a0d9,0x3f3504eb,2
np.float32,0x41d5a0d9,0xb5b3bc81,2
np.float32,0xc1d5a0d9,0xb5b3bc81,2
np.float32,0x4255a0d9,0xbf800000,2
np.float32,0xc255a0d9,0xbf800000,2
np.float32,0x416231d6,0xb319a6a2,2
np.float32,0xc16231d6,0xb319a6a2,2
np.float32,0x41e231d6,0xbf800000,2
np.float32,0xc1e231d6,0xbf800000,2
np.float32,0x426231d6,0x3f800000,2
np.float32,0xc26231d6,0x3f800000,2
np.float32,0x416ec2d4,0xbf3504f7,2
np.float32,0xc16ec2d4,0xbf3504f7,2
np.float32,0x41eec2d4,0x353ef0a7,2
np.float32,0xc1eec2d4,0x353ef0a7,2
np.float32,0x426ec2d4,0xbf800000,2
np.float32,0xc26ec2d4,0xbf800000,2
np.float32,0x417b53d2,0xbf800000,2
np.float32,0xc17b53d2,0xbf800000,2
np.float32,0x41fb53d2,0x3f800000,2
np.float32,0xc1fb53d2,0x3f800000,2
np.float32,0x427b53d2,0x3f800000,2
np.float32,0xc27b53d2,0x3f800000,2
np.float32,0x4183f268,0xbf3504e7,2
np.float32,0xc183f268,0xbf3504e7,2
np.float32,0x4203f268,0xb6059a13,2
np.float32,0xc203f268,0xb6059a13,2
np.float32,0x4283f268,0xbf800000,2
np.float32,0xc283f268,0xbf800000,2
np.float32,0x418a3ae7,0x35b08908,2
np.float32,0xc18a3ae7,0x35b08908,2
np.float32,0x420a3ae7,0xbf800000,2
np.float32,0xc20a3ae7,0xbf800000,2
np.float32,0x428a3ae7,0x3f800000,2
np.float32,0xc28a3ae7,0x3f800000,2
np.float32,0x41908365,0x3f3504f0,2
np.float32,0xc1908365,0x3f3504f0,2
np.float32,0x42108365,0xb512200d,2
np.float32,0xc2108365,0xb512200d,2
np.float32,0x42908365,0xbf800000,2
np.float32,0xc2908365,0xbf800000,2
np.float32,0x4196cbe4,0x3f800000,2
np.float32,0xc196cbe4,0x3f800000,2
np.float32,0x4216cbe4,0x3f800000,2
np.float32,0xc216cbe4,0x3f800000,2
np.float32,0x4296cbe4,0x3f800000,2
np.float32,0xc296cbe4,0x3f800000,2
np.float32,0x419d1463,0x3f3504ef,2
np.float32,0xc19d1463,0x3f3504ef,2
np.float32,0x421d1463,0xb5455799,2
np.float32,0xc21d1463,0xb5455799,2
np.float32,0x429d1463,0xbf800000,2
np.float32,0xc29d1463,0xbf800000,2
np.float32,0x41a35ce2,0xb53889b6,2
np.float32,0xc1a35ce2,0xb53889b6,2
np.float32,0x42235ce2,0xbf800000,2
np.float32,0xc2235ce2,0xbf800000,2
np.float32,0x42a35ce2,0x3f800000,2
np.float32,0xc2a35ce2,0x3f800000,2
np.float32,0x41a9a561,0xbf3504ff,2
np.float32,0xc1a9a561,0xbf3504ff,2
np.float32,0x4229a561,0x360733d0,2
np.float32,0xc229a561,0x360733d0,2
np.float32,0x42a9a561,0xbf800000,2
np.float32,0xc2a9a561,0xbf800000,2
np.float32,0x41afede0,0xbf800000,2
np.float32,0xc1afede0,0xbf800000,2
np.float32,0x422fede0,0x3f800000,2
np.float32,0xc22fede0,0x3f800000,2
np.float32,0x42afede0,0x3f800000,2
np.float32,0xc2afede0,0x3f800000,2
np.float32,0x41b6365e,0xbf3504f6,2
np.float32,0xc1b6365e,0xbf3504f6,2
np.float32,0x4236365e,0x350bb91c,2
np.float32,0xc236365e,0x350bb91c,2
np.float32,0x42b6365e,0xbf800000,2
np.float32,0xc2b6365e,0xbf800000,2
np.float32,0x41bc7edd,0x33800add,2
np.float32,0xc1bc7edd,0x33800add,2
np.float32,0x423c7edd,0xbf800000,2
np.float32,0xc23c7edd,0xbf800000,2
np.float32,0x42bc7edd,0x3f800000,2
np.float32,0xc2bc7edd,0x3f800000,2
np.float32,0x41c2c75c,0x3f3504f8,2
np.float32,0xc1c2c75c,0x3f3504f8,2
np.float32,0x4242c75c,0x354bbe8a,2
np.float32,0xc242c75c,0x354bbe8a,2
np.float32,0x42c2c75c,0xbf800000,2
np.float32,0xc2c2c75c,0xbf800000,2
np.float32,0x41c90fdb,0x3f800000,2
np.float32,0xc1c90fdb,0x3f800000,2
np.float32,0x42490fdb,0x3f800000,2
np.float32,0xc2490fdb,0x3f800000,2
np.float32,0x42c90fdb,0x3f800000,2
np.float32,0xc2c90fdb,0x3f800000,2
np.float32,0x41cf585a,0x3f3504e7,2
np.float32,0xc1cf585a,0x3f3504e7,2
np.float32,0x424f585a,0xb608cd8c,2
np.float32,0xc24f585a,0xb608cd8c,2
np.float32,0x42cf585a,0xbf800000,2
np.float32,0xc2cf585a,0xbf800000,2
np.float32,0x41d5a0d9,0xb5b3bc81,2
np.float32,0xc1d5a0d9,0xb5b3bc81,2
np.float32,0x4255a0d9,0xbf800000,2
np.float32,0xc255a0d9,0xbf800000,2
np.float32,0x42d5a0d9,0x3f800000,2
np.float32,0xc2d5a0d9,0x3f800000,2
np.float32,0x41dbe958,0xbf350507,2
np.float32,0xc1dbe958,0xbf350507,2
np.float32,0x425be958,0x365eab75,2
np.float32,0xc25be958,0x365eab75,2
np.float32,0x42dbe958,0xbf800000,2
np.float32,0xc2dbe958,0xbf800000,2
np.float32,0x41e231d6,0xbf800000,2
np.float32,0xc1e231d6,0xbf800000,2
np.float32,0x426231d6,0x3f800000,2
np.float32,0xc26231d6,0x3f800000,2
np.float32,0x42e231d6,0x3f800000,2
np.float32,0xc2e231d6,0x3f800000,2
np.float32,0x41e87a55,0xbf3504ef,2
np.float32,0xc1e87a55,0xbf3504ef,2
np.float32,0x42687a55,0xb552257b,2
np.float32,0xc2687a55,0xb552257b,2
np.float32,0x42e87a55,0xbf800000,2
np.float32,0xc2e87a55,0xbf800000,2
np.float32,0x41eec2d4,0x353ef0a7,2
np.float32,0xc1eec2d4,0x353ef0a7,2
np.float32,0x426ec2d4,0xbf800000,2
np.float32,0xc26ec2d4,0xbf800000,2
np.float32,0x42eec2d4,0x3f800000,2
np.float32,0xc2eec2d4,0x3f800000,2
np.float32,0x41f50b53,0x3f3504ff,2
np.float32,0xc1f50b53,0x3f3504ff,2
np.float32,0x42750b53,0x360a6748,2
np.float32,0xc2750b53,0x360a6748,2
np.float32,0x42f50b53,0xbf800000,2
np.float32,0xc2f50b53,0xbf800000,2
np.float32,0x41fb53d2,0x3f800000,2
np.float32,0xc1fb53d2,0x3f800000,2
np.float32,0x427b53d2,0x3f800000,2
np.float32,0xc27b53d2,0x3f800000,2
np.float32,0x42fb53d2,0x3f800000,2
np.float32,0xc2fb53d2,0x3f800000,2
np.float32,0x4200ce28,0x3f3504f6,2
np.float32,0xc200ce28,0x3f3504f6,2
np.float32,0x4280ce28,0x34fdd672,2
np.float32,0xc280ce28,0x34fdd672,2
np.float32,0x4300ce28,0xbf800000,2
np.float32,0xc300ce28,0xbf800000,2
np.float32,0x4203f268,0xb6059a13,2
np.float32,0xc203f268,0xb6059a13,2
np.float32,0x4283f268,0xbf800000,2
np.float32,0xc283f268,0xbf800000,2
np.float32,0x4303f268,0x3f800000,2
np.float32,0xc303f268,0x3f800000,2
np.float32,0x420716a7,0xbf3504f8,2
np.float32,0xc20716a7,0xbf3504f8,2
np.float32,0x428716a7,0x35588c6d,2
np.float32,0xc28716a7,0x35588c6d,2
np.float32,0x430716a7,0xbf800000,2
np.float32,0xc30716a7,0xbf800000,2
np.float32,0x420a3ae7,0xbf800000,2
np.float32,0xc20a3ae7,0xbf800000,2
np.float32,0x428a3ae7,0x3f800000,2
np.float32,0xc28a3ae7,0x3f800000,2
np.float32,0x430a3ae7,0x3f800000,2
np.float32,0xc30a3ae7,0x3f800000,2
np.float32,0x420d5f26,0xbf3504e7,2
np.float32,0xc20d5f26,0xbf3504e7,2
np.float32,0x428d5f26,0xb60c0105,2
np.float32,0xc28d5f26,0xb60c0105,2
np.float32,0x430d5f26,0xbf800000,2
np.float32,0xc30d5f26,0xbf800000,2
np.float32,0x42108365,0xb512200d,2
np.float32,0xc2108365,0xb512200d,2
np.float32,0x42908365,0xbf800000,2
np.float32,0xc2908365,0xbf800000,2
np.float32,0x43108365,0x3f800000,2
np.float32,0xc3108365,0x3f800000,2
np.float32,0x4213a7a5,0x3f350507,2
np.float32,0xc213a7a5,0x3f350507,2
np.float32,0x4293a7a5,0x3661deee,2
np.float32,0xc293a7a5,0x3661deee,2
np.float32,0x4313a7a5,0xbf800000,2
np.float32,0xc313a7a5,0xbf800000,2
np.float32,0x4216cbe4,0x3f800000,2
np.float32,0xc216cbe4,0x3f800000,2
np.float32,0x4296cbe4,0x3f800000,2
np.float32,0xc296cbe4,0x3f800000,2
np.float32,0x4316cbe4,0x3f800000,2
np.float32,0xc316cbe4,0x3f800000,2
np.float32,0x4219f024,0x3f3504d8,2
np.float32,0xc219f024,0x3f3504d8,2
np.float32,0x4299f024,0xb69bde6c,2
np.float32,0xc299f024,0xb69bde6c,2
np.float32,0x4319f024,0xbf800000,2
np.float32,0xc319f024,0xbf800000,2
np.float32,0x421d1463,0xb5455799,2
np.float32,0xc21d1463,0xb5455799,2
np.float32,0x429d1463,0xbf800000,2
np.float32,0xc29d1463,0xbf800000,2
np.float32,0x431d1463,0x3f800000,2
np.float32,0xc31d1463,0x3f800000,2
np.float32,0x422038a3,0xbf350516,2
np.float32,0xc22038a3,0xbf350516,2
np.float32,0x42a038a3,0x36c6cd61,2
np.float32,0xc2a038a3,0x36c6cd61,2
np.float32,0x432038a3,0xbf800000,2
np.float32,0xc32038a3,0xbf800000,2
np.float32,0x42235ce2,0xbf800000,2
np.float32,0xc2235ce2,0xbf800000,2
np.float32,0x42a35ce2,0x3f800000,2
np.float32,0xc2a35ce2,0x3f800000,2
np.float32,0x43235ce2,0x3f800000,2
np.float32,0xc3235ce2,0x3f800000,2
np.float32,0x42268121,0xbf3504f6,2
np.float32,0xc2268121,0xbf3504f6,2
np.float32,0x42a68121,0x34e43aac,2
np.float32,0xc2a68121,0x34e43aac,2
np.float32,0x43268121,0xbf800000,2
np.float32,0xc3268121,0xbf800000,2
np.float32,0x4229a561,0x360733d0,2
np.float32,0xc229a561,0x360733d0,2
np.float32,0x42a9a561,0xbf800000,2
np.float32,0xc2a9a561,0xbf800000,2
np.float32,0x4329a561,0x3f800000,2
np.float32,0xc329a561,0x3f800000,2
np.float32,0x422cc9a0,0x3f3504f8,2
np.float32,0xc22cc9a0,0x3f3504f8,2
np.float32,0x42acc9a0,0x35655a50,2
np.float32,0xc2acc9a0,0x35655a50,2
np.float32,0x432cc9a0,0xbf800000,2
np.float32,0xc32cc9a0,0xbf800000,2
np.float32,0x422fede0,0x3f800000,2
np.float32,0xc22fede0,0x3f800000,2
np.float32,0x42afede0,0x3f800000,2
np.float32,0xc2afede0,0x3f800000,2
np.float32,0x432fede0,0x3f800000,2
np.float32,0xc32fede0,0x3f800000,2
np.float32,0x4233121f,0x3f3504e7,2
np.float32,0xc233121f,0x3f3504e7,2
np.float32,0x42b3121f,0xb60f347d,2
np.float32,0xc2b3121f,0xb60f347d,2
np.float32,0x4333121f,0xbf800000,2
np.float32,0xc333121f,0xbf800000,2
np.float32,0x4236365e,0x350bb91c,2
np.float32,0xc236365e,0x350bb91c,2
np.float32,0x42b6365e,0xbf800000,2
np.float32,0xc2b6365e,0xbf800000,2
np.float32,0x4336365e,0x3f800000,2
np.float32,0xc336365e,0x3f800000,2
np.float32,0x42395a9e,0xbf350507,2
np.float32,0xc2395a9e,0xbf350507,2
np.float32,0x42b95a9e,0x36651267,2
np.float32,0xc2b95a9e,0x36651267,2
np.float32,0x43395a9e,0xbf800000,2
np.float32,0xc3395a9e,0xbf800000,2
np.float32,0x423c7edd,0xbf800000,2
np.float32,0xc23c7edd,0xbf800000,2
np.float32,0x42bc7edd,0x3f800000,2
np.float32,0xc2bc7edd,0x3f800000,2
np.float32,0x433c7edd,0x3f800000,2
np.float32,0xc33c7edd,0x3f800000,2
np.float32,0x423fa31d,0xbf3504d7,2
np.float32,0xc23fa31d,0xbf3504d7,2
np.float32,0x42bfa31d,0xb69d7828,2
np.float32,0xc2bfa31d,0xb69d7828,2
np.float32,0x433fa31d,0xbf800000,2
np.float32,0xc33fa31d,0xbf800000,2
np.float32,0x4242c75c,0x354bbe8a,2
np.float32,0xc242c75c,0x354bbe8a,2
np.float32,0x42c2c75c,0xbf800000,2
np.float32,0xc2c2c75c,0xbf800000,2
np.float32,0x4342c75c,0x3f800000,2
np.float32,0xc342c75c,0x3f800000,2
np.float32,0x4245eb9c,0x3f350517,2
np.float32,0xc245eb9c,0x3f350517,2
np.float32,0x42c5eb9c,0x36c8671d,2
np.float32,0xc2c5eb9c,0x36c8671d,2
np.float32,0x4345eb9c,0xbf800000,2
np.float32,0xc345eb9c,0xbf800000,2
np.float32,0x42490fdb,0x3f800000,2
np.float32,0xc2490fdb,0x3f800000,2
np.float32,0x42c90fdb,0x3f800000,2
np.float32,0xc2c90fdb,0x3f800000,2
np.float32,0x43490fdb,0x3f800000,2
np.float32,0xc3490fdb,0x3f800000,2
np.float32,0x424c341a,0x3f3504f5,2
np.float32,0xc24c341a,0x3f3504f5,2
np.float32,0x42cc341a,0x34ca9ee6,2
np.float32,0xc2cc341a,0x34ca9ee6,2
np.float32,0x434c341a,0xbf800000,2
np.float32,0xc34c341a,0xbf800000,2
np.float32,0x424f585a,0xb608cd8c,2
np.float32,0xc24f585a,0xb608cd8c,2
np.float32,0x42cf585a,0xbf800000,2
np.float32,0xc2cf585a,0xbf800000,2
np.float32,0x434f585a,0x3f800000,2
np.float32,0xc34f585a,0x3f800000,2
np.float32,0x42527c99,0xbf3504f9,2
np.float32,0xc2527c99,0xbf3504f9,2
np.float32,0x42d27c99,0x35722833,2
np.float32,0xc2d27c99,0x35722833,2
np.float32,0x43527c99,0xbf800000,2
np.float32,0xc3527c99,0xbf800000,2
np.float32,0x4255a0d9,0xbf800000,2
np.float32,0xc255a0d9,0xbf800000,2
np.float32,0x42d5a0d9,0x3f800000,2
np.float32,0xc2d5a0d9,0x3f800000,2
np.float32,0x4355a0d9,0x3f800000,2
np.float32,0xc355a0d9,0x3f800000,2
np.float32,0x4258c518,0xbf3504e6,2
np.float32,0xc258c518,0xbf3504e6,2
np.float32,0x42d8c518,0xb61267f6,2
np.float32,0xc2d8c518,0xb61267f6,2
np.float32,0x4358c518,0xbf800000,2
np.float32,0xc358c518,0xbf800000,2
np.float32,0x425be958,0x365eab75,2
np.float32,0xc25be958,0x365eab75,2
np.float32,0x42dbe958,0xbf800000,2
np.float32,0xc2dbe958,0xbf800000,2
np.float32,0x435be958,0x3f800000,2
np.float32,0xc35be958,0x3f800000,2
np.float32,0x425f0d97,0x3f350508,2
np.float32,0xc25f0d97,0x3f350508,2
np.float32,0x42df0d97,0x366845e0,2
np.float32,0xc2df0d97,0x366845e0,2
np.float32,0x435f0d97,0xbf800000,2
np.float32,0xc35f0d97,0xbf800000,2
np.float32,0x426231d6,0x3f800000,2
np.float32,0xc26231d6,0x3f800000,2
np.float32,0x42e231d6,0x3f800000,2
np.float32,0xc2e231d6,0x3f800000,2
np.float32,0x436231d6,0x3f800000,2
np.float32,0xc36231d6,0x3f800000,2
np.float32,0x42655616,0x3f3504d7,2
np.float32,0xc2655616,0x3f3504d7,2
np.float32,0x42e55616,0xb69f11e5,2
np.float32,0xc2e55616,0xb69f11e5,2
np.float32,0x43655616,0xbf800000,2
np.float32,0xc3655616,0xbf800000,2
np.float32,0x42687a55,0xb552257b,2
np.float32,0xc2687a55,0xb552257b,2
np.float32,0x42e87a55,0xbf800000,2
np.float32,0xc2e87a55,0xbf800000,2
np.float32,0x43687a55,0x3f800000,2
np.float32,0xc3687a55,0x3f800000,2
np.float32,0x426b9e95,0xbf350517,2
np.float32,0xc26b9e95,0xbf350517,2
np.float32,0x42eb9e95,0x36ca00d9,2
np.float32,0xc2eb9e95,0x36ca00d9,2
np.float32,0x436b9e95,0xbf800000,2
np.float32,0xc36b9e95,0xbf800000,2
np.float32,0x426ec2d4,0xbf800000,2
np.float32,0xc26ec2d4,0xbf800000,2
np.float32,0x42eec2d4,0x3f800000,2
np.float32,0xc2eec2d4,0x3f800000,2
np.float32,0x436ec2d4,0x3f800000,2
np.float32,0xc36ec2d4,0x3f800000,2
np.float32,0x4271e713,0xbf3504f5,2
np.float32,0xc271e713,0xbf3504f5,2
np.float32,0x42f1e713,0x34b10321,2
np.float32,0xc2f1e713,0x34b10321,2
np.float32,0x4371e713,0xbf800000,2
np.float32,0xc371e713,0xbf800000,2
np.float32,0x42750b53,0x360a6748,2
np.float32,0xc2750b53,0x360a6748,2
np.float32,0x42f50b53,0xbf800000,2
np.float32,0xc2f50b53,0xbf800000,2
np.float32,0x43750b53,0x3f800000,2
np.float32,0xc3750b53,0x3f800000,2
np.float32,0x42782f92,0x3f3504f9,2
np.float32,0xc2782f92,0x3f3504f9,2
np.float32,0x42f82f92,0x357ef616,2
np.float32,0xc2f82f92,0x357ef616,2
np.float32,0x43782f92,0xbf800000,2
np.float32,0xc3782f92,0xbf800000,2
np.float32,0x427b53d2,0x3f800000,2
np.float32,0xc27b53d2,0x3f800000,2
np.float32,0x42fb53d2,0x3f800000,2
np.float32,0xc2fb53d2,0x3f800000,2
np.float32,0x437b53d2,0x3f800000,2
np.float32,0xc37b53d2,0x3f800000,2
np.float32,0x427e7811,0x3f3504e6,2
np.float32,0xc27e7811,0x3f3504e6,2
np.float32,0x42fe7811,0xb6159b6f,2
np.float32,0xc2fe7811,0xb6159b6f,2
np.float32,0x437e7811,0xbf800000,2
np.float32,0xc37e7811,0xbf800000,2
np.float32,0x4280ce28,0x34fdd672,2
np.float32,0xc280ce28,0x34fdd672,2
np.float32,0x4300ce28,0xbf800000,2
np.float32,0xc300ce28,0xbf800000,2
np.float32,0x4380ce28,0x3f800000,2
np.float32,0xc380ce28,0x3f800000,2
np.float32,0x42826048,0xbf350508,2
np.float32,0xc2826048,0xbf350508,2
np.float32,0x43026048,0x366b7958,2
np.float32,0xc3026048,0x366b7958,2
np.float32,0x43826048,0xbf800000,2
np.float32,0xc3826048,0xbf800000,2
np.float32,0x4283f268,0xbf800000,2
np.float32,0xc283f268,0xbf800000,2
np.float32,0x4303f268,0x3f800000,2
np.float32,0xc303f268,0x3f800000,2
np.float32,0x4383f268,0x3f800000,2
np.float32,0xc383f268,0x3f800000,2
np.float32,0x42858487,0xbf350504,2
np.float32,0xc2858487,0xbf350504,2
np.float32,0x43058487,0x363ea8be,2
np.float32,0xc3058487,0x363ea8be,2
np.float32,0x43858487,0xbf800000,2
np.float32,0xc3858487,0xbf800000,2
np.float32,0x428716a7,0x35588c6d,2
np.float32,0xc28716a7,0x35588c6d,2
np.float32,0x430716a7,0xbf800000,2
np.float32,0xc30716a7,0xbf800000,2
np.float32,0x438716a7,0x3f800000,2
np.float32,0xc38716a7,0x3f800000,2
np.float32,0x4288a8c7,0x3f350517,2
np.float32,0xc288a8c7,0x3f350517,2
np.float32,0x4308a8c7,0x36cb9a96,2
np.float32,0xc308a8c7,0x36cb9a96,2
np.float32,0x4388a8c7,0xbf800000,2
np.float32,0xc388a8c7,0xbf800000,2
np.float32,0x428a3ae7,0x3f800000,2
np.float32,0xc28a3ae7,0x3f800000,2
np.float32,0x430a3ae7,0x3f800000,2
np.float32,0xc30a3ae7,0x3f800000,2
np.float32,0x438a3ae7,0x3f800000,2
np.float32,0xc38a3ae7,0x3f800000,2
np.float32,0x428bcd06,0x3f3504f5,2
np.float32,0xc28bcd06,0x3f3504f5,2
np.float32,0x430bcd06,0x3497675b,2
np.float32,0xc30bcd06,0x3497675b,2
np.float32,0x438bcd06,0xbf800000,2
np.float32,0xc38bcd06,0xbf800000,2
np.float32,0x428d5f26,0xb60c0105,2
np.float32,0xc28d5f26,0xb60c0105,2
np.float32,0x430d5f26,0xbf800000,2
np.float32,0xc30d5f26,0xbf800000,2
np.float32,0x438d5f26,0x3f800000,2
np.float32,0xc38d5f26,0x3f800000,2
np.float32,0x428ef146,0xbf350526,2
np.float32,0xc28ef146,0xbf350526,2
np.float32,0x430ef146,0x3710bc40,2
np.float32,0xc30ef146,0x3710bc40,2
np.float32,0x438ef146,0xbf800000,2
np.float32,0xc38ef146,0xbf800000,2
np.float32,0x42908365,0xbf800000,2
np.float32,0xc2908365,0xbf800000,2
np.float32,0x43108365,0x3f800000,2
np.float32,0xc3108365,0x3f800000,2
np.float32,0x43908365,0x3f800000,2
np.float32,0xc3908365,0x3f800000,2
np.float32,0x42921585,0xbf3504e6,2
np.float32,0xc2921585,0xbf3504e6,2
np.float32,0x43121585,0xb618cee8,2
np.float32,0xc3121585,0xb618cee8,2
np.float32,0x43921585,0xbf800000,2
np.float32,0xc3921585,0xbf800000,2
np.float32,0x4293a7a5,0x3661deee,2
np.float32,0xc293a7a5,0x3661deee,2
np.float32,0x4313a7a5,0xbf800000,2
np.float32,0xc313a7a5,0xbf800000,2
np.float32,0x4393a7a5,0x3f800000,2
np.float32,0xc393a7a5,0x3f800000,2
np.float32,0x429539c5,0x3f350536,2
np.float32,0xc29539c5,0x3f350536,2
np.float32,0x431539c5,0x373bab34,2
np.float32,0xc31539c5,0x373bab34,2
np.float32,0x439539c5,0xbf800000,2
np.float32,0xc39539c5,0xbf800000,2
np.float32,0x4296cbe4,0x3f800000,2
np.float32,0xc296cbe4,0x3f800000,2
np.float32,0x4316cbe4,0x3f800000,2
np.float32,0xc316cbe4,0x3f800000,2
np.float32,0x4396cbe4,0x3f800000,2
np.float32,0xc396cbe4,0x3f800000,2
np.float32,0x42985e04,0x3f3504d7,2
np.float32,0xc2985e04,0x3f3504d7,2
np.float32,0x43185e04,0xb6a2455d,2
np.float32,0xc3185e04,0xb6a2455d,2
np.float32,0x43985e04,0xbf800000,2
np.float32,0xc3985e04,0xbf800000,2
np.float32,0x4299f024,0xb69bde6c,2
np.float32,0xc299f024,0xb69bde6c,2
np.float32,0x4319f024,0xbf800000,2
np.float32,0xc319f024,0xbf800000,2
np.float32,0x4399f024,0x3f800000,2
np.float32,0xc399f024,0x3f800000,2
np.float32,0x429b8243,0xbf3504ea,2
np.float32,0xc29b8243,0xbf3504ea,2
np.float32,0x431b8243,0xb5cb2eb8,2
np.float32,0xc31b8243,0xb5cb2eb8,2
np.float32,0x439b8243,0xbf800000,2
np.float32,0xc39b8243,0xbf800000,2
np.float32,0x435b2047,0x3f3504c1,2
np.float32,0x42a038a2,0xb5e4ca7e,2
np.float32,0x432038a2,0xbf800000,2
np.float32,0x4345eb9b,0xbf800000,2
np.float32,0x42c5eb9b,0xb5de638c,2
np.float32,0x42eb9e94,0xb5d7fc9b,2
np.float32,0x4350ea79,0x3631dadb,2
np.float32,0x42dbe957,0xbf800000,2
np.float32,0x425be957,0xb505522a,2
np.float32,0x435be957,0x3f800000,2
np.float32,0x46027eb2,0x3e7d94c9,2
np.float32,0x4477baed,0xbe7f1824,2
np.float32,0x454b8024,0x3e7f5268,2
np.float32,0x455d2c09,0x3e7f40cb,2
np.float32,0x4768d3de,0xba14b4af,2
np.float32,0x46c1e7cd,0x3e7fb102,2
np.float32,0x44a52949,0xbe7dc9d5,2
np.float32,0x4454633a,0x3e7dbc7d,2
np.float32,0x4689810b,0x3e7eb02b,2
np.float32,0x473473cd,0xbe7eef6f,2
np.float32,0x44a5193f,0x3e7e1b1f,2
np.float32,0x46004b36,0x3e7dac59,2
np.float32,0x467f604b,0x3d7ffd3a,2
np.float32,0x45ea1805,0x3dffd2e0,2
np.float32,0x457b6af3,0x3dff7831,2
np.float32,0x44996159,0xbe7d85f4,2
np.float32,0x47883553,0xbb80584e,2
np.float32,0x44e19f0c,0xbdffcfe6,2
np.float32,0x472b3bf6,0xbe7f7a82,2
np.float32,0x4600bb4e,0x3a135e33,2
np.float32,0x449f4556,0x3e7e42e5,2
np.float32,0x474e9420,0x3dff77b2,2
np.float32,0x45cbdb23,0x3dff7240,2
np.float32,0x44222747,0x3dffb039,2
np.float32,0x4772e419,0xbdff74b8,2

View file

@ -0,0 +1,412 @@
dtype,input,output,ulperrortol
## +ve denormals ##
np.float32,0x004b4716,0x3f800000,3
np.float32,0x007b2490,0x3f800000,3
np.float32,0x007c99fa,0x3f800000,3
np.float32,0x00734a0c,0x3f800000,3
np.float32,0x0070de24,0x3f800000,3
np.float32,0x00495d65,0x3f800000,3
np.float32,0x006894f6,0x3f800000,3
np.float32,0x00555a76,0x3f800000,3
np.float32,0x004e1fb8,0x3f800000,3
np.float32,0x00687de9,0x3f800000,3
## -ve denormals ##
np.float32,0x805b59af,0x3f800000,3
np.float32,0x807ed8ed,0x3f800000,3
np.float32,0x807142ad,0x3f800000,3
np.float32,0x80772002,0x3f800000,3
np.float32,0x8062abcb,0x3f800000,3
np.float32,0x8045e31c,0x3f800000,3
np.float32,0x805f01c2,0x3f800000,3
np.float32,0x80506432,0x3f800000,3
np.float32,0x8060089d,0x3f800000,3
np.float32,0x8071292f,0x3f800000,3
## floats that output a denormal ##
np.float32,0xc2cf3fc1,0x00000001,3
np.float32,0xc2c79726,0x00000021,3
np.float32,0xc2cb295d,0x00000005,3
np.float32,0xc2b49e6b,0x00068c4c,3
np.float32,0xc2ca8116,0x00000008,3
np.float32,0xc2c23f82,0x000001d7,3
np.float32,0xc2cb69c0,0x00000005,3
np.float32,0xc2cc1f4d,0x00000003,3
np.float32,0xc2ae094e,0x00affc4c,3
np.float32,0xc2c86c44,0x00000015,3
## random floats between -87.0f and 88.0f ##
np.float32,0x4030d7e0,0x417d9a05,3
np.float32,0x426f60e8,0x6aa1be2c,3
np.float32,0x41a1b220,0x4e0efc11,3
np.float32,0xc20cc722,0x26159da7,3
np.float32,0x41c492bc,0x512ec79d,3
np.float32,0x40980210,0x42e73a0e,3
np.float32,0xbf1f7b80,0x3f094de3,3
np.float32,0x42a678a4,0x7b87a383,3
np.float32,0xc20f3cfd,0x25a1c304,3
np.float32,0x423ff34c,0x6216467f,3
np.float32,0x00000000,0x3f800000,3
## floats that cause an overflow ##
np.float32,0x7f06d8c1,0x7f800000,3
np.float32,0x7f451912,0x7f800000,3
np.float32,0x7ecceac3,0x7f800000,3
np.float32,0x7f643b45,0x7f800000,3
np.float32,0x7e910ea0,0x7f800000,3
np.float32,0x7eb4756b,0x7f800000,3
np.float32,0x7f4ec708,0x7f800000,3
np.float32,0x7f6b4551,0x7f800000,3
np.float32,0x7d8edbda,0x7f800000,3
np.float32,0x7f730718,0x7f800000,3
np.float32,0x42b17217,0x7f7fff84,3
np.float32,0x42b17218,0x7f800000,3
np.float32,0x42b17219,0x7f800000,3
np.float32,0xfef2b0bc,0x00000000,3
np.float32,0xff69f83e,0x00000000,3
np.float32,0xff4ecb12,0x00000000,3
np.float32,0xfeac6d86,0x00000000,3
np.float32,0xfde0cdb8,0x00000000,3
np.float32,0xff26aef4,0x00000000,3
np.float32,0xff6f9277,0x00000000,3
np.float32,0xff7adfc4,0x00000000,3
np.float32,0xff0ad40e,0x00000000,3
np.float32,0xff6fd8f3,0x00000000,3
np.float32,0xc2cff1b4,0x00000001,3
np.float32,0xc2cff1b5,0x00000000,3
np.float32,0xc2cff1b6,0x00000000,3
np.float32,0x7f800000,0x7f800000,3
np.float32,0xff800000,0x00000000,3
np.float32,0x4292f27c,0x7480000a,3
np.float32,0x42a920be,0x7c7fff94,3
np.float32,0x41c214c9,0x50ffffd9,3
np.float32,0x41abe686,0x4effffd9,3
np.float32,0x4287db5a,0x707fffd3,3
np.float32,0x41902cbb,0x4c800078,3
np.float32,0x42609466,0x67ffffeb,3
np.float32,0x41a65af5,0x4e7fffd1,3
np.float32,0x417f13ff,0x4affffc9,3
np.float32,0x426d0e6c,0x6a3504f2,3
np.float32,0x41bc8934,0x507fff51,3
np.float32,0x42a7bdde,0x7c0000d6,3
np.float32,0x4120cf66,0x46b504f6,3
np.float32,0x4244da8f,0x62ffff1a,3
np.float32,0x41a0cf69,0x4e000034,3
np.float32,0x41cd2bec,0x52000005,3
np.float32,0x42893e41,0x7100009e,3
np.float32,0x41b437e1,0x4fb50502,3
np.float32,0x41d8430f,0x5300001d,3
np.float32,0x4244da92,0x62ffffda,3
np.float32,0x41a0cf63,0x4dffffa9,3
np.float32,0x3eb17218,0x3fb504f3,3
np.float32,0x428729e8,0x703504dc,3
np.float32,0x41a0cf67,0x4e000014,3
np.float32,0x4252b77d,0x65800011,3
np.float32,0x41902cb9,0x4c800058,3
np.float32,0x42a0cf67,0x79800052,3
np.float32,0x4152b77b,0x48ffffe9,3
np.float32,0x41265af3,0x46ffffc8,3
np.float32,0x42187e0b,0x5affff9a,3
np.float32,0xc0d2b77c,0x3ab504f6,3
np.float32,0xc283b2ac,0x10000072,3
np.float32,0xc1cff1b4,0x2cb504f5,3
np.float32,0xc05dce9e,0x3d000000,3
np.float32,0xc28ec9d2,0x0bfffea5,3
np.float32,0xc23c893a,0x1d7fffde,3
np.float32,0xc2a920c0,0x027fff6c,3
np.float32,0xc1f9886f,0x2900002b,3
np.float32,0xc2c42920,0x000000b5,3
np.float32,0xc2893e41,0x0dfffec5,3
np.float32,0xc2c4da93,0x00000080,3
np.float32,0xc17f1401,0x3400000c,3
np.float32,0xc1902cb6,0x327fffaf,3
np.float32,0xc27c4e3b,0x11ffffc5,3
np.float32,0xc268e5c5,0x157ffe9d,3
np.float32,0xc2b4e953,0x0005a826,3
np.float32,0xc287db5a,0x0e800016,3
np.float32,0xc207db5a,0x2700000b,3
np.float32,0xc2b2d4fe,0x000ffff1,3
np.float32,0xc268e5c0,0x157fffdd,3
np.float32,0xc22920bd,0x2100003b,3
np.float32,0xc2902caf,0x0b80011e,3
np.float32,0xc1902cba,0x327fff2f,3
np.float32,0xc2ca6625,0x00000008,3
np.float32,0xc280ece8,0x10fffeb5,3
np.float32,0xc2918f94,0x0b0000ea,3
np.float32,0xc29b43d5,0x077ffffc,3
np.float32,0xc1e61ff7,0x2ab504f5,3
np.float32,0xc2867878,0x0effff15,3
np.float32,0xc2a2324a,0x04fffff4,3
#float64
## near zero ##
np.float64,0x8000000000000000,0x3ff0000000000000,1
np.float64,0x8010000000000000,0x3ff0000000000000,1
np.float64,0x8000000000000001,0x3ff0000000000000,1
np.float64,0x8360000000000000,0x3ff0000000000000,1
np.float64,0x9a70000000000000,0x3ff0000000000000,1
np.float64,0xb9b0000000000000,0x3ff0000000000000,1
np.float64,0xb810000000000000,0x3ff0000000000000,1
np.float64,0xbc30000000000000,0x3ff0000000000000,1
np.float64,0xb6a0000000000000,0x3ff0000000000000,1
np.float64,0x0000000000000000,0x3ff0000000000000,1
np.float64,0x0010000000000000,0x3ff0000000000000,1
np.float64,0x0000000000000001,0x3ff0000000000000,1
np.float64,0x0360000000000000,0x3ff0000000000000,1
np.float64,0x1a70000000000000,0x3ff0000000000000,1
np.float64,0x3c30000000000000,0x3ff0000000000000,1
np.float64,0x36a0000000000000,0x3ff0000000000000,1
np.float64,0x39b0000000000000,0x3ff0000000000000,1
np.float64,0x3810000000000000,0x3ff0000000000000,1
## underflow ##
np.float64,0xc0c6276800000000,0x0000000000000000,1
np.float64,0xc0c62d918ce2421d,0x0000000000000000,1
np.float64,0xc0c62d918ce2421e,0x0000000000000000,1
np.float64,0xc0c62d91a0000000,0x0000000000000000,1
np.float64,0xc0c62d9180000000,0x0000000000000000,1
np.float64,0xc0c62dea45ee3e06,0x0000000000000000,1
np.float64,0xc0c62dea45ee3e07,0x0000000000000000,1
np.float64,0xc0c62dea40000000,0x0000000000000000,1
np.float64,0xc0c62dea60000000,0x0000000000000000,1
np.float64,0xc0875f1120000000,0x0000000000000000,1
np.float64,0xc0875f113c30b1c8,0x0000000000000000,1
np.float64,0xc0875f1140000000,0x0000000000000000,1
np.float64,0xc093480000000000,0x0000000000000000,1
np.float64,0xffefffffffffffff,0x0000000000000000,1
np.float64,0xc7efffffe0000000,0x0000000000000000,1
## overflow ##
np.float64,0x40862e52fefa39ef,0x7ff0000000000000,1
np.float64,0x40872e42fefa39ef,0x7ff0000000000000,1
## +/- INF, +/- NAN ##
np.float64,0x7ff0000000000000,0x7ff0000000000000,1
np.float64,0xfff0000000000000,0x0000000000000000,1
np.float64,0x7ff8000000000000,0x7ff8000000000000,1
np.float64,0xfff8000000000000,0xfff8000000000000,1
## output denormal ##
np.float64,0xc087438520000000,0x0000000000000001,1
np.float64,0xc08743853f2f4461,0x0000000000000001,1
np.float64,0xc08743853f2f4460,0x0000000000000001,1
np.float64,0xc087438540000000,0x0000000000000001,1
## between -745.13321910 and 709.78271289 ##
np.float64,0xbff760cd14774bd9,0x3fcdb14ced00ceb6,1
np.float64,0xbff760cd20000000,0x3fcdb14cd7993879,1
np.float64,0xbff760cd00000000,0x3fcdb14d12fbd264,1
np.float64,0xc07f1cf360000000,0x130c1b369af14fda,1
np.float64,0xbeb0000000000000,0x3feffffe00001000,1
np.float64,0xbd70000000000000,0x3fefffffffffe000,1
np.float64,0xc084fd46e5c84952,0x0360000000000139,1
np.float64,0xc084fd46e5c84953,0x035ffffffffffe71,1
np.float64,0xc084fd46e0000000,0x0360000b9096d32c,1
np.float64,0xc084fd4700000000,0x035fff9721d12104,1
np.float64,0xc086232bc0000000,0x0010003af5e64635,1
np.float64,0xc086232bdd7abcd2,0x001000000000007c,1
np.float64,0xc086232bdd7abcd3,0x000ffffffffffe7c,1
np.float64,0xc086232be0000000,0x000ffffaf57a6fc9,1
np.float64,0xc086233920000000,0x000fe590e3b45eb0,1
np.float64,0xc086233938000000,0x000fe56133493c57,1
np.float64,0xc086233940000000,0x000fe5514deffbbc,1
np.float64,0xc086234c98000000,0x000fbf1024c32ccb,1
np.float64,0xc086234ca0000000,0x000fbf0065bae78d,1
np.float64,0xc086234c80000000,0x000fbf3f623a7724,1
np.float64,0xc086234ec0000000,0x000fbad237c846f9,1
np.float64,0xc086234ec8000000,0x000fbac27cfdec97,1
np.float64,0xc086234ee0000000,0x000fba934cfd3dc2,1
np.float64,0xc086234ef0000000,0x000fba73d7f618d9,1
np.float64,0xc086234f00000000,0x000fba54632dddc0,1
np.float64,0xc0862356e0000000,0x000faae0945b761a,1
np.float64,0xc0862356f0000000,0x000faac13eb9a310,1
np.float64,0xc086235700000000,0x000faaa1e9567b0a,1
np.float64,0xc086236020000000,0x000f98cd75c11ed7,1
np.float64,0xc086236ca0000000,0x000f8081b4d93f89,1
np.float64,0xc086236cb0000000,0x000f8062b3f4d6c5,1
np.float64,0xc086236cc0000000,0x000f8043b34e6f8c,1
np.float64,0xc086238d98000000,0x000f41220d9b0d2c,1
np.float64,0xc086238da0000000,0x000f4112cc80a01f,1
np.float64,0xc086238d80000000,0x000f414fd145db5b,1
np.float64,0xc08624fd00000000,0x000cbfce8ea1e6c4,1
np.float64,0xc086256080000000,0x000c250747fcd46e,1
np.float64,0xc08626c480000000,0x000a34f4bd975193,1
np.float64,0xbf50000000000000,0x3feff800ffeaac00,1
np.float64,0xbe10000000000000,0x3fefffffff800000,1
np.float64,0xbcd0000000000000,0x3feffffffffffff8,1
np.float64,0xc055d589e0000000,0x38100004bf94f63e,1
np.float64,0xc055d58a00000000,0x380ffff97f292ce8,1
np.float64,0xbfd962d900000000,0x3fe585a4b00110e1,1
np.float64,0x3ff4bed280000000,0x400d411e7a58a303,1
np.float64,0x3fff0b3620000000,0x401bd7737ffffcf3,1
np.float64,0x3ff0000000000000,0x4005bf0a8b145769,1
np.float64,0x3eb0000000000000,0x3ff0000100000800,1
np.float64,0x3d70000000000000,0x3ff0000000001000,1
np.float64,0x40862e42e0000000,0x7fefff841808287f,1
np.float64,0x40862e42fefa39ef,0x7fefffffffffff2a,1
np.float64,0x40862e0000000000,0x7feef85a11e73f2d,1
np.float64,0x4000000000000000,0x401d8e64b8d4ddae,1
np.float64,0x4009242920000000,0x40372a52c383a488,1
np.float64,0x4049000000000000,0x44719103e4080b45,1
np.float64,0x4008000000000000,0x403415e5bf6fb106,1
np.float64,0x3f50000000000000,0x3ff00400800aab55,1
np.float64,0x3e10000000000000,0x3ff0000000400000,1
np.float64,0x3cd0000000000000,0x3ff0000000000004,1
np.float64,0x40562e40a0000000,0x47effed088821c3f,1
np.float64,0x40562e42e0000000,0x47effff082e6c7ff,1
np.float64,0x40562e4300000000,0x47f00000417184b8,1
np.float64,0x3fe8000000000000,0x4000ef9db467dcf8,1
np.float64,0x402b12e8d4f33589,0x412718f68c71a6fe,1
np.float64,0x402b12e8d4f3358a,0x412718f68c71a70a,1
np.float64,0x402b12e8c0000000,0x412718f59a7f472e,1
np.float64,0x402b12e8e0000000,0x412718f70c0eac62,1
##use 1th entry
np.float64,0x40631659AE147CB4,0x4db3a95025a4890f,1
np.float64,0xC061B87D2E85A4E2,0x332640c8e2de2c51,1
np.float64,0x405A4A50BE243AF4,0x496a45e4b7f0339a,1
np.float64,0xC0839898B98EC5C6,0x0764027828830df4,1
#use 2th entry
np.float64,0xC072428C44B6537C,0x2596ade838b96f3e,1
np.float64,0xC053057C5E1AE9BF,0x3912c8fad18fdadf,1
np.float64,0x407E89C78328BAA3,0x6bfe35d5b9a1a194,1
np.float64,0x4083501B6DD87112,0x77a855503a38924e,1
#use 3th entry
np.float64,0x40832C6195F24540,0x7741e73c80e5eb2f,1
np.float64,0xC083D4CD557C2EC9,0x06b61727c2d2508e,1
np.float64,0x400C48F5F67C99BD,0x404128820f02b92e,1
np.float64,0x4056E36D9B2DF26A,0x4830f52ff34a8242,1
#use 4th entry
np.float64,0x4080FF700D8CBD06,0x70fa70df9bc30f20,1
np.float64,0x406C276D39E53328,0x543eb8e20a8f4741,1
np.float64,0xC070D6159BBD8716,0x27a4a0548c904a75,1
np.float64,0xC052EBCF8ED61F83,0x391c0e92368d15e4,1
#use 5th entry
np.float64,0xC061F892A8AC5FBE,0x32f807a89efd3869,1
np.float64,0x4021D885D2DBA085,0x40bd4dc86d3e3270,1
np.float64,0x40767AEEEE7D4FCF,0x605e22851ee2afb7,1
np.float64,0xC0757C5D75D08C80,0x20f0751599b992a2,1
#use 6th entry
np.float64,0x405ACF7A284C4CE3,0x499a4e0b7a27027c,1
np.float64,0xC085A6C9E80D7AF5,0x0175914009d62ec2,1
np.float64,0xC07E4C02F86F1DAE,0x1439269b29a9231e,1
np.float64,0x4080D80F9691CC87,0x7088a6cdafb041de,1
#use 7th entry
np.float64,0x407FDFD84FBA0AC1,0x6deb1ae6f9bc4767,1
np.float64,0x40630C06A1A2213D,0x4dac7a9d51a838b7,1
np.float64,0x40685FDB30BB8B4F,0x5183f5cc2cac9e79,1
np.float64,0x408045A2208F77F4,0x6ee299e08e2aa2f0,1
#use 8th entry
np.float64,0xC08104E391F5078B,0x0ed397b7cbfbd230,1
np.float64,0xC031501CAEFAE395,0x3e6040fd1ea35085,1
np.float64,0xC079229124F6247C,0x1babf4f923306b1e,1
np.float64,0x407FB65F44600435,0x6db03beaf2512b8a,1
#use 9th entry
np.float64,0xC07EDEE8E8E8A5AC,0x136536cec9cbef48,1
np.float64,0x4072BB4086099A14,0x5af4d3c3008b56cc,1
np.float64,0x4050442A2EC42CB4,0x45cd393bd8fad357,1
np.float64,0xC06AC28FB3D419B4,0x2ca1b9d3437df85f,1
#use 10th entry
np.float64,0x40567FC6F0A68076,0x480c977fd5f3122e,1
np.float64,0x40620A2F7EDA59BB,0x4cf278e96f4ce4d7,1
np.float64,0xC085044707CD557C,0x034aad6c968a045a,1
np.float64,0xC07374EA5AC516AA,0x23dd6afdc03e83d5,1
#use 11th entry
np.float64,0x4073CC95332619C1,0x5c804b1498bbaa54,1
np.float64,0xC0799FEBBE257F31,0x1af6a954c43b87d2,1
np.float64,0x408159F19EA424F6,0x7200858efcbfc84d,1
np.float64,0x404A81F6F24C0792,0x44b664a07ce5bbfa,1
#use 12th entry
np.float64,0x40295FF1EFB9A741,0x4113c0e74c52d7b0,1
np.float64,0x4073975F4CC411DA,0x5c32be40b4fec2c1,1
np.float64,0x406E9DE52E82A77E,0x56049c9a3f1ae089,1
np.float64,0x40748C2F52560ED9,0x5d93bc14fd4cd23b,1
#use 13th entry
np.float64,0x4062A553CDC4D04C,0x4d6266bfde301318,1
np.float64,0xC079EC1D63598AB7,0x1a88cb184dab224c,1
np.float64,0xC0725C1CB3167427,0x25725b46f8a081f6,1
np.float64,0x407888771D9B45F9,0x6353b1ec6bd7ce80,1
#use 14th entry
np.float64,0xC082CBA03AA89807,0x09b383723831ce56,1
np.float64,0xC083A8961BB67DD7,0x0735b118d5275552,1
np.float64,0xC076BC6ECA12E7E3,0x1f2222679eaef615,1
np.float64,0xC072752503AA1A5B,0x254eb832242c77e1,1
#use 15th entry
np.float64,0xC058800792125DEC,0x371882372a0b48d4,1
np.float64,0x4082909FD863E81C,0x7580d5f386920142,1
np.float64,0xC071616F8FB534F9,0x26dbe20ef64a412b,1
np.float64,0x406D1AB571CAA747,0x54ee0d55cb38ac20,1
#use 16th entry
np.float64,0x406956428B7DAD09,0x52358682c271237f,1
np.float64,0xC07EFC2D9D17B621,0x133b3e77c27a4d45,1
np.float64,0xC08469BAC5BA3CCA,0x050863e5f42cc52f,1
np.float64,0x407189D9626386A5,0x593cb1c0b3b5c1d3,1
#use 17th entry
np.float64,0x4077E652E3DEB8C6,0x6269a10dcbd3c752,1
np.float64,0x407674C97DB06878,0x605485dcc2426ec2,1
np.float64,0xC07CE9969CF4268D,0x16386cf8996669f2,1
np.float64,0x40780EE32D5847C4,0x62a436bd1abe108d,1
#use 18th entry
np.float64,0x4076C3AA5E1E8DA1,0x60c62f56a5e72e24,1
np.float64,0xC0730AFC7239B9BE,0x24758ead095cec1e,1
np.float64,0xC085CC2B9C420DDB,0x0109cdaa2e5694c1,1
np.float64,0x406D0765CB6D7AA4,0x54e06f8dd91bd945,1
#use 19th entry
np.float64,0xC082D011F3B495E7,0x09a6647661d279c2,1
np.float64,0xC072826AF8F6AFBC,0x253acd3cd224507e,1
np.float64,0x404EB9C4810CEA09,0x457933dbf07e8133,1
np.float64,0x408284FBC97C58CE,0x755f6eb234aa4b98,1
#use 20th entry
np.float64,0x40856008CF6EDC63,0x7d9c0b3c03f4f73c,1
np.float64,0xC077CB2E9F013B17,0x1d9b3d3a166a55db,1
np.float64,0xC0479CA3C20AD057,0x3bad40e081555b99,1
np.float64,0x40844CD31107332A,0x7a821d70aea478e2,1
#use 21th entry
np.float64,0xC07C8FCC0BFCC844,0x16ba1cc8c539d19b,1
np.float64,0xC085C4E9A3ABA488,0x011ff675ba1a2217,1
np.float64,0x4074D538B32966E5,0x5dfd9d78043c6ad9,1
np.float64,0xC0630CA16902AD46,0x3231a446074cede6,1
#use 22th entry
np.float64,0xC06C826733D7D0B7,0x2b5f1078314d41e1,1
np.float64,0xC0520DF55B2B907F,0x396c13a6ce8e833e,1
np.float64,0xC080712072B0F437,0x107eae02d11d98ea,1
np.float64,0x40528A6150E19EFB,0x469fdabda02228c5,1
#use 23th entry
np.float64,0xC07B1D74B6586451,0x18d1253883ae3b48,1
np.float64,0x4045AFD7867DAEC0,0x43d7d634fc4c5d98,1
np.float64,0xC07A08B91F9ED3E2,0x1a60973e6397fc37,1
np.float64,0x407B3ECF0AE21C8C,0x673e03e9d98d7235,1
#use 24th entry
np.float64,0xC078AEB6F30CEABF,0x1c530b93ab54a1b3,1
np.float64,0x4084495006A41672,0x7a775b6dc7e63064,1
np.float64,0x40830B1C0EBF95DD,0x76e1e6eed77cfb89,1
np.float64,0x407D93E8F33D8470,0x6a9adbc9e1e4f1e5,1
#use 25th entry
np.float64,0x4066B11A09EFD9E8,0x504dd528065c28a7,1
np.float64,0x408545823723AEEB,0x7d504a9b1844f594,1
np.float64,0xC068C711F2CA3362,0x2e104f3496ea118e,1
np.float64,0x407F317FCC3CA873,0x6cf0732c9948ebf4,1
#use 26th entry
np.float64,0x407AFB3EBA2ED50F,0x66dc28a129c868d5,1
np.float64,0xC075377037708ADE,0x21531a329f3d793e,1
np.float64,0xC07C30066A1F3246,0x174448baa16ded2b,1
np.float64,0xC06689A75DE2ABD3,0x2fad70662fae230b,1
#use 27th entry
np.float64,0x4081514E9FCCF1E0,0x71e673b9efd15f44,1
np.float64,0xC0762C710AF68460,0x1ff1ed7d8947fe43,1
np.float64,0xC0468102FF70D9C4,0x3be0c3a8ff3419a3,1
np.float64,0xC07EA4CEEF02A83E,0x13b908f085102c61,1
#use 28th entry
np.float64,0xC06290B04AE823C4,0x328a83da3c2e3351,1
np.float64,0xC0770EB1D1C395FB,0x1eab281c1f1db5fe,1
np.float64,0xC06F5D4D838A5BAE,0x29500ea32fb474ea,1
np.float64,0x40723B3133B54C5D,0x5a3c82c7c3a2b848,1
#use 29th entry
np.float64,0x4085E6454CE3B4AA,0x7f20319b9638d06a,1
np.float64,0x408389F2A0585D4B,0x7850667c58aab3d0,1
np.float64,0xC0382798F9C8AE69,0x3dc1c79fe8739d6d,1
np.float64,0xC08299D827608418,0x0a4335f76cdbaeb5,1
#use 30th entry
np.float64,0xC06F3DED43301BF1,0x2965670ae46750a8,1
np.float64,0xC070CAF6BDD577D9,0x27b4aa4ffdd29981,1
np.float64,0x4078529AD4B2D9F2,0x6305c12755d5e0a6,1
np.float64,0xC055B14E75A31B96,0x381c2eda6d111e5d,1
#use 31th entry
np.float64,0x407B13EE414FA931,0x6700772c7544564d,1
np.float64,0x407EAFDE9DE3EC54,0x6c346a0e49724a3c,1
np.float64,0xC08362F398B9530D,0x07ffeddbadf980cb,1
np.float64,0x407E865CDD9EEB86,0x6bf866cac5e0d126,1
#use 32th entry
np.float64,0x407FB62DBC794C86,0x6db009f708ac62cb,1
np.float64,0xC063D0BAA68CDDDE,0x31a3b2a51ce50430,1
np.float64,0xC05E7706A2231394,0x34f24bead6fab5c9,1
np.float64,0x4083E3A06FDE444E,0x79527b7a386d1937,1

View file

@ -0,0 +1,118 @@
dtype,input,output,ulperrortol
## +ve denormals ##
np.float32,0x004b4716,0xc2afbc1b,4
np.float32,0x007b2490,0xc2aec01e,4
np.float32,0x007c99fa,0xc2aeba17,4
np.float32,0x00734a0c,0xc2aee1dc,4
np.float32,0x0070de24,0xc2aeecba,4
np.float32,0x007fffff,0xc2aeac50,4
np.float32,0x00000001,0xc2ce8ed0,4
## -ve denormals ##
np.float32,0x80495d65,0xffc00000,4
np.float32,0x806894f6,0xffc00000,4
np.float32,0x80555a76,0xffc00000,4
np.float32,0x804e1fb8,0xffc00000,4
np.float32,0x80687de9,0xffc00000,4
np.float32,0x807fffff,0xffc00000,4
np.float32,0x80000001,0xffc00000,4
## +/-0.0f, +/-FLT_MIN +/-FLT_MAX ##
np.float32,0x00000000,0xff800000,4
np.float32,0x80000000,0xff800000,4
np.float32,0x7f7fffff,0x42b17218,4
np.float32,0x80800000,0xffc00000,4
np.float32,0xff7fffff,0xffc00000,4
## 1.00f + 0x00000001 ##
np.float32,0x3f800000,0x00000000,4
np.float32,0x3f800001,0x33ffffff,4
np.float32,0x3f800002,0x347ffffe,4
np.float32,0x3f7fffff,0xb3800000,4
np.float32,0x3f7ffffe,0xb4000000,4
np.float32,0x3f7ffffd,0xb4400001,4
np.float32,0x402df853,0x3f7ffffe,4
np.float32,0x402df854,0x3f7fffff,4
np.float32,0x402df855,0x3f800000,4
np.float32,0x402df856,0x3f800001,4
np.float32,0x3ebc5ab0,0xbf800001,4
np.float32,0x3ebc5ab1,0xbf800000,4
np.float32,0x3ebc5ab2,0xbf800000,4
np.float32,0x3ebc5ab3,0xbf7ffffe,4
np.float32,0x423ef575,0x407768ab,4
np.float32,0x427b8c61,0x408485dd,4
np.float32,0x4211e9ee,0x406630b0,4
np.float32,0x424d5c41,0x407c0fed,4
np.float32,0x42be722a,0x4091cc91,4
np.float32,0x42b73d30,0x4090908b,4
np.float32,0x427e48e2,0x4084de7f,4
np.float32,0x428f759b,0x4088bba3,4
np.float32,0x41629069,0x4029a0cc,4
np.float32,0x4272c99d,0x40836379,4
np.float32,0x4d1b7458,0x4197463d,4
np.float32,0x4f10c594,0x41ace2b2,4
np.float32,0x4ea397c2,0x41a85171,4
np.float32,0x4fefa9d1,0x41b6769c,4
np.float32,0x4ebac6ab,0x41a960dc,4
np.float32,0x4f6efb42,0x41b0e535,4
np.float32,0x4e9ab8e7,0x41a7df44,4
np.float32,0x4e81b5d1,0x41a67625,4
np.float32,0x5014d9f2,0x41b832bd,4
np.float32,0x4f02175c,0x41ac07b8,4
np.float32,0x7f034f89,0x42b01c47,4
np.float32,0x7f56d00e,0x42b11849,4
np.float32,0x7f1cd5f6,0x42b0773a,4
np.float32,0x7e979174,0x42af02d7,4
np.float32,0x7f23369f,0x42b08ba2,4
np.float32,0x7f0637ae,0x42b0277d,4
np.float32,0x7efcb6e8,0x42b00897,4
np.float32,0x7f7907c8,0x42b163f6,4
np.float32,0x7e95c4c2,0x42aefcba,4
np.float32,0x7f4577b2,0x42b0ed2d,4
np.float32,0x3f49c92e,0xbe73ae84,4
np.float32,0x3f4a23d1,0xbe71e2f8,4
np.float32,0x3f4abb67,0xbe6ee430,4
np.float32,0x3f48169a,0xbe7c5532,4
np.float32,0x3f47f5fa,0xbe7cfc37,4
np.float32,0x3f488309,0xbe7a2ad8,4
np.float32,0x3f479df4,0xbe7ebf5f,4
np.float32,0x3f47cfff,0xbe7dbec9,4
np.float32,0x3f496704,0xbe75a125,4
np.float32,0x3f478ee8,0xbe7f0c92,4
np.float32,0x3f4a763b,0xbe7041ce,4
np.float32,0x3f47a108,0xbe7eaf94,4
np.float32,0x3f48136c,0xbe7c6578,4
np.float32,0x3f481c17,0xbe7c391c,4
np.float32,0x3f47cd28,0xbe7dcd56,4
np.float32,0x3f478be8,0xbe7f1bf7,4
np.float32,0x3f4c1f8e,0xbe67e367,4
np.float32,0x3f489b0c,0xbe79b03f,4
np.float32,0x3f4934cf,0xbe76a08a,4
np.float32,0x3f4954df,0xbe75fd6a,4
np.float32,0x3f47a3f5,0xbe7ea093,4
np.float32,0x3f4ba4fc,0xbe6a4b02,4
np.float32,0x3f47a0e1,0xbe7eb05c,4
np.float32,0x3f48c30a,0xbe78e42f,4
np.float32,0x3f48cab8,0xbe78bd05,4
np.float32,0x3f4b0569,0xbe6d6ea4,4
np.float32,0x3f47de32,0xbe7d7607,4
np.float32,0x3f477328,0xbe7f9b00,4
np.float32,0x3f496dab,0xbe757f52,4
np.float32,0x3f47662c,0xbe7fddac,4
np.float32,0x3f48ddd8,0xbe785b80,4
np.float32,0x3f481866,0xbe7c4bff,4
np.float32,0x3f48b119,0xbe793fb6,4
np.float32,0x3f48c7e8,0xbe78cb5c,4
np.float32,0x3f4985f6,0xbe7503da,4
np.float32,0x3f483fdf,0xbe7b8212,4
np.float32,0x3f4b1c76,0xbe6cfa67,4
np.float32,0x3f480b2e,0xbe7c8fa8,4
np.float32,0x3f48745f,0xbe7a75bf,4
np.float32,0x3f485bda,0xbe7af308,4
np.float32,0x3f47a660,0xbe7e942c,4
np.float32,0x3f47d4d5,0xbe7da600,4
np.float32,0x3f4b0a26,0xbe6d56be,4
np.float32,0x3f4a4883,0xbe712924,4
np.float32,0x3f4769e7,0xbe7fca84,4
np.float32,0x3f499702,0xbe74ad3f,4
np.float32,0x3f494ab1,0xbe763131,4
np.float32,0x3f476b69,0xbe7fc2c6,4
np.float32,0x3f4884e8,0xbe7a214a,4
np.float32,0x3f486945,0xbe7aae76,4

View file

@ -0,0 +1,660 @@
dtype,input,output,ulperrortol
## +ve denormals ##
np.float32,0x004b4716,0x004b4716,2
np.float32,0x007b2490,0x007b2490,2
np.float32,0x007c99fa,0x007c99fa,2
np.float32,0x00734a0c,0x00734a0c,2
np.float32,0x0070de24,0x0070de24,2
np.float32,0x007fffff,0x007fffff,2
np.float32,0x00000001,0x00000001,2
## -ve denormals ##
np.float32,0x80495d65,0x80495d65,2
np.float32,0x806894f6,0x806894f6,2
np.float32,0x80555a76,0x80555a76,2
np.float32,0x804e1fb8,0x804e1fb8,2
np.float32,0x80687de9,0x80687de9,2
np.float32,0x807fffff,0x807fffff,2
np.float32,0x80000001,0x80000001,2
## +/-0.0f, +/-FLT_MIN +/-FLT_MAX ##
np.float32,0x00000000,0x00000000,2
np.float32,0x80000000,0x80000000,2
np.float32,0x00800000,0x00800000,2
np.float32,0x80800000,0x80800000,2
## 1.00f ##
np.float32,0x3f800000,0x3f576aa4,2
np.float32,0x3f800001,0x3f576aa6,2
np.float32,0x3f800002,0x3f576aa7,2
np.float32,0xc090a8b0,0x3f7b4e48,2
np.float32,0x41ce3184,0x3f192d43,2
np.float32,0xc1d85848,0xbf7161cb,2
np.float32,0x402b8820,0x3ee3f29f,2
np.float32,0x42b4e454,0x3f1d0151,2
np.float32,0x42a67a60,0x3f7ffa4c,2
np.float32,0x41d92388,0x3f67beef,2
np.float32,0x422dd66c,0xbeffb0c1,2
np.float32,0xc28f5be6,0xbf0bae79,2
np.float32,0x41ab2674,0x3f0ffe2b,2
np.float32,0x3f490fdb,0x3f3504f3,2
np.float32,0xbf490fdb,0xbf3504f3,2
np.float32,0x3fc90fdb,0x3f800000,2
np.float32,0xbfc90fdb,0xbf800000,2
np.float32,0x40490fdb,0xb3bbbd2e,2
np.float32,0xc0490fdb,0x33bbbd2e,2
np.float32,0x3fc90fdb,0x3f800000,2
np.float32,0xbfc90fdb,0xbf800000,2
np.float32,0x40490fdb,0xb3bbbd2e,2
np.float32,0xc0490fdb,0x33bbbd2e,2
np.float32,0x40c90fdb,0x343bbd2e,2
np.float32,0xc0c90fdb,0xb43bbd2e,2
np.float32,0x4016cbe4,0x3f3504f3,2
np.float32,0xc016cbe4,0xbf3504f3,2
np.float32,0x4096cbe4,0xbf800000,2
np.float32,0xc096cbe4,0x3f800000,2
np.float32,0x4116cbe4,0xb2ccde2e,2
np.float32,0xc116cbe4,0x32ccde2e,2
np.float32,0x40490fdb,0xb3bbbd2e,2
np.float32,0xc0490fdb,0x33bbbd2e,2
np.float32,0x40c90fdb,0x343bbd2e,2
np.float32,0xc0c90fdb,0xb43bbd2e,2
np.float32,0x41490fdb,0x34bbbd2e,2
np.float32,0xc1490fdb,0xb4bbbd2e,2
np.float32,0x407b53d2,0xbf3504f5,2
np.float32,0xc07b53d2,0x3f3504f5,2
np.float32,0x40fb53d2,0x3f800000,2
np.float32,0xc0fb53d2,0xbf800000,2
np.float32,0x417b53d2,0xb535563d,2
np.float32,0xc17b53d2,0x3535563d,2
np.float32,0x4096cbe4,0xbf800000,2
np.float32,0xc096cbe4,0x3f800000,2
np.float32,0x4116cbe4,0xb2ccde2e,2
np.float32,0xc116cbe4,0x32ccde2e,2
np.float32,0x4196cbe4,0x334cde2e,2
np.float32,0xc196cbe4,0xb34cde2e,2
np.float32,0x40afede0,0xbf3504ef,2
np.float32,0xc0afede0,0x3f3504ef,2
np.float32,0x412fede0,0xbf800000,2
np.float32,0xc12fede0,0x3f800000,2
np.float32,0x41afede0,0xb5b222c4,2
np.float32,0xc1afede0,0x35b222c4,2
np.float32,0x40c90fdb,0x343bbd2e,2
np.float32,0xc0c90fdb,0xb43bbd2e,2
np.float32,0x41490fdb,0x34bbbd2e,2
np.float32,0xc1490fdb,0xb4bbbd2e,2
np.float32,0x41c90fdb,0x353bbd2e,2
np.float32,0xc1c90fdb,0xb53bbd2e,2
np.float32,0x40e231d6,0x3f3504f3,2
np.float32,0xc0e231d6,0xbf3504f3,2
np.float32,0x416231d6,0x3f800000,2
np.float32,0xc16231d6,0xbf800000,2
np.float32,0x41e231d6,0xb399a6a2,2
np.float32,0xc1e231d6,0x3399a6a2,2
np.float32,0x40fb53d2,0x3f800000,2
np.float32,0xc0fb53d2,0xbf800000,2
np.float32,0x417b53d2,0xb535563d,2
np.float32,0xc17b53d2,0x3535563d,2
np.float32,0x41fb53d2,0x35b5563d,2
np.float32,0xc1fb53d2,0xb5b5563d,2
np.float32,0x410a3ae7,0x3f3504eb,2
np.float32,0xc10a3ae7,0xbf3504eb,2
np.float32,0x418a3ae7,0xbf800000,2
np.float32,0xc18a3ae7,0x3f800000,2
np.float32,0x420a3ae7,0xb6308908,2
np.float32,0xc20a3ae7,0x36308908,2
np.float32,0x4116cbe4,0xb2ccde2e,2
np.float32,0xc116cbe4,0x32ccde2e,2
np.float32,0x4196cbe4,0x334cde2e,2
np.float32,0xc196cbe4,0xb34cde2e,2
np.float32,0x4216cbe4,0x33ccde2e,2
np.float32,0xc216cbe4,0xb3ccde2e,2
np.float32,0x41235ce2,0xbf3504f7,2
np.float32,0xc1235ce2,0x3f3504f7,2
np.float32,0x41a35ce2,0x3f800000,2
np.float32,0xc1a35ce2,0xbf800000,2
np.float32,0x42235ce2,0xb5b889b6,2
np.float32,0xc2235ce2,0x35b889b6,2
np.float32,0x412fede0,0xbf800000,2
np.float32,0xc12fede0,0x3f800000,2
np.float32,0x41afede0,0xb5b222c4,2
np.float32,0xc1afede0,0x35b222c4,2
np.float32,0x422fede0,0x363222c4,2
np.float32,0xc22fede0,0xb63222c4,2
np.float32,0x413c7edd,0xbf3504f3,2
np.float32,0xc13c7edd,0x3f3504f3,2
np.float32,0x41bc7edd,0xbf800000,2
np.float32,0xc1bc7edd,0x3f800000,2
np.float32,0x423c7edd,0xb4000add,2
np.float32,0xc23c7edd,0x34000add,2
np.float32,0x41490fdb,0x34bbbd2e,2
np.float32,0xc1490fdb,0xb4bbbd2e,2
np.float32,0x41c90fdb,0x353bbd2e,2
np.float32,0xc1c90fdb,0xb53bbd2e,2
np.float32,0x42490fdb,0x35bbbd2e,2
np.float32,0xc2490fdb,0xb5bbbd2e,2
np.float32,0x4155a0d9,0x3f3504fb,2
np.float32,0xc155a0d9,0xbf3504fb,2
np.float32,0x41d5a0d9,0x3f800000,2
np.float32,0xc1d5a0d9,0xbf800000,2
np.float32,0x4255a0d9,0xb633bc81,2
np.float32,0xc255a0d9,0x3633bc81,2
np.float32,0x416231d6,0x3f800000,2
np.float32,0xc16231d6,0xbf800000,2
np.float32,0x41e231d6,0xb399a6a2,2
np.float32,0xc1e231d6,0x3399a6a2,2
np.float32,0x426231d6,0x3419a6a2,2
np.float32,0xc26231d6,0xb419a6a2,2
np.float32,0x416ec2d4,0x3f3504ef,2
np.float32,0xc16ec2d4,0xbf3504ef,2
np.float32,0x41eec2d4,0xbf800000,2
np.float32,0xc1eec2d4,0x3f800000,2
np.float32,0x426ec2d4,0xb5bef0a7,2
np.float32,0xc26ec2d4,0x35bef0a7,2
np.float32,0x417b53d2,0xb535563d,2
np.float32,0xc17b53d2,0x3535563d,2
np.float32,0x41fb53d2,0x35b5563d,2
np.float32,0xc1fb53d2,0xb5b5563d,2
np.float32,0x427b53d2,0x3635563d,2
np.float32,0xc27b53d2,0xb635563d,2
np.float32,0x4183f268,0xbf3504ff,2
np.float32,0xc183f268,0x3f3504ff,2
np.float32,0x4203f268,0x3f800000,2
np.float32,0xc203f268,0xbf800000,2
np.float32,0x4283f268,0xb6859a13,2
np.float32,0xc283f268,0x36859a13,2
np.float32,0x418a3ae7,0xbf800000,2
np.float32,0xc18a3ae7,0x3f800000,2
np.float32,0x420a3ae7,0xb6308908,2
np.float32,0xc20a3ae7,0x36308908,2
np.float32,0x428a3ae7,0x36b08908,2
np.float32,0xc28a3ae7,0xb6b08908,2
np.float32,0x41908365,0xbf3504f6,2
np.float32,0xc1908365,0x3f3504f6,2
np.float32,0x42108365,0xbf800000,2
np.float32,0xc2108365,0x3f800000,2
np.float32,0x42908365,0x3592200d,2
np.float32,0xc2908365,0xb592200d,2
np.float32,0x4196cbe4,0x334cde2e,2
np.float32,0xc196cbe4,0xb34cde2e,2
np.float32,0x4216cbe4,0x33ccde2e,2
np.float32,0xc216cbe4,0xb3ccde2e,2
np.float32,0x4296cbe4,0x344cde2e,2
np.float32,0xc296cbe4,0xb44cde2e,2
np.float32,0x419d1463,0x3f3504f8,2
np.float32,0xc19d1463,0xbf3504f8,2
np.float32,0x421d1463,0x3f800000,2
np.float32,0xc21d1463,0xbf800000,2
np.float32,0x429d1463,0xb5c55799,2
np.float32,0xc29d1463,0x35c55799,2
np.float32,0x41a35ce2,0x3f800000,2
np.float32,0xc1a35ce2,0xbf800000,2
np.float32,0x42235ce2,0xb5b889b6,2
np.float32,0xc2235ce2,0x35b889b6,2
np.float32,0x42a35ce2,0x363889b6,2
np.float32,0xc2a35ce2,0xb63889b6,2
np.float32,0x41a9a561,0x3f3504e7,2
np.float32,0xc1a9a561,0xbf3504e7,2
np.float32,0x4229a561,0xbf800000,2
np.float32,0xc229a561,0x3f800000,2
np.float32,0x42a9a561,0xb68733d0,2
np.float32,0xc2a9a561,0x368733d0,2
np.float32,0x41afede0,0xb5b222c4,2
np.float32,0xc1afede0,0x35b222c4,2
np.float32,0x422fede0,0x363222c4,2
np.float32,0xc22fede0,0xb63222c4,2
np.float32,0x42afede0,0x36b222c4,2
np.float32,0xc2afede0,0xb6b222c4,2
np.float32,0x41b6365e,0xbf3504f0,2
np.float32,0xc1b6365e,0x3f3504f0,2
np.float32,0x4236365e,0x3f800000,2
np.float32,0xc236365e,0xbf800000,2
np.float32,0x42b6365e,0x358bb91c,2
np.float32,0xc2b6365e,0xb58bb91c,2
np.float32,0x41bc7edd,0xbf800000,2
np.float32,0xc1bc7edd,0x3f800000,2
np.float32,0x423c7edd,0xb4000add,2
np.float32,0xc23c7edd,0x34000add,2
np.float32,0x42bc7edd,0x34800add,2
np.float32,0xc2bc7edd,0xb4800add,2
np.float32,0x41c2c75c,0xbf3504ef,2
np.float32,0xc1c2c75c,0x3f3504ef,2
np.float32,0x4242c75c,0xbf800000,2
np.float32,0xc242c75c,0x3f800000,2
np.float32,0x42c2c75c,0xb5cbbe8a,2
np.float32,0xc2c2c75c,0x35cbbe8a,2
np.float32,0x41c90fdb,0x353bbd2e,2
np.float32,0xc1c90fdb,0xb53bbd2e,2
np.float32,0x42490fdb,0x35bbbd2e,2
np.float32,0xc2490fdb,0xb5bbbd2e,2
np.float32,0x42c90fdb,0x363bbd2e,2
np.float32,0xc2c90fdb,0xb63bbd2e,2
np.float32,0x41cf585a,0x3f3504ff,2
np.float32,0xc1cf585a,0xbf3504ff,2
np.float32,0x424f585a,0x3f800000,2
np.float32,0xc24f585a,0xbf800000,2
np.float32,0x42cf585a,0xb688cd8c,2
np.float32,0xc2cf585a,0x3688cd8c,2
np.float32,0x41d5a0d9,0x3f800000,2
np.float32,0xc1d5a0d9,0xbf800000,2
np.float32,0x4255a0d9,0xb633bc81,2
np.float32,0xc255a0d9,0x3633bc81,2
np.float32,0x42d5a0d9,0x36b3bc81,2
np.float32,0xc2d5a0d9,0xb6b3bc81,2
np.float32,0x41dbe958,0x3f3504e0,2
np.float32,0xc1dbe958,0xbf3504e0,2
np.float32,0x425be958,0xbf800000,2
np.float32,0xc25be958,0x3f800000,2
np.float32,0x42dbe958,0xb6deab75,2
np.float32,0xc2dbe958,0x36deab75,2
np.float32,0x41e231d6,0xb399a6a2,2
np.float32,0xc1e231d6,0x3399a6a2,2
np.float32,0x426231d6,0x3419a6a2,2
np.float32,0xc26231d6,0xb419a6a2,2
np.float32,0x42e231d6,0x3499a6a2,2
np.float32,0xc2e231d6,0xb499a6a2,2
np.float32,0x41e87a55,0xbf3504f8,2
np.float32,0xc1e87a55,0x3f3504f8,2
np.float32,0x42687a55,0x3f800000,2
np.float32,0xc2687a55,0xbf800000,2
np.float32,0x42e87a55,0xb5d2257b,2
np.float32,0xc2e87a55,0x35d2257b,2
np.float32,0x41eec2d4,0xbf800000,2
np.float32,0xc1eec2d4,0x3f800000,2
np.float32,0x426ec2d4,0xb5bef0a7,2
np.float32,0xc26ec2d4,0x35bef0a7,2
np.float32,0x42eec2d4,0x363ef0a7,2
np.float32,0xc2eec2d4,0xb63ef0a7,2
np.float32,0x41f50b53,0xbf3504e7,2
np.float32,0xc1f50b53,0x3f3504e7,2
np.float32,0x42750b53,0xbf800000,2
np.float32,0xc2750b53,0x3f800000,2
np.float32,0x42f50b53,0xb68a6748,2
np.float32,0xc2f50b53,0x368a6748,2
np.float32,0x41fb53d2,0x35b5563d,2
np.float32,0xc1fb53d2,0xb5b5563d,2
np.float32,0x427b53d2,0x3635563d,2
np.float32,0xc27b53d2,0xb635563d,2
np.float32,0x42fb53d2,0x36b5563d,2
np.float32,0xc2fb53d2,0xb6b5563d,2
np.float32,0x4200ce28,0x3f3504f0,2
np.float32,0xc200ce28,0xbf3504f0,2
np.float32,0x4280ce28,0x3f800000,2
np.float32,0xc280ce28,0xbf800000,2
np.float32,0x4300ce28,0x357dd672,2
np.float32,0xc300ce28,0xb57dd672,2
np.float32,0x4203f268,0x3f800000,2
np.float32,0xc203f268,0xbf800000,2
np.float32,0x4283f268,0xb6859a13,2
np.float32,0xc283f268,0x36859a13,2
np.float32,0x4303f268,0x37059a13,2
np.float32,0xc303f268,0xb7059a13,2
np.float32,0x420716a7,0x3f3504ee,2
np.float32,0xc20716a7,0xbf3504ee,2
np.float32,0x428716a7,0xbf800000,2
np.float32,0xc28716a7,0x3f800000,2
np.float32,0x430716a7,0xb5d88c6d,2
np.float32,0xc30716a7,0x35d88c6d,2
np.float32,0x420a3ae7,0xb6308908,2
np.float32,0xc20a3ae7,0x36308908,2
np.float32,0x428a3ae7,0x36b08908,2
np.float32,0xc28a3ae7,0xb6b08908,2
np.float32,0x430a3ae7,0x37308908,2
np.float32,0xc30a3ae7,0xb7308908,2
np.float32,0x420d5f26,0xbf350500,2
np.float32,0xc20d5f26,0x3f350500,2
np.float32,0x428d5f26,0x3f800000,2
np.float32,0xc28d5f26,0xbf800000,2
np.float32,0x430d5f26,0xb68c0105,2
np.float32,0xc30d5f26,0x368c0105,2
np.float32,0x42108365,0xbf800000,2
np.float32,0xc2108365,0x3f800000,2
np.float32,0x42908365,0x3592200d,2
np.float32,0xc2908365,0xb592200d,2
np.float32,0x43108365,0xb612200d,2
np.float32,0xc3108365,0x3612200d,2
np.float32,0x4213a7a5,0xbf3504df,2
np.float32,0xc213a7a5,0x3f3504df,2
np.float32,0x4293a7a5,0xbf800000,2
np.float32,0xc293a7a5,0x3f800000,2
np.float32,0x4313a7a5,0xb6e1deee,2
np.float32,0xc313a7a5,0x36e1deee,2
np.float32,0x4216cbe4,0x33ccde2e,2
np.float32,0xc216cbe4,0xb3ccde2e,2
np.float32,0x4296cbe4,0x344cde2e,2
np.float32,0xc296cbe4,0xb44cde2e,2
np.float32,0x4316cbe4,0x34ccde2e,2
np.float32,0xc316cbe4,0xb4ccde2e,2
np.float32,0x4219f024,0x3f35050f,2
np.float32,0xc219f024,0xbf35050f,2
np.float32,0x4299f024,0x3f800000,2
np.float32,0xc299f024,0xbf800000,2
np.float32,0x4319f024,0xb71bde6c,2
np.float32,0xc319f024,0x371bde6c,2
np.float32,0x421d1463,0x3f800000,2
np.float32,0xc21d1463,0xbf800000,2
np.float32,0x429d1463,0xb5c55799,2
np.float32,0xc29d1463,0x35c55799,2
np.float32,0x431d1463,0x36455799,2
np.float32,0xc31d1463,0xb6455799,2
np.float32,0x422038a3,0x3f3504d0,2
np.float32,0xc22038a3,0xbf3504d0,2
np.float32,0x42a038a3,0xbf800000,2
np.float32,0xc2a038a3,0x3f800000,2
np.float32,0x432038a3,0xb746cd61,2
np.float32,0xc32038a3,0x3746cd61,2
np.float32,0x42235ce2,0xb5b889b6,2
np.float32,0xc2235ce2,0x35b889b6,2
np.float32,0x42a35ce2,0x363889b6,2
np.float32,0xc2a35ce2,0xb63889b6,2
np.float32,0x43235ce2,0x36b889b6,2
np.float32,0xc3235ce2,0xb6b889b6,2
np.float32,0x42268121,0xbf3504f1,2
np.float32,0xc2268121,0x3f3504f1,2
np.float32,0x42a68121,0x3f800000,2
np.float32,0xc2a68121,0xbf800000,2
np.float32,0x43268121,0x35643aac,2
np.float32,0xc3268121,0xb5643aac,2
np.float32,0x4229a561,0xbf800000,2
np.float32,0xc229a561,0x3f800000,2
np.float32,0x42a9a561,0xb68733d0,2
np.float32,0xc2a9a561,0x368733d0,2
np.float32,0x4329a561,0x370733d0,2
np.float32,0xc329a561,0xb70733d0,2
np.float32,0x422cc9a0,0xbf3504ee,2
np.float32,0xc22cc9a0,0x3f3504ee,2
np.float32,0x42acc9a0,0xbf800000,2
np.float32,0xc2acc9a0,0x3f800000,2
np.float32,0x432cc9a0,0xb5e55a50,2
np.float32,0xc32cc9a0,0x35e55a50,2
np.float32,0x422fede0,0x363222c4,2
np.float32,0xc22fede0,0xb63222c4,2
np.float32,0x42afede0,0x36b222c4,2
np.float32,0xc2afede0,0xb6b222c4,2
np.float32,0x432fede0,0x373222c4,2
np.float32,0xc32fede0,0xb73222c4,2
np.float32,0x4233121f,0x3f350500,2
np.float32,0xc233121f,0xbf350500,2
np.float32,0x42b3121f,0x3f800000,2
np.float32,0xc2b3121f,0xbf800000,2
np.float32,0x4333121f,0xb68f347d,2
np.float32,0xc333121f,0x368f347d,2
np.float32,0x4236365e,0x3f800000,2
np.float32,0xc236365e,0xbf800000,2
np.float32,0x42b6365e,0x358bb91c,2
np.float32,0xc2b6365e,0xb58bb91c,2
np.float32,0x4336365e,0xb60bb91c,2
np.float32,0xc336365e,0x360bb91c,2
np.float32,0x42395a9e,0x3f3504df,2
np.float32,0xc2395a9e,0xbf3504df,2
np.float32,0x42b95a9e,0xbf800000,2
np.float32,0xc2b95a9e,0x3f800000,2
np.float32,0x43395a9e,0xb6e51267,2
np.float32,0xc3395a9e,0x36e51267,2
np.float32,0x423c7edd,0xb4000add,2
np.float32,0xc23c7edd,0x34000add,2
np.float32,0x42bc7edd,0x34800add,2
np.float32,0xc2bc7edd,0xb4800add,2
np.float32,0x433c7edd,0x35000add,2
np.float32,0xc33c7edd,0xb5000add,2
np.float32,0x423fa31d,0xbf35050f,2
np.float32,0xc23fa31d,0x3f35050f,2
np.float32,0x42bfa31d,0x3f800000,2
np.float32,0xc2bfa31d,0xbf800000,2
np.float32,0x433fa31d,0xb71d7828,2
np.float32,0xc33fa31d,0x371d7828,2
np.float32,0x4242c75c,0xbf800000,2
np.float32,0xc242c75c,0x3f800000,2
np.float32,0x42c2c75c,0xb5cbbe8a,2
np.float32,0xc2c2c75c,0x35cbbe8a,2
np.float32,0x4342c75c,0x364bbe8a,2
np.float32,0xc342c75c,0xb64bbe8a,2
np.float32,0x4245eb9c,0xbf3504d0,2
np.float32,0xc245eb9c,0x3f3504d0,2
np.float32,0x42c5eb9c,0xbf800000,2
np.float32,0xc2c5eb9c,0x3f800000,2
np.float32,0x4345eb9c,0xb748671d,2
np.float32,0xc345eb9c,0x3748671d,2
np.float32,0x42490fdb,0x35bbbd2e,2
np.float32,0xc2490fdb,0xb5bbbd2e,2
np.float32,0x42c90fdb,0x363bbd2e,2
np.float32,0xc2c90fdb,0xb63bbd2e,2
np.float32,0x43490fdb,0x36bbbd2e,2
np.float32,0xc3490fdb,0xb6bbbd2e,2
np.float32,0x424c341a,0x3f3504f1,2
np.float32,0xc24c341a,0xbf3504f1,2
np.float32,0x42cc341a,0x3f800000,2
np.float32,0xc2cc341a,0xbf800000,2
np.float32,0x434c341a,0x354a9ee6,2
np.float32,0xc34c341a,0xb54a9ee6,2
np.float32,0x424f585a,0x3f800000,2
np.float32,0xc24f585a,0xbf800000,2
np.float32,0x42cf585a,0xb688cd8c,2
np.float32,0xc2cf585a,0x3688cd8c,2
np.float32,0x434f585a,0x3708cd8c,2
np.float32,0xc34f585a,0xb708cd8c,2
np.float32,0x42527c99,0x3f3504ee,2
np.float32,0xc2527c99,0xbf3504ee,2
np.float32,0x42d27c99,0xbf800000,2
np.float32,0xc2d27c99,0x3f800000,2
np.float32,0x43527c99,0xb5f22833,2
np.float32,0xc3527c99,0x35f22833,2
np.float32,0x4255a0d9,0xb633bc81,2
np.float32,0xc255a0d9,0x3633bc81,2
np.float32,0x42d5a0d9,0x36b3bc81,2
np.float32,0xc2d5a0d9,0xb6b3bc81,2
np.float32,0x4355a0d9,0x3733bc81,2
np.float32,0xc355a0d9,0xb733bc81,2
np.float32,0x4258c518,0xbf350500,2
np.float32,0xc258c518,0x3f350500,2
np.float32,0x42d8c518,0x3f800000,2
np.float32,0xc2d8c518,0xbf800000,2
np.float32,0x4358c518,0xb69267f6,2
np.float32,0xc358c518,0x369267f6,2
np.float32,0x425be958,0xbf800000,2
np.float32,0xc25be958,0x3f800000,2
np.float32,0x42dbe958,0xb6deab75,2
np.float32,0xc2dbe958,0x36deab75,2
np.float32,0x435be958,0x375eab75,2
np.float32,0xc35be958,0xb75eab75,2
np.float32,0x425f0d97,0xbf3504df,2
np.float32,0xc25f0d97,0x3f3504df,2
np.float32,0x42df0d97,0xbf800000,2
np.float32,0xc2df0d97,0x3f800000,2
np.float32,0x435f0d97,0xb6e845e0,2
np.float32,0xc35f0d97,0x36e845e0,2
np.float32,0x426231d6,0x3419a6a2,2
np.float32,0xc26231d6,0xb419a6a2,2
np.float32,0x42e231d6,0x3499a6a2,2
np.float32,0xc2e231d6,0xb499a6a2,2
np.float32,0x436231d6,0x3519a6a2,2
np.float32,0xc36231d6,0xb519a6a2,2
np.float32,0x42655616,0x3f35050f,2
np.float32,0xc2655616,0xbf35050f,2
np.float32,0x42e55616,0x3f800000,2
np.float32,0xc2e55616,0xbf800000,2
np.float32,0x43655616,0xb71f11e5,2
np.float32,0xc3655616,0x371f11e5,2
np.float32,0x42687a55,0x3f800000,2
np.float32,0xc2687a55,0xbf800000,2
np.float32,0x42e87a55,0xb5d2257b,2
np.float32,0xc2e87a55,0x35d2257b,2
np.float32,0x43687a55,0x3652257b,2
np.float32,0xc3687a55,0xb652257b,2
np.float32,0x426b9e95,0x3f3504cf,2
np.float32,0xc26b9e95,0xbf3504cf,2
np.float32,0x42eb9e95,0xbf800000,2
np.float32,0xc2eb9e95,0x3f800000,2
np.float32,0x436b9e95,0xb74a00d9,2
np.float32,0xc36b9e95,0x374a00d9,2
np.float32,0x426ec2d4,0xb5bef0a7,2
np.float32,0xc26ec2d4,0x35bef0a7,2
np.float32,0x42eec2d4,0x363ef0a7,2
np.float32,0xc2eec2d4,0xb63ef0a7,2
np.float32,0x436ec2d4,0x36bef0a7,2
np.float32,0xc36ec2d4,0xb6bef0a7,2
np.float32,0x4271e713,0xbf3504f1,2
np.float32,0xc271e713,0x3f3504f1,2
np.float32,0x42f1e713,0x3f800000,2
np.float32,0xc2f1e713,0xbf800000,2
np.float32,0x4371e713,0x35310321,2
np.float32,0xc371e713,0xb5310321,2
np.float32,0x42750b53,0xbf800000,2
np.float32,0xc2750b53,0x3f800000,2
np.float32,0x42f50b53,0xb68a6748,2
np.float32,0xc2f50b53,0x368a6748,2
np.float32,0x43750b53,0x370a6748,2
np.float32,0xc3750b53,0xb70a6748,2
np.float32,0x42782f92,0xbf3504ee,2
np.float32,0xc2782f92,0x3f3504ee,2
np.float32,0x42f82f92,0xbf800000,2
np.float32,0xc2f82f92,0x3f800000,2
np.float32,0x43782f92,0xb5fef616,2
np.float32,0xc3782f92,0x35fef616,2
np.float32,0x427b53d2,0x3635563d,2
np.float32,0xc27b53d2,0xb635563d,2
np.float32,0x42fb53d2,0x36b5563d,2
np.float32,0xc2fb53d2,0xb6b5563d,2
np.float32,0x437b53d2,0x3735563d,2
np.float32,0xc37b53d2,0xb735563d,2
np.float32,0x427e7811,0x3f350500,2
np.float32,0xc27e7811,0xbf350500,2
np.float32,0x42fe7811,0x3f800000,2
np.float32,0xc2fe7811,0xbf800000,2
np.float32,0x437e7811,0xb6959b6f,2
np.float32,0xc37e7811,0x36959b6f,2
np.float32,0x4280ce28,0x3f800000,2
np.float32,0xc280ce28,0xbf800000,2
np.float32,0x4300ce28,0x357dd672,2
np.float32,0xc300ce28,0xb57dd672,2
np.float32,0x4380ce28,0xb5fdd672,2
np.float32,0xc380ce28,0x35fdd672,2
np.float32,0x42826048,0x3f3504de,2
np.float32,0xc2826048,0xbf3504de,2
np.float32,0x43026048,0xbf800000,2
np.float32,0xc3026048,0x3f800000,2
np.float32,0x43826048,0xb6eb7958,2
np.float32,0xc3826048,0x36eb7958,2
np.float32,0x4283f268,0xb6859a13,2
np.float32,0xc283f268,0x36859a13,2
np.float32,0x4303f268,0x37059a13,2
np.float32,0xc303f268,0xb7059a13,2
np.float32,0x4383f268,0x37859a13,2
np.float32,0xc383f268,0xb7859a13,2
np.float32,0x42858487,0xbf3504e2,2
np.float32,0xc2858487,0x3f3504e2,2
np.float32,0x43058487,0x3f800000,2
np.float32,0xc3058487,0xbf800000,2
np.float32,0x43858487,0x36bea8be,2
np.float32,0xc3858487,0xb6bea8be,2
np.float32,0x428716a7,0xbf800000,2
np.float32,0xc28716a7,0x3f800000,2
np.float32,0x430716a7,0xb5d88c6d,2
np.float32,0xc30716a7,0x35d88c6d,2
np.float32,0x438716a7,0x36588c6d,2
np.float32,0xc38716a7,0xb6588c6d,2
np.float32,0x4288a8c7,0xbf3504cf,2
np.float32,0xc288a8c7,0x3f3504cf,2
np.float32,0x4308a8c7,0xbf800000,2
np.float32,0xc308a8c7,0x3f800000,2
np.float32,0x4388a8c7,0xb74b9a96,2
np.float32,0xc388a8c7,0x374b9a96,2
np.float32,0x428a3ae7,0x36b08908,2
np.float32,0xc28a3ae7,0xb6b08908,2
np.float32,0x430a3ae7,0x37308908,2
np.float32,0xc30a3ae7,0xb7308908,2
np.float32,0x438a3ae7,0x37b08908,2
np.float32,0xc38a3ae7,0xb7b08908,2
np.float32,0x428bcd06,0x3f3504f2,2
np.float32,0xc28bcd06,0xbf3504f2,2
np.float32,0x430bcd06,0x3f800000,2
np.float32,0xc30bcd06,0xbf800000,2
np.float32,0x438bcd06,0x3517675b,2
np.float32,0xc38bcd06,0xb517675b,2
np.float32,0x428d5f26,0x3f800000,2
np.float32,0xc28d5f26,0xbf800000,2
np.float32,0x430d5f26,0xb68c0105,2
np.float32,0xc30d5f26,0x368c0105,2
np.float32,0x438d5f26,0x370c0105,2
np.float32,0xc38d5f26,0xb70c0105,2
np.float32,0x428ef146,0x3f3504c0,2
np.float32,0xc28ef146,0xbf3504c0,2
np.float32,0x430ef146,0xbf800000,2
np.float32,0xc30ef146,0x3f800000,2
np.float32,0x438ef146,0xb790bc40,2
np.float32,0xc38ef146,0x3790bc40,2
np.float32,0x42908365,0x3592200d,2
np.float32,0xc2908365,0xb592200d,2
np.float32,0x43108365,0xb612200d,2
np.float32,0xc3108365,0x3612200d,2
np.float32,0x43908365,0xb692200d,2
np.float32,0xc3908365,0x3692200d,2
np.float32,0x42921585,0xbf350501,2
np.float32,0xc2921585,0x3f350501,2
np.float32,0x43121585,0x3f800000,2
np.float32,0xc3121585,0xbf800000,2
np.float32,0x43921585,0xb698cee8,2
np.float32,0xc3921585,0x3698cee8,2
np.float32,0x4293a7a5,0xbf800000,2
np.float32,0xc293a7a5,0x3f800000,2
np.float32,0x4313a7a5,0xb6e1deee,2
np.float32,0xc313a7a5,0x36e1deee,2
np.float32,0x4393a7a5,0x3761deee,2
np.float32,0xc393a7a5,0xb761deee,2
np.float32,0x429539c5,0xbf3504b1,2
np.float32,0xc29539c5,0x3f3504b1,2
np.float32,0x431539c5,0xbf800000,2
np.float32,0xc31539c5,0x3f800000,2
np.float32,0x439539c5,0xb7bbab34,2
np.float32,0xc39539c5,0x37bbab34,2
np.float32,0x4296cbe4,0x344cde2e,2
np.float32,0xc296cbe4,0xb44cde2e,2
np.float32,0x4316cbe4,0x34ccde2e,2
np.float32,0xc316cbe4,0xb4ccde2e,2
np.float32,0x4396cbe4,0x354cde2e,2
np.float32,0xc396cbe4,0xb54cde2e,2
np.float32,0x42985e04,0x3f350510,2
np.float32,0xc2985e04,0xbf350510,2
np.float32,0x43185e04,0x3f800000,2
np.float32,0xc3185e04,0xbf800000,2
np.float32,0x43985e04,0xb722455d,2
np.float32,0xc3985e04,0x3722455d,2
np.float32,0x4299f024,0x3f800000,2
np.float32,0xc299f024,0xbf800000,2
np.float32,0x4319f024,0xb71bde6c,2
np.float32,0xc319f024,0x371bde6c,2
np.float32,0x4399f024,0x379bde6c,2
np.float32,0xc399f024,0xb79bde6c,2
np.float32,0x429b8243,0x3f3504fc,2
np.float32,0xc29b8243,0xbf3504fc,2
np.float32,0x431b8243,0xbf800000,2
np.float32,0xc31b8243,0x3f800000,2
np.float32,0x439b8243,0x364b2eb8,2
np.float32,0xc39b8243,0xb64b2eb8,2
np.float32,0x435b2047,0xbf350525,2
np.float32,0x42a038a2,0xbf800000,2
np.float32,0x432038a2,0x3664ca7e,2
np.float32,0x4345eb9b,0x365e638c,2
np.float32,0x42c5eb9b,0xbf800000,2
np.float32,0x42eb9e94,0xbf800000,2
np.float32,0x4350ea79,0x3f800000,2
np.float32,0x42dbe957,0x3585522a,2
np.float32,0x425be957,0xbf800000,2
np.float32,0x435be957,0xb605522a,2
np.float32,0x476362a2,0xbd7ff911,2
np.float32,0x464c99a4,0x3e7f4d41,2
np.float32,0x4471f73d,0x3e7fe1b0,2
np.float32,0x445a6752,0x3e7ef367,2
np.float32,0x474fa400,0x3e7f9fcd,2
np.float32,0x45c1e72f,0xbe7fc7af,2
np.float32,0x4558c91d,0x3e7e9f31,2
np.float32,0x43784f94,0xbdff6654,2
np.float32,0x466e8500,0xbe7ea0a3,2
np.float32,0x468e1c25,0x3e7e22fb,2
np.float32,0x44ea6cfc,0x3dff70c3,2
np.float32,0x4605126c,0x3e7f89ef,2
np.float32,0x4788b3c6,0xbb87d853,2
np.float32,0x4531b042,0x3dffd163,2
np.float32,0x43f1f71d,0x3dfff387,2
np.float32,0x462c3fa5,0xbd7fe13d,2
np.float32,0x441c5354,0xbdff76b4,2
np.float32,0x44908b69,0x3e7dcf0d,2
np.float32,0x478813ad,0xbe7e9d80,2
np.float32,0x441c4351,0x3dff937b,2

View file

@ -0,0 +1,42 @@
"""
Tests of the ._exceptions module. Primarily for exercising the __str__ methods.
"""
import numpy as np
_ArrayMemoryError = np.core._exceptions._ArrayMemoryError
class TestArrayMemoryError:
def test_str(self):
e = _ArrayMemoryError((1023,), np.dtype(np.uint8))
str(e) # not crashing is enough
# testing these properties is easier than testing the full string repr
def test__size_to_string(self):
""" Test e._size_to_string """
f = _ArrayMemoryError._size_to_string
Ki = 1024
assert f(0) == '0 bytes'
assert f(1) == '1 bytes'
assert f(1023) == '1023 bytes'
assert f(Ki) == '1.00 KiB'
assert f(Ki+1) == '1.00 KiB'
assert f(10*Ki) == '10.0 KiB'
assert f(int(999.4*Ki)) == '999. KiB'
assert f(int(1023.4*Ki)) == '1023. KiB'
assert f(int(1023.5*Ki)) == '1.00 MiB'
assert f(Ki*Ki) == '1.00 MiB'
# 1023.9999 Mib should round to 1 GiB
assert f(int(Ki*Ki*Ki*0.9999)) == '1.00 GiB'
assert f(Ki*Ki*Ki*Ki*Ki*Ki) == '1.00 EiB'
# larger than sys.maxsize, adding larger prefices isn't going to help
# anyway.
assert f(Ki*Ki*Ki*Ki*Ki*Ki*123456) == '123456. EiB'
def test__total_size(self):
""" Test e._total_size """
e = _ArrayMemoryError((1,), np.dtype(np.uint8))
assert e._total_size == 1
e = _ArrayMemoryError((2, 4), np.dtype((np.uint64, 16)))
assert e._total_size == 1024

View file

@ -0,0 +1,54 @@
from numpy.testing import assert_
import numbers
import numpy as np
from numpy.core.numerictypes import sctypes
class TestABC:
def test_abstract(self):
assert_(issubclass(np.number, numbers.Number))
assert_(issubclass(np.inexact, numbers.Complex))
assert_(issubclass(np.complexfloating, numbers.Complex))
assert_(issubclass(np.floating, numbers.Real))
assert_(issubclass(np.integer, numbers.Integral))
assert_(issubclass(np.signedinteger, numbers.Integral))
assert_(issubclass(np.unsignedinteger, numbers.Integral))
def test_floats(self):
for t in sctypes['float']:
assert_(isinstance(t(), numbers.Real),
"{0} is not instance of Real".format(t.__name__))
assert_(issubclass(t, numbers.Real),
"{0} is not subclass of Real".format(t.__name__))
assert_(not isinstance(t(), numbers.Rational),
"{0} is instance of Rational".format(t.__name__))
assert_(not issubclass(t, numbers.Rational),
"{0} is subclass of Rational".format(t.__name__))
def test_complex(self):
for t in sctypes['complex']:
assert_(isinstance(t(), numbers.Complex),
"{0} is not instance of Complex".format(t.__name__))
assert_(issubclass(t, numbers.Complex),
"{0} is not subclass of Complex".format(t.__name__))
assert_(not isinstance(t(), numbers.Real),
"{0} is instance of Real".format(t.__name__))
assert_(not issubclass(t, numbers.Real),
"{0} is subclass of Real".format(t.__name__))
def test_int(self):
for t in sctypes['int']:
assert_(isinstance(t(), numbers.Integral),
"{0} is not instance of Integral".format(t.__name__))
assert_(issubclass(t, numbers.Integral),
"{0} is not subclass of Integral".format(t.__name__))
def test_uint(self):
for t in sctypes['uint']:
assert_(isinstance(t(), numbers.Integral),
"{0} is not instance of Integral".format(t.__name__))
assert_(issubclass(t, numbers.Integral),
"{0} is not subclass of Integral".format(t.__name__))

View file

@ -0,0 +1,567 @@
import sys
import numpy as np
from numpy.core._rational_tests import rational
import pytest
from numpy.testing import (
assert_, assert_equal, assert_array_equal, assert_raises, assert_warns,
HAS_REFCOUNT
)
# Switch between new behaviour when NPY_RELAXED_STRIDES_CHECKING is set.
NPY_RELAXED_STRIDES_CHECKING = np.ones((10, 1), order='C').flags.f_contiguous
def test_array_array():
tobj = type(object)
ones11 = np.ones((1, 1), np.float64)
tndarray = type(ones11)
# Test is_ndarray
assert_equal(np.array(ones11, dtype=np.float64), ones11)
if HAS_REFCOUNT:
old_refcount = sys.getrefcount(tndarray)
np.array(ones11)
assert_equal(old_refcount, sys.getrefcount(tndarray))
# test None
assert_equal(np.array(None, dtype=np.float64),
np.array(np.nan, dtype=np.float64))
if HAS_REFCOUNT:
old_refcount = sys.getrefcount(tobj)
np.array(None, dtype=np.float64)
assert_equal(old_refcount, sys.getrefcount(tobj))
# test scalar
assert_equal(np.array(1.0, dtype=np.float64),
np.ones((), dtype=np.float64))
if HAS_REFCOUNT:
old_refcount = sys.getrefcount(np.float64)
np.array(np.array(1.0, dtype=np.float64), dtype=np.float64)
assert_equal(old_refcount, sys.getrefcount(np.float64))
# test string
S2 = np.dtype((bytes, 2))
S3 = np.dtype((bytes, 3))
S5 = np.dtype((bytes, 5))
assert_equal(np.array(b"1.0", dtype=np.float64),
np.ones((), dtype=np.float64))
assert_equal(np.array(b"1.0").dtype, S3)
assert_equal(np.array(b"1.0", dtype=bytes).dtype, S3)
assert_equal(np.array(b"1.0", dtype=S2), np.array(b"1."))
assert_equal(np.array(b"1", dtype=S5), np.ones((), dtype=S5))
# test string
U2 = np.dtype((str, 2))
U3 = np.dtype((str, 3))
U5 = np.dtype((str, 5))
assert_equal(np.array("1.0", dtype=np.float64),
np.ones((), dtype=np.float64))
assert_equal(np.array("1.0").dtype, U3)
assert_equal(np.array("1.0", dtype=str).dtype, U3)
assert_equal(np.array("1.0", dtype=U2), np.array(str("1.")))
assert_equal(np.array("1", dtype=U5), np.ones((), dtype=U5))
builtins = getattr(__builtins__, '__dict__', __builtins__)
assert_(hasattr(builtins, 'get'))
# test memoryview
dat = np.array(memoryview(b'1.0'), dtype=np.float64)
assert_equal(dat, [49.0, 46.0, 48.0])
assert_(dat.dtype.type is np.float64)
dat = np.array(memoryview(b'1.0'))
assert_equal(dat, [49, 46, 48])
assert_(dat.dtype.type is np.uint8)
# test array interface
a = np.array(100.0, dtype=np.float64)
o = type("o", (object,),
dict(__array_interface__=a.__array_interface__))
assert_equal(np.array(o, dtype=np.float64), a)
# test array_struct interface
a = np.array([(1, 4.0, 'Hello'), (2, 6.0, 'World')],
dtype=[('f0', int), ('f1', float), ('f2', str)])
o = type("o", (object,),
dict(__array_struct__=a.__array_struct__))
## wasn't what I expected... is np.array(o) supposed to equal a ?
## instead we get a array([...], dtype=">V18")
assert_equal(bytes(np.array(o).data), bytes(a.data))
# test array
o = type("o", (object,),
dict(__array__=lambda *x: np.array(100.0, dtype=np.float64)))()
assert_equal(np.array(o, dtype=np.float64), np.array(100.0, np.float64))
# test recursion
nested = 1.5
for i in range(np.MAXDIMS):
nested = [nested]
# no error
np.array(nested)
# Exceeds recursion limit
assert_raises(ValueError, np.array, [nested], dtype=np.float64)
# Try with lists...
assert_equal(np.array([None] * 10, dtype=np.float64),
np.full((10,), np.nan, dtype=np.float64))
assert_equal(np.array([[None]] * 10, dtype=np.float64),
np.full((10, 1), np.nan, dtype=np.float64))
assert_equal(np.array([[None] * 10], dtype=np.float64),
np.full((1, 10), np.nan, dtype=np.float64))
assert_equal(np.array([[None] * 10] * 10, dtype=np.float64),
np.full((10, 10), np.nan, dtype=np.float64))
assert_equal(np.array([1.0] * 10, dtype=np.float64),
np.ones((10,), dtype=np.float64))
assert_equal(np.array([[1.0]] * 10, dtype=np.float64),
np.ones((10, 1), dtype=np.float64))
assert_equal(np.array([[1.0] * 10], dtype=np.float64),
np.ones((1, 10), dtype=np.float64))
assert_equal(np.array([[1.0] * 10] * 10, dtype=np.float64),
np.ones((10, 10), dtype=np.float64))
# Try with tuples
assert_equal(np.array((None,) * 10, dtype=np.float64),
np.full((10,), np.nan, dtype=np.float64))
assert_equal(np.array([(None,)] * 10, dtype=np.float64),
np.full((10, 1), np.nan, dtype=np.float64))
assert_equal(np.array([(None,) * 10], dtype=np.float64),
np.full((1, 10), np.nan, dtype=np.float64))
assert_equal(np.array([(None,) * 10] * 10, dtype=np.float64),
np.full((10, 10), np.nan, dtype=np.float64))
assert_equal(np.array((1.0,) * 10, dtype=np.float64),
np.ones((10,), dtype=np.float64))
assert_equal(np.array([(1.0,)] * 10, dtype=np.float64),
np.ones((10, 1), dtype=np.float64))
assert_equal(np.array([(1.0,) * 10], dtype=np.float64),
np.ones((1, 10), dtype=np.float64))
assert_equal(np.array([(1.0,) * 10] * 10, dtype=np.float64),
np.ones((10, 10), dtype=np.float64))
@pytest.mark.parametrize("array", [True, False])
def test_array_impossible_casts(array):
# All builtin types can forst cast as least theoretically
# but user dtypes cannot necessarily.
rt = rational(1, 2)
if array:
rt = np.array(rt)
with assert_raises(ValueError):
np.array(rt, dtype="M8")
def test_fastCopyAndTranspose():
# 0D array
a = np.array(2)
b = np.fastCopyAndTranspose(a)
assert_equal(b, a.T)
assert_(b.flags.owndata)
# 1D array
a = np.array([3, 2, 7, 0])
b = np.fastCopyAndTranspose(a)
assert_equal(b, a.T)
assert_(b.flags.owndata)
# 2D array
a = np.arange(6).reshape(2, 3)
b = np.fastCopyAndTranspose(a)
assert_equal(b, a.T)
assert_(b.flags.owndata)
def test_array_astype():
a = np.arange(6, dtype='f4').reshape(2, 3)
# Default behavior: allows unsafe casts, keeps memory layout,
# always copies.
b = a.astype('i4')
assert_equal(a, b)
assert_equal(b.dtype, np.dtype('i4'))
assert_equal(a.strides, b.strides)
b = a.T.astype('i4')
assert_equal(a.T, b)
assert_equal(b.dtype, np.dtype('i4'))
assert_equal(a.T.strides, b.strides)
b = a.astype('f4')
assert_equal(a, b)
assert_(not (a is b))
# copy=False parameter can sometimes skip a copy
b = a.astype('f4', copy=False)
assert_(a is b)
# order parameter allows overriding of the memory layout,
# forcing a copy if the layout is wrong
b = a.astype('f4', order='F', copy=False)
assert_equal(a, b)
assert_(not (a is b))
assert_(b.flags.f_contiguous)
b = a.astype('f4', order='C', copy=False)
assert_equal(a, b)
assert_(a is b)
assert_(b.flags.c_contiguous)
# casting parameter allows catching bad casts
b = a.astype('c8', casting='safe')
assert_equal(a, b)
assert_equal(b.dtype, np.dtype('c8'))
assert_raises(TypeError, a.astype, 'i4', casting='safe')
# subok=False passes through a non-subclassed array
b = a.astype('f4', subok=0, copy=False)
assert_(a is b)
class MyNDArray(np.ndarray):
pass
a = np.array([[0, 1, 2], [3, 4, 5]], dtype='f4').view(MyNDArray)
# subok=True passes through a subclass
b = a.astype('f4', subok=True, copy=False)
assert_(a is b)
# subok=True is default, and creates a subtype on a cast
b = a.astype('i4', copy=False)
assert_equal(a, b)
assert_equal(type(b), MyNDArray)
# subok=False never returns a subclass
b = a.astype('f4', subok=False, copy=False)
assert_equal(a, b)
assert_(not (a is b))
assert_(type(b) is not MyNDArray)
# Make sure converting from string object to fixed length string
# does not truncate.
a = np.array([b'a'*100], dtype='O')
b = a.astype('S')
assert_equal(a, b)
assert_equal(b.dtype, np.dtype('S100'))
a = np.array([u'a'*100], dtype='O')
b = a.astype('U')
assert_equal(a, b)
assert_equal(b.dtype, np.dtype('U100'))
# Same test as above but for strings shorter than 64 characters
a = np.array([b'a'*10], dtype='O')
b = a.astype('S')
assert_equal(a, b)
assert_equal(b.dtype, np.dtype('S10'))
a = np.array([u'a'*10], dtype='O')
b = a.astype('U')
assert_equal(a, b)
assert_equal(b.dtype, np.dtype('U10'))
a = np.array(123456789012345678901234567890, dtype='O').astype('S')
assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30'))
a = np.array(123456789012345678901234567890, dtype='O').astype('U')
assert_array_equal(a, np.array(u'1234567890' * 3, dtype='U30'))
a = np.array([123456789012345678901234567890], dtype='O').astype('S')
assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30'))
a = np.array([123456789012345678901234567890], dtype='O').astype('U')
assert_array_equal(a, np.array(u'1234567890' * 3, dtype='U30'))
a = np.array(123456789012345678901234567890, dtype='S')
assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30'))
a = np.array(123456789012345678901234567890, dtype='U')
assert_array_equal(a, np.array(u'1234567890' * 3, dtype='U30'))
a = np.array(u'a\u0140', dtype='U')
b = np.ndarray(buffer=a, dtype='uint32', shape=2)
assert_(b.size == 2)
a = np.array([1000], dtype='i4')
assert_raises(TypeError, a.astype, 'S1', casting='safe')
a = np.array(1000, dtype='i4')
assert_raises(TypeError, a.astype, 'U1', casting='safe')
@pytest.mark.parametrize("t",
np.sctypes['uint'] + np.sctypes['int'] + np.sctypes['float']
)
def test_array_astype_warning(t):
# test ComplexWarning when casting from complex to float or int
a = np.array(10, dtype=np.complex_)
assert_warns(np.ComplexWarning, a.astype, t)
@pytest.mark.parametrize(["dtype", "out_dtype"],
[(np.bytes_, np.bool_),
(np.unicode, np.bool_),
(np.dtype("S10,S9"), np.dtype("?,?"))])
def test_string_to_boolean_cast(dtype, out_dtype):
"""
Currently, for `astype` strings are cast to booleans effectively by
calling `bool(int(string)`. This is not consistent (see gh-9875) and
will eventually be deprecated.
"""
arr = np.array(["10", "10\0\0\0", "0\0\0", "0"], dtype=dtype)
expected = np.array([True, True, False, False], dtype=out_dtype)
assert_array_equal(arr.astype(out_dtype), expected)
@pytest.mark.parametrize(["dtype", "out_dtype"],
[(np.bytes_, np.bool_),
(np.unicode, np.bool_),
(np.dtype("S10,S9"), np.dtype("?,?"))])
def test_string_to_boolean_cast_errors(dtype, out_dtype):
"""
These currently error out, since cast to integers fails, but should not
error out in the future.
"""
for invalid in ["False", "True", "", "\0", "non-empty"]:
arr = np.array([invalid], dtype=dtype)
with assert_raises(ValueError):
arr.astype(out_dtype)
@pytest.mark.parametrize("str_type", [str, bytes, np.str_, np.unicode_])
@pytest.mark.parametrize("scalar_type",
[np.complex64, np.complex128, np.clongdouble])
def test_string_to_complex_cast(str_type, scalar_type):
value = scalar_type(b"1+3j")
assert scalar_type(value) == 1+3j
assert np.array([value], dtype=object).astype(scalar_type)[()] == 1+3j
assert np.array(value).astype(scalar_type)[()] == 1+3j
arr = np.zeros(1, dtype=scalar_type)
arr[0] = value
assert arr[0] == 1+3j
@pytest.mark.parametrize("dtype", np.typecodes["AllFloat"])
def test_none_to_nan_cast(dtype):
# Note that at the time of writing this test, the scalar constructors
# reject None
arr = np.zeros(1, dtype=dtype)
arr[0] = None
assert np.isnan(arr)[0]
assert np.isnan(np.array(None, dtype=dtype))[()]
assert np.isnan(np.array([None], dtype=dtype))[0]
assert np.isnan(np.array(None).astype(dtype))[()]
def test_copyto_fromscalar():
a = np.arange(6, dtype='f4').reshape(2, 3)
# Simple copy
np.copyto(a, 1.5)
assert_equal(a, 1.5)
np.copyto(a.T, 2.5)
assert_equal(a, 2.5)
# Where-masked copy
mask = np.array([[0, 1, 0], [0, 0, 1]], dtype='?')
np.copyto(a, 3.5, where=mask)
assert_equal(a, [[2.5, 3.5, 2.5], [2.5, 2.5, 3.5]])
mask = np.array([[0, 1], [1, 1], [1, 0]], dtype='?')
np.copyto(a.T, 4.5, where=mask)
assert_equal(a, [[2.5, 4.5, 4.5], [4.5, 4.5, 3.5]])
def test_copyto():
a = np.arange(6, dtype='i4').reshape(2, 3)
# Simple copy
np.copyto(a, [[3, 1, 5], [6, 2, 1]])
assert_equal(a, [[3, 1, 5], [6, 2, 1]])
# Overlapping copy should work
np.copyto(a[:, :2], a[::-1, 1::-1])
assert_equal(a, [[2, 6, 5], [1, 3, 1]])
# Defaults to 'same_kind' casting
assert_raises(TypeError, np.copyto, a, 1.5)
# Force a copy with 'unsafe' casting, truncating 1.5 to 1
np.copyto(a, 1.5, casting='unsafe')
assert_equal(a, 1)
# Copying with a mask
np.copyto(a, 3, where=[True, False, True])
assert_equal(a, [[3, 1, 3], [3, 1, 3]])
# Casting rule still applies with a mask
assert_raises(TypeError, np.copyto, a, 3.5, where=[True, False, True])
# Lists of integer 0's and 1's is ok too
np.copyto(a, 4.0, casting='unsafe', where=[[0, 1, 1], [1, 0, 0]])
assert_equal(a, [[3, 4, 4], [4, 1, 3]])
# Overlapping copy with mask should work
np.copyto(a[:, :2], a[::-1, 1::-1], where=[[0, 1], [1, 1]])
assert_equal(a, [[3, 4, 4], [4, 3, 3]])
# 'dst' must be an array
assert_raises(TypeError, np.copyto, [1, 2, 3], [2, 3, 4])
def test_copyto_permut():
# test explicit overflow case
pad = 500
l = [True] * pad + [True, True, True, True]
r = np.zeros(len(l)-pad)
d = np.ones(len(l)-pad)
mask = np.array(l)[pad:]
np.copyto(r, d, where=mask[::-1])
# test all permutation of possible masks, 9 should be sufficient for
# current 4 byte unrolled code
power = 9
d = np.ones(power)
for i in range(2**power):
r = np.zeros(power)
l = [(i & x) != 0 for x in range(power)]
mask = np.array(l)
np.copyto(r, d, where=mask)
assert_array_equal(r == 1, l)
assert_equal(r.sum(), sum(l))
r = np.zeros(power)
np.copyto(r, d, where=mask[::-1])
assert_array_equal(r == 1, l[::-1])
assert_equal(r.sum(), sum(l))
r = np.zeros(power)
np.copyto(r[::2], d[::2], where=mask[::2])
assert_array_equal(r[::2] == 1, l[::2])
assert_equal(r[::2].sum(), sum(l[::2]))
r = np.zeros(power)
np.copyto(r[::2], d[::2], where=mask[::-2])
assert_array_equal(r[::2] == 1, l[::-2])
assert_equal(r[::2].sum(), sum(l[::-2]))
for c in [0xFF, 0x7F, 0x02, 0x10]:
r = np.zeros(power)
mask = np.array(l)
imask = np.array(l).view(np.uint8)
imask[mask != 0] = c
np.copyto(r, d, where=mask)
assert_array_equal(r == 1, l)
assert_equal(r.sum(), sum(l))
r = np.zeros(power)
np.copyto(r, d, where=True)
assert_equal(r.sum(), r.size)
r = np.ones(power)
d = np.zeros(power)
np.copyto(r, d, where=False)
assert_equal(r.sum(), r.size)
def test_copy_order():
a = np.arange(24).reshape(2, 1, 3, 4)
b = a.copy(order='F')
c = np.arange(24).reshape(2, 1, 4, 3).swapaxes(2, 3)
def check_copy_result(x, y, ccontig, fcontig, strides=False):
assert_(not (x is y))
assert_equal(x, y)
assert_equal(res.flags.c_contiguous, ccontig)
assert_equal(res.flags.f_contiguous, fcontig)
# This check is impossible only because
# NPY_RELAXED_STRIDES_CHECKING changes the strides actively
if not NPY_RELAXED_STRIDES_CHECKING:
if strides:
assert_equal(x.strides, y.strides)
else:
assert_(x.strides != y.strides)
# Validate the initial state of a, b, and c
assert_(a.flags.c_contiguous)
assert_(not a.flags.f_contiguous)
assert_(not b.flags.c_contiguous)
assert_(b.flags.f_contiguous)
assert_(not c.flags.c_contiguous)
assert_(not c.flags.f_contiguous)
# Copy with order='C'
res = a.copy(order='C')
check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)
res = b.copy(order='C')
check_copy_result(res, b, ccontig=True, fcontig=False, strides=False)
res = c.copy(order='C')
check_copy_result(res, c, ccontig=True, fcontig=False, strides=False)
res = np.copy(a, order='C')
check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)
res = np.copy(b, order='C')
check_copy_result(res, b, ccontig=True, fcontig=False, strides=False)
res = np.copy(c, order='C')
check_copy_result(res, c, ccontig=True, fcontig=False, strides=False)
# Copy with order='F'
res = a.copy(order='F')
check_copy_result(res, a, ccontig=False, fcontig=True, strides=False)
res = b.copy(order='F')
check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)
res = c.copy(order='F')
check_copy_result(res, c, ccontig=False, fcontig=True, strides=False)
res = np.copy(a, order='F')
check_copy_result(res, a, ccontig=False, fcontig=True, strides=False)
res = np.copy(b, order='F')
check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)
res = np.copy(c, order='F')
check_copy_result(res, c, ccontig=False, fcontig=True, strides=False)
# Copy with order='K'
res = a.copy(order='K')
check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)
res = b.copy(order='K')
check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)
res = c.copy(order='K')
check_copy_result(res, c, ccontig=False, fcontig=False, strides=True)
res = np.copy(a, order='K')
check_copy_result(res, a, ccontig=True, fcontig=False, strides=True)
res = np.copy(b, order='K')
check_copy_result(res, b, ccontig=False, fcontig=True, strides=True)
res = np.copy(c, order='K')
check_copy_result(res, c, ccontig=False, fcontig=False, strides=True)
def test_contiguous_flags():
a = np.ones((4, 4, 1))[::2,:,:]
if NPY_RELAXED_STRIDES_CHECKING:
a.strides = a.strides[:2] + (-123,)
b = np.ones((2, 2, 1, 2, 2)).swapaxes(3, 4)
def check_contig(a, ccontig, fcontig):
assert_(a.flags.c_contiguous == ccontig)
assert_(a.flags.f_contiguous == fcontig)
# Check if new arrays are correct:
check_contig(a, False, False)
check_contig(b, False, False)
if NPY_RELAXED_STRIDES_CHECKING:
check_contig(np.empty((2, 2, 0, 2, 2)), True, True)
check_contig(np.array([[[1], [2]]], order='F'), True, True)
else:
check_contig(np.empty((2, 2, 0, 2, 2)), True, False)
check_contig(np.array([[[1], [2]]], order='F'), False, True)
check_contig(np.empty((2, 2)), True, False)
check_contig(np.empty((2, 2), order='F'), False, True)
# Check that np.array creates correct contiguous flags:
check_contig(np.array(a, copy=False), False, False)
check_contig(np.array(a, copy=False, order='C'), True, False)
check_contig(np.array(a, ndmin=4, copy=False, order='F'), False, True)
if NPY_RELAXED_STRIDES_CHECKING:
# Check slicing update of flags and :
check_contig(a[0], True, True)
check_contig(a[None, ::4, ..., None], True, True)
check_contig(b[0, 0, ...], False, True)
check_contig(b[:,:, 0:0,:,:], True, True)
else:
# Check slicing update of flags:
check_contig(a[0], True, False)
# Would be nice if this was C-Contiguous:
check_contig(a[None, 0, ..., None], False, False)
check_contig(b[0, 0, 0, ...], False, True)
# Test ravel and squeeze.
check_contig(a.ravel(), True, True)
check_contig(np.ones((1, 3, 1)).squeeze(), True, True)
def test_broadcast_arrays():
# Test user defined dtypes
a = np.array([(1, 2, 3)], dtype='u4,u4,u4')
b = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype='u4,u4,u4')
result = np.broadcast_arrays(a, b)
assert_equal(result[0], np.array([(1, 2, 3), (1, 2, 3), (1, 2, 3)], dtype='u4,u4,u4'))
assert_equal(result[1], np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype='u4,u4,u4'))

View file

@ -0,0 +1,886 @@
# -*- coding: utf-8 -*-
import sys
import gc
from hypothesis import given
from hypothesis.extra import numpy as hynp
import pytest
import numpy as np
from numpy.testing import (
assert_, assert_equal, assert_raises, assert_warns, HAS_REFCOUNT,
assert_raises_regex,
)
import textwrap
class TestArrayRepr:
def test_nan_inf(self):
x = np.array([np.nan, np.inf])
assert_equal(repr(x), 'array([nan, inf])')
def test_subclass(self):
class sub(np.ndarray): pass
# one dimensional
x1d = np.array([1, 2]).view(sub)
assert_equal(repr(x1d), 'sub([1, 2])')
# two dimensional
x2d = np.array([[1, 2], [3, 4]]).view(sub)
assert_equal(repr(x2d),
'sub([[1, 2],\n'
' [3, 4]])')
# two dimensional with flexible dtype
xstruct = np.ones((2,2), dtype=[('a', '<i4')]).view(sub)
assert_equal(repr(xstruct),
"sub([[(1,), (1,)],\n"
" [(1,), (1,)]], dtype=[('a', '<i4')])"
)
@pytest.mark.xfail(reason="See gh-10544")
def test_object_subclass(self):
class sub(np.ndarray):
def __new__(cls, inp):
obj = np.asarray(inp).view(cls)
return obj
def __getitem__(self, ind):
ret = super(sub, self).__getitem__(ind)
return sub(ret)
# test that object + subclass is OK:
x = sub([None, None])
assert_equal(repr(x), 'sub([None, None], dtype=object)')
assert_equal(str(x), '[None None]')
x = sub([None, sub([None, None])])
assert_equal(repr(x),
'sub([None, sub([None, None], dtype=object)], dtype=object)')
assert_equal(str(x), '[None sub([None, None], dtype=object)]')
def test_0d_object_subclass(self):
# make sure that subclasses which return 0ds instead
# of scalars don't cause infinite recursion in str
class sub(np.ndarray):
def __new__(cls, inp):
obj = np.asarray(inp).view(cls)
return obj
def __getitem__(self, ind):
ret = super(sub, self).__getitem__(ind)
return sub(ret)
x = sub(1)
assert_equal(repr(x), 'sub(1)')
assert_equal(str(x), '1')
x = sub([1, 1])
assert_equal(repr(x), 'sub([1, 1])')
assert_equal(str(x), '[1 1]')
# check it works properly with object arrays too
x = sub(None)
assert_equal(repr(x), 'sub(None, dtype=object)')
assert_equal(str(x), 'None')
# plus recursive object arrays (even depth > 1)
y = sub(None)
x[()] = y
y[()] = x
assert_equal(repr(x),
'sub(sub(sub(..., dtype=object), dtype=object), dtype=object)')
assert_equal(str(x), '...')
x[()] = 0 # resolve circular references for garbage collector
# nested 0d-subclass-object
x = sub(None)
x[()] = sub(None)
assert_equal(repr(x), 'sub(sub(None, dtype=object), dtype=object)')
assert_equal(str(x), 'None')
# gh-10663
class DuckCounter(np.ndarray):
def __getitem__(self, item):
result = super(DuckCounter, self).__getitem__(item)
if not isinstance(result, DuckCounter):
result = result[...].view(DuckCounter)
return result
def to_string(self):
return {0: 'zero', 1: 'one', 2: 'two'}.get(self.item(), 'many')
def __str__(self):
if self.shape == ():
return self.to_string()
else:
fmt = {'all': lambda x: x.to_string()}
return np.array2string(self, formatter=fmt)
dc = np.arange(5).view(DuckCounter)
assert_equal(str(dc), "[zero one two many many]")
assert_equal(str(dc[0]), "zero")
def test_self_containing(self):
arr0d = np.array(None)
arr0d[()] = arr0d
assert_equal(repr(arr0d),
'array(array(..., dtype=object), dtype=object)')
arr0d[()] = 0 # resolve recursion for garbage collector
arr1d = np.array([None, None])
arr1d[1] = arr1d
assert_equal(repr(arr1d),
'array([None, array(..., dtype=object)], dtype=object)')
arr1d[1] = 0 # resolve recursion for garbage collector
first = np.array(None)
second = np.array(None)
first[()] = second
second[()] = first
assert_equal(repr(first),
'array(array(array(..., dtype=object), dtype=object), dtype=object)')
first[()] = 0 # resolve circular references for garbage collector
def test_containing_list(self):
# printing square brackets directly would be ambiguuous
arr1d = np.array([None, None])
arr1d[0] = [1, 2]
arr1d[1] = [3]
assert_equal(repr(arr1d),
'array([list([1, 2]), list([3])], dtype=object)')
def test_void_scalar_recursion(self):
# gh-9345
repr(np.void(b'test')) # RecursionError ?
def test_fieldless_structured(self):
# gh-10366
no_fields = np.dtype([])
arr_no_fields = np.empty(4, dtype=no_fields)
assert_equal(repr(arr_no_fields), 'array([(), (), (), ()], dtype=[])')
class TestComplexArray:
def test_str(self):
rvals = [0, 1, -1, np.inf, -np.inf, np.nan]
cvals = [complex(rp, ip) for rp in rvals for ip in rvals]
dtypes = [np.complex64, np.cdouble, np.clongdouble]
actual = [str(np.array([c], dt)) for c in cvals for dt in dtypes]
wanted = [
'[0.+0.j]', '[0.+0.j]', '[0.+0.j]',
'[0.+1.j]', '[0.+1.j]', '[0.+1.j]',
'[0.-1.j]', '[0.-1.j]', '[0.-1.j]',
'[0.+infj]', '[0.+infj]', '[0.+infj]',
'[0.-infj]', '[0.-infj]', '[0.-infj]',
'[0.+nanj]', '[0.+nanj]', '[0.+nanj]',
'[1.+0.j]', '[1.+0.j]', '[1.+0.j]',
'[1.+1.j]', '[1.+1.j]', '[1.+1.j]',
'[1.-1.j]', '[1.-1.j]', '[1.-1.j]',
'[1.+infj]', '[1.+infj]', '[1.+infj]',
'[1.-infj]', '[1.-infj]', '[1.-infj]',
'[1.+nanj]', '[1.+nanj]', '[1.+nanj]',
'[-1.+0.j]', '[-1.+0.j]', '[-1.+0.j]',
'[-1.+1.j]', '[-1.+1.j]', '[-1.+1.j]',
'[-1.-1.j]', '[-1.-1.j]', '[-1.-1.j]',
'[-1.+infj]', '[-1.+infj]', '[-1.+infj]',
'[-1.-infj]', '[-1.-infj]', '[-1.-infj]',
'[-1.+nanj]', '[-1.+nanj]', '[-1.+nanj]',
'[inf+0.j]', '[inf+0.j]', '[inf+0.j]',
'[inf+1.j]', '[inf+1.j]', '[inf+1.j]',
'[inf-1.j]', '[inf-1.j]', '[inf-1.j]',
'[inf+infj]', '[inf+infj]', '[inf+infj]',
'[inf-infj]', '[inf-infj]', '[inf-infj]',
'[inf+nanj]', '[inf+nanj]', '[inf+nanj]',
'[-inf+0.j]', '[-inf+0.j]', '[-inf+0.j]',
'[-inf+1.j]', '[-inf+1.j]', '[-inf+1.j]',
'[-inf-1.j]', '[-inf-1.j]', '[-inf-1.j]',
'[-inf+infj]', '[-inf+infj]', '[-inf+infj]',
'[-inf-infj]', '[-inf-infj]', '[-inf-infj]',
'[-inf+nanj]', '[-inf+nanj]', '[-inf+nanj]',
'[nan+0.j]', '[nan+0.j]', '[nan+0.j]',
'[nan+1.j]', '[nan+1.j]', '[nan+1.j]',
'[nan-1.j]', '[nan-1.j]', '[nan-1.j]',
'[nan+infj]', '[nan+infj]', '[nan+infj]',
'[nan-infj]', '[nan-infj]', '[nan-infj]',
'[nan+nanj]', '[nan+nanj]', '[nan+nanj]']
for res, val in zip(actual, wanted):
assert_equal(res, val)
class TestArray2String:
def test_basic(self):
"""Basic test of array2string."""
a = np.arange(3)
assert_(np.array2string(a) == '[0 1 2]')
assert_(np.array2string(a, max_line_width=4, legacy='1.13') == '[0 1\n 2]')
assert_(np.array2string(a, max_line_width=4) == '[0\n 1\n 2]')
def test_unexpected_kwarg(self):
# ensure than an appropriate TypeError
# is raised when array2string receives
# an unexpected kwarg
with assert_raises_regex(TypeError, 'nonsense'):
np.array2string(np.array([1, 2, 3]),
nonsense=None)
def test_format_function(self):
"""Test custom format function for each element in array."""
def _format_function(x):
if np.abs(x) < 1:
return '.'
elif np.abs(x) < 2:
return 'o'
else:
return 'O'
x = np.arange(3)
x_hex = "[0x0 0x1 0x2]"
x_oct = "[0o0 0o1 0o2]"
assert_(np.array2string(x, formatter={'all':_format_function}) ==
"[. o O]")
assert_(np.array2string(x, formatter={'int_kind':_format_function}) ==
"[. o O]")
assert_(np.array2string(x, formatter={'all':lambda x: "%.4f" % x}) ==
"[0.0000 1.0000 2.0000]")
assert_equal(np.array2string(x, formatter={'int':lambda x: hex(x)}),
x_hex)
assert_equal(np.array2string(x, formatter={'int':lambda x: oct(x)}),
x_oct)
x = np.arange(3.)
assert_(np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) ==
"[0.00 1.00 2.00]")
assert_(np.array2string(x, formatter={'float':lambda x: "%.2f" % x}) ==
"[0.00 1.00 2.00]")
s = np.array(['abc', 'def'])
assert_(np.array2string(s, formatter={'numpystr':lambda s: s*2}) ==
'[abcabc defdef]')
def test_structure_format(self):
dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
x = np.array([('Sarah', (8.0, 7.0)), ('John', (6.0, 7.0))], dtype=dt)
assert_equal(np.array2string(x),
"[('Sarah', [8., 7.]) ('John', [6., 7.])]")
np.set_printoptions(legacy='1.13')
try:
# for issue #5692
A = np.zeros(shape=10, dtype=[("A", "M8[s]")])
A[5:].fill(np.datetime64('NaT'))
assert_equal(
np.array2string(A),
textwrap.dedent("""\
[('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',)
('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) ('NaT',) ('NaT',)
('NaT',) ('NaT',) ('NaT',)]""")
)
finally:
np.set_printoptions(legacy=False)
# same again, but with non-legacy behavior
assert_equal(
np.array2string(A),
textwrap.dedent("""\
[('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',)
('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',)
('1970-01-01T00:00:00',) ( 'NaT',)
( 'NaT',) ( 'NaT',)
( 'NaT',) ( 'NaT',)]""")
)
# and again, with timedeltas
A = np.full(10, 123456, dtype=[("A", "m8[s]")])
A[5:].fill(np.datetime64('NaT'))
assert_equal(
np.array2string(A),
textwrap.dedent("""\
[(123456,) (123456,) (123456,) (123456,) (123456,) ( 'NaT',) ( 'NaT',)
( 'NaT',) ( 'NaT',) ( 'NaT',)]""")
)
# See #8160
struct_int = np.array([([1, -1],), ([123, 1],)], dtype=[('B', 'i4', 2)])
assert_equal(np.array2string(struct_int),
"[([ 1, -1],) ([123, 1],)]")
struct_2dint = np.array([([[0, 1], [2, 3]],), ([[12, 0], [0, 0]],)],
dtype=[('B', 'i4', (2, 2))])
assert_equal(np.array2string(struct_2dint),
"[([[ 0, 1], [ 2, 3]],) ([[12, 0], [ 0, 0]],)]")
# See #8172
array_scalar = np.array(
(1., 2.1234567890123456789, 3.), dtype=('f8,f8,f8'))
assert_equal(np.array2string(array_scalar), "(1., 2.12345679, 3.)")
def test_unstructured_void_repr(self):
a = np.array([27, 91, 50, 75, 7, 65, 10, 8,
27, 91, 51, 49,109, 82,101,100], dtype='u1').view('V8')
assert_equal(repr(a[0]), r"void(b'\x1B\x5B\x32\x4B\x07\x41\x0A\x08')")
assert_equal(str(a[0]), r"b'\x1B\x5B\x32\x4B\x07\x41\x0A\x08'")
assert_equal(repr(a),
r"array([b'\x1B\x5B\x32\x4B\x07\x41\x0A\x08'," "\n"
r" b'\x1B\x5B\x33\x31\x6D\x52\x65\x64'], dtype='|V8')")
assert_equal(eval(repr(a), vars(np)), a)
assert_equal(eval(repr(a[0]), vars(np)), a[0])
def test_edgeitems_kwarg(self):
# previously the global print options would be taken over the kwarg
arr = np.zeros(3, int)
assert_equal(
np.array2string(arr, edgeitems=1, threshold=0),
"[0 ... 0]"
)
def test_summarize_1d(self):
A = np.arange(1001)
strA = '[ 0 1 2 ... 998 999 1000]'
assert_equal(str(A), strA)
reprA = 'array([ 0, 1, 2, ..., 998, 999, 1000])'
assert_equal(repr(A), reprA)
def test_summarize_2d(self):
A = np.arange(1002).reshape(2, 501)
strA = '[[ 0 1 2 ... 498 499 500]\n' \
' [ 501 502 503 ... 999 1000 1001]]'
assert_equal(str(A), strA)
reprA = 'array([[ 0, 1, 2, ..., 498, 499, 500],\n' \
' [ 501, 502, 503, ..., 999, 1000, 1001]])'
assert_equal(repr(A), reprA)
def test_linewidth(self):
a = np.full(6, 1)
def make_str(a, width, **kw):
return np.array2string(a, separator="", max_line_width=width, **kw)
assert_equal(make_str(a, 8, legacy='1.13'), '[111111]')
assert_equal(make_str(a, 7, legacy='1.13'), '[111111]')
assert_equal(make_str(a, 5, legacy='1.13'), '[1111\n'
' 11]')
assert_equal(make_str(a, 8), '[111111]')
assert_equal(make_str(a, 7), '[11111\n'
' 1]')
assert_equal(make_str(a, 5), '[111\n'
' 111]')
b = a[None,None,:]
assert_equal(make_str(b, 12, legacy='1.13'), '[[[111111]]]')
assert_equal(make_str(b, 9, legacy='1.13'), '[[[111111]]]')
assert_equal(make_str(b, 8, legacy='1.13'), '[[[11111\n'
' 1]]]')
assert_equal(make_str(b, 12), '[[[111111]]]')
assert_equal(make_str(b, 9), '[[[111\n'
' 111]]]')
assert_equal(make_str(b, 8), '[[[11\n'
' 11\n'
' 11]]]')
def test_wide_element(self):
a = np.array(['xxxxx'])
assert_equal(
np.array2string(a, max_line_width=5),
"['xxxxx']"
)
assert_equal(
np.array2string(a, max_line_width=5, legacy='1.13'),
"[ 'xxxxx']"
)
@given(hynp.from_dtype(np.dtype("U")))
def test_any_text(self, text):
# This test checks that, given any value that can be represented in an
# array of dtype("U") (i.e. unicode string), ...
a = np.array([text, text, text])
# casting a list of them to an array does not e.g. truncate the value
assert_equal(a[0], text)
# and that np.array2string puts a newline in the expected location
expected_repr = "[{0!r} {0!r}\n {0!r}]".format(text)
result = np.array2string(a, max_line_width=len(repr(text)) * 2 + 3)
assert_equal(result, expected_repr)
@pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
def test_refcount(self):
# make sure we do not hold references to the array due to a recursive
# closure (gh-10620)
gc.disable()
a = np.arange(2)
r1 = sys.getrefcount(a)
np.array2string(a)
np.array2string(a)
r2 = sys.getrefcount(a)
gc.collect()
gc.enable()
assert_(r1 == r2)
class TestPrintOptions:
"""Test getting and setting global print options."""
def setup(self):
self.oldopts = np.get_printoptions()
def teardown(self):
np.set_printoptions(**self.oldopts)
def test_basic(self):
x = np.array([1.5, 0, 1.234567890])
assert_equal(repr(x), "array([1.5 , 0. , 1.23456789])")
np.set_printoptions(precision=4)
assert_equal(repr(x), "array([1.5 , 0. , 1.2346])")
def test_precision_zero(self):
np.set_printoptions(precision=0)
for values, string in (
([0.], "0."), ([.3], "0."), ([-.3], "-0."), ([.7], "1."),
([1.5], "2."), ([-1.5], "-2."), ([-15.34], "-15."),
([100.], "100."), ([.2, -1, 122.51], " 0., -1., 123."),
([0], "0"), ([-12], "-12"), ([complex(.3, -.7)], "0.-1.j")):
x = np.array(values)
assert_equal(repr(x), "array([%s])" % string)
def test_formatter(self):
x = np.arange(3)
np.set_printoptions(formatter={'all':lambda x: str(x-1)})
assert_equal(repr(x), "array([-1, 0, 1])")
def test_formatter_reset(self):
x = np.arange(3)
np.set_printoptions(formatter={'all':lambda x: str(x-1)})
assert_equal(repr(x), "array([-1, 0, 1])")
np.set_printoptions(formatter={'int':None})
assert_equal(repr(x), "array([0, 1, 2])")
np.set_printoptions(formatter={'all':lambda x: str(x-1)})
assert_equal(repr(x), "array([-1, 0, 1])")
np.set_printoptions(formatter={'all':None})
assert_equal(repr(x), "array([0, 1, 2])")
np.set_printoptions(formatter={'int':lambda x: str(x-1)})
assert_equal(repr(x), "array([-1, 0, 1])")
np.set_printoptions(formatter={'int_kind':None})
assert_equal(repr(x), "array([0, 1, 2])")
x = np.arange(3.)
np.set_printoptions(formatter={'float':lambda x: str(x-1)})
assert_equal(repr(x), "array([-1.0, 0.0, 1.0])")
np.set_printoptions(formatter={'float_kind':None})
assert_equal(repr(x), "array([0., 1., 2.])")
def test_0d_arrays(self):
assert_equal(str(np.array(u'café', '<U4')), u'café')
assert_equal(repr(np.array('café', '<U4')),
"array('café', dtype='<U4')")
assert_equal(str(np.array('test', np.str_)), 'test')
a = np.zeros(1, dtype=[('a', '<i4', (3,))])
assert_equal(str(a[0]), '([0, 0, 0],)')
assert_equal(repr(np.datetime64('2005-02-25')[...]),
"array('2005-02-25', dtype='datetime64[D]')")
assert_equal(repr(np.timedelta64('10', 'Y')[...]),
"array(10, dtype='timedelta64[Y]')")
# repr of 0d arrays is affected by printoptions
x = np.array(1)
np.set_printoptions(formatter={'all':lambda x: "test"})
assert_equal(repr(x), "array(test)")
# str is unaffected
assert_equal(str(x), "1")
# check `style` arg raises
assert_warns(DeprecationWarning, np.array2string,
np.array(1.), style=repr)
# but not in legacy mode
np.array2string(np.array(1.), style=repr, legacy='1.13')
# gh-10934 style was broken in legacy mode, check it works
np.array2string(np.array(1.), legacy='1.13')
def test_float_spacing(self):
x = np.array([1., 2., 3.])
y = np.array([1., 2., -10.])
z = np.array([100., 2., -1.])
w = np.array([-100., 2., 1.])
assert_equal(repr(x), 'array([1., 2., 3.])')
assert_equal(repr(y), 'array([ 1., 2., -10.])')
assert_equal(repr(np.array(y[0])), 'array(1.)')
assert_equal(repr(np.array(y[-1])), 'array(-10.)')
assert_equal(repr(z), 'array([100., 2., -1.])')
assert_equal(repr(w), 'array([-100., 2., 1.])')
assert_equal(repr(np.array([np.nan, np.inf])), 'array([nan, inf])')
assert_equal(repr(np.array([np.nan, -np.inf])), 'array([ nan, -inf])')
x = np.array([np.inf, 100000, 1.1234])
y = np.array([np.inf, 100000, -1.1234])
z = np.array([np.inf, 1.1234, -1e120])
np.set_printoptions(precision=2)
assert_equal(repr(x), 'array([ inf, 1.00e+05, 1.12e+00])')
assert_equal(repr(y), 'array([ inf, 1.00e+05, -1.12e+00])')
assert_equal(repr(z), 'array([ inf, 1.12e+000, -1.00e+120])')
def test_bool_spacing(self):
assert_equal(repr(np.array([True, True])),
'array([ True, True])')
assert_equal(repr(np.array([True, False])),
'array([ True, False])')
assert_equal(repr(np.array([True])),
'array([ True])')
assert_equal(repr(np.array(True)),
'array(True)')
assert_equal(repr(np.array(False)),
'array(False)')
def test_sign_spacing(self):
a = np.arange(4.)
b = np.array([1.234e9])
c = np.array([1.0 + 1.0j, 1.123456789 + 1.123456789j], dtype='c16')
assert_equal(repr(a), 'array([0., 1., 2., 3.])')
assert_equal(repr(np.array(1.)), 'array(1.)')
assert_equal(repr(b), 'array([1.234e+09])')
assert_equal(repr(np.array([0.])), 'array([0.])')
assert_equal(repr(c),
"array([1. +1.j , 1.12345679+1.12345679j])")
assert_equal(repr(np.array([0., -0.])), 'array([ 0., -0.])')
np.set_printoptions(sign=' ')
assert_equal(repr(a), 'array([ 0., 1., 2., 3.])')
assert_equal(repr(np.array(1.)), 'array( 1.)')
assert_equal(repr(b), 'array([ 1.234e+09])')
assert_equal(repr(c),
"array([ 1. +1.j , 1.12345679+1.12345679j])")
assert_equal(repr(np.array([0., -0.])), 'array([ 0., -0.])')
np.set_printoptions(sign='+')
assert_equal(repr(a), 'array([+0., +1., +2., +3.])')
assert_equal(repr(np.array(1.)), 'array(+1.)')
assert_equal(repr(b), 'array([+1.234e+09])')
assert_equal(repr(c),
"array([+1. +1.j , +1.12345679+1.12345679j])")
np.set_printoptions(legacy='1.13')
assert_equal(repr(a), 'array([ 0., 1., 2., 3.])')
assert_equal(repr(b), 'array([ 1.23400000e+09])')
assert_equal(repr(-b), 'array([ -1.23400000e+09])')
assert_equal(repr(np.array(1.)), 'array(1.0)')
assert_equal(repr(np.array([0.])), 'array([ 0.])')
assert_equal(repr(c),
"array([ 1.00000000+1.j , 1.12345679+1.12345679j])")
# gh-10383
assert_equal(str(np.array([-1., 10])), "[ -1. 10.]")
assert_raises(TypeError, np.set_printoptions, wrongarg=True)
def test_float_overflow_nowarn(self):
# make sure internal computations in FloatingFormat don't
# warn about overflow
repr(np.array([1e4, 0.1], dtype='f2'))
def test_sign_spacing_structured(self):
a = np.ones(2, dtype='<f,<f')
assert_equal(repr(a),
"array([(1., 1.), (1., 1.)], dtype=[('f0', '<f4'), ('f1', '<f4')])")
assert_equal(repr(a[0]), "(1., 1.)")
def test_floatmode(self):
x = np.array([0.6104, 0.922, 0.457, 0.0906, 0.3733, 0.007244,
0.5933, 0.947, 0.2383, 0.4226], dtype=np.float16)
y = np.array([0.2918820979355541, 0.5064172631089138,
0.2848750619642916, 0.4342965294660567,
0.7326538397312751, 0.3459503329096204,
0.0862072768214508, 0.39112753029631175],
dtype=np.float64)
z = np.arange(6, dtype=np.float16)/10
c = np.array([1.0 + 1.0j, 1.123456789 + 1.123456789j], dtype='c16')
# also make sure 1e23 is right (is between two fp numbers)
w = np.array(['1e{}'.format(i) for i in range(25)], dtype=np.float64)
# note: we construct w from the strings `1eXX` instead of doing
# `10.**arange(24)` because it turns out the two are not equivalent in
# python. On some architectures `1e23 != 10.**23`.
wp = np.array([1.234e1, 1e2, 1e123])
# unique mode
np.set_printoptions(floatmode='unique')
assert_equal(repr(x),
"array([0.6104 , 0.922 , 0.457 , 0.0906 , 0.3733 , 0.007244,\n"
" 0.5933 , 0.947 , 0.2383 , 0.4226 ], dtype=float16)")
assert_equal(repr(y),
"array([0.2918820979355541 , 0.5064172631089138 , 0.2848750619642916 ,\n"
" 0.4342965294660567 , 0.7326538397312751 , 0.3459503329096204 ,\n"
" 0.0862072768214508 , 0.39112753029631175])")
assert_equal(repr(z),
"array([0. , 0.1, 0.2, 0.3, 0.4, 0.5], dtype=float16)")
assert_equal(repr(w),
"array([1.e+00, 1.e+01, 1.e+02, 1.e+03, 1.e+04, 1.e+05, 1.e+06, 1.e+07,\n"
" 1.e+08, 1.e+09, 1.e+10, 1.e+11, 1.e+12, 1.e+13, 1.e+14, 1.e+15,\n"
" 1.e+16, 1.e+17, 1.e+18, 1.e+19, 1.e+20, 1.e+21, 1.e+22, 1.e+23,\n"
" 1.e+24])")
assert_equal(repr(wp), "array([1.234e+001, 1.000e+002, 1.000e+123])")
assert_equal(repr(c),
"array([1. +1.j , 1.123456789+1.123456789j])")
# maxprec mode, precision=8
np.set_printoptions(floatmode='maxprec', precision=8)
assert_equal(repr(x),
"array([0.6104 , 0.922 , 0.457 , 0.0906 , 0.3733 , 0.007244,\n"
" 0.5933 , 0.947 , 0.2383 , 0.4226 ], dtype=float16)")
assert_equal(repr(y),
"array([0.2918821 , 0.50641726, 0.28487506, 0.43429653, 0.73265384,\n"
" 0.34595033, 0.08620728, 0.39112753])")
assert_equal(repr(z),
"array([0. , 0.1, 0.2, 0.3, 0.4, 0.5], dtype=float16)")
assert_equal(repr(w[::5]),
"array([1.e+00, 1.e+05, 1.e+10, 1.e+15, 1.e+20])")
assert_equal(repr(wp), "array([1.234e+001, 1.000e+002, 1.000e+123])")
assert_equal(repr(c),
"array([1. +1.j , 1.12345679+1.12345679j])")
# fixed mode, precision=4
np.set_printoptions(floatmode='fixed', precision=4)
assert_equal(repr(x),
"array([0.6104, 0.9219, 0.4570, 0.0906, 0.3733, 0.0072, 0.5933, 0.9468,\n"
" 0.2383, 0.4226], dtype=float16)")
assert_equal(repr(y),
"array([0.2919, 0.5064, 0.2849, 0.4343, 0.7327, 0.3460, 0.0862, 0.3911])")
assert_equal(repr(z),
"array([0.0000, 0.1000, 0.2000, 0.3000, 0.3999, 0.5000], dtype=float16)")
assert_equal(repr(w[::5]),
"array([1.0000e+00, 1.0000e+05, 1.0000e+10, 1.0000e+15, 1.0000e+20])")
assert_equal(repr(wp), "array([1.2340e+001, 1.0000e+002, 1.0000e+123])")
assert_equal(repr(np.zeros(3)), "array([0.0000, 0.0000, 0.0000])")
assert_equal(repr(c),
"array([1.0000+1.0000j, 1.1235+1.1235j])")
# for larger precision, representation error becomes more apparent:
np.set_printoptions(floatmode='fixed', precision=8)
assert_equal(repr(z),
"array([0.00000000, 0.09997559, 0.19995117, 0.30004883, 0.39990234,\n"
" 0.50000000], dtype=float16)")
# maxprec_equal mode, precision=8
np.set_printoptions(floatmode='maxprec_equal', precision=8)
assert_equal(repr(x),
"array([0.610352, 0.921875, 0.457031, 0.090576, 0.373291, 0.007244,\n"
" 0.593262, 0.946777, 0.238281, 0.422607], dtype=float16)")
assert_equal(repr(y),
"array([0.29188210, 0.50641726, 0.28487506, 0.43429653, 0.73265384,\n"
" 0.34595033, 0.08620728, 0.39112753])")
assert_equal(repr(z),
"array([0.0, 0.1, 0.2, 0.3, 0.4, 0.5], dtype=float16)")
assert_equal(repr(w[::5]),
"array([1.e+00, 1.e+05, 1.e+10, 1.e+15, 1.e+20])")
assert_equal(repr(wp), "array([1.234e+001, 1.000e+002, 1.000e+123])")
assert_equal(repr(c),
"array([1.00000000+1.00000000j, 1.12345679+1.12345679j])")
def test_legacy_mode_scalars(self):
# in legacy mode, str of floats get truncated, and complex scalars
# use * for non-finite imaginary part
np.set_printoptions(legacy='1.13')
assert_equal(str(np.float64(1.123456789123456789)), '1.12345678912')
assert_equal(str(np.complex128(complex(1, np.nan))), '(1+nan*j)')
np.set_printoptions(legacy=False)
assert_equal(str(np.float64(1.123456789123456789)),
'1.1234567891234568')
assert_equal(str(np.complex128(complex(1, np.nan))), '(1+nanj)')
def test_legacy_stray_comma(self):
np.set_printoptions(legacy='1.13')
assert_equal(str(np.arange(10000)), '[ 0 1 2 ..., 9997 9998 9999]')
np.set_printoptions(legacy=False)
assert_equal(str(np.arange(10000)), '[ 0 1 2 ... 9997 9998 9999]')
def test_dtype_linewidth_wrapping(self):
np.set_printoptions(linewidth=75)
assert_equal(repr(np.arange(10,20., dtype='f4')),
"array([10., 11., 12., 13., 14., 15., 16., 17., 18., 19.], dtype=float32)")
assert_equal(repr(np.arange(10,23., dtype='f4')), textwrap.dedent("""\
array([10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22.],
dtype=float32)"""))
styp = '<U4'
assert_equal(repr(np.ones(3, dtype=styp)),
"array(['1', '1', '1'], dtype='{}')".format(styp))
assert_equal(repr(np.ones(12, dtype=styp)), textwrap.dedent("""\
array(['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],
dtype='{}')""".format(styp)))
def test_linewidth_repr(self):
a = np.full(7, fill_value=2)
np.set_printoptions(linewidth=17)
assert_equal(
repr(a),
textwrap.dedent("""\
array([2, 2, 2,
2, 2, 2,
2])""")
)
np.set_printoptions(linewidth=17, legacy='1.13')
assert_equal(
repr(a),
textwrap.dedent("""\
array([2, 2, 2,
2, 2, 2, 2])""")
)
a = np.full(8, fill_value=2)
np.set_printoptions(linewidth=18, legacy=False)
assert_equal(
repr(a),
textwrap.dedent("""\
array([2, 2, 2,
2, 2, 2,
2, 2])""")
)
np.set_printoptions(linewidth=18, legacy='1.13')
assert_equal(
repr(a),
textwrap.dedent("""\
array([2, 2, 2, 2,
2, 2, 2, 2])""")
)
def test_linewidth_str(self):
a = np.full(18, fill_value=2)
np.set_printoptions(linewidth=18)
assert_equal(
str(a),
textwrap.dedent("""\
[2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2
2 2]""")
)
np.set_printoptions(linewidth=18, legacy='1.13')
assert_equal(
str(a),
textwrap.dedent("""\
[2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2]""")
)
def test_edgeitems(self):
np.set_printoptions(edgeitems=1, threshold=1)
a = np.arange(27).reshape((3, 3, 3))
assert_equal(
repr(a),
textwrap.dedent("""\
array([[[ 0, ..., 2],
...,
[ 6, ..., 8]],
...,
[[18, ..., 20],
...,
[24, ..., 26]]])""")
)
b = np.zeros((3, 3, 1, 1))
assert_equal(
repr(b),
textwrap.dedent("""\
array([[[[0.]],
...,
[[0.]]],
...,
[[[0.]],
...,
[[0.]]]])""")
)
# 1.13 had extra trailing spaces, and was missing newlines
np.set_printoptions(legacy='1.13')
assert_equal(
repr(a),
textwrap.dedent("""\
array([[[ 0, ..., 2],
...,
[ 6, ..., 8]],
...,
[[18, ..., 20],
...,
[24, ..., 26]]])""")
)
assert_equal(
repr(b),
textwrap.dedent("""\
array([[[[ 0.]],
...,
[[ 0.]]],
...,
[[[ 0.]],
...,
[[ 0.]]]])""")
)
def test_bad_args(self):
assert_raises(ValueError, np.set_printoptions, threshold=float('nan'))
assert_raises(TypeError, np.set_printoptions, threshold='1')
assert_raises(TypeError, np.set_printoptions, threshold=b'1')
def test_unicode_object_array():
expected = "array(['é'], dtype=object)"
x = np.array([u'\xe9'], dtype=object)
assert_equal(repr(x), expected)
class TestContextManager:
def test_ctx_mgr(self):
# test that context manager actually works
with np.printoptions(precision=2):
s = str(np.array([2.0]) / 3)
assert_equal(s, '[0.67]')
def test_ctx_mgr_restores(self):
# test that print options are actually restrored
opts = np.get_printoptions()
with np.printoptions(precision=opts['precision'] - 1,
linewidth=opts['linewidth'] - 4):
pass
assert_equal(np.get_printoptions(), opts)
def test_ctx_mgr_exceptions(self):
# test that print options are restored even if an exception is raised
opts = np.get_printoptions()
try:
with np.printoptions(precision=2, linewidth=11):
raise ValueError
except ValueError:
pass
assert_equal(np.get_printoptions(), opts)
def test_ctx_mgr_as_smth(self):
opts = {"precision": 2}
with np.printoptions(**opts) as ctx:
saved_opts = ctx.copy()
assert_equal({k: saved_opts[k] for k in opts}, opts)

View file

@ -0,0 +1,156 @@
"""
Tests for numpy/core/src/multiarray/conversion_utils.c
"""
import re
import pytest
import numpy as np
import numpy.core._multiarray_tests as mt
class StringConverterTestCase:
allow_bytes = True
case_insensitive = True
exact_match = False
def _check_value_error(self, val):
pattern = r'\(got {}\)'.format(re.escape(repr(val)))
with pytest.raises(ValueError, match=pattern) as exc:
self.conv(val)
def _check(self, val, expected):
assert self.conv(val) == expected
if self.allow_bytes:
assert self.conv(val.encode('ascii')) == expected
else:
with pytest.raises(TypeError):
self.conv(val.encode('ascii'))
if len(val) != 1:
if self.exact_match:
self._check_value_error(val[:1])
self._check_value_error(val + '\0')
else:
assert self.conv(val[:1]) == expected
if self.case_insensitive:
if val != val.lower():
assert self.conv(val.lower()) == expected
if val != val.upper():
assert self.conv(val.upper()) == expected
else:
if val != val.lower():
self._check_value_error(val.lower())
if val != val.upper():
self._check_value_error(val.upper())
def test_wrong_type(self):
# common cases which apply to all the below
with pytest.raises(TypeError):
self.conv({})
with pytest.raises(TypeError):
self.conv([])
def test_wrong_value(self):
# nonsense strings
self._check_value_error('')
self._check_value_error('\N{greek small letter pi}')
if self.allow_bytes:
self._check_value_error(b'')
# bytes which can't be converted to strings via utf8
self._check_value_error(b"\xFF")
if self.exact_match:
self._check_value_error("there's no way this is supported")
class TestByteorderConverter(StringConverterTestCase):
""" Tests of PyArray_ByteorderConverter """
conv = mt.run_byteorder_converter
def test_valid(self):
for s in ['big', '>']:
self._check(s, 'NPY_BIG')
for s in ['little', '<']:
self._check(s, 'NPY_LITTLE')
for s in ['native', '=']:
self._check(s, 'NPY_NATIVE')
for s in ['ignore', '|']:
self._check(s, 'NPY_IGNORE')
for s in ['swap']:
self._check(s, 'NPY_SWAP')
class TestSortkindConverter(StringConverterTestCase):
""" Tests of PyArray_SortkindConverter """
conv = mt.run_sortkind_converter
def test_valid(self):
self._check('quick', 'NPY_QUICKSORT')
self._check('heap', 'NPY_HEAPSORT')
self._check('merge', 'NPY_STABLESORT') # alias
self._check('stable', 'NPY_STABLESORT')
class TestSelectkindConverter(StringConverterTestCase):
""" Tests of PyArray_SelectkindConverter """
conv = mt.run_selectkind_converter
case_insensitive = False
exact_match = True
def test_valid(self):
self._check('introselect', 'NPY_INTROSELECT')
class TestSearchsideConverter(StringConverterTestCase):
""" Tests of PyArray_SearchsideConverter """
conv = mt.run_searchside_converter
def test_valid(self):
self._check('left', 'NPY_SEARCHLEFT')
self._check('right', 'NPY_SEARCHRIGHT')
class TestOrderConverter(StringConverterTestCase):
""" Tests of PyArray_OrderConverter """
conv = mt.run_order_converter
def test_valid(self):
self._check('c', 'NPY_CORDER')
self._check('f', 'NPY_FORTRANORDER')
self._check('a', 'NPY_ANYORDER')
self._check('k', 'NPY_KEEPORDER')
def test_flatten_invalid_order(self):
# invalid after gh-14596
with pytest.raises(ValueError):
self.conv('Z')
for order in [False, True, 0, 8]:
with pytest.raises(TypeError):
self.conv(order)
class TestClipmodeConverter(StringConverterTestCase):
""" Tests of PyArray_ClipmodeConverter """
conv = mt.run_clipmode_converter
def test_valid(self):
self._check('clip', 'NPY_CLIP')
self._check('wrap', 'NPY_WRAP')
self._check('raise', 'NPY_RAISE')
# integer values allowed here
assert self.conv(np.CLIP) == 'NPY_CLIP'
assert self.conv(np.WRAP) == 'NPY_WRAP'
assert self.conv(np.RAISE) == 'NPY_RAISE'
class TestCastingConverter(StringConverterTestCase):
""" Tests of PyArray_CastingConverter """
conv = mt.run_casting_converter
case_insensitive = False
exact_match = True
def test_valid(self):
self._check("no", "NPY_NO_CASTING")
self._check("equiv", "NPY_EQUIV_CASTING")
self._check("safe", "NPY_SAFE_CASTING")
self._check("same_kind", "NPY_SAME_KIND_CASTING")
self._check("unsafe", "NPY_UNSAFE_CASTING")

View file

@ -0,0 +1,171 @@
import sys, platform, re, pytest
from numpy.core._multiarray_umath import __cpu_features__
def assert_features_equal(actual, desired, fname):
__tracebackhide__ = True # Hide traceback for py.test
actual, desired = str(actual), str(desired)
if actual == desired:
return
detected = str(__cpu_features__).replace("'", "")
try:
with open("/proc/cpuinfo", "r") as fd:
cpuinfo = fd.read(2048)
except Exception as err:
cpuinfo = str(err)
try:
import subprocess
auxv = subprocess.check_output(['/bin/true'], env=dict(LD_SHOW_AUXV="1"))
auxv = auxv.decode()
except Exception as err:
auxv = str(err)
import textwrap
error_report = textwrap.indent(
"""
###########################################
### Extra debugging information
###########################################
-------------------------------------------
--- NumPy Detections
-------------------------------------------
%s
-------------------------------------------
--- SYS / CPUINFO
-------------------------------------------
%s....
-------------------------------------------
--- SYS / AUXV
-------------------------------------------
%s
""" % (detected, cpuinfo, auxv), prefix='\r')
raise AssertionError((
"Failure Detection\n"
" NAME: '%s'\n"
" ACTUAL: %s\n"
" DESIRED: %s\n"
"%s"
) % (fname, actual, desired, error_report))
class AbstractTest(object):
features = []
features_groups = {}
features_map = {}
features_flags = set()
def load_flags(self):
# a hook
pass
def test_features(self):
self.load_flags()
for gname, features in self.features_groups.items():
test_features = [self.cpu_have(f) for f in features]
assert_features_equal(__cpu_features__.get(gname), all(test_features), gname)
for feature_name in self.features:
cpu_have = self.cpu_have(feature_name)
npy_have = __cpu_features__.get(feature_name)
assert_features_equal(npy_have, cpu_have, feature_name)
def cpu_have(self, feature_name):
map_names = self.features_map.get(feature_name, feature_name)
if isinstance(map_names, str):
return map_names in self.features_flags
for f in map_names:
if f in self.features_flags:
return True
return False
def load_flags_cpuinfo(self, magic_key):
self.features_flags = self.get_cpuinfo_item(magic_key)
def get_cpuinfo_item(self, magic_key):
values = set()
with open('/proc/cpuinfo') as fd:
for line in fd:
if not line.startswith(magic_key):
continue
flags_value = [s.strip() for s in line.split(':', 1)]
if len(flags_value) == 2:
values = values.union(flags_value[1].upper().split())
return values
def load_flags_auxv(self):
import subprocess
auxv = subprocess.check_output(['/bin/true'], env=dict(LD_SHOW_AUXV="1"))
for at in auxv.split(b'\n'):
if not at.startswith(b"AT_HWCAP"):
continue
hwcap_value = [s.strip() for s in at.split(b':', 1)]
if len(hwcap_value) == 2:
self.features_flags = self.features_flags.union(
hwcap_value[1].upper().decode().split()
)
is_linux = sys.platform.startswith('linux')
machine = platform.machine()
is_x86 = re.match("^(amd64|x86|i386|i686)", machine, re.IGNORECASE)
@pytest.mark.skipif(not is_linux or not is_x86, reason="Only for Linux and x86")
class Test_X86_Features(AbstractTest):
features = [
"MMX", "SSE", "SSE2", "SSE3", "SSSE3", "SSE41", "POPCNT", "SSE42",
"AVX", "F16C", "XOP", "FMA4", "FMA3", "AVX2", "AVX512F", "AVX512CD",
"AVX512ER", "AVX512PF", "AVX5124FMAPS", "AVX5124VNNIW", "AVX512VPOPCNTDQ",
"AVX512VL", "AVX512BW", "AVX512DQ", "AVX512VNNI", "AVX512IFMA",
"AVX512VBMI", "AVX512VBMI2", "AVX512BITALG",
]
features_groups = dict(
AVX512_KNL = ["AVX512F", "AVX512CD", "AVX512ER", "AVX512PF"],
AVX512_KNM = ["AVX512F", "AVX512CD", "AVX512ER", "AVX512PF", "AVX5124FMAPS",
"AVX5124VNNIW", "AVX512VPOPCNTDQ"],
AVX512_SKX = ["AVX512F", "AVX512CD", "AVX512BW", "AVX512DQ", "AVX512VL"],
AVX512_CLX = ["AVX512F", "AVX512CD", "AVX512BW", "AVX512DQ", "AVX512VL", "AVX512VNNI"],
AVX512_CNL = ["AVX512F", "AVX512CD", "AVX512BW", "AVX512DQ", "AVX512VL", "AVX512IFMA",
"AVX512VBMI"],
AVX512_ICL = ["AVX512F", "AVX512CD", "AVX512BW", "AVX512DQ", "AVX512VL", "AVX512IFMA",
"AVX512VBMI", "AVX512VNNI", "AVX512VBMI2", "AVX512BITALG", "AVX512VPOPCNTDQ"],
)
features_map = dict(
SSE3="PNI", SSE41="SSE4_1", SSE42="SSE4_2", FMA3="FMA",
AVX512VNNI="AVX512_VNNI", AVX512BITALG="AVX512_BITALG", AVX512VBMI2="AVX512_VBMI2",
AVX5124FMAPS="AVX512_4FMAPS", AVX5124VNNIW="AVX512_4VNNIW", AVX512VPOPCNTDQ="AVX512_VPOPCNTDQ",
)
def load_flags(self):
self.load_flags_cpuinfo("flags")
is_power = re.match("^(powerpc|ppc)64", machine, re.IGNORECASE)
@pytest.mark.skipif(not is_linux or not is_power, reason="Only for Linux and Power")
class Test_POWER_Features(AbstractTest):
features = ["VSX", "VSX2", "VSX3"]
features_map = dict(VSX2="ARCH_2_07", VSX3="ARCH_3_00")
def load_flags(self):
self.load_flags_auxv()
is_arm = re.match("^(arm|aarch64)", machine, re.IGNORECASE)
@pytest.mark.skipif(not is_linux or not is_arm, reason="Only for Linux and ARM")
class Test_ARM_Features(AbstractTest):
features = [
"NEON", "ASIMD", "FPHP", "ASIMDHP", "ASIMDDP", "ASIMDFHM"
]
features_groups = dict(
NEON_FP16 = ["NEON", "HALF"],
NEON_VFPV4 = ["NEON", "VFPV4"],
)
def load_flags(self):
self.load_flags_cpuinfo("Features")
arch = self.get_cpuinfo_item("CPU architecture")
# in case of mounting virtual filesystem of aarch64 kernel
is_rootfs_v8 = int('0'+next(iter(arch))) > 7 if arch else 0
if re.match("^(aarch64|AARCH64)", machine) or is_rootfs_v8:
self.features_map = dict(
NEON="ASIMD", HALF="ASIMD", VFPV4="ASIMD"
)
else:
self.features_map = dict(
# ELF auxiliary vector and /proc/cpuinfo on Linux kernel(armv8 aarch32)
# doesn't provide information about ASIMD, so we assume that ASIMD is supported
# if the kernel reports any one of the following ARM8 features.
ASIMD=("AES", "SHA1", "SHA2", "PMULL", "CRC32")
)

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,667 @@
import numpy as np
from numpy.core.multiarray import _vec_string
from numpy.testing import (
assert_, assert_equal, assert_array_equal, assert_raises,
assert_raises_regex
)
kw_unicode_true = {'unicode': True} # make 2to3 work properly
kw_unicode_false = {'unicode': False}
class TestBasic:
def test_from_object_array(self):
A = np.array([['abc', 2],
['long ', '0123456789']], dtype='O')
B = np.char.array(A)
assert_equal(B.dtype.itemsize, 10)
assert_array_equal(B, [[b'abc', b'2'],
[b'long', b'0123456789']])
def test_from_object_array_unicode(self):
A = np.array([['abc', u'Sigma \u03a3'],
['long ', '0123456789']], dtype='O')
assert_raises(ValueError, np.char.array, (A,))
B = np.char.array(A, **kw_unicode_true)
assert_equal(B.dtype.itemsize, 10 * np.array('a', 'U').dtype.itemsize)
assert_array_equal(B, [['abc', u'Sigma \u03a3'],
['long', '0123456789']])
def test_from_string_array(self):
A = np.array([[b'abc', b'foo'],
[b'long ', b'0123456789']])
assert_equal(A.dtype.type, np.string_)
B = np.char.array(A)
assert_array_equal(B, A)
assert_equal(B.dtype, A.dtype)
assert_equal(B.shape, A.shape)
B[0, 0] = 'changed'
assert_(B[0, 0] != A[0, 0])
C = np.char.asarray(A)
assert_array_equal(C, A)
assert_equal(C.dtype, A.dtype)
C[0, 0] = 'changed again'
assert_(C[0, 0] != B[0, 0])
assert_(C[0, 0] == A[0, 0])
def test_from_unicode_array(self):
A = np.array([['abc', u'Sigma \u03a3'],
['long ', '0123456789']])
assert_equal(A.dtype.type, np.unicode_)
B = np.char.array(A)
assert_array_equal(B, A)
assert_equal(B.dtype, A.dtype)
assert_equal(B.shape, A.shape)
B = np.char.array(A, **kw_unicode_true)
assert_array_equal(B, A)
assert_equal(B.dtype, A.dtype)
assert_equal(B.shape, A.shape)
def fail():
np.char.array(A, **kw_unicode_false)
assert_raises(UnicodeEncodeError, fail)
def test_unicode_upconvert(self):
A = np.char.array(['abc'])
B = np.char.array([u'\u03a3'])
assert_(issubclass((A + B).dtype.type, np.unicode_))
def test_from_string(self):
A = np.char.array(b'abc')
assert_equal(len(A), 1)
assert_equal(len(A[0]), 3)
assert_(issubclass(A.dtype.type, np.string_))
def test_from_unicode(self):
A = np.char.array(u'\u03a3')
assert_equal(len(A), 1)
assert_equal(len(A[0]), 1)
assert_equal(A.itemsize, 4)
assert_(issubclass(A.dtype.type, np.unicode_))
class TestVecString:
def test_non_existent_method(self):
def fail():
_vec_string('a', np.string_, 'bogus')
assert_raises(AttributeError, fail)
def test_non_string_array(self):
def fail():
_vec_string(1, np.string_, 'strip')
assert_raises(TypeError, fail)
def test_invalid_args_tuple(self):
def fail():
_vec_string(['a'], np.string_, 'strip', 1)
assert_raises(TypeError, fail)
def test_invalid_type_descr(self):
def fail():
_vec_string(['a'], 'BOGUS', 'strip')
assert_raises(TypeError, fail)
def test_invalid_function_args(self):
def fail():
_vec_string(['a'], np.string_, 'strip', (1,))
assert_raises(TypeError, fail)
def test_invalid_result_type(self):
def fail():
_vec_string(['a'], np.int_, 'strip')
assert_raises(TypeError, fail)
def test_broadcast_error(self):
def fail():
_vec_string([['abc', 'def']], np.int_, 'find', (['a', 'd', 'j'],))
assert_raises(ValueError, fail)
class TestWhitespace:
def setup(self):
self.A = np.array([['abc ', '123 '],
['789 ', 'xyz ']]).view(np.chararray)
self.B = np.array([['abc', '123'],
['789', 'xyz']]).view(np.chararray)
def test1(self):
assert_(np.all(self.A == self.B))
assert_(np.all(self.A >= self.B))
assert_(np.all(self.A <= self.B))
assert_(not np.any(self.A > self.B))
assert_(not np.any(self.A < self.B))
assert_(not np.any(self.A != self.B))
class TestChar:
def setup(self):
self.A = np.array('abc1', dtype='c').view(np.chararray)
def test_it(self):
assert_equal(self.A.shape, (4,))
assert_equal(self.A.upper()[:2].tobytes(), b'AB')
class TestComparisons:
def setup(self):
self.A = np.array([['abc', '123'],
['789', 'xyz']]).view(np.chararray)
self.B = np.array([['efg', '123 '],
['051', 'tuv']]).view(np.chararray)
def test_not_equal(self):
assert_array_equal((self.A != self.B), [[True, False], [True, True]])
def test_equal(self):
assert_array_equal((self.A == self.B), [[False, True], [False, False]])
def test_greater_equal(self):
assert_array_equal((self.A >= self.B), [[False, True], [True, True]])
def test_less_equal(self):
assert_array_equal((self.A <= self.B), [[True, True], [False, False]])
def test_greater(self):
assert_array_equal((self.A > self.B), [[False, False], [True, True]])
def test_less(self):
assert_array_equal((self.A < self.B), [[True, False], [False, False]])
class TestComparisonsMixed1(TestComparisons):
"""Ticket #1276"""
def setup(self):
TestComparisons.setup(self)
self.B = np.array([['efg', '123 '],
['051', 'tuv']], np.unicode_).view(np.chararray)
class TestComparisonsMixed2(TestComparisons):
"""Ticket #1276"""
def setup(self):
TestComparisons.setup(self)
self.A = np.array([['abc', '123'],
['789', 'xyz']], np.unicode_).view(np.chararray)
class TestInformation:
def setup(self):
self.A = np.array([[' abc ', ''],
['12345', 'MixedCase'],
['123 \t 345 \0 ', 'UPPER']]).view(np.chararray)
self.B = np.array([[u' \u03a3 ', u''],
[u'12345', u'MixedCase'],
[u'123 \t 345 \0 ', u'UPPER']]).view(np.chararray)
def test_len(self):
assert_(issubclass(np.char.str_len(self.A).dtype.type, np.integer))
assert_array_equal(np.char.str_len(self.A), [[5, 0], [5, 9], [12, 5]])
assert_array_equal(np.char.str_len(self.B), [[3, 0], [5, 9], [12, 5]])
def test_count(self):
assert_(issubclass(self.A.count('').dtype.type, np.integer))
assert_array_equal(self.A.count('a'), [[1, 0], [0, 1], [0, 0]])
assert_array_equal(self.A.count('123'), [[0, 0], [1, 0], [1, 0]])
# Python doesn't seem to like counting NULL characters
# assert_array_equal(self.A.count('\0'), [[0, 0], [0, 0], [1, 0]])
assert_array_equal(self.A.count('a', 0, 2), [[1, 0], [0, 0], [0, 0]])
assert_array_equal(self.B.count('a'), [[0, 0], [0, 1], [0, 0]])
assert_array_equal(self.B.count('123'), [[0, 0], [1, 0], [1, 0]])
# assert_array_equal(self.B.count('\0'), [[0, 0], [0, 0], [1, 0]])
def test_endswith(self):
assert_(issubclass(self.A.endswith('').dtype.type, np.bool_))
assert_array_equal(self.A.endswith(' '), [[1, 0], [0, 0], [1, 0]])
assert_array_equal(self.A.endswith('3', 0, 3), [[0, 0], [1, 0], [1, 0]])
def fail():
self.A.endswith('3', 'fdjk')
assert_raises(TypeError, fail)
def test_find(self):
assert_(issubclass(self.A.find('a').dtype.type, np.integer))
assert_array_equal(self.A.find('a'), [[1, -1], [-1, 6], [-1, -1]])
assert_array_equal(self.A.find('3'), [[-1, -1], [2, -1], [2, -1]])
assert_array_equal(self.A.find('a', 0, 2), [[1, -1], [-1, -1], [-1, -1]])
assert_array_equal(self.A.find(['1', 'P']), [[-1, -1], [0, -1], [0, 1]])
def test_index(self):
def fail():
self.A.index('a')
assert_raises(ValueError, fail)
assert_(np.char.index('abcba', 'b') == 1)
assert_(issubclass(np.char.index('abcba', 'b').dtype.type, np.integer))
def test_isalnum(self):
assert_(issubclass(self.A.isalnum().dtype.type, np.bool_))
assert_array_equal(self.A.isalnum(), [[False, False], [True, True], [False, True]])
def test_isalpha(self):
assert_(issubclass(self.A.isalpha().dtype.type, np.bool_))
assert_array_equal(self.A.isalpha(), [[False, False], [False, True], [False, True]])
def test_isdigit(self):
assert_(issubclass(self.A.isdigit().dtype.type, np.bool_))
assert_array_equal(self.A.isdigit(), [[False, False], [True, False], [False, False]])
def test_islower(self):
assert_(issubclass(self.A.islower().dtype.type, np.bool_))
assert_array_equal(self.A.islower(), [[True, False], [False, False], [False, False]])
def test_isspace(self):
assert_(issubclass(self.A.isspace().dtype.type, np.bool_))
assert_array_equal(self.A.isspace(), [[False, False], [False, False], [False, False]])
def test_istitle(self):
assert_(issubclass(self.A.istitle().dtype.type, np.bool_))
assert_array_equal(self.A.istitle(), [[False, False], [False, False], [False, False]])
def test_isupper(self):
assert_(issubclass(self.A.isupper().dtype.type, np.bool_))
assert_array_equal(self.A.isupper(), [[False, False], [False, False], [False, True]])
def test_rfind(self):
assert_(issubclass(self.A.rfind('a').dtype.type, np.integer))
assert_array_equal(self.A.rfind('a'), [[1, -1], [-1, 6], [-1, -1]])
assert_array_equal(self.A.rfind('3'), [[-1, -1], [2, -1], [6, -1]])
assert_array_equal(self.A.rfind('a', 0, 2), [[1, -1], [-1, -1], [-1, -1]])
assert_array_equal(self.A.rfind(['1', 'P']), [[-1, -1], [0, -1], [0, 2]])
def test_rindex(self):
def fail():
self.A.rindex('a')
assert_raises(ValueError, fail)
assert_(np.char.rindex('abcba', 'b') == 3)
assert_(issubclass(np.char.rindex('abcba', 'b').dtype.type, np.integer))
def test_startswith(self):
assert_(issubclass(self.A.startswith('').dtype.type, np.bool_))
assert_array_equal(self.A.startswith(' '), [[1, 0], [0, 0], [0, 0]])
assert_array_equal(self.A.startswith('1', 0, 3), [[0, 0], [1, 0], [1, 0]])
def fail():
self.A.startswith('3', 'fdjk')
assert_raises(TypeError, fail)
class TestMethods:
def setup(self):
self.A = np.array([[' abc ', ''],
['12345', 'MixedCase'],
['123 \t 345 \0 ', 'UPPER']],
dtype='S').view(np.chararray)
self.B = np.array([[u' \u03a3 ', u''],
[u'12345', u'MixedCase'],
[u'123 \t 345 \0 ', u'UPPER']]).view(np.chararray)
def test_capitalize(self):
tgt = [[b' abc ', b''],
[b'12345', b'Mixedcase'],
[b'123 \t 345 \0 ', b'Upper']]
assert_(issubclass(self.A.capitalize().dtype.type, np.string_))
assert_array_equal(self.A.capitalize(), tgt)
tgt = [[u' \u03c3 ', ''],
['12345', 'Mixedcase'],
['123 \t 345 \0 ', 'Upper']]
assert_(issubclass(self.B.capitalize().dtype.type, np.unicode_))
assert_array_equal(self.B.capitalize(), tgt)
def test_center(self):
assert_(issubclass(self.A.center(10).dtype.type, np.string_))
C = self.A.center([10, 20])
assert_array_equal(np.char.str_len(C), [[10, 20], [10, 20], [12, 20]])
C = self.A.center(20, b'#')
assert_(np.all(C.startswith(b'#')))
assert_(np.all(C.endswith(b'#')))
C = np.char.center(b'FOO', [[10, 20], [15, 8]])
tgt = [[b' FOO ', b' FOO '],
[b' FOO ', b' FOO ']]
assert_(issubclass(C.dtype.type, np.string_))
assert_array_equal(C, tgt)
def test_decode(self):
A = np.char.array([b'\\u03a3'])
assert_(A.decode('unicode-escape')[0] == '\u03a3')
def test_encode(self):
B = self.B.encode('unicode_escape')
assert_(B[0][0] == str(' \\u03a3 ').encode('latin1'))
def test_expandtabs(self):
T = self.A.expandtabs()
assert_(T[2, 0] == b'123 345 \0')
def test_join(self):
# NOTE: list(b'123') == [49, 50, 51]
# so that b','.join(b'123') results to an error on Py3
A0 = self.A.decode('ascii')
A = np.char.join([',', '#'], A0)
assert_(issubclass(A.dtype.type, np.unicode_))
tgt = np.array([[' ,a,b,c, ', ''],
['1,2,3,4,5', 'M#i#x#e#d#C#a#s#e'],
['1,2,3, ,\t, ,3,4,5, ,\x00, ', 'U#P#P#E#R']])
assert_array_equal(np.char.join([',', '#'], A0), tgt)
def test_ljust(self):
assert_(issubclass(self.A.ljust(10).dtype.type, np.string_))
C = self.A.ljust([10, 20])
assert_array_equal(np.char.str_len(C), [[10, 20], [10, 20], [12, 20]])
C = self.A.ljust(20, b'#')
assert_array_equal(C.startswith(b'#'), [
[False, True], [False, False], [False, False]])
assert_(np.all(C.endswith(b'#')))
C = np.char.ljust(b'FOO', [[10, 20], [15, 8]])
tgt = [[b'FOO ', b'FOO '],
[b'FOO ', b'FOO ']]
assert_(issubclass(C.dtype.type, np.string_))
assert_array_equal(C, tgt)
def test_lower(self):
tgt = [[b' abc ', b''],
[b'12345', b'mixedcase'],
[b'123 \t 345 \0 ', b'upper']]
assert_(issubclass(self.A.lower().dtype.type, np.string_))
assert_array_equal(self.A.lower(), tgt)
tgt = [[u' \u03c3 ', u''],
[u'12345', u'mixedcase'],
[u'123 \t 345 \0 ', u'upper']]
assert_(issubclass(self.B.lower().dtype.type, np.unicode_))
assert_array_equal(self.B.lower(), tgt)
def test_lstrip(self):
tgt = [[b'abc ', b''],
[b'12345', b'MixedCase'],
[b'123 \t 345 \0 ', b'UPPER']]
assert_(issubclass(self.A.lstrip().dtype.type, np.string_))
assert_array_equal(self.A.lstrip(), tgt)
tgt = [[b' abc', b''],
[b'2345', b'ixedCase'],
[b'23 \t 345 \x00', b'UPPER']]
assert_array_equal(self.A.lstrip([b'1', b'M']), tgt)
tgt = [[u'\u03a3 ', ''],
['12345', 'MixedCase'],
['123 \t 345 \0 ', 'UPPER']]
assert_(issubclass(self.B.lstrip().dtype.type, np.unicode_))
assert_array_equal(self.B.lstrip(), tgt)
def test_partition(self):
P = self.A.partition([b'3', b'M'])
tgt = [[(b' abc ', b'', b''), (b'', b'', b'')],
[(b'12', b'3', b'45'), (b'', b'M', b'ixedCase')],
[(b'12', b'3', b' \t 345 \0 '), (b'UPPER', b'', b'')]]
assert_(issubclass(P.dtype.type, np.string_))
assert_array_equal(P, tgt)
def test_replace(self):
R = self.A.replace([b'3', b'a'],
[b'##########', b'@'])
tgt = [[b' abc ', b''],
[b'12##########45', b'MixedC@se'],
[b'12########## \t ##########45 \x00', b'UPPER']]
assert_(issubclass(R.dtype.type, np.string_))
assert_array_equal(R, tgt)
def test_rjust(self):
assert_(issubclass(self.A.rjust(10).dtype.type, np.string_))
C = self.A.rjust([10, 20])
assert_array_equal(np.char.str_len(C), [[10, 20], [10, 20], [12, 20]])
C = self.A.rjust(20, b'#')
assert_(np.all(C.startswith(b'#')))
assert_array_equal(C.endswith(b'#'),
[[False, True], [False, False], [False, False]])
C = np.char.rjust(b'FOO', [[10, 20], [15, 8]])
tgt = [[b' FOO', b' FOO'],
[b' FOO', b' FOO']]
assert_(issubclass(C.dtype.type, np.string_))
assert_array_equal(C, tgt)
def test_rpartition(self):
P = self.A.rpartition([b'3', b'M'])
tgt = [[(b'', b'', b' abc '), (b'', b'', b'')],
[(b'12', b'3', b'45'), (b'', b'M', b'ixedCase')],
[(b'123 \t ', b'3', b'45 \0 '), (b'', b'', b'UPPER')]]
assert_(issubclass(P.dtype.type, np.string_))
assert_array_equal(P, tgt)
def test_rsplit(self):
A = self.A.rsplit(b'3')
tgt = [[[b' abc '], [b'']],
[[b'12', b'45'], [b'MixedCase']],
[[b'12', b' \t ', b'45 \x00 '], [b'UPPER']]]
assert_(issubclass(A.dtype.type, np.object_))
assert_equal(A.tolist(), tgt)
def test_rstrip(self):
assert_(issubclass(self.A.rstrip().dtype.type, np.string_))
tgt = [[b' abc', b''],
[b'12345', b'MixedCase'],
[b'123 \t 345', b'UPPER']]
assert_array_equal(self.A.rstrip(), tgt)
tgt = [[b' abc ', b''],
[b'1234', b'MixedCase'],
[b'123 \t 345 \x00', b'UPP']
]
assert_array_equal(self.A.rstrip([b'5', b'ER']), tgt)
tgt = [[u' \u03a3', ''],
['12345', 'MixedCase'],
['123 \t 345', 'UPPER']]
assert_(issubclass(self.B.rstrip().dtype.type, np.unicode_))
assert_array_equal(self.B.rstrip(), tgt)
def test_strip(self):
tgt = [[b'abc', b''],
[b'12345', b'MixedCase'],
[b'123 \t 345', b'UPPER']]
assert_(issubclass(self.A.strip().dtype.type, np.string_))
assert_array_equal(self.A.strip(), tgt)
tgt = [[b' abc ', b''],
[b'234', b'ixedCas'],
[b'23 \t 345 \x00', b'UPP']]
assert_array_equal(self.A.strip([b'15', b'EReM']), tgt)
tgt = [[u'\u03a3', ''],
['12345', 'MixedCase'],
['123 \t 345', 'UPPER']]
assert_(issubclass(self.B.strip().dtype.type, np.unicode_))
assert_array_equal(self.B.strip(), tgt)
def test_split(self):
A = self.A.split(b'3')
tgt = [
[[b' abc '], [b'']],
[[b'12', b'45'], [b'MixedCase']],
[[b'12', b' \t ', b'45 \x00 '], [b'UPPER']]]
assert_(issubclass(A.dtype.type, np.object_))
assert_equal(A.tolist(), tgt)
def test_splitlines(self):
A = np.char.array(['abc\nfds\nwer']).splitlines()
assert_(issubclass(A.dtype.type, np.object_))
assert_(A.shape == (1,))
assert_(len(A[0]) == 3)
def test_swapcase(self):
tgt = [[b' ABC ', b''],
[b'12345', b'mIXEDcASE'],
[b'123 \t 345 \0 ', b'upper']]
assert_(issubclass(self.A.swapcase().dtype.type, np.string_))
assert_array_equal(self.A.swapcase(), tgt)
tgt = [[u' \u03c3 ', u''],
[u'12345', u'mIXEDcASE'],
[u'123 \t 345 \0 ', u'upper']]
assert_(issubclass(self.B.swapcase().dtype.type, np.unicode_))
assert_array_equal(self.B.swapcase(), tgt)
def test_title(self):
tgt = [[b' Abc ', b''],
[b'12345', b'Mixedcase'],
[b'123 \t 345 \0 ', b'Upper']]
assert_(issubclass(self.A.title().dtype.type, np.string_))
assert_array_equal(self.A.title(), tgt)
tgt = [[u' \u03a3 ', u''],
[u'12345', u'Mixedcase'],
[u'123 \t 345 \0 ', u'Upper']]
assert_(issubclass(self.B.title().dtype.type, np.unicode_))
assert_array_equal(self.B.title(), tgt)
def test_upper(self):
tgt = [[b' ABC ', b''],
[b'12345', b'MIXEDCASE'],
[b'123 \t 345 \0 ', b'UPPER']]
assert_(issubclass(self.A.upper().dtype.type, np.string_))
assert_array_equal(self.A.upper(), tgt)
tgt = [[u' \u03a3 ', u''],
[u'12345', u'MIXEDCASE'],
[u'123 \t 345 \0 ', u'UPPER']]
assert_(issubclass(self.B.upper().dtype.type, np.unicode_))
assert_array_equal(self.B.upper(), tgt)
def test_isnumeric(self):
def fail():
self.A.isnumeric()
assert_raises(TypeError, fail)
assert_(issubclass(self.B.isnumeric().dtype.type, np.bool_))
assert_array_equal(self.B.isnumeric(), [
[False, False], [True, False], [False, False]])
def test_isdecimal(self):
def fail():
self.A.isdecimal()
assert_raises(TypeError, fail)
assert_(issubclass(self.B.isdecimal().dtype.type, np.bool_))
assert_array_equal(self.B.isdecimal(), [
[False, False], [True, False], [False, False]])
class TestOperations:
def setup(self):
self.A = np.array([['abc', '123'],
['789', 'xyz']]).view(np.chararray)
self.B = np.array([['efg', '456'],
['051', 'tuv']]).view(np.chararray)
def test_add(self):
AB = np.array([['abcefg', '123456'],
['789051', 'xyztuv']]).view(np.chararray)
assert_array_equal(AB, (self.A + self.B))
assert_(len((self.A + self.B)[0][0]) == 6)
def test_radd(self):
QA = np.array([['qabc', 'q123'],
['q789', 'qxyz']]).view(np.chararray)
assert_array_equal(QA, ('q' + self.A))
def test_mul(self):
A = self.A
for r in (2, 3, 5, 7, 197):
Ar = np.array([[A[0, 0]*r, A[0, 1]*r],
[A[1, 0]*r, A[1, 1]*r]]).view(np.chararray)
assert_array_equal(Ar, (self.A * r))
for ob in [object(), 'qrs']:
with assert_raises_regex(ValueError,
'Can only multiply by integers'):
A*ob
def test_rmul(self):
A = self.A
for r in (2, 3, 5, 7, 197):
Ar = np.array([[A[0, 0]*r, A[0, 1]*r],
[A[1, 0]*r, A[1, 1]*r]]).view(np.chararray)
assert_array_equal(Ar, (r * self.A))
for ob in [object(), 'qrs']:
with assert_raises_regex(ValueError,
'Can only multiply by integers'):
ob * A
def test_mod(self):
"""Ticket #856"""
F = np.array([['%d', '%f'], ['%s', '%r']]).view(np.chararray)
C = np.array([[3, 7], [19, 1]])
FC = np.array([['3', '7.000000'],
['19', '1']]).view(np.chararray)
assert_array_equal(FC, F % C)
A = np.array([['%.3f', '%d'], ['%s', '%r']]).view(np.chararray)
A1 = np.array([['1.000', '1'], ['1', '1']]).view(np.chararray)
assert_array_equal(A1, (A % 1))
A2 = np.array([['1.000', '2'], ['3', '4']]).view(np.chararray)
assert_array_equal(A2, (A % [[1, 2], [3, 4]]))
def test_rmod(self):
assert_(("%s" % self.A) == str(self.A))
assert_(("%r" % self.A) == repr(self.A))
for ob in [42, object()]:
with assert_raises_regex(
TypeError, "unsupported operand type.* and 'chararray'"):
ob % self.A
def test_slice(self):
"""Regression test for https://github.com/numpy/numpy/issues/5982"""
arr = np.array([['abc ', 'def '], ['geh ', 'ijk ']],
dtype='S4').view(np.chararray)
sl1 = arr[:]
assert_array_equal(sl1, arr)
assert_(sl1.base is arr)
assert_(sl1.base.base is arr.base)
sl2 = arr[:, :]
assert_array_equal(sl2, arr)
assert_(sl2.base is arr)
assert_(sl2.base.base is arr.base)
assert_(arr[0, 0] == b'abc')
def test_empty_indexing():
"""Regression test for ticket 1948."""
# Check that indexing a chararray with an empty list/array returns an
# empty chararray instead of a chararray with a single empty string in it.
s = np.chararray((4,))
assert_(s[[]].size == 0)

View file

@ -0,0 +1,620 @@
"""
Tests related to deprecation warnings. Also a convenient place
to document how deprecations should eventually be turned into errors.
"""
import datetime
import operator
import warnings
import pytest
import tempfile
import re
import numpy as np
from numpy.testing import (
assert_raises, assert_warns, assert_, assert_array_equal
)
from numpy.core._multiarray_tests import fromstring_null_term_c_api
try:
import pytz
_has_pytz = True
except ImportError:
_has_pytz = False
class _DeprecationTestCase:
# Just as warning: warnings uses re.match, so the start of this message
# must match.
message = ''
warning_cls = DeprecationWarning
def setup(self):
self.warn_ctx = warnings.catch_warnings(record=True)
self.log = self.warn_ctx.__enter__()
# Do *not* ignore other DeprecationWarnings. Ignoring warnings
# can give very confusing results because of
# https://bugs.python.org/issue4180 and it is probably simplest to
# try to keep the tests cleanly giving only the right warning type.
# (While checking them set to "error" those are ignored anyway)
# We still have them show up, because otherwise they would be raised
warnings.filterwarnings("always", category=self.warning_cls)
warnings.filterwarnings("always", message=self.message,
category=self.warning_cls)
def teardown(self):
self.warn_ctx.__exit__()
def assert_deprecated(self, function, num=1, ignore_others=False,
function_fails=False,
exceptions=np._NoValue,
args=(), kwargs={}):
"""Test if DeprecationWarnings are given and raised.
This first checks if the function when called gives `num`
DeprecationWarnings, after that it tries to raise these
DeprecationWarnings and compares them with `exceptions`.
The exceptions can be different for cases where this code path
is simply not anticipated and the exception is replaced.
Parameters
----------
function : callable
The function to test
num : int
Number of DeprecationWarnings to expect. This should normally be 1.
ignore_others : bool
Whether warnings of the wrong type should be ignored (note that
the message is not checked)
function_fails : bool
If the function would normally fail, setting this will check for
warnings inside a try/except block.
exceptions : Exception or tuple of Exceptions
Exception to expect when turning the warnings into an error.
The default checks for DeprecationWarnings. If exceptions is
empty the function is expected to run successfully.
args : tuple
Arguments for `function`
kwargs : dict
Keyword arguments for `function`
"""
# reset the log
self.log[:] = []
if exceptions is np._NoValue:
exceptions = (self.warning_cls,)
try:
function(*args, **kwargs)
except (Exception if function_fails else tuple()):
pass
# just in case, clear the registry
num_found = 0
for warning in self.log:
if warning.category is self.warning_cls:
num_found += 1
elif not ignore_others:
raise AssertionError(
"expected %s but got: %s" %
(self.warning_cls.__name__, warning.category))
if num is not None and num_found != num:
msg = "%i warnings found but %i expected." % (len(self.log), num)
lst = [str(w) for w in self.log]
raise AssertionError("\n".join([msg] + lst))
with warnings.catch_warnings():
warnings.filterwarnings("error", message=self.message,
category=self.warning_cls)
try:
function(*args, **kwargs)
if exceptions != tuple():
raise AssertionError(
"No error raised during function call")
except exceptions:
if exceptions == tuple():
raise AssertionError(
"Error raised during function call")
def assert_not_deprecated(self, function, args=(), kwargs={}):
"""Test that warnings are not raised.
This is just a shorthand for:
self.assert_deprecated(function, num=0, ignore_others=True,
exceptions=tuple(), args=args, kwargs=kwargs)
"""
self.assert_deprecated(function, num=0, ignore_others=True,
exceptions=tuple(), args=args, kwargs=kwargs)
class _VisibleDeprecationTestCase(_DeprecationTestCase):
warning_cls = np.VisibleDeprecationWarning
class TestNonTupleNDIndexDeprecation:
def test_basic(self):
a = np.zeros((5, 5))
with warnings.catch_warnings():
warnings.filterwarnings('always')
assert_warns(FutureWarning, a.__getitem__, [[0, 1], [0, 1]])
assert_warns(FutureWarning, a.__getitem__, [slice(None)])
warnings.filterwarnings('error')
assert_raises(FutureWarning, a.__getitem__, [[0, 1], [0, 1]])
assert_raises(FutureWarning, a.__getitem__, [slice(None)])
# a a[[0, 1]] always was advanced indexing, so no error/warning
a[[0, 1]]
class TestComparisonDeprecations(_DeprecationTestCase):
"""This tests the deprecation, for non-element-wise comparison logic.
This used to mean that when an error occurred during element-wise comparison
(i.e. broadcasting) NotImplemented was returned, but also in the comparison
itself, False was given instead of the error.
Also test FutureWarning for the None comparison.
"""
message = "elementwise.* comparison failed; .*"
def test_normal_types(self):
for op in (operator.eq, operator.ne):
# Broadcasting errors:
self.assert_deprecated(op, args=(np.zeros(3), []))
a = np.zeros(3, dtype='i,i')
# (warning is issued a couple of times here)
self.assert_deprecated(op, args=(a, a[:-1]), num=None)
# ragged array comparison returns True/False
a = np.array([1, np.array([1,2,3])], dtype=object)
b = np.array([1, np.array([1,2,3])], dtype=object)
self.assert_deprecated(op, args=(a, b), num=None)
def test_string(self):
# For two string arrays, strings always raised the broadcasting error:
a = np.array(['a', 'b'])
b = np.array(['a', 'b', 'c'])
assert_raises(ValueError, lambda x, y: x == y, a, b)
# The empty list is not cast to string, and this used to pass due
# to dtype mismatch; now (2018-06-21) it correctly leads to a
# FutureWarning.
assert_warns(FutureWarning, lambda: a == [])
def test_void_dtype_equality_failures(self):
class NotArray:
def __array__(self):
raise TypeError
# Needed so Python 3 does not raise DeprecationWarning twice.
def __ne__(self, other):
return NotImplemented
self.assert_deprecated(lambda: np.arange(2) == NotArray())
self.assert_deprecated(lambda: np.arange(2) != NotArray())
struct1 = np.zeros(2, dtype="i4,i4")
struct2 = np.zeros(2, dtype="i4,i4,i4")
assert_warns(FutureWarning, lambda: struct1 == 1)
assert_warns(FutureWarning, lambda: struct1 == struct2)
assert_warns(FutureWarning, lambda: struct1 != 1)
assert_warns(FutureWarning, lambda: struct1 != struct2)
def test_array_richcompare_legacy_weirdness(self):
# It doesn't really work to use assert_deprecated here, b/c part of
# the point of assert_deprecated is to check that when warnings are
# set to "error" mode then the error is propagated -- which is good!
# But here we are testing a bunch of code that is deprecated *because*
# it has the habit of swallowing up errors and converting them into
# different warnings. So assert_warns will have to be sufficient.
assert_warns(FutureWarning, lambda: np.arange(2) == "a")
assert_warns(FutureWarning, lambda: np.arange(2) != "a")
# No warning for scalar comparisons
with warnings.catch_warnings():
warnings.filterwarnings("error")
assert_(not (np.array(0) == "a"))
assert_(np.array(0) != "a")
assert_(not (np.int16(0) == "a"))
assert_(np.int16(0) != "a")
for arg1 in [np.asarray(0), np.int16(0)]:
struct = np.zeros(2, dtype="i4,i4")
for arg2 in [struct, "a"]:
for f in [operator.lt, operator.le, operator.gt, operator.ge]:
with warnings.catch_warnings() as l:
warnings.filterwarnings("always")
assert_raises(TypeError, f, arg1, arg2)
assert_(not l)
class TestDatetime64Timezone(_DeprecationTestCase):
"""Parsing of datetime64 with timezones deprecated in 1.11.0, because
datetime64 is now timezone naive rather than UTC only.
It will be quite a while before we can remove this, because, at the very
least, a lot of existing code uses the 'Z' modifier to avoid conversion
from local time to UTC, even if otherwise it handles time in a timezone
naive fashion.
"""
def test_string(self):
self.assert_deprecated(np.datetime64, args=('2000-01-01T00+01',))
self.assert_deprecated(np.datetime64, args=('2000-01-01T00Z',))
@pytest.mark.skipif(not _has_pytz,
reason="The pytz module is not available.")
def test_datetime(self):
tz = pytz.timezone('US/Eastern')
dt = datetime.datetime(2000, 1, 1, 0, 0, tzinfo=tz)
self.assert_deprecated(np.datetime64, args=(dt,))
class TestNonCContiguousViewDeprecation(_DeprecationTestCase):
"""View of non-C-contiguous arrays deprecated in 1.11.0.
The deprecation will not be raised for arrays that are both C and F
contiguous, as C contiguous is dominant. There are more such arrays
with relaxed stride checking than without so the deprecation is not
as visible with relaxed stride checking in force.
"""
def test_fortran_contiguous(self):
self.assert_deprecated(np.ones((2,2)).T.view, args=(complex,))
self.assert_deprecated(np.ones((2,2)).T.view, args=(np.int8,))
class TestArrayDataAttributeAssignmentDeprecation(_DeprecationTestCase):
"""Assigning the 'data' attribute of an ndarray is unsafe as pointed
out in gh-7093. Eventually, such assignment should NOT be allowed, but
in the interests of maintaining backwards compatibility, only a Deprecation-
Warning will be raised instead for the time being to give developers time to
refactor relevant code.
"""
def test_data_attr_assignment(self):
a = np.arange(10)
b = np.linspace(0, 1, 10)
self.message = ("Assigning the 'data' attribute is an "
"inherently unsafe operation and will "
"be removed in the future.")
self.assert_deprecated(a.__setattr__, args=('data', b.data))
class TestBinaryReprInsufficientWidthParameterForRepresentation(_DeprecationTestCase):
"""
If a 'width' parameter is passed into ``binary_repr`` that is insufficient to
represent the number in base 2 (positive) or 2's complement (negative) form,
the function used to silently ignore the parameter and return a representation
using the minimal number of bits needed for the form in question. Such behavior
is now considered unsafe from a user perspective and will raise an error in the future.
"""
def test_insufficient_width_positive(self):
args = (10,)
kwargs = {'width': 2}
self.message = ("Insufficient bit width provided. This behavior "
"will raise an error in the future.")
self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)
def test_insufficient_width_negative(self):
args = (-5,)
kwargs = {'width': 2}
self.message = ("Insufficient bit width provided. This behavior "
"will raise an error in the future.")
self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)
class TestNumericStyleTypecodes(_DeprecationTestCase):
"""
Deprecate the old numeric-style dtypes, which are especially
confusing for complex types, e.g. Complex32 -> complex64. When the
deprecation cycle is complete, the check for the strings should be
removed from PyArray_DescrConverter in descriptor.c, and the
deprecated keys should not be added as capitalized aliases in
_add_aliases in numerictypes.py.
"""
def test_all_dtypes(self):
deprecated_types = [
'Bool', 'Complex32', 'Complex64', 'Float16', 'Float32', 'Float64',
'Int8', 'Int16', 'Int32', 'Int64', 'Object0', 'Timedelta64',
'UInt8', 'UInt16', 'UInt32', 'UInt64', 'Void0'
]
for dt in deprecated_types:
self.assert_deprecated(np.dtype, exceptions=(TypeError,),
args=(dt,))
class TestTestDeprecated:
def test_assert_deprecated(self):
test_case_instance = _DeprecationTestCase()
test_case_instance.setup()
assert_raises(AssertionError,
test_case_instance.assert_deprecated,
lambda: None)
def foo():
warnings.warn("foo", category=DeprecationWarning, stacklevel=2)
test_case_instance.assert_deprecated(foo)
test_case_instance.teardown()
class TestNonNumericConjugate(_DeprecationTestCase):
"""
Deprecate no-op behavior of ndarray.conjugate on non-numeric dtypes,
which conflicts with the error behavior of np.conjugate.
"""
def test_conjugate(self):
for a in np.array(5), np.array(5j):
self.assert_not_deprecated(a.conjugate)
for a in (np.array('s'), np.array('2016', 'M'),
np.array((1, 2), [('a', int), ('b', int)])):
self.assert_deprecated(a.conjugate)
class TestNPY_CHAR(_DeprecationTestCase):
# 2017-05-03, 1.13.0
def test_npy_char_deprecation(self):
from numpy.core._multiarray_tests import npy_char_deprecation
self.assert_deprecated(npy_char_deprecation)
assert_(npy_char_deprecation() == 'S1')
class TestPyArray_AS1D(_DeprecationTestCase):
def test_npy_pyarrayas1d_deprecation(self):
from numpy.core._multiarray_tests import npy_pyarrayas1d_deprecation
assert_raises(NotImplementedError, npy_pyarrayas1d_deprecation)
class TestPyArray_AS2D(_DeprecationTestCase):
def test_npy_pyarrayas2d_deprecation(self):
from numpy.core._multiarray_tests import npy_pyarrayas2d_deprecation
assert_raises(NotImplementedError, npy_pyarrayas2d_deprecation)
class Test_UPDATEIFCOPY(_DeprecationTestCase):
"""
v1.14 deprecates creating an array with the UPDATEIFCOPY flag, use
WRITEBACKIFCOPY instead
"""
def test_npy_updateifcopy_deprecation(self):
from numpy.core._multiarray_tests import npy_updateifcopy_deprecation
arr = np.arange(9).reshape(3, 3)
v = arr.T
self.assert_deprecated(npy_updateifcopy_deprecation, args=(v,))
class TestDatetimeEvent(_DeprecationTestCase):
# 2017-08-11, 1.14.0
def test_3_tuple(self):
for cls in (np.datetime64, np.timedelta64):
# two valid uses - (unit, num) and (unit, num, den, None)
self.assert_not_deprecated(cls, args=(1, ('ms', 2)))
self.assert_not_deprecated(cls, args=(1, ('ms', 2, 1, None)))
# trying to use the event argument, removed in 1.7.0, is deprecated
# it used to be a uint8
self.assert_deprecated(cls, args=(1, ('ms', 2, 'event')))
self.assert_deprecated(cls, args=(1, ('ms', 2, 63)))
self.assert_deprecated(cls, args=(1, ('ms', 2, 1, 'event')))
self.assert_deprecated(cls, args=(1, ('ms', 2, 1, 63)))
class TestTruthTestingEmptyArrays(_DeprecationTestCase):
# 2017-09-25, 1.14.0
message = '.*truth value of an empty array is ambiguous.*'
def test_1d(self):
self.assert_deprecated(bool, args=(np.array([]),))
def test_2d(self):
self.assert_deprecated(bool, args=(np.zeros((1, 0)),))
self.assert_deprecated(bool, args=(np.zeros((0, 1)),))
self.assert_deprecated(bool, args=(np.zeros((0, 0)),))
class TestBincount(_DeprecationTestCase):
# 2017-06-01, 1.14.0
def test_bincount_minlength(self):
self.assert_deprecated(lambda: np.bincount([1, 2, 3], minlength=None))
class TestAlen(_DeprecationTestCase):
# 2019-08-02, 1.18.0
def test_alen(self):
self.assert_deprecated(lambda: np.alen(np.array([1, 2, 3])))
class TestGeneratorSum(_DeprecationTestCase):
# 2018-02-25, 1.15.0
def test_generator_sum(self):
self.assert_deprecated(np.sum, args=((i for i in range(5)),))
class TestSctypeNA(_VisibleDeprecationTestCase):
# 2018-06-24, 1.16
def test_sctypeNA(self):
self.assert_deprecated(lambda: np.sctypeNA['?'])
self.assert_deprecated(lambda: np.typeNA['?'])
self.assert_deprecated(lambda: np.typeNA.get('?'))
class TestPositiveOnNonNumerical(_DeprecationTestCase):
# 2018-06-28, 1.16.0
def test_positive_on_non_number(self):
self.assert_deprecated(operator.pos, args=(np.array('foo'),))
class TestFromstring(_DeprecationTestCase):
# 2017-10-19, 1.14
def test_fromstring(self):
self.assert_deprecated(np.fromstring, args=('\x00'*80,))
class TestFromStringAndFileInvalidData(_DeprecationTestCase):
# 2019-06-08, 1.17.0
# Tests should be moved to real tests when deprecation is done.
message = "string or file could not be read to its end"
@pytest.mark.parametrize("invalid_str", [",invalid_data", "invalid_sep"])
def test_deprecate_unparsable_data_file(self, invalid_str):
x = np.array([1.51, 2, 3.51, 4], dtype=float)
with tempfile.TemporaryFile(mode="w") as f:
x.tofile(f, sep=',', format='%.2f')
f.write(invalid_str)
f.seek(0)
self.assert_deprecated(lambda: np.fromfile(f, sep=","))
f.seek(0)
self.assert_deprecated(lambda: np.fromfile(f, sep=",", count=5))
# Should not raise:
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
f.seek(0)
res = np.fromfile(f, sep=",", count=4)
assert_array_equal(res, x)
@pytest.mark.parametrize("invalid_str", [",invalid_data", "invalid_sep"])
def test_deprecate_unparsable_string(self, invalid_str):
x = np.array([1.51, 2, 3.51, 4], dtype=float)
x_str = "1.51,2,3.51,4{}".format(invalid_str)
self.assert_deprecated(lambda: np.fromstring(x_str, sep=","))
self.assert_deprecated(lambda: np.fromstring(x_str, sep=",", count=5))
# The C-level API can use not fixed size, but 0 terminated strings,
# so test that as well:
bytestr = x_str.encode("ascii")
self.assert_deprecated(lambda: fromstring_null_term_c_api(bytestr))
with assert_warns(DeprecationWarning):
# this is slightly strange, in that fromstring leaves data
# potentially uninitialized (would be good to error when all is
# read, but count is larger then actual data maybe).
res = np.fromstring(x_str, sep=",", count=5)
assert_array_equal(res[:-1], x)
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
# Should not raise:
res = np.fromstring(x_str, sep=",", count=4)
assert_array_equal(res, x)
class Test_GetSet_NumericOps(_DeprecationTestCase):
# 2018-09-20, 1.16.0
def test_get_numeric_ops(self):
from numpy.core._multiarray_tests import getset_numericops
self.assert_deprecated(getset_numericops, num=2)
# empty kwargs prevents any state actually changing which would break
# other tests.
self.assert_deprecated(np.set_numeric_ops, kwargs={})
assert_raises(ValueError, np.set_numeric_ops, add='abc')
class TestShape1Fields(_DeprecationTestCase):
warning_cls = FutureWarning
# 2019-05-20, 1.17.0
def test_shape_1_fields(self):
self.assert_deprecated(np.dtype, args=([('a', int, 1)],))
class TestNonZero(_DeprecationTestCase):
# 2019-05-26, 1.17.0
def test_zerod(self):
self.assert_deprecated(lambda: np.nonzero(np.array(0)))
self.assert_deprecated(lambda: np.nonzero(np.array(1)))
def test_deprecate_ragged_arrays():
# 2019-11-29 1.19.0
#
# NEP 34 deprecated automatic object dtype when creating ragged
# arrays. Also see the "ragged" tests in `test_multiarray`
#
# emits a VisibleDeprecationWarning
arg = [1, [2, 3]]
with assert_warns(np.VisibleDeprecationWarning):
np.array(arg)
class TestToString(_DeprecationTestCase):
# 2020-03-06 1.19.0
message = re.escape("tostring() is deprecated. Use tobytes() instead.")
def test_tostring(self):
arr = np.array(list(b"test\xFF"), dtype=np.uint8)
self.assert_deprecated(arr.tostring)
def test_tostring_matches_tobytes(self):
arr = np.array(list(b"test\xFF"), dtype=np.uint8)
b = arr.tobytes()
with assert_warns(DeprecationWarning):
s = arr.tostring()
assert s == b
class TestDTypeCoercion(_DeprecationTestCase):
# 2020-02-06 1.19.0
message = "Converting .* to a dtype .*is deprecated"
deprecated_types = [
# The builtin scalar super types:
np.generic, np.flexible, np.number,
np.inexact, np.floating, np.complexfloating,
np.integer, np.unsignedinteger, np.signedinteger,
# character is a deprecated S1 special case:
np.character,
]
def test_dtype_coercion(self):
for scalar_type in self.deprecated_types:
self.assert_deprecated(np.dtype, args=(scalar_type,))
def test_array_construction(self):
for scalar_type in self.deprecated_types:
self.assert_deprecated(np.array, args=([], scalar_type,))
def test_not_deprecated(self):
# All specific types are not deprecated:
for group in np.sctypes.values():
for scalar_type in group:
self.assert_not_deprecated(np.dtype, args=(scalar_type,))
for scalar_type in [type, dict, list, tuple]:
# Typical python types are coerced to object currently:
self.assert_not_deprecated(np.dtype, args=(scalar_type,))
class BuiltInRoundComplexDType(_DeprecationTestCase):
# 2020-03-31 1.19.0
deprecated_types = [np.csingle, np.cdouble, np.clongdouble]
not_deprecated_types = [
np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64,
np.float16, np.float32, np.float64,
]
def test_deprecated(self):
for scalar_type in self.deprecated_types:
scalar = scalar_type(0)
self.assert_deprecated(round, args=(scalar,))
self.assert_deprecated(round, args=(scalar, 0))
self.assert_deprecated(round, args=(scalar,), kwargs={'ndigits': 0})
def test_not_deprecated(self):
for scalar_type in self.not_deprecated_types:
scalar = scalar_type(0)
self.assert_not_deprecated(round, args=(scalar,))
self.assert_not_deprecated(round, args=(scalar, 0))
self.assert_not_deprecated(round, args=(scalar,), kwargs={'ndigits': 0})

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,59 @@
import pytest
import sysconfig
import numpy as np
from numpy.testing import assert_, assert_raises
# The floating point emulation on ARM EABI systems lacking a hardware FPU is
# known to be buggy. This is an attempt to identify these hosts. It may not
# catch all possible cases, but it catches the known cases of gh-413 and
# gh-15562.
hosttype = sysconfig.get_config_var('HOST_GNU_TYPE')
arm_softfloat = False if hosttype is None else hosttype.endswith('gnueabi')
class TestErrstate:
@pytest.mark.skipif(arm_softfloat,
reason='platform/cpu issue with FPU (gh-413,-15562)')
def test_invalid(self):
with np.errstate(all='raise', under='ignore'):
a = -np.arange(3)
# This should work
with np.errstate(invalid='ignore'):
np.sqrt(a)
# While this should fail!
with assert_raises(FloatingPointError):
np.sqrt(a)
@pytest.mark.skipif(arm_softfloat,
reason='platform/cpu issue with FPU (gh-15562)')
def test_divide(self):
with np.errstate(all='raise', under='ignore'):
a = -np.arange(3)
# This should work
with np.errstate(divide='ignore'):
a // 0
# While this should fail!
with assert_raises(FloatingPointError):
a // 0
# As should this, see gh-15562
with assert_raises(FloatingPointError):
a // a
def test_errcall(self):
def foo(*args):
print(args)
olderrcall = np.geterrcall()
with np.errstate(call=foo):
assert_(np.geterrcall() is foo, 'call is not foo')
with np.errstate(call=None):
assert_(np.geterrcall() is None, 'call is not None')
assert_(np.geterrcall() is olderrcall, 'call is not olderrcall')
def test_errstate_decorator(self):
@np.errstate(all='ignore')
def foo():
a = -np.arange(3)
a // 0
foo()

View file

@ -0,0 +1,219 @@
import itertools
import contextlib
import operator
import pytest
import numpy as np
import numpy.core._multiarray_tests as mt
from numpy.testing import assert_raises, assert_equal
INT64_MAX = np.iinfo(np.int64).max
INT64_MIN = np.iinfo(np.int64).min
INT64_MID = 2**32
# int128 is not two's complement, the sign bit is separate
INT128_MAX = 2**128 - 1
INT128_MIN = -INT128_MAX
INT128_MID = 2**64
INT64_VALUES = (
[INT64_MIN + j for j in range(20)] +
[INT64_MAX - j for j in range(20)] +
[INT64_MID + j for j in range(-20, 20)] +
[2*INT64_MID + j for j in range(-20, 20)] +
[INT64_MID//2 + j for j in range(-20, 20)] +
list(range(-70, 70))
)
INT128_VALUES = (
[INT128_MIN + j for j in range(20)] +
[INT128_MAX - j for j in range(20)] +
[INT128_MID + j for j in range(-20, 20)] +
[2*INT128_MID + j for j in range(-20, 20)] +
[INT128_MID//2 + j for j in range(-20, 20)] +
list(range(-70, 70)) +
[False] # negative zero
)
INT64_POS_VALUES = [x for x in INT64_VALUES if x > 0]
@contextlib.contextmanager
def exc_iter(*args):
"""
Iterate over Cartesian product of *args, and if an exception is raised,
add information of the current iterate.
"""
value = [None]
def iterate():
for v in itertools.product(*args):
value[0] = v
yield v
try:
yield iterate()
except Exception:
import traceback
msg = "At: %r\n%s" % (repr(value[0]),
traceback.format_exc())
raise AssertionError(msg)
def test_safe_binop():
# Test checked arithmetic routines
ops = [
(operator.add, 1),
(operator.sub, 2),
(operator.mul, 3)
]
with exc_iter(ops, INT64_VALUES, INT64_VALUES) as it:
for xop, a, b in it:
pyop, op = xop
c = pyop(a, b)
if not (INT64_MIN <= c <= INT64_MAX):
assert_raises(OverflowError, mt.extint_safe_binop, a, b, op)
else:
d = mt.extint_safe_binop(a, b, op)
if c != d:
# assert_equal is slow
assert_equal(d, c)
def test_to_128():
with exc_iter(INT64_VALUES) as it:
for a, in it:
b = mt.extint_to_128(a)
if a != b:
assert_equal(b, a)
def test_to_64():
with exc_iter(INT128_VALUES) as it:
for a, in it:
if not (INT64_MIN <= a <= INT64_MAX):
assert_raises(OverflowError, mt.extint_to_64, a)
else:
b = mt.extint_to_64(a)
if a != b:
assert_equal(b, a)
def test_mul_64_64():
with exc_iter(INT64_VALUES, INT64_VALUES) as it:
for a, b in it:
c = a * b
d = mt.extint_mul_64_64(a, b)
if c != d:
assert_equal(d, c)
def test_add_128():
with exc_iter(INT128_VALUES, INT128_VALUES) as it:
for a, b in it:
c = a + b
if not (INT128_MIN <= c <= INT128_MAX):
assert_raises(OverflowError, mt.extint_add_128, a, b)
else:
d = mt.extint_add_128(a, b)
if c != d:
assert_equal(d, c)
def test_sub_128():
with exc_iter(INT128_VALUES, INT128_VALUES) as it:
for a, b in it:
c = a - b
if not (INT128_MIN <= c <= INT128_MAX):
assert_raises(OverflowError, mt.extint_sub_128, a, b)
else:
d = mt.extint_sub_128(a, b)
if c != d:
assert_equal(d, c)
def test_neg_128():
with exc_iter(INT128_VALUES) as it:
for a, in it:
b = -a
c = mt.extint_neg_128(a)
if b != c:
assert_equal(c, b)
def test_shl_128():
with exc_iter(INT128_VALUES) as it:
for a, in it:
if a < 0:
b = -(((-a) << 1) & (2**128-1))
else:
b = (a << 1) & (2**128-1)
c = mt.extint_shl_128(a)
if b != c:
assert_equal(c, b)
def test_shr_128():
with exc_iter(INT128_VALUES) as it:
for a, in it:
if a < 0:
b = -((-a) >> 1)
else:
b = a >> 1
c = mt.extint_shr_128(a)
if b != c:
assert_equal(c, b)
def test_gt_128():
with exc_iter(INT128_VALUES, INT128_VALUES) as it:
for a, b in it:
c = a > b
d = mt.extint_gt_128(a, b)
if c != d:
assert_equal(d, c)
@pytest.mark.slow
def test_divmod_128_64():
with exc_iter(INT128_VALUES, INT64_POS_VALUES) as it:
for a, b in it:
if a >= 0:
c, cr = divmod(a, b)
else:
c, cr = divmod(-a, b)
c = -c
cr = -cr
d, dr = mt.extint_divmod_128_64(a, b)
if c != d or d != dr or b*d + dr != a:
assert_equal(d, c)
assert_equal(dr, cr)
assert_equal(b*d + dr, a)
def test_floordiv_128_64():
with exc_iter(INT128_VALUES, INT64_POS_VALUES) as it:
for a, b in it:
c = a // b
d = mt.extint_floordiv_128_64(a, b)
if c != d:
assert_equal(d, c)
def test_ceildiv_128_64():
with exc_iter(INT128_VALUES, INT64_POS_VALUES) as it:
for a, b in it:
c = (a + b - 1) // b
d = mt.extint_ceildiv_128_64(a, b)
if c != d:
assert_equal(d, c)

View file

@ -0,0 +1,370 @@
from numpy import (
logspace, linspace, geomspace, dtype, array, sctypes, arange, isnan,
ndarray, sqrt, nextafter, stack
)
from numpy.testing import (
assert_, assert_equal, assert_raises, assert_array_equal, assert_allclose,
)
class PhysicalQuantity(float):
def __new__(cls, value):
return float.__new__(cls, value)
def __add__(self, x):
assert_(isinstance(x, PhysicalQuantity))
return PhysicalQuantity(float(x) + float(self))
__radd__ = __add__
def __sub__(self, x):
assert_(isinstance(x, PhysicalQuantity))
return PhysicalQuantity(float(self) - float(x))
def __rsub__(self, x):
assert_(isinstance(x, PhysicalQuantity))
return PhysicalQuantity(float(x) - float(self))
def __mul__(self, x):
return PhysicalQuantity(float(x) * float(self))
__rmul__ = __mul__
def __div__(self, x):
return PhysicalQuantity(float(self) / float(x))
def __rdiv__(self, x):
return PhysicalQuantity(float(x) / float(self))
class PhysicalQuantity2(ndarray):
__array_priority__ = 10
class TestLogspace:
def test_basic(self):
y = logspace(0, 6)
assert_(len(y) == 50)
y = logspace(0, 6, num=100)
assert_(y[-1] == 10 ** 6)
y = logspace(0, 6, endpoint=False)
assert_(y[-1] < 10 ** 6)
y = logspace(0, 6, num=7)
assert_array_equal(y, [1, 10, 100, 1e3, 1e4, 1e5, 1e6])
def test_start_stop_array(self):
start = array([0., 1.])
stop = array([6., 7.])
t1 = logspace(start, stop, 6)
t2 = stack([logspace(_start, _stop, 6)
for _start, _stop in zip(start, stop)], axis=1)
assert_equal(t1, t2)
t3 = logspace(start, stop[0], 6)
t4 = stack([logspace(_start, stop[0], 6)
for _start in start], axis=1)
assert_equal(t3, t4)
t5 = logspace(start, stop, 6, axis=-1)
assert_equal(t5, t2.T)
def test_dtype(self):
y = logspace(0, 6, dtype='float32')
assert_equal(y.dtype, dtype('float32'))
y = logspace(0, 6, dtype='float64')
assert_equal(y.dtype, dtype('float64'))
y = logspace(0, 6, dtype='int32')
assert_equal(y.dtype, dtype('int32'))
def test_physical_quantities(self):
a = PhysicalQuantity(1.0)
b = PhysicalQuantity(5.0)
assert_equal(logspace(a, b), logspace(1.0, 5.0))
def test_subclass(self):
a = array(1).view(PhysicalQuantity2)
b = array(7).view(PhysicalQuantity2)
ls = logspace(a, b)
assert type(ls) is PhysicalQuantity2
assert_equal(ls, logspace(1.0, 7.0))
ls = logspace(a, b, 1)
assert type(ls) is PhysicalQuantity2
assert_equal(ls, logspace(1.0, 7.0, 1))
class TestGeomspace:
def test_basic(self):
y = geomspace(1, 1e6)
assert_(len(y) == 50)
y = geomspace(1, 1e6, num=100)
assert_(y[-1] == 10 ** 6)
y = geomspace(1, 1e6, endpoint=False)
assert_(y[-1] < 10 ** 6)
y = geomspace(1, 1e6, num=7)
assert_array_equal(y, [1, 10, 100, 1e3, 1e4, 1e5, 1e6])
y = geomspace(8, 2, num=3)
assert_allclose(y, [8, 4, 2])
assert_array_equal(y.imag, 0)
y = geomspace(-1, -100, num=3)
assert_array_equal(y, [-1, -10, -100])
assert_array_equal(y.imag, 0)
y = geomspace(-100, -1, num=3)
assert_array_equal(y, [-100, -10, -1])
assert_array_equal(y.imag, 0)
def test_complex(self):
# Purely imaginary
y = geomspace(1j, 16j, num=5)
assert_allclose(y, [1j, 2j, 4j, 8j, 16j])
assert_array_equal(y.real, 0)
y = geomspace(-4j, -324j, num=5)
assert_allclose(y, [-4j, -12j, -36j, -108j, -324j])
assert_array_equal(y.real, 0)
y = geomspace(1+1j, 1000+1000j, num=4)
assert_allclose(y, [1+1j, 10+10j, 100+100j, 1000+1000j])
y = geomspace(-1+1j, -1000+1000j, num=4)
assert_allclose(y, [-1+1j, -10+10j, -100+100j, -1000+1000j])
# Logarithmic spirals
y = geomspace(-1, 1, num=3, dtype=complex)
assert_allclose(y, [-1, 1j, +1])
y = geomspace(0+3j, -3+0j, 3)
assert_allclose(y, [0+3j, -3/sqrt(2)+3j/sqrt(2), -3+0j])
y = geomspace(0+3j, 3+0j, 3)
assert_allclose(y, [0+3j, 3/sqrt(2)+3j/sqrt(2), 3+0j])
y = geomspace(-3+0j, 0-3j, 3)
assert_allclose(y, [-3+0j, -3/sqrt(2)-3j/sqrt(2), 0-3j])
y = geomspace(0+3j, -3+0j, 3)
assert_allclose(y, [0+3j, -3/sqrt(2)+3j/sqrt(2), -3+0j])
y = geomspace(-2-3j, 5+7j, 7)
assert_allclose(y, [-2-3j, -0.29058977-4.15771027j,
2.08885354-4.34146838j, 4.58345529-3.16355218j,
6.41401745-0.55233457j, 6.75707386+3.11795092j,
5+7j])
# Type promotion should prevent the -5 from becoming a NaN
y = geomspace(3j, -5, 2)
assert_allclose(y, [3j, -5])
y = geomspace(-5, 3j, 2)
assert_allclose(y, [-5, 3j])
def test_dtype(self):
y = geomspace(1, 1e6, dtype='float32')
assert_equal(y.dtype, dtype('float32'))
y = geomspace(1, 1e6, dtype='float64')
assert_equal(y.dtype, dtype('float64'))
y = geomspace(1, 1e6, dtype='int32')
assert_equal(y.dtype, dtype('int32'))
# Native types
y = geomspace(1, 1e6, dtype=float)
assert_equal(y.dtype, dtype('float_'))
y = geomspace(1, 1e6, dtype=complex)
assert_equal(y.dtype, dtype('complex'))
def test_start_stop_array_scalar(self):
lim1 = array([120, 100], dtype="int8")
lim2 = array([-120, -100], dtype="int8")
lim3 = array([1200, 1000], dtype="uint16")
t1 = geomspace(lim1[0], lim1[1], 5)
t2 = geomspace(lim2[0], lim2[1], 5)
t3 = geomspace(lim3[0], lim3[1], 5)
t4 = geomspace(120.0, 100.0, 5)
t5 = geomspace(-120.0, -100.0, 5)
t6 = geomspace(1200.0, 1000.0, 5)
# t3 uses float32, t6 uses float64
assert_allclose(t1, t4, rtol=1e-2)
assert_allclose(t2, t5, rtol=1e-2)
assert_allclose(t3, t6, rtol=1e-5)
def test_start_stop_array(self):
# Try to use all special cases.
start = array([1.e0, 32., 1j, -4j, 1+1j, -1])
stop = array([1.e4, 2., 16j, -324j, 10000+10000j, 1])
t1 = geomspace(start, stop, 5)
t2 = stack([geomspace(_start, _stop, 5)
for _start, _stop in zip(start, stop)], axis=1)
assert_equal(t1, t2)
t3 = geomspace(start, stop[0], 5)
t4 = stack([geomspace(_start, stop[0], 5)
for _start in start], axis=1)
assert_equal(t3, t4)
t5 = geomspace(start, stop, 5, axis=-1)
assert_equal(t5, t2.T)
def test_physical_quantities(self):
a = PhysicalQuantity(1.0)
b = PhysicalQuantity(5.0)
assert_equal(geomspace(a, b), geomspace(1.0, 5.0))
def test_subclass(self):
a = array(1).view(PhysicalQuantity2)
b = array(7).view(PhysicalQuantity2)
gs = geomspace(a, b)
assert type(gs) is PhysicalQuantity2
assert_equal(gs, geomspace(1.0, 7.0))
gs = geomspace(a, b, 1)
assert type(gs) is PhysicalQuantity2
assert_equal(gs, geomspace(1.0, 7.0, 1))
def test_bounds(self):
assert_raises(ValueError, geomspace, 0, 10)
assert_raises(ValueError, geomspace, 10, 0)
assert_raises(ValueError, geomspace, 0, 0)
class TestLinspace:
def test_basic(self):
y = linspace(0, 10)
assert_(len(y) == 50)
y = linspace(2, 10, num=100)
assert_(y[-1] == 10)
y = linspace(2, 10, endpoint=False)
assert_(y[-1] < 10)
assert_raises(ValueError, linspace, 0, 10, num=-1)
def test_corner(self):
y = list(linspace(0, 1, 1))
assert_(y == [0.0], y)
assert_raises(TypeError, linspace, 0, 1, num=2.5)
def test_type(self):
t1 = linspace(0, 1, 0).dtype
t2 = linspace(0, 1, 1).dtype
t3 = linspace(0, 1, 2).dtype
assert_equal(t1, t2)
assert_equal(t2, t3)
def test_dtype(self):
y = linspace(0, 6, dtype='float32')
assert_equal(y.dtype, dtype('float32'))
y = linspace(0, 6, dtype='float64')
assert_equal(y.dtype, dtype('float64'))
y = linspace(0, 6, dtype='int32')
assert_equal(y.dtype, dtype('int32'))
def test_start_stop_array_scalar(self):
lim1 = array([-120, 100], dtype="int8")
lim2 = array([120, -100], dtype="int8")
lim3 = array([1200, 1000], dtype="uint16")
t1 = linspace(lim1[0], lim1[1], 5)
t2 = linspace(lim2[0], lim2[1], 5)
t3 = linspace(lim3[0], lim3[1], 5)
t4 = linspace(-120.0, 100.0, 5)
t5 = linspace(120.0, -100.0, 5)
t6 = linspace(1200.0, 1000.0, 5)
assert_equal(t1, t4)
assert_equal(t2, t5)
assert_equal(t3, t6)
def test_start_stop_array(self):
start = array([-120, 120], dtype="int8")
stop = array([100, -100], dtype="int8")
t1 = linspace(start, stop, 5)
t2 = stack([linspace(_start, _stop, 5)
for _start, _stop in zip(start, stop)], axis=1)
assert_equal(t1, t2)
t3 = linspace(start, stop[0], 5)
t4 = stack([linspace(_start, stop[0], 5)
for _start in start], axis=1)
assert_equal(t3, t4)
t5 = linspace(start, stop, 5, axis=-1)
assert_equal(t5, t2.T)
def test_complex(self):
lim1 = linspace(1 + 2j, 3 + 4j, 5)
t1 = array([1.0+2.j, 1.5+2.5j, 2.0+3j, 2.5+3.5j, 3.0+4j])
lim2 = linspace(1j, 10, 5)
t2 = array([0.0+1.j, 2.5+0.75j, 5.0+0.5j, 7.5+0.25j, 10.0+0j])
assert_equal(lim1, t1)
assert_equal(lim2, t2)
def test_physical_quantities(self):
a = PhysicalQuantity(0.0)
b = PhysicalQuantity(1.0)
assert_equal(linspace(a, b), linspace(0.0, 1.0))
def test_subclass(self):
a = array(0).view(PhysicalQuantity2)
b = array(1).view(PhysicalQuantity2)
ls = linspace(a, b)
assert type(ls) is PhysicalQuantity2
assert_equal(ls, linspace(0.0, 1.0))
ls = linspace(a, b, 1)
assert type(ls) is PhysicalQuantity2
assert_equal(ls, linspace(0.0, 1.0, 1))
def test_array_interface(self):
# Regression test for https://github.com/numpy/numpy/pull/6659
# Ensure that start/stop can be objects that implement
# __array_interface__ and are convertible to numeric scalars
class Arrayish:
"""
A generic object that supports the __array_interface__ and hence
can in principle be converted to a numeric scalar, but is not
otherwise recognized as numeric, but also happens to support
multiplication by floats.
Data should be an object that implements the buffer interface,
and contains at least 4 bytes.
"""
def __init__(self, data):
self._data = data
@property
def __array_interface__(self):
return {'shape': (), 'typestr': '<i4', 'data': self._data,
'version': 3}
def __mul__(self, other):
# For the purposes of this test any multiplication is an
# identity operation :)
return self
one = Arrayish(array(1, dtype='<i4'))
five = Arrayish(array(5, dtype='<i4'))
assert_equal(linspace(one, five), linspace(1, 5))
def test_denormal_numbers(self):
# Regression test for gh-5437. Will probably fail when compiled
# with ICC, which flushes denormals to zero
for ftype in sctypes['float']:
stop = nextafter(ftype(0), ftype(1)) * 5 # A denormal number
assert_(any(linspace(0, stop, 10, endpoint=False, dtype=ftype)))
def test_equivalent_to_arange(self):
for j in range(1000):
assert_equal(linspace(0, j, j+1, dtype=int),
arange(j+1, dtype=int))
def test_retstep(self):
for num in [0, 1, 2]:
for ept in [False, True]:
y = linspace(0, 1, num, endpoint=ept, retstep=True)
assert isinstance(y, tuple) and len(y) == 2
if num == 2:
y0_expect = [0.0, 1.0] if ept else [0.0, 0.5]
assert_array_equal(y[0], y0_expect)
assert_equal(y[1], y0_expect[1])
elif num == 1 and not ept:
assert_array_equal(y[0], [0.0])
assert_equal(y[1], 1.0)
else:
assert_array_equal(y[0], [0.0][:num])
assert isnan(y[1])
def test_object(self):
start = array(1, dtype='O')
stop = array(2, dtype='O')
y = linspace(start, stop, 3)
assert_array_equal(y, array([1., 1.5, 2.]))

View file

@ -0,0 +1,121 @@
""" Test functions for limits module.
"""
import numpy as np
from numpy.core import finfo, iinfo
from numpy import half, single, double, longdouble
from numpy.testing import assert_equal, assert_, assert_raises
from numpy.core.getlimits import _discovered_machar, _float_ma
##################################################
class TestPythonFloat:
def test_singleton(self):
ftype = finfo(float)
ftype2 = finfo(float)
assert_equal(id(ftype), id(ftype2))
class TestHalf:
def test_singleton(self):
ftype = finfo(half)
ftype2 = finfo(half)
assert_equal(id(ftype), id(ftype2))
class TestSingle:
def test_singleton(self):
ftype = finfo(single)
ftype2 = finfo(single)
assert_equal(id(ftype), id(ftype2))
class TestDouble:
def test_singleton(self):
ftype = finfo(double)
ftype2 = finfo(double)
assert_equal(id(ftype), id(ftype2))
class TestLongdouble:
def test_singleton(self):
ftype = finfo(longdouble)
ftype2 = finfo(longdouble)
assert_equal(id(ftype), id(ftype2))
class TestFinfo:
def test_basic(self):
dts = list(zip(['f2', 'f4', 'f8', 'c8', 'c16'],
[np.float16, np.float32, np.float64, np.complex64,
np.complex128]))
for dt1, dt2 in dts:
for attr in ('bits', 'eps', 'epsneg', 'iexp', 'machar', 'machep',
'max', 'maxexp', 'min', 'minexp', 'negep', 'nexp',
'nmant', 'precision', 'resolution', 'tiny'):
assert_equal(getattr(finfo(dt1), attr),
getattr(finfo(dt2), attr), attr)
assert_raises(ValueError, finfo, 'i4')
class TestIinfo:
def test_basic(self):
dts = list(zip(['i1', 'i2', 'i4', 'i8',
'u1', 'u2', 'u4', 'u8'],
[np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64]))
for dt1, dt2 in dts:
for attr in ('bits', 'min', 'max'):
assert_equal(getattr(iinfo(dt1), attr),
getattr(iinfo(dt2), attr), attr)
assert_raises(ValueError, iinfo, 'f4')
def test_unsigned_max(self):
types = np.sctypes['uint']
for T in types:
assert_equal(iinfo(T).max, T(-1))
class TestRepr:
def test_iinfo_repr(self):
expected = "iinfo(min=-32768, max=32767, dtype=int16)"
assert_equal(repr(np.iinfo(np.int16)), expected)
def test_finfo_repr(self):
expected = "finfo(resolution=1e-06, min=-3.4028235e+38," + \
" max=3.4028235e+38, dtype=float32)"
assert_equal(repr(np.finfo(np.float32)), expected)
def test_instances():
iinfo(10)
finfo(3.0)
def assert_ma_equal(discovered, ma_like):
# Check MachAr-like objects same as calculated MachAr instances
for key, value in discovered.__dict__.items():
assert_equal(value, getattr(ma_like, key))
if hasattr(value, 'shape'):
assert_equal(value.shape, getattr(ma_like, key).shape)
assert_equal(value.dtype, getattr(ma_like, key).dtype)
def test_known_types():
# Test we are correctly compiling parameters for known types
for ftype, ma_like in ((np.float16, _float_ma[16]),
(np.float32, _float_ma[32]),
(np.float64, _float_ma[64])):
assert_ma_equal(_discovered_machar(ftype), ma_like)
# Suppress warning for broken discovery of double double on PPC
with np.errstate(all='ignore'):
ld_ma = _discovered_machar(np.longdouble)
bytes = np.dtype(np.longdouble).itemsize
if (ld_ma.it, ld_ma.maxexp) == (63, 16384) and bytes in (12, 16):
# 80-bit extended precision
assert_ma_equal(ld_ma, _float_ma[80])
elif (ld_ma.it, ld_ma.maxexp) == (112, 16384) and bytes == 16:
# IEE 754 128-bit
assert_ma_equal(ld_ma, _float_ma[128])
def test_plausible_finfo():
# Assert that finfo returns reasonable results for all types
for ftype in np.sctypes['float'] + np.sctypes['complex']:
info = np.finfo(ftype)
assert_(info.nmant > 1)
assert_(info.minexp < -1)
assert_(info.maxexp > 1)

View file

@ -0,0 +1,539 @@
import platform
import pytest
import numpy as np
from numpy import uint16, float16, float32, float64
from numpy.testing import assert_, assert_equal
def assert_raises_fpe(strmatch, callable, *args, **kwargs):
try:
callable(*args, **kwargs)
except FloatingPointError as exc:
assert_(str(exc).find(strmatch) >= 0,
"Did not raise floating point %s error" % strmatch)
else:
assert_(False,
"Did not raise floating point %s error" % strmatch)
class TestHalf:
def setup(self):
# An array of all possible float16 values
self.all_f16 = np.arange(0x10000, dtype=uint16)
self.all_f16.dtype = float16
self.all_f32 = np.array(self.all_f16, dtype=float32)
self.all_f64 = np.array(self.all_f16, dtype=float64)
# An array of all non-NaN float16 values, in sorted order
self.nonan_f16 = np.concatenate(
(np.arange(0xfc00, 0x7fff, -1, dtype=uint16),
np.arange(0x0000, 0x7c01, 1, dtype=uint16)))
self.nonan_f16.dtype = float16
self.nonan_f32 = np.array(self.nonan_f16, dtype=float32)
self.nonan_f64 = np.array(self.nonan_f16, dtype=float64)
# An array of all finite float16 values, in sorted order
self.finite_f16 = self.nonan_f16[1:-1]
self.finite_f32 = self.nonan_f32[1:-1]
self.finite_f64 = self.nonan_f64[1:-1]
def test_half_conversions(self):
"""Checks that all 16-bit values survive conversion
to/from 32-bit and 64-bit float"""
# Because the underlying routines preserve the NaN bits, every
# value is preserved when converting to/from other floats.
# Convert from float32 back to float16
b = np.array(self.all_f32, dtype=float16)
assert_equal(self.all_f16.view(dtype=uint16),
b.view(dtype=uint16))
# Convert from float64 back to float16
b = np.array(self.all_f64, dtype=float16)
assert_equal(self.all_f16.view(dtype=uint16),
b.view(dtype=uint16))
# Convert float16 to longdouble and back
# This doesn't necessarily preserve the extra NaN bits,
# so exclude NaNs.
a_ld = np.array(self.nonan_f16, dtype=np.longdouble)
b = np.array(a_ld, dtype=float16)
assert_equal(self.nonan_f16.view(dtype=uint16),
b.view(dtype=uint16))
# Check the range for which all integers can be represented
i_int = np.arange(-2048, 2049)
i_f16 = np.array(i_int, dtype=float16)
j = np.array(i_f16, dtype=int)
assert_equal(i_int, j)
@pytest.mark.parametrize("offset", [None, "up", "down"])
@pytest.mark.parametrize("shift", [None, "up", "down"])
@pytest.mark.parametrize("float_t", [np.float32, np.float64])
def test_half_conversion_rounding(self, float_t, shift, offset):
# Assumes that round to even is used during casting.
max_pattern = np.float16(np.finfo(np.float16).max).view(np.uint16)
# Test all (positive) finite numbers, denormals are most interesting
# however:
f16s_patterns = np.arange(0, max_pattern+1, dtype=np.uint16)
f16s_float = f16s_patterns.view(np.float16).astype(float_t)
# Shift the values by half a bit up or a down (or do not shift),
if shift == "up":
f16s_float = 0.5 * (f16s_float[:-1] + f16s_float[1:])[1:]
elif shift == "down":
f16s_float = 0.5 * (f16s_float[:-1] + f16s_float[1:])[:-1]
else:
f16s_float = f16s_float[1:-1]
# Increase the float by a minimal value:
if offset == "up":
f16s_float = np.nextafter(f16s_float, float_t(1e50))
elif offset == "down":
f16s_float = np.nextafter(f16s_float, float_t(-1e50))
# Convert back to float16 and its bit pattern:
res_patterns = f16s_float.astype(np.float16).view(np.uint16)
# The above calculations tries the original values, or the exact
# mid points between the float16 values. It then further offsets them
# by as little as possible. If no offset occurs, "round to even"
# logic will be necessary, an arbitrarily small offset should cause
# normal up/down rounding always.
# Calculate the expected pattern:
cmp_patterns = f16s_patterns[1:-1].copy()
if shift == "down" and offset != "up":
shift_pattern = -1
elif shift == "up" and offset != "down":
shift_pattern = 1
else:
# There cannot be a shift, either shift is None, so all rounding
# will go back to original, or shift is reduced by offset too much.
shift_pattern = 0
# If rounding occurs, is it normal rounding or round to even?
if offset is None:
# Round to even occurs, modify only non-even, cast to allow + (-1)
cmp_patterns[0::2].view(np.int16)[...] += shift_pattern
else:
cmp_patterns.view(np.int16)[...] += shift_pattern
assert_equal(res_patterns, cmp_patterns)
@pytest.mark.parametrize(["float_t", "uint_t", "bits"],
[(np.float32, np.uint32, 23),
(np.float64, np.uint64, 52)])
def test_half_conversion_denormal_round_even(self, float_t, uint_t, bits):
# Test specifically that all bits are considered when deciding
# whether round to even should occur (i.e. no bits are lost at the
# end. Compare also gh-12721. The most bits can get lost for the
# smallest denormal:
smallest_value = np.uint16(1).view(np.float16).astype(float_t)
assert smallest_value == 2**-24
# Will be rounded to zero based on round to even rule:
rounded_to_zero = smallest_value / float_t(2)
assert rounded_to_zero.astype(np.float16) == 0
# The significand will be all 0 for the float_t, test that we do not
# lose the lower ones of these:
for i in range(bits):
# slightly increasing the value should make it round up:
larger_pattern = rounded_to_zero.view(uint_t) | uint_t(1 << i)
larger_value = larger_pattern.view(float_t)
assert larger_value.astype(np.float16) == smallest_value
def test_nans_infs(self):
with np.errstate(all='ignore'):
# Check some of the ufuncs
assert_equal(np.isnan(self.all_f16), np.isnan(self.all_f32))
assert_equal(np.isinf(self.all_f16), np.isinf(self.all_f32))
assert_equal(np.isfinite(self.all_f16), np.isfinite(self.all_f32))
assert_equal(np.signbit(self.all_f16), np.signbit(self.all_f32))
assert_equal(np.spacing(float16(65504)), np.inf)
# Check comparisons of all values with NaN
nan = float16(np.nan)
assert_(not (self.all_f16 == nan).any())
assert_(not (nan == self.all_f16).any())
assert_((self.all_f16 != nan).all())
assert_((nan != self.all_f16).all())
assert_(not (self.all_f16 < nan).any())
assert_(not (nan < self.all_f16).any())
assert_(not (self.all_f16 <= nan).any())
assert_(not (nan <= self.all_f16).any())
assert_(not (self.all_f16 > nan).any())
assert_(not (nan > self.all_f16).any())
assert_(not (self.all_f16 >= nan).any())
assert_(not (nan >= self.all_f16).any())
def test_half_values(self):
"""Confirms a small number of known half values"""
a = np.array([1.0, -1.0,
2.0, -2.0,
0.0999755859375, 0.333251953125, # 1/10, 1/3
65504, -65504, # Maximum magnitude
2.0**(-14), -2.0**(-14), # Minimum normal
2.0**(-24), -2.0**(-24), # Minimum subnormal
0, -1/1e1000, # Signed zeros
np.inf, -np.inf])
b = np.array([0x3c00, 0xbc00,
0x4000, 0xc000,
0x2e66, 0x3555,
0x7bff, 0xfbff,
0x0400, 0x8400,
0x0001, 0x8001,
0x0000, 0x8000,
0x7c00, 0xfc00], dtype=uint16)
b.dtype = float16
assert_equal(a, b)
def test_half_rounding(self):
"""Checks that rounding when converting to half is correct"""
a = np.array([2.0**-25 + 2.0**-35, # Rounds to minimum subnormal
2.0**-25, # Underflows to zero (nearest even mode)
2.0**-26, # Underflows to zero
1.0+2.0**-11 + 2.0**-16, # rounds to 1.0+2**(-10)
1.0+2.0**-11, # rounds to 1.0 (nearest even mode)
1.0+2.0**-12, # rounds to 1.0
65519, # rounds to 65504
65520], # rounds to inf
dtype=float64)
rounded = [2.0**-24,
0.0,
0.0,
1.0+2.0**(-10),
1.0,
1.0,
65504,
np.inf]
# Check float64->float16 rounding
b = np.array(a, dtype=float16)
assert_equal(b, rounded)
# Check float32->float16 rounding
a = np.array(a, dtype=float32)
b = np.array(a, dtype=float16)
assert_equal(b, rounded)
def test_half_correctness(self):
"""Take every finite float16, and check the casting functions with
a manual conversion."""
# Create an array of all finite float16s
a_bits = self.finite_f16.view(dtype=uint16)
# Convert to 64-bit float manually
a_sgn = (-1.0)**((a_bits & 0x8000) >> 15)
a_exp = np.array((a_bits & 0x7c00) >> 10, dtype=np.int32) - 15
a_man = (a_bits & 0x03ff) * 2.0**(-10)
# Implicit bit of normalized floats
a_man[a_exp != -15] += 1
# Denormalized exponent is -14
a_exp[a_exp == -15] = -14
a_manual = a_sgn * a_man * 2.0**a_exp
a32_fail = np.nonzero(self.finite_f32 != a_manual)[0]
if len(a32_fail) != 0:
bad_index = a32_fail[0]
assert_equal(self.finite_f32, a_manual,
"First non-equal is half value %x -> %g != %g" %
(self.finite_f16[bad_index],
self.finite_f32[bad_index],
a_manual[bad_index]))
a64_fail = np.nonzero(self.finite_f64 != a_manual)[0]
if len(a64_fail) != 0:
bad_index = a64_fail[0]
assert_equal(self.finite_f64, a_manual,
"First non-equal is half value %x -> %g != %g" %
(self.finite_f16[bad_index],
self.finite_f64[bad_index],
a_manual[bad_index]))
def test_half_ordering(self):
"""Make sure comparisons are working right"""
# All non-NaN float16 values in reverse order
a = self.nonan_f16[::-1].copy()
# 32-bit float copy
b = np.array(a, dtype=float32)
# Should sort the same
a.sort()
b.sort()
assert_equal(a, b)
# Comparisons should work
assert_((a[:-1] <= a[1:]).all())
assert_(not (a[:-1] > a[1:]).any())
assert_((a[1:] >= a[:-1]).all())
assert_(not (a[1:] < a[:-1]).any())
# All != except for +/-0
assert_equal(np.nonzero(a[:-1] < a[1:])[0].size, a.size-2)
assert_equal(np.nonzero(a[1:] > a[:-1])[0].size, a.size-2)
def test_half_funcs(self):
"""Test the various ArrFuncs"""
# fill
assert_equal(np.arange(10, dtype=float16),
np.arange(10, dtype=float32))
# fillwithscalar
a = np.zeros((5,), dtype=float16)
a.fill(1)
assert_equal(a, np.ones((5,), dtype=float16))
# nonzero and copyswap
a = np.array([0, 0, -1, -1/1e20, 0, 2.0**-24, 7.629e-6], dtype=float16)
assert_equal(a.nonzero()[0],
[2, 5, 6])
a = a.byteswap().newbyteorder()
assert_equal(a.nonzero()[0],
[2, 5, 6])
# dot
a = np.arange(0, 10, 0.5, dtype=float16)
b = np.ones((20,), dtype=float16)
assert_equal(np.dot(a, b),
95)
# argmax
a = np.array([0, -np.inf, -2, 0.5, 12.55, 7.3, 2.1, 12.4], dtype=float16)
assert_equal(a.argmax(),
4)
a = np.array([0, -np.inf, -2, np.inf, 12.55, np.nan, 2.1, 12.4], dtype=float16)
assert_equal(a.argmax(),
5)
# getitem
a = np.arange(10, dtype=float16)
for i in range(10):
assert_equal(a.item(i), i)
def test_spacing_nextafter(self):
"""Test np.spacing and np.nextafter"""
# All non-negative finite #'s
a = np.arange(0x7c00, dtype=uint16)
hinf = np.array((np.inf,), dtype=float16)
hnan = np.array((np.nan,), dtype=float16)
a_f16 = a.view(dtype=float16)
assert_equal(np.spacing(a_f16[:-1]), a_f16[1:]-a_f16[:-1])
assert_equal(np.nextafter(a_f16[:-1], hinf), a_f16[1:])
assert_equal(np.nextafter(a_f16[0], -hinf), -a_f16[1])
assert_equal(np.nextafter(a_f16[1:], -hinf), a_f16[:-1])
assert_equal(np.nextafter(hinf, a_f16), a_f16[-1])
assert_equal(np.nextafter(-hinf, a_f16), -a_f16[-1])
assert_equal(np.nextafter(hinf, hinf), hinf)
assert_equal(np.nextafter(hinf, -hinf), a_f16[-1])
assert_equal(np.nextafter(-hinf, hinf), -a_f16[-1])
assert_equal(np.nextafter(-hinf, -hinf), -hinf)
assert_equal(np.nextafter(a_f16, hnan), hnan[0])
assert_equal(np.nextafter(hnan, a_f16), hnan[0])
assert_equal(np.nextafter(hnan, hnan), hnan)
assert_equal(np.nextafter(hinf, hnan), hnan)
assert_equal(np.nextafter(hnan, hinf), hnan)
# switch to negatives
a |= 0x8000
assert_equal(np.spacing(a_f16[0]), np.spacing(a_f16[1]))
assert_equal(np.spacing(a_f16[1:]), a_f16[:-1]-a_f16[1:])
assert_equal(np.nextafter(a_f16[0], hinf), -a_f16[1])
assert_equal(np.nextafter(a_f16[1:], hinf), a_f16[:-1])
assert_equal(np.nextafter(a_f16[:-1], -hinf), a_f16[1:])
assert_equal(np.nextafter(hinf, a_f16), -a_f16[-1])
assert_equal(np.nextafter(-hinf, a_f16), a_f16[-1])
assert_equal(np.nextafter(a_f16, hnan), hnan[0])
assert_equal(np.nextafter(hnan, a_f16), hnan[0])
def test_half_ufuncs(self):
"""Test the various ufuncs"""
a = np.array([0, 1, 2, 4, 2], dtype=float16)
b = np.array([-2, 5, 1, 4, 3], dtype=float16)
c = np.array([0, -1, -np.inf, np.nan, 6], dtype=float16)
assert_equal(np.add(a, b), [-2, 6, 3, 8, 5])
assert_equal(np.subtract(a, b), [2, -4, 1, 0, -1])
assert_equal(np.multiply(a, b), [0, 5, 2, 16, 6])
assert_equal(np.divide(a, b), [0, 0.199951171875, 2, 1, 0.66650390625])
assert_equal(np.equal(a, b), [False, False, False, True, False])
assert_equal(np.not_equal(a, b), [True, True, True, False, True])
assert_equal(np.less(a, b), [False, True, False, False, True])
assert_equal(np.less_equal(a, b), [False, True, False, True, True])
assert_equal(np.greater(a, b), [True, False, True, False, False])
assert_equal(np.greater_equal(a, b), [True, False, True, True, False])
assert_equal(np.logical_and(a, b), [False, True, True, True, True])
assert_equal(np.logical_or(a, b), [True, True, True, True, True])
assert_equal(np.logical_xor(a, b), [True, False, False, False, False])
assert_equal(np.logical_not(a), [True, False, False, False, False])
assert_equal(np.isnan(c), [False, False, False, True, False])
assert_equal(np.isinf(c), [False, False, True, False, False])
assert_equal(np.isfinite(c), [True, True, False, False, True])
assert_equal(np.signbit(b), [True, False, False, False, False])
assert_equal(np.copysign(b, a), [2, 5, 1, 4, 3])
assert_equal(np.maximum(a, b), [0, 5, 2, 4, 3])
x = np.maximum(b, c)
assert_(np.isnan(x[3]))
x[3] = 0
assert_equal(x, [0, 5, 1, 0, 6])
assert_equal(np.minimum(a, b), [-2, 1, 1, 4, 2])
x = np.minimum(b, c)
assert_(np.isnan(x[3]))
x[3] = 0
assert_equal(x, [-2, -1, -np.inf, 0, 3])
assert_equal(np.fmax(a, b), [0, 5, 2, 4, 3])
assert_equal(np.fmax(b, c), [0, 5, 1, 4, 6])
assert_equal(np.fmin(a, b), [-2, 1, 1, 4, 2])
assert_equal(np.fmin(b, c), [-2, -1, -np.inf, 4, 3])
assert_equal(np.floor_divide(a, b), [0, 0, 2, 1, 0])
assert_equal(np.remainder(a, b), [0, 1, 0, 0, 2])
assert_equal(np.divmod(a, b), ([0, 0, 2, 1, 0], [0, 1, 0, 0, 2]))
assert_equal(np.square(b), [4, 25, 1, 16, 9])
assert_equal(np.reciprocal(b), [-0.5, 0.199951171875, 1, 0.25, 0.333251953125])
assert_equal(np.ones_like(b), [1, 1, 1, 1, 1])
assert_equal(np.conjugate(b), b)
assert_equal(np.absolute(b), [2, 5, 1, 4, 3])
assert_equal(np.negative(b), [2, -5, -1, -4, -3])
assert_equal(np.positive(b), b)
assert_equal(np.sign(b), [-1, 1, 1, 1, 1])
assert_equal(np.modf(b), ([0, 0, 0, 0, 0], b))
assert_equal(np.frexp(b), ([-0.5, 0.625, 0.5, 0.5, 0.75], [2, 3, 1, 3, 2]))
assert_equal(np.ldexp(b, [0, 1, 2, 4, 2]), [-2, 10, 4, 64, 12])
def test_half_coercion(self):
"""Test that half gets coerced properly with the other types"""
a16 = np.array((1,), dtype=float16)
a32 = np.array((1,), dtype=float32)
b16 = float16(1)
b32 = float32(1)
assert_equal(np.power(a16, 2).dtype, float16)
assert_equal(np.power(a16, 2.0).dtype, float16)
assert_equal(np.power(a16, b16).dtype, float16)
assert_equal(np.power(a16, b32).dtype, float16)
assert_equal(np.power(a16, a16).dtype, float16)
assert_equal(np.power(a16, a32).dtype, float32)
assert_equal(np.power(b16, 2).dtype, float64)
assert_equal(np.power(b16, 2.0).dtype, float64)
assert_equal(np.power(b16, b16).dtype, float16)
assert_equal(np.power(b16, b32).dtype, float32)
assert_equal(np.power(b16, a16).dtype, float16)
assert_equal(np.power(b16, a32).dtype, float32)
assert_equal(np.power(a32, a16).dtype, float32)
assert_equal(np.power(a32, b16).dtype, float32)
assert_equal(np.power(b32, a16).dtype, float16)
assert_equal(np.power(b32, b16).dtype, float32)
@pytest.mark.skipif(platform.machine() == "armv5tel",
reason="See gh-413.")
def test_half_fpe(self):
with np.errstate(all='raise'):
sx16 = np.array((1e-4,), dtype=float16)
bx16 = np.array((1e4,), dtype=float16)
sy16 = float16(1e-4)
by16 = float16(1e4)
# Underflow errors
assert_raises_fpe('underflow', lambda a, b:a*b, sx16, sx16)
assert_raises_fpe('underflow', lambda a, b:a*b, sx16, sy16)
assert_raises_fpe('underflow', lambda a, b:a*b, sy16, sx16)
assert_raises_fpe('underflow', lambda a, b:a*b, sy16, sy16)
assert_raises_fpe('underflow', lambda a, b:a/b, sx16, bx16)
assert_raises_fpe('underflow', lambda a, b:a/b, sx16, by16)
assert_raises_fpe('underflow', lambda a, b:a/b, sy16, bx16)
assert_raises_fpe('underflow', lambda a, b:a/b, sy16, by16)
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(2.**-14), float16(2**11))
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(-2.**-14), float16(2**11))
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(2.**-14+2**-24), float16(2))
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(-2.**-14-2**-24), float16(2))
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(2.**-14+2**-23), float16(4))
# Overflow errors
assert_raises_fpe('overflow', lambda a, b:a*b, bx16, bx16)
assert_raises_fpe('overflow', lambda a, b:a*b, bx16, by16)
assert_raises_fpe('overflow', lambda a, b:a*b, by16, bx16)
assert_raises_fpe('overflow', lambda a, b:a*b, by16, by16)
assert_raises_fpe('overflow', lambda a, b:a/b, bx16, sx16)
assert_raises_fpe('overflow', lambda a, b:a/b, bx16, sy16)
assert_raises_fpe('overflow', lambda a, b:a/b, by16, sx16)
assert_raises_fpe('overflow', lambda a, b:a/b, by16, sy16)
assert_raises_fpe('overflow', lambda a, b:a+b,
float16(65504), float16(17))
assert_raises_fpe('overflow', lambda a, b:a-b,
float16(-65504), float16(17))
assert_raises_fpe('overflow', np.nextafter, float16(65504), float16(np.inf))
assert_raises_fpe('overflow', np.nextafter, float16(-65504), float16(-np.inf))
assert_raises_fpe('overflow', np.spacing, float16(65504))
# Invalid value errors
assert_raises_fpe('invalid', np.divide, float16(np.inf), float16(np.inf))
assert_raises_fpe('invalid', np.spacing, float16(np.inf))
assert_raises_fpe('invalid', np.spacing, float16(np.nan))
# These should not raise
float16(65472)+float16(32)
float16(2**-13)/float16(2)
float16(2**-14)/float16(2**10)
np.spacing(float16(-65504))
np.nextafter(float16(65504), float16(-np.inf))
np.nextafter(float16(-65504), float16(np.inf))
np.nextafter(float16(np.inf), float16(0))
np.nextafter(float16(-np.inf), float16(0))
np.nextafter(float16(0), float16(np.nan))
np.nextafter(float16(np.nan), float16(0))
float16(2**-14)/float16(2**10)
float16(-2**-14)/float16(2**10)
float16(2**-14+2**-23)/float16(2)
float16(-2**-14-2**-23)/float16(2)
def test_half_array_interface(self):
"""Test that half is compatible with __array_interface__"""
class Dummy:
pass
a = np.ones((1,), dtype=float16)
b = Dummy()
b.__array_interface__ = a.__array_interface__
c = np.array(b)
assert_(c.dtype == float16)
assert_equal(a, c)

View file

@ -0,0 +1,133 @@
import numpy as np
from numpy.testing import (
assert_raises, assert_raises_regex,
)
class TestIndexErrors:
'''Tests to exercise indexerrors not covered by other tests.'''
def test_arraytypes_fasttake(self):
'take from a 0-length dimension'
x = np.empty((2, 3, 0, 4))
assert_raises(IndexError, x.take, [0], axis=2)
assert_raises(IndexError, x.take, [1], axis=2)
assert_raises(IndexError, x.take, [0], axis=2, mode='wrap')
assert_raises(IndexError, x.take, [0], axis=2, mode='clip')
def test_take_from_object(self):
# Check exception taking from object array
d = np.zeros(5, dtype=object)
assert_raises(IndexError, d.take, [6])
# Check exception taking from 0-d array
d = np.zeros((5, 0), dtype=object)
assert_raises(IndexError, d.take, [1], axis=1)
assert_raises(IndexError, d.take, [0], axis=1)
assert_raises(IndexError, d.take, [0])
assert_raises(IndexError, d.take, [0], mode='wrap')
assert_raises(IndexError, d.take, [0], mode='clip')
def test_multiindex_exceptions(self):
a = np.empty(5, dtype=object)
assert_raises(IndexError, a.item, 20)
a = np.empty((5, 0), dtype=object)
assert_raises(IndexError, a.item, (0, 0))
a = np.empty(5, dtype=object)
assert_raises(IndexError, a.itemset, 20, 0)
a = np.empty((5, 0), dtype=object)
assert_raises(IndexError, a.itemset, (0, 0), 0)
def test_put_exceptions(self):
a = np.zeros((5, 5))
assert_raises(IndexError, a.put, 100, 0)
a = np.zeros((5, 5), dtype=object)
assert_raises(IndexError, a.put, 100, 0)
a = np.zeros((5, 5, 0))
assert_raises(IndexError, a.put, 100, 0)
a = np.zeros((5, 5, 0), dtype=object)
assert_raises(IndexError, a.put, 100, 0)
def test_iterators_exceptions(self):
"cases in iterators.c"
def assign(obj, ind, val):
obj[ind] = val
a = np.zeros([1, 2, 3])
assert_raises(IndexError, lambda: a[0, 5, None, 2])
assert_raises(IndexError, lambda: a[0, 5, 0, 2])
assert_raises(IndexError, lambda: assign(a, (0, 5, None, 2), 1))
assert_raises(IndexError, lambda: assign(a, (0, 5, 0, 2), 1))
a = np.zeros([1, 0, 3])
assert_raises(IndexError, lambda: a[0, 0, None, 2])
assert_raises(IndexError, lambda: assign(a, (0, 0, None, 2), 1))
a = np.zeros([1, 2, 3])
assert_raises(IndexError, lambda: a.flat[10])
assert_raises(IndexError, lambda: assign(a.flat, 10, 5))
a = np.zeros([1, 0, 3])
assert_raises(IndexError, lambda: a.flat[10])
assert_raises(IndexError, lambda: assign(a.flat, 10, 5))
a = np.zeros([1, 2, 3])
assert_raises(IndexError, lambda: a.flat[np.array(10)])
assert_raises(IndexError, lambda: assign(a.flat, np.array(10), 5))
a = np.zeros([1, 0, 3])
assert_raises(IndexError, lambda: a.flat[np.array(10)])
assert_raises(IndexError, lambda: assign(a.flat, np.array(10), 5))
a = np.zeros([1, 2, 3])
assert_raises(IndexError, lambda: a.flat[np.array([10])])
assert_raises(IndexError, lambda: assign(a.flat, np.array([10]), 5))
a = np.zeros([1, 0, 3])
assert_raises(IndexError, lambda: a.flat[np.array([10])])
assert_raises(IndexError, lambda: assign(a.flat, np.array([10]), 5))
def test_mapping(self):
"cases from mapping.c"
def assign(obj, ind, val):
obj[ind] = val
a = np.zeros((0, 10))
assert_raises(IndexError, lambda: a[12])
a = np.zeros((3, 5))
assert_raises(IndexError, lambda: a[(10, 20)])
assert_raises(IndexError, lambda: assign(a, (10, 20), 1))
a = np.zeros((3, 0))
assert_raises(IndexError, lambda: a[(1, 0)])
assert_raises(IndexError, lambda: assign(a, (1, 0), 1))
a = np.zeros((10,))
assert_raises(IndexError, lambda: assign(a, 10, 1))
a = np.zeros((0,))
assert_raises(IndexError, lambda: assign(a, 10, 1))
a = np.zeros((3, 5))
assert_raises(IndexError, lambda: a[(1, [1, 20])])
assert_raises(IndexError, lambda: assign(a, (1, [1, 20]), 1))
a = np.zeros((3, 0))
assert_raises(IndexError, lambda: a[(1, [0, 1])])
assert_raises(IndexError, lambda: assign(a, (1, [0, 1]), 1))
def test_mapping_error_message(self):
a = np.zeros((3, 5))
index = (1, 2, 3, 4, 5)
assert_raises_regex(
IndexError,
"too many indices for array: "
"array is 2-dimensional, but 5 were indexed",
lambda: a[index])
def test_methods(self):
"cases from methods.c"
a = np.zeros((3, 3))
assert_raises(IndexError, lambda: a.item(100))
assert_raises(IndexError, lambda: a.itemset(100, 1))
a = np.zeros((0, 3))
assert_raises(IndexError, lambda: a.item(100))
assert_raises(IndexError, lambda: a.itemset(100, 1))

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,86 @@
import sys
import numpy as np
from numpy.testing import (
assert_, assert_raises, assert_array_equal, HAS_REFCOUNT
)
class TestTake:
def test_simple(self):
a = [[1, 2], [3, 4]]
a_str = [[b'1', b'2'], [b'3', b'4']]
modes = ['raise', 'wrap', 'clip']
indices = [-1, 4]
index_arrays = [np.empty(0, dtype=np.intp),
np.empty(tuple(), dtype=np.intp),
np.empty((1, 1), dtype=np.intp)]
real_indices = {'raise': {-1: 1, 4: IndexError},
'wrap': {-1: 1, 4: 0},
'clip': {-1: 0, 4: 1}}
# Currently all types but object, use the same function generation.
# So it should not be necessary to test all. However test also a non
# refcounted struct on top of object, which has a size that hits the
# default (non-specialized) path.
types = int, object, np.dtype([('', 'i2', 3)])
for t in types:
# ta works, even if the array may be odd if buffer interface is used
ta = np.array(a if np.issubdtype(t, np.number) else a_str, dtype=t)
tresult = list(ta.T.copy())
for index_array in index_arrays:
if index_array.size != 0:
tresult[0].shape = (2,) + index_array.shape
tresult[1].shape = (2,) + index_array.shape
for mode in modes:
for index in indices:
real_index = real_indices[mode][index]
if real_index is IndexError and index_array.size != 0:
index_array.put(0, index)
assert_raises(IndexError, ta.take, index_array,
mode=mode, axis=1)
elif index_array.size != 0:
index_array.put(0, index)
res = ta.take(index_array, mode=mode, axis=1)
assert_array_equal(res, tresult[real_index])
else:
res = ta.take(index_array, mode=mode, axis=1)
assert_(res.shape == (2,) + index_array.shape)
def test_refcounting(self):
objects = [object() for i in range(10)]
for mode in ('raise', 'clip', 'wrap'):
a = np.array(objects)
b = np.array([2, 2, 4, 5, 3, 5])
a.take(b, out=a[:6], mode=mode)
del a
if HAS_REFCOUNT:
assert_(all(sys.getrefcount(o) == 3 for o in objects))
# not contiguous, example:
a = np.array(objects * 2)[::2]
a.take(b, out=a[:6], mode=mode)
del a
if HAS_REFCOUNT:
assert_(all(sys.getrefcount(o) == 3 for o in objects))
def test_unicode_mode(self):
d = np.arange(10)
k = b'\xc3\xa4'.decode("UTF8")
assert_raises(ValueError, d.take, 5, mode=k)
def test_empty_partition(self):
# In reference to github issue #6530
a_original = np.array([0, 2, 4, 6, 8, 10])
a = a_original.copy()
# An empty partition should be a successful no-op
a.partition(np.array([], dtype=np.int16))
assert_array_equal(a, a_original)
def test_empty_argpartition(self):
# In reference to github issue #6530
a = np.array([0, 2, 4, 6, 8, 10])
a = a.argpartition(np.array([], dtype=np.int16))
b = np.array([0, 1, 2, 3, 4, 5])
assert_array_equal(a, b)

View file

@ -0,0 +1,369 @@
import warnings
import pytest
import numpy as np
from numpy.testing import (
assert_, assert_equal, assert_raises, assert_warns, assert_array_equal,
temppath,
)
from numpy.core.tests._locales import CommaDecimalPointLocale
LD_INFO = np.finfo(np.longdouble)
longdouble_longer_than_double = (LD_INFO.eps < np.finfo(np.double).eps)
_o = 1 + LD_INFO.eps
string_to_longdouble_inaccurate = (_o != np.longdouble(repr(_o)))
del _o
def test_scalar_extraction():
"""Confirm that extracting a value doesn't convert to python float"""
o = 1 + LD_INFO.eps
a = np.array([o, o, o])
assert_equal(a[1], o)
# Conversions string -> long double
# 0.1 not exactly representable in base 2 floating point.
repr_precision = len(repr(np.longdouble(0.1)))
# +2 from macro block starting around line 842 in scalartypes.c.src.
@pytest.mark.skipif(LD_INFO.precision + 2 >= repr_precision,
reason="repr precision not enough to show eps")
def test_repr_roundtrip():
# We will only see eps in repr if within printing precision.
o = 1 + LD_INFO.eps
assert_equal(np.longdouble(repr(o)), o, "repr was %s" % repr(o))
@pytest.mark.skipif(string_to_longdouble_inaccurate, reason="Need strtold_l")
def test_repr_roundtrip_bytes():
o = 1 + LD_INFO.eps
assert_equal(np.longdouble(repr(o).encode("ascii")), o)
@pytest.mark.skipif(string_to_longdouble_inaccurate, reason="Need strtold_l")
@pytest.mark.parametrize("strtype", (np.str_, np.bytes_, str, bytes))
def test_array_and_stringlike_roundtrip(strtype):
"""
Test that string representations of long-double roundtrip both
for array casting and scalar coercion, see also gh-15608.
"""
o = 1 + LD_INFO.eps
if strtype in (np.bytes_, bytes):
o_str = strtype(repr(o).encode("ascii"))
else:
o_str = strtype(repr(o))
# Test that `o` is correctly coerced from the string-like
assert o == np.longdouble(o_str)
# Test that arrays also roundtrip correctly:
o_strarr = np.asarray([o] * 3, dtype=strtype)
assert (o == o_strarr.astype(np.longdouble)).all()
# And array coercion and casting to string give the same as scalar repr:
assert (o_strarr == o_str).all()
assert (np.asarray([o] * 3).astype(strtype) == o_str).all()
def test_bogus_string():
assert_raises(ValueError, np.longdouble, "spam")
assert_raises(ValueError, np.longdouble, "1.0 flub")
@pytest.mark.skipif(string_to_longdouble_inaccurate, reason="Need strtold_l")
def test_fromstring():
o = 1 + LD_INFO.eps
s = (" " + repr(o))*5
a = np.array([o]*5)
assert_equal(np.fromstring(s, sep=" ", dtype=np.longdouble), a,
err_msg="reading '%s'" % s)
def test_fromstring_complex():
for ctype in ["complex", "cdouble", "cfloat"]:
# Check spacing between separator
assert_equal(np.fromstring("1, 2 , 3 ,4", sep=",", dtype=ctype),
np.array([1., 2., 3., 4.]))
# Real component not specified
assert_equal(np.fromstring("1j, -2j, 3j, 4e1j", sep=",", dtype=ctype),
np.array([1.j, -2.j, 3.j, 40.j]))
# Both components specified
assert_equal(np.fromstring("1+1j,2-2j, -3+3j, -4e1+4j", sep=",", dtype=ctype),
np.array([1. + 1.j, 2. - 2.j, - 3. + 3.j, - 40. + 4j]))
# Spaces at wrong places
with assert_warns(DeprecationWarning):
assert_equal(np.fromstring("1+2 j,3", dtype=ctype, sep=","),
np.array([1.]))
with assert_warns(DeprecationWarning):
assert_equal(np.fromstring("1+ 2j,3", dtype=ctype, sep=","),
np.array([1.]))
with assert_warns(DeprecationWarning):
assert_equal(np.fromstring("1 +2j,3", dtype=ctype, sep=","),
np.array([1.]))
with assert_warns(DeprecationWarning):
assert_equal(np.fromstring("1+j", dtype=ctype, sep=","),
np.array([1.]))
with assert_warns(DeprecationWarning):
assert_equal(np.fromstring("1+", dtype=ctype, sep=","),
np.array([1.]))
with assert_warns(DeprecationWarning):
assert_equal(np.fromstring("1j+1", dtype=ctype, sep=","),
np.array([1j]))
def test_fromstring_bogus():
with assert_warns(DeprecationWarning):
assert_equal(np.fromstring("1. 2. 3. flop 4.", dtype=float, sep=" "),
np.array([1., 2., 3.]))
def test_fromstring_empty():
with assert_warns(DeprecationWarning):
assert_equal(np.fromstring("xxxxx", sep="x"),
np.array([]))
def test_fromstring_missing():
with assert_warns(DeprecationWarning):
assert_equal(np.fromstring("1xx3x4x5x6", sep="x"),
np.array([1]))
class TestFileBased:
ldbl = 1 + LD_INFO.eps
tgt = np.array([ldbl]*5)
out = ''.join([repr(t) + '\n' for t in tgt])
def test_fromfile_bogus(self):
with temppath() as path:
with open(path, 'wt') as f:
f.write("1. 2. 3. flop 4.\n")
with assert_warns(DeprecationWarning):
res = np.fromfile(path, dtype=float, sep=" ")
assert_equal(res, np.array([1., 2., 3.]))
def test_fromfile_complex(self):
for ctype in ["complex", "cdouble", "cfloat"]:
# Check spacing between separator and only real component specified
with temppath() as path:
with open(path, 'wt') as f:
f.write("1, 2 , 3 ,4\n")
res = np.fromfile(path, dtype=ctype, sep=",")
assert_equal(res, np.array([1., 2., 3., 4.]))
# Real component not specified
with temppath() as path:
with open(path, 'wt') as f:
f.write("1j, -2j, 3j, 4e1j\n")
res = np.fromfile(path, dtype=ctype, sep=",")
assert_equal(res, np.array([1.j, -2.j, 3.j, 40.j]))
# Both components specified
with temppath() as path:
with open(path, 'wt') as f:
f.write("1+1j,2-2j, -3+3j, -4e1+4j\n")
res = np.fromfile(path, dtype=ctype, sep=",")
assert_equal(res, np.array([1. + 1.j, 2. - 2.j, - 3. + 3.j, - 40. + 4j]))
# Spaces at wrong places
with temppath() as path:
with open(path, 'wt') as f:
f.write("1+2 j,3\n")
with assert_warns(DeprecationWarning):
res = np.fromfile(path, dtype=ctype, sep=",")
assert_equal(res, np.array([1.]))
# Spaces at wrong places
with temppath() as path:
with open(path, 'wt') as f:
f.write("1+ 2j,3\n")
with assert_warns(DeprecationWarning):
res = np.fromfile(path, dtype=ctype, sep=",")
assert_equal(res, np.array([1.]))
# Spaces at wrong places
with temppath() as path:
with open(path, 'wt') as f:
f.write("1 +2j,3\n")
with assert_warns(DeprecationWarning):
res = np.fromfile(path, dtype=ctype, sep=",")
assert_equal(res, np.array([1.]))
# Spaces at wrong places
with temppath() as path:
with open(path, 'wt') as f:
f.write("1+j\n")
with assert_warns(DeprecationWarning):
res = np.fromfile(path, dtype=ctype, sep=",")
assert_equal(res, np.array([1.]))
# Spaces at wrong places
with temppath() as path:
with open(path, 'wt') as f:
f.write("1+\n")
with assert_warns(DeprecationWarning):
res = np.fromfile(path, dtype=ctype, sep=",")
assert_equal(res, np.array([1.]))
# Spaces at wrong places
with temppath() as path:
with open(path, 'wt') as f:
f.write("1j+1\n")
with assert_warns(DeprecationWarning):
res = np.fromfile(path, dtype=ctype, sep=",")
assert_equal(res, np.array([1.j]))
@pytest.mark.skipif(string_to_longdouble_inaccurate,
reason="Need strtold_l")
def test_fromfile(self):
with temppath() as path:
with open(path, 'wt') as f:
f.write(self.out)
res = np.fromfile(path, dtype=np.longdouble, sep="\n")
assert_equal(res, self.tgt)
@pytest.mark.skipif(string_to_longdouble_inaccurate,
reason="Need strtold_l")
def test_genfromtxt(self):
with temppath() as path:
with open(path, 'wt') as f:
f.write(self.out)
res = np.genfromtxt(path, dtype=np.longdouble)
assert_equal(res, self.tgt)
@pytest.mark.skipif(string_to_longdouble_inaccurate,
reason="Need strtold_l")
def test_loadtxt(self):
with temppath() as path:
with open(path, 'wt') as f:
f.write(self.out)
res = np.loadtxt(path, dtype=np.longdouble)
assert_equal(res, self.tgt)
@pytest.mark.skipif(string_to_longdouble_inaccurate,
reason="Need strtold_l")
def test_tofile_roundtrip(self):
with temppath() as path:
self.tgt.tofile(path, sep=" ")
res = np.fromfile(path, dtype=np.longdouble, sep=" ")
assert_equal(res, self.tgt)
# Conversions long double -> string
def test_repr_exact():
o = 1 + LD_INFO.eps
assert_(repr(o) != '1')
@pytest.mark.skipif(longdouble_longer_than_double, reason="BUG #2376")
@pytest.mark.skipif(string_to_longdouble_inaccurate,
reason="Need strtold_l")
def test_format():
o = 1 + LD_INFO.eps
assert_("{0:.40g}".format(o) != '1')
@pytest.mark.skipif(longdouble_longer_than_double, reason="BUG #2376")
@pytest.mark.skipif(string_to_longdouble_inaccurate,
reason="Need strtold_l")
def test_percent():
o = 1 + LD_INFO.eps
assert_("%.40g" % o != '1')
@pytest.mark.skipif(longdouble_longer_than_double,
reason="array repr problem")
@pytest.mark.skipif(string_to_longdouble_inaccurate,
reason="Need strtold_l")
def test_array_repr():
o = 1 + LD_INFO.eps
a = np.array([o])
b = np.array([1], dtype=np.longdouble)
if not np.all(a != b):
raise ValueError("precision loss creating arrays")
assert_(repr(a) != repr(b))
#
# Locale tests: scalar types formatting should be independent of the locale
#
class TestCommaDecimalPointLocale(CommaDecimalPointLocale):
def test_repr_roundtrip_foreign(self):
o = 1.5
assert_equal(o, np.longdouble(repr(o)))
def test_fromstring_foreign_repr(self):
f = 1.234
a = np.fromstring(repr(f), dtype=float, sep=" ")
assert_equal(a[0], f)
def test_fromstring_best_effort_float(self):
with assert_warns(DeprecationWarning):
assert_equal(np.fromstring("1,234", dtype=float, sep=" "),
np.array([1.]))
def test_fromstring_best_effort(self):
with assert_warns(DeprecationWarning):
assert_equal(np.fromstring("1,234", dtype=np.longdouble, sep=" "),
np.array([1.]))
def test_fromstring_foreign(self):
s = "1.234"
a = np.fromstring(s, dtype=np.longdouble, sep=" ")
assert_equal(a[0], np.longdouble(s))
def test_fromstring_foreign_sep(self):
a = np.array([1, 2, 3, 4])
b = np.fromstring("1,2,3,4,", dtype=np.longdouble, sep=",")
assert_array_equal(a, b)
def test_fromstring_foreign_value(self):
with assert_warns(DeprecationWarning):
b = np.fromstring("1,234", dtype=np.longdouble, sep=" ")
assert_array_equal(b[0], 1)
@pytest.mark.parametrize("int_val", [
# cases discussed in gh-10723
# and gh-9968
2 ** 1024, 0])
def test_longdouble_from_int(int_val):
# for issue gh-9968
str_val = str(int_val)
# we'll expect a RuntimeWarning on platforms
# with np.longdouble equivalent to np.double
# for large integer input
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', RuntimeWarning)
# can be inf==inf on some platforms
assert np.longdouble(int_val) == np.longdouble(str_val)
# we can't directly compare the int and
# max longdouble value on all platforms
if np.allclose(np.finfo(np.longdouble).max,
np.finfo(np.double).max) and w:
assert w[0].category is RuntimeWarning
@pytest.mark.parametrize("bool_val", [
True, False])
def test_longdouble_from_bool(bool_val):
assert np.longdouble(bool_val) == np.longdouble(int(bool_val))

View file

@ -0,0 +1,30 @@
"""
Test machar. Given recent changes to hardcode type data, we might want to get
rid of both MachAr and this test at some point.
"""
from numpy.core.machar import MachAr
import numpy.core.numerictypes as ntypes
from numpy import errstate, array
class TestMachAr:
def _run_machar_highprec(self):
# Instantiate MachAr instance with high enough precision to cause
# underflow
try:
hiprec = ntypes.float96
MachAr(lambda v: array(v, hiprec))
except AttributeError:
# Fixme, this needs to raise a 'skip' exception.
"Skipping test: no ntypes.float96 available on this platform."
def test_underlow(self):
# Regression test for #759:
# instantiating MachAr for dtype = np.float96 raises spurious warning.
with errstate(all='raise'):
try:
self._run_machar_highprec()
except FloatingPointError as e:
msg = "Caught %s exception, should not have been raised." % e
raise AssertionError(msg)

View file

@ -0,0 +1,926 @@
import itertools
import pytest
import numpy as np
from numpy.core._multiarray_tests import solve_diophantine, internal_overlap
from numpy.core import _umath_tests
from numpy.lib.stride_tricks import as_strided
from numpy.testing import (
assert_, assert_raises, assert_equal, assert_array_equal
)
ndims = 2
size = 10
shape = tuple([size] * ndims)
MAY_SHARE_BOUNDS = 0
MAY_SHARE_EXACT = -1
def _indices_for_nelems(nelems):
"""Returns slices of length nelems, from start onwards, in direction sign."""
if nelems == 0:
return [size // 2] # int index
res = []
for step in (1, 2):
for sign in (-1, 1):
start = size // 2 - nelems * step * sign // 2
stop = start + nelems * step * sign
res.append(slice(start, stop, step * sign))
return res
def _indices_for_axis():
"""Returns (src, dst) pairs of indices."""
res = []
for nelems in (0, 2, 3):
ind = _indices_for_nelems(nelems)
res.extend(itertools.product(ind, ind)) # all assignments of size "nelems"
return res
def _indices(ndims):
"""Returns ((axis0_src, axis0_dst), (axis1_src, axis1_dst), ... ) index pairs."""
ind = _indices_for_axis()
return itertools.product(ind, repeat=ndims)
def _check_assignment(srcidx, dstidx):
"""Check assignment arr[dstidx] = arr[srcidx] works."""
arr = np.arange(np.product(shape)).reshape(shape)
cpy = arr.copy()
cpy[dstidx] = arr[srcidx]
arr[dstidx] = arr[srcidx]
assert_(np.all(arr == cpy),
'assigning arr[%s] = arr[%s]' % (dstidx, srcidx))
def test_overlapping_assignments():
# Test automatically generated assignments which overlap in memory.
inds = _indices(ndims)
for ind in inds:
srcidx = tuple([a[0] for a in ind])
dstidx = tuple([a[1] for a in ind])
_check_assignment(srcidx, dstidx)
@pytest.mark.slow
def test_diophantine_fuzz():
# Fuzz test the diophantine solver
rng = np.random.RandomState(1234)
max_int = np.iinfo(np.intp).max
for ndim in range(10):
feasible_count = 0
infeasible_count = 0
min_count = 500//(ndim + 1)
while min(feasible_count, infeasible_count) < min_count:
# Ensure big and small integer problems
A_max = 1 + rng.randint(0, 11, dtype=np.intp)**6
U_max = rng.randint(0, 11, dtype=np.intp)**6
A_max = min(max_int, A_max)
U_max = min(max_int-1, U_max)
A = tuple(int(rng.randint(1, A_max+1, dtype=np.intp))
for j in range(ndim))
U = tuple(int(rng.randint(0, U_max+2, dtype=np.intp))
for j in range(ndim))
b_ub = min(max_int-2, sum(a*ub for a, ub in zip(A, U)))
b = rng.randint(-1, b_ub+2, dtype=np.intp)
if ndim == 0 and feasible_count < min_count:
b = 0
X = solve_diophantine(A, U, b)
if X is None:
# Check the simplified decision problem agrees
X_simplified = solve_diophantine(A, U, b, simplify=1)
assert_(X_simplified is None, (A, U, b, X_simplified))
# Check no solution exists (provided the problem is
# small enough so that brute force checking doesn't
# take too long)
ranges = tuple(range(0, a*ub+1, a) for a, ub in zip(A, U))
size = 1
for r in ranges:
size *= len(r)
if size < 100000:
assert_(not any(sum(w) == b for w in itertools.product(*ranges)))
infeasible_count += 1
else:
# Check the simplified decision problem agrees
X_simplified = solve_diophantine(A, U, b, simplify=1)
assert_(X_simplified is not None, (A, U, b, X_simplified))
# Check validity
assert_(sum(a*x for a, x in zip(A, X)) == b)
assert_(all(0 <= x <= ub for x, ub in zip(X, U)))
feasible_count += 1
def test_diophantine_overflow():
# Smoke test integer overflow detection
max_intp = np.iinfo(np.intp).max
max_int64 = np.iinfo(np.int64).max
if max_int64 <= max_intp:
# Check that the algorithm works internally in 128-bit;
# solving this problem requires large intermediate numbers
A = (max_int64//2, max_int64//2 - 10)
U = (max_int64//2, max_int64//2 - 10)
b = 2*(max_int64//2) - 10
assert_equal(solve_diophantine(A, U, b), (1, 1))
def check_may_share_memory_exact(a, b):
got = np.may_share_memory(a, b, max_work=MAY_SHARE_EXACT)
assert_equal(np.may_share_memory(a, b),
np.may_share_memory(a, b, max_work=MAY_SHARE_BOUNDS))
a.fill(0)
b.fill(0)
a.fill(1)
exact = b.any()
err_msg = ""
if got != exact:
err_msg = " " + "\n ".join([
"base_a - base_b = %r" % (a.__array_interface__['data'][0] - b.__array_interface__['data'][0],),
"shape_a = %r" % (a.shape,),
"shape_b = %r" % (b.shape,),
"strides_a = %r" % (a.strides,),
"strides_b = %r" % (b.strides,),
"size_a = %r" % (a.size,),
"size_b = %r" % (b.size,)
])
assert_equal(got, exact, err_msg=err_msg)
def test_may_share_memory_manual():
# Manual test cases for may_share_memory
# Base arrays
xs0 = [
np.zeros([13, 21, 23, 22], dtype=np.int8),
np.zeros([13, 21, 23*2, 22], dtype=np.int8)[:,:,::2,:]
]
# Generate all negative stride combinations
xs = []
for x in xs0:
for ss in itertools.product(*(([slice(None), slice(None, None, -1)],)*4)):
xp = x[ss]
xs.append(xp)
for x in xs:
# The default is a simple extent check
assert_(np.may_share_memory(x[:,0,:], x[:,1,:]))
assert_(np.may_share_memory(x[:,0,:], x[:,1,:], max_work=None))
# Exact checks
check_may_share_memory_exact(x[:,0,:], x[:,1,:])
check_may_share_memory_exact(x[:,::7], x[:,3::3])
try:
xp = x.ravel()
if xp.flags.owndata:
continue
xp = xp.view(np.int16)
except ValueError:
continue
# 0-size arrays cannot overlap
check_may_share_memory_exact(x.ravel()[6:6],
xp.reshape(13, 21, 23, 11)[:,::7])
# Test itemsize is dealt with
check_may_share_memory_exact(x[:,::7],
xp.reshape(13, 21, 23, 11))
check_may_share_memory_exact(x[:,::7],
xp.reshape(13, 21, 23, 11)[:,3::3])
check_may_share_memory_exact(x.ravel()[6:7],
xp.reshape(13, 21, 23, 11)[:,::7])
# Check unit size
x = np.zeros([1], dtype=np.int8)
check_may_share_memory_exact(x, x)
check_may_share_memory_exact(x, x.copy())
def iter_random_view_pairs(x, same_steps=True, equal_size=False):
rng = np.random.RandomState(1234)
if equal_size and same_steps:
raise ValueError()
def random_slice(n, step):
start = rng.randint(0, n+1, dtype=np.intp)
stop = rng.randint(start, n+1, dtype=np.intp)
if rng.randint(0, 2, dtype=np.intp) == 0:
stop, start = start, stop
step *= -1
return slice(start, stop, step)
def random_slice_fixed_size(n, step, size):
start = rng.randint(0, n+1 - size*step)
stop = start + (size-1)*step + 1
if rng.randint(0, 2) == 0:
stop, start = start-1, stop-1
if stop < 0:
stop = None
step *= -1
return slice(start, stop, step)
# First a few regular views
yield x, x
for j in range(1, 7, 3):
yield x[j:], x[:-j]
yield x[...,j:], x[...,:-j]
# An array with zero stride internal overlap
strides = list(x.strides)
strides[0] = 0
xp = as_strided(x, shape=x.shape, strides=strides)
yield x, xp
yield xp, xp
# An array with non-zero stride internal overlap
strides = list(x.strides)
if strides[0] > 1:
strides[0] = 1
xp = as_strided(x, shape=x.shape, strides=strides)
yield x, xp
yield xp, xp
# Then discontiguous views
while True:
steps = tuple(rng.randint(1, 11, dtype=np.intp)
if rng.randint(0, 5, dtype=np.intp) == 0 else 1
for j in range(x.ndim))
s1 = tuple(random_slice(p, s) for p, s in zip(x.shape, steps))
t1 = np.arange(x.ndim)
rng.shuffle(t1)
if equal_size:
t2 = t1
else:
t2 = np.arange(x.ndim)
rng.shuffle(t2)
a = x[s1]
if equal_size:
if a.size == 0:
continue
steps2 = tuple(rng.randint(1, max(2, p//(1+pa)))
if rng.randint(0, 5) == 0 else 1
for p, s, pa in zip(x.shape, s1, a.shape))
s2 = tuple(random_slice_fixed_size(p, s, pa)
for p, s, pa in zip(x.shape, steps2, a.shape))
elif same_steps:
steps2 = steps
else:
steps2 = tuple(rng.randint(1, 11, dtype=np.intp)
if rng.randint(0, 5, dtype=np.intp) == 0 else 1
for j in range(x.ndim))
if not equal_size:
s2 = tuple(random_slice(p, s) for p, s in zip(x.shape, steps2))
a = a.transpose(t1)
b = x[s2].transpose(t2)
yield a, b
def check_may_share_memory_easy_fuzz(get_max_work, same_steps, min_count):
# Check that overlap problems with common strides are solved with
# little work.
x = np.zeros([17,34,71,97], dtype=np.int16)
feasible = 0
infeasible = 0
pair_iter = iter_random_view_pairs(x, same_steps)
while min(feasible, infeasible) < min_count:
a, b = next(pair_iter)
bounds_overlap = np.may_share_memory(a, b)
may_share_answer = np.may_share_memory(a, b)
easy_answer = np.may_share_memory(a, b, max_work=get_max_work(a, b))
exact_answer = np.may_share_memory(a, b, max_work=MAY_SHARE_EXACT)
if easy_answer != exact_answer:
# assert_equal is slow...
assert_equal(easy_answer, exact_answer)
if may_share_answer != bounds_overlap:
assert_equal(may_share_answer, bounds_overlap)
if bounds_overlap:
if exact_answer:
feasible += 1
else:
infeasible += 1
@pytest.mark.slow
def test_may_share_memory_easy_fuzz():
# Check that overlap problems with common strides are always
# solved with little work.
check_may_share_memory_easy_fuzz(get_max_work=lambda a, b: 1,
same_steps=True,
min_count=2000)
@pytest.mark.slow
def test_may_share_memory_harder_fuzz():
# Overlap problems with not necessarily common strides take more
# work.
#
# The work bound below can't be reduced much. Harder problems can
# also exist but not be detected here, as the set of problems
# comes from RNG.
check_may_share_memory_easy_fuzz(get_max_work=lambda a, b: max(a.size, b.size)//2,
same_steps=False,
min_count=2000)
def test_shares_memory_api():
x = np.zeros([4, 5, 6], dtype=np.int8)
assert_equal(np.shares_memory(x, x), True)
assert_equal(np.shares_memory(x, x.copy()), False)
a = x[:,::2,::3]
b = x[:,::3,::2]
assert_equal(np.shares_memory(a, b), True)
assert_equal(np.shares_memory(a, b, max_work=None), True)
assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=1)
def test_may_share_memory_bad_max_work():
x = np.zeros([1])
assert_raises(OverflowError, np.may_share_memory, x, x, max_work=10**100)
assert_raises(OverflowError, np.shares_memory, x, x, max_work=10**100)
def test_internal_overlap_diophantine():
def check(A, U, exists=None):
X = solve_diophantine(A, U, 0, require_ub_nontrivial=1)
if exists is None:
exists = (X is not None)
if X is not None:
assert_(sum(a*x for a, x in zip(A, X)) == sum(a*u//2 for a, u in zip(A, U)))
assert_(all(0 <= x <= u for x, u in zip(X, U)))
assert_(any(x != u//2 for x, u in zip(X, U)))
if exists:
assert_(X is not None, repr(X))
else:
assert_(X is None, repr(X))
# Smoke tests
check((3, 2), (2*2, 3*2), exists=True)
check((3*2, 2), (15*2, (3-1)*2), exists=False)
def test_internal_overlap_slices():
# Slicing an array never generates internal overlap
x = np.zeros([17,34,71,97], dtype=np.int16)
rng = np.random.RandomState(1234)
def random_slice(n, step):
start = rng.randint(0, n+1, dtype=np.intp)
stop = rng.randint(start, n+1, dtype=np.intp)
if rng.randint(0, 2, dtype=np.intp) == 0:
stop, start = start, stop
step *= -1
return slice(start, stop, step)
cases = 0
min_count = 5000
while cases < min_count:
steps = tuple(rng.randint(1, 11, dtype=np.intp)
if rng.randint(0, 5, dtype=np.intp) == 0 else 1
for j in range(x.ndim))
t1 = np.arange(x.ndim)
rng.shuffle(t1)
s1 = tuple(random_slice(p, s) for p, s in zip(x.shape, steps))
a = x[s1].transpose(t1)
assert_(not internal_overlap(a))
cases += 1
def check_internal_overlap(a, manual_expected=None):
got = internal_overlap(a)
# Brute-force check
m = set()
ranges = tuple(range(n) for n in a.shape)
for v in itertools.product(*ranges):
offset = sum(s*w for s, w in zip(a.strides, v))
if offset in m:
expected = True
break
else:
m.add(offset)
else:
expected = False
# Compare
if got != expected:
assert_equal(got, expected, err_msg=repr((a.strides, a.shape)))
if manual_expected is not None and expected != manual_expected:
assert_equal(expected, manual_expected)
return got
def test_internal_overlap_manual():
# Stride tricks can construct arrays with internal overlap
# We don't care about memory bounds, the array is not
# read/write accessed
x = np.arange(1).astype(np.int8)
# Check low-dimensional special cases
check_internal_overlap(x, False) # 1-dim
check_internal_overlap(x.reshape([]), False) # 0-dim
a = as_strided(x, strides=(3, 4), shape=(4, 4))
check_internal_overlap(a, False)
a = as_strided(x, strides=(3, 4), shape=(5, 4))
check_internal_overlap(a, True)
a = as_strided(x, strides=(0,), shape=(0,))
check_internal_overlap(a, False)
a = as_strided(x, strides=(0,), shape=(1,))
check_internal_overlap(a, False)
a = as_strided(x, strides=(0,), shape=(2,))
check_internal_overlap(a, True)
a = as_strided(x, strides=(0, -9993), shape=(87, 22))
check_internal_overlap(a, True)
a = as_strided(x, strides=(0, -9993), shape=(1, 22))
check_internal_overlap(a, False)
a = as_strided(x, strides=(0, -9993), shape=(0, 22))
check_internal_overlap(a, False)
def test_internal_overlap_fuzz():
# Fuzz check; the brute-force check is fairly slow
x = np.arange(1).astype(np.int8)
overlap = 0
no_overlap = 0
min_count = 100
rng = np.random.RandomState(1234)
while min(overlap, no_overlap) < min_count:
ndim = rng.randint(1, 4, dtype=np.intp)
strides = tuple(rng.randint(-1000, 1000, dtype=np.intp)
for j in range(ndim))
shape = tuple(rng.randint(1, 30, dtype=np.intp)
for j in range(ndim))
a = as_strided(x, strides=strides, shape=shape)
result = check_internal_overlap(a)
if result:
overlap += 1
else:
no_overlap += 1
def test_non_ndarray_inputs():
# Regression check for gh-5604
class MyArray:
def __init__(self, data):
self.data = data
@property
def __array_interface__(self):
return self.data.__array_interface__
class MyArray2:
def __init__(self, data):
self.data = data
def __array__(self):
return self.data
for cls in [MyArray, MyArray2]:
x = np.arange(5)
assert_(np.may_share_memory(cls(x[::2]), x[1::2]))
assert_(not np.shares_memory(cls(x[::2]), x[1::2]))
assert_(np.shares_memory(cls(x[1::3]), x[::2]))
assert_(np.may_share_memory(cls(x[1::3]), x[::2]))
def view_element_first_byte(x):
"""Construct an array viewing the first byte of each element of `x`"""
from numpy.lib.stride_tricks import DummyArray
interface = dict(x.__array_interface__)
interface['typestr'] = '|b1'
interface['descr'] = [('', '|b1')]
return np.asarray(DummyArray(interface, x))
def assert_copy_equivalent(operation, args, out, **kwargs):
"""
Check that operation(*args, out=out) produces results
equivalent to out[...] = operation(*args, out=out.copy())
"""
kwargs['out'] = out
kwargs2 = dict(kwargs)
kwargs2['out'] = out.copy()
out_orig = out.copy()
out[...] = operation(*args, **kwargs2)
expected = out.copy()
out[...] = out_orig
got = operation(*args, **kwargs).copy()
if (got != expected).any():
assert_equal(got, expected)
class TestUFunc:
"""
Test ufunc call memory overlap handling
"""
def check_unary_fuzz(self, operation, get_out_axis_size, dtype=np.int16,
count=5000):
shapes = [7, 13, 8, 21, 29, 32]
rng = np.random.RandomState(1234)
for ndim in range(1, 6):
x = rng.randint(0, 2**16, size=shapes[:ndim]).astype(dtype)
it = iter_random_view_pairs(x, same_steps=False, equal_size=True)
min_count = count // (ndim + 1)**2
overlapping = 0
while overlapping < min_count:
a, b = next(it)
a_orig = a.copy()
b_orig = b.copy()
if get_out_axis_size is None:
assert_copy_equivalent(operation, [a], out=b)
if np.shares_memory(a, b):
overlapping += 1
else:
for axis in itertools.chain(range(ndim), [None]):
a[...] = a_orig
b[...] = b_orig
# Determine size for reduction axis (None if scalar)
outsize, scalarize = get_out_axis_size(a, b, axis)
if outsize == 'skip':
continue
# Slice b to get an output array of the correct size
sl = [slice(None)] * ndim
if axis is None:
if outsize is None:
sl = [slice(0, 1)] + [0]*(ndim - 1)
else:
sl = [slice(0, outsize)] + [0]*(ndim - 1)
else:
if outsize is None:
k = b.shape[axis]//2
if ndim == 1:
sl[axis] = slice(k, k + 1)
else:
sl[axis] = k
else:
assert b.shape[axis] >= outsize
sl[axis] = slice(0, outsize)
b_out = b[tuple(sl)]
if scalarize:
b_out = b_out.reshape([])
if np.shares_memory(a, b_out):
overlapping += 1
# Check result
assert_copy_equivalent(operation, [a], out=b_out, axis=axis)
@pytest.mark.slow
def test_unary_ufunc_call_fuzz(self):
self.check_unary_fuzz(np.invert, None, np.int16)
def test_binary_ufunc_accumulate_fuzz(self):
def get_out_axis_size(a, b, axis):
if axis is None:
if a.ndim == 1:
return a.size, False
else:
return 'skip', False # accumulate doesn't support this
else:
return a.shape[axis], False
self.check_unary_fuzz(np.add.accumulate, get_out_axis_size,
dtype=np.int16, count=500)
def test_binary_ufunc_reduce_fuzz(self):
def get_out_axis_size(a, b, axis):
return None, (axis is None or a.ndim == 1)
self.check_unary_fuzz(np.add.reduce, get_out_axis_size,
dtype=np.int16, count=500)
def test_binary_ufunc_reduceat_fuzz(self):
def get_out_axis_size(a, b, axis):
if axis is None:
if a.ndim == 1:
return a.size, False
else:
return 'skip', False # reduceat doesn't support this
else:
return a.shape[axis], False
def do_reduceat(a, out, axis):
if axis is None:
size = len(a)
step = size//len(out)
else:
size = a.shape[axis]
step = a.shape[axis] // out.shape[axis]
idx = np.arange(0, size, step)
return np.add.reduceat(a, idx, out=out, axis=axis)
self.check_unary_fuzz(do_reduceat, get_out_axis_size,
dtype=np.int16, count=500)
def test_binary_ufunc_reduceat_manual(self):
def check(ufunc, a, ind, out):
c1 = ufunc.reduceat(a.copy(), ind.copy(), out=out.copy())
c2 = ufunc.reduceat(a, ind, out=out)
assert_array_equal(c1, c2)
# Exactly same input/output arrays
a = np.arange(10000, dtype=np.int16)
check(np.add, a, a[::-1].copy(), a)
# Overlap with index
a = np.arange(10000, dtype=np.int16)
check(np.add, a, a[::-1], a)
@pytest.mark.slow
def test_unary_gufunc_fuzz(self):
shapes = [7, 13, 8, 21, 29, 32]
gufunc = _umath_tests.euclidean_pdist
rng = np.random.RandomState(1234)
for ndim in range(2, 6):
x = rng.rand(*shapes[:ndim])
it = iter_random_view_pairs(x, same_steps=False, equal_size=True)
min_count = 500 // (ndim + 1)**2
overlapping = 0
while overlapping < min_count:
a, b = next(it)
if min(a.shape[-2:]) < 2 or min(b.shape[-2:]) < 2 or a.shape[-1] < 2:
continue
# Ensure the shapes are so that euclidean_pdist is happy
if b.shape[-1] > b.shape[-2]:
b = b[...,0,:]
else:
b = b[...,:,0]
n = a.shape[-2]
p = n * (n - 1) // 2
if p <= b.shape[-1] and p > 0:
b = b[...,:p]
else:
n = max(2, int(np.sqrt(b.shape[-1]))//2)
p = n * (n - 1) // 2
a = a[...,:n,:]
b = b[...,:p]
# Call
if np.shares_memory(a, b):
overlapping += 1
with np.errstate(over='ignore', invalid='ignore'):
assert_copy_equivalent(gufunc, [a], out=b)
def test_ufunc_at_manual(self):
def check(ufunc, a, ind, b=None):
a0 = a.copy()
if b is None:
ufunc.at(a0, ind.copy())
c1 = a0.copy()
ufunc.at(a, ind)
c2 = a.copy()
else:
ufunc.at(a0, ind.copy(), b.copy())
c1 = a0.copy()
ufunc.at(a, ind, b)
c2 = a.copy()
assert_array_equal(c1, c2)
# Overlap with index
a = np.arange(10000, dtype=np.int16)
check(np.invert, a[::-1], a)
# Overlap with second data array
a = np.arange(100, dtype=np.int16)
ind = np.arange(0, 100, 2, dtype=np.int16)
check(np.add, a, ind, a[25:75])
def test_unary_ufunc_1d_manual(self):
# Exercise branches in PyArray_EQUIVALENTLY_ITERABLE
def check(a, b):
a_orig = a.copy()
b_orig = b.copy()
b0 = b.copy()
c1 = ufunc(a, out=b0)
c2 = ufunc(a, out=b)
assert_array_equal(c1, c2)
# Trigger "fancy ufunc loop" code path
mask = view_element_first_byte(b).view(np.bool_)
a[...] = a_orig
b[...] = b_orig
c1 = ufunc(a, out=b.copy(), where=mask.copy()).copy()
a[...] = a_orig
b[...] = b_orig
c2 = ufunc(a, out=b, where=mask.copy()).copy()
# Also, mask overlapping with output
a[...] = a_orig
b[...] = b_orig
c3 = ufunc(a, out=b, where=mask).copy()
assert_array_equal(c1, c2)
assert_array_equal(c1, c3)
dtypes = [np.int8, np.int16, np.int32, np.int64, np.float32,
np.float64, np.complex64, np.complex128]
dtypes = [np.dtype(x) for x in dtypes]
for dtype in dtypes:
if np.issubdtype(dtype, np.integer):
ufunc = np.invert
else:
ufunc = np.reciprocal
n = 1000
k = 10
indices = [
np.index_exp[:n],
np.index_exp[k:k+n],
np.index_exp[n-1::-1],
np.index_exp[k+n-1:k-1:-1],
np.index_exp[:2*n:2],
np.index_exp[k:k+2*n:2],
np.index_exp[2*n-1::-2],
np.index_exp[k+2*n-1:k-1:-2],
]
for xi, yi in itertools.product(indices, indices):
v = np.arange(1, 1 + n*2 + k, dtype=dtype)
x = v[xi]
y = v[yi]
with np.errstate(all='ignore'):
check(x, y)
# Scalar cases
check(x[:1], y)
check(x[-1:], y)
check(x[:1].reshape([]), y)
check(x[-1:].reshape([]), y)
def test_unary_ufunc_where_same(self):
# Check behavior at wheremask overlap
ufunc = np.invert
def check(a, out, mask):
c1 = ufunc(a, out=out.copy(), where=mask.copy())
c2 = ufunc(a, out=out, where=mask)
assert_array_equal(c1, c2)
# Check behavior with same input and output arrays
x = np.arange(100).astype(np.bool_)
check(x, x, x)
check(x, x.copy(), x)
check(x, x, x.copy())
@pytest.mark.slow
def test_binary_ufunc_1d_manual(self):
ufunc = np.add
def check(a, b, c):
c0 = c.copy()
c1 = ufunc(a, b, out=c0)
c2 = ufunc(a, b, out=c)
assert_array_equal(c1, c2)
for dtype in [np.int8, np.int16, np.int32, np.int64,
np.float32, np.float64, np.complex64, np.complex128]:
# Check different data dependency orders
n = 1000
k = 10
indices = []
for p in [1, 2]:
indices.extend([
np.index_exp[:p*n:p],
np.index_exp[k:k+p*n:p],
np.index_exp[p*n-1::-p],
np.index_exp[k+p*n-1:k-1:-p],
])
for x, y, z in itertools.product(indices, indices, indices):
v = np.arange(6*n).astype(dtype)
x = v[x]
y = v[y]
z = v[z]
check(x, y, z)
# Scalar cases
check(x[:1], y, z)
check(x[-1:], y, z)
check(x[:1].reshape([]), y, z)
check(x[-1:].reshape([]), y, z)
check(x, y[:1], z)
check(x, y[-1:], z)
check(x, y[:1].reshape([]), z)
check(x, y[-1:].reshape([]), z)
def test_inplace_op_simple_manual(self):
rng = np.random.RandomState(1234)
x = rng.rand(200, 200) # bigger than bufsize
x += x.T
assert_array_equal(x - x.T, 0)

View file

@ -0,0 +1,213 @@
import sys
import os
import shutil
import mmap
import pytest
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryFile, mktemp, mkdtemp
from numpy import (
memmap, sum, average, product, ndarray, isscalar, add, subtract, multiply)
from numpy import arange, allclose, asarray
from numpy.testing import (
assert_, assert_equal, assert_array_equal, suppress_warnings
)
class TestMemmap:
def setup(self):
self.tmpfp = NamedTemporaryFile(prefix='mmap')
self.tempdir = mkdtemp()
self.shape = (3, 4)
self.dtype = 'float32'
self.data = arange(12, dtype=self.dtype)
self.data.resize(self.shape)
def teardown(self):
self.tmpfp.close()
shutil.rmtree(self.tempdir)
def test_roundtrip(self):
# Write data to file
fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+',
shape=self.shape)
fp[:] = self.data[:]
del fp # Test __del__ machinery, which handles cleanup
# Read data back from file
newfp = memmap(self.tmpfp, dtype=self.dtype, mode='r',
shape=self.shape)
assert_(allclose(self.data, newfp))
assert_array_equal(self.data, newfp)
assert_equal(newfp.flags.writeable, False)
def test_open_with_filename(self):
tmpname = mktemp('', 'mmap', dir=self.tempdir)
fp = memmap(tmpname, dtype=self.dtype, mode='w+',
shape=self.shape)
fp[:] = self.data[:]
del fp
def test_unnamed_file(self):
with TemporaryFile() as f:
fp = memmap(f, dtype=self.dtype, shape=self.shape)
del fp
def test_attributes(self):
offset = 1
mode = "w+"
fp = memmap(self.tmpfp, dtype=self.dtype, mode=mode,
shape=self.shape, offset=offset)
assert_equal(offset, fp.offset)
assert_equal(mode, fp.mode)
del fp
def test_filename(self):
tmpname = mktemp('', 'mmap', dir=self.tempdir)
fp = memmap(tmpname, dtype=self.dtype, mode='w+',
shape=self.shape)
abspath = os.path.abspath(tmpname)
fp[:] = self.data[:]
assert_equal(abspath, fp.filename)
b = fp[:1]
assert_equal(abspath, b.filename)
del b
del fp
def test_path(self):
tmpname = mktemp('', 'mmap', dir=self.tempdir)
fp = memmap(Path(tmpname), dtype=self.dtype, mode='w+',
shape=self.shape)
# os.path.realpath does not resolve symlinks on Windows
# see: https://bugs.python.org/issue9949
# use Path.resolve, just as memmap class does internally
abspath = str(Path(tmpname).resolve())
fp[:] = self.data[:]
assert_equal(abspath, str(fp.filename.resolve()))
b = fp[:1]
assert_equal(abspath, str(b.filename.resolve()))
del b
del fp
def test_filename_fileobj(self):
fp = memmap(self.tmpfp, dtype=self.dtype, mode="w+",
shape=self.shape)
assert_equal(fp.filename, self.tmpfp.name)
@pytest.mark.skipif(sys.platform == 'gnu0',
reason="Known to fail on hurd")
def test_flush(self):
fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+',
shape=self.shape)
fp[:] = self.data[:]
assert_equal(fp[0], self.data[0])
fp.flush()
def test_del(self):
# Make sure a view does not delete the underlying mmap
fp_base = memmap(self.tmpfp, dtype=self.dtype, mode='w+',
shape=self.shape)
fp_base[0] = 5
fp_view = fp_base[0:1]
assert_equal(fp_view[0], 5)
del fp_view
# Should still be able to access and assign values after
# deleting the view
assert_equal(fp_base[0], 5)
fp_base[0] = 6
assert_equal(fp_base[0], 6)
def test_arithmetic_drops_references(self):
fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+',
shape=self.shape)
tmp = (fp + 10)
if isinstance(tmp, memmap):
assert_(tmp._mmap is not fp._mmap)
def test_indexing_drops_references(self):
fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+',
shape=self.shape)
tmp = fp[(1, 2), (2, 3)]
if isinstance(tmp, memmap):
assert_(tmp._mmap is not fp._mmap)
def test_slicing_keeps_references(self):
fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+',
shape=self.shape)
assert_(fp[:2, :2]._mmap is fp._mmap)
def test_view(self):
fp = memmap(self.tmpfp, dtype=self.dtype, shape=self.shape)
new1 = fp.view()
new2 = new1.view()
assert_(new1.base is fp)
assert_(new2.base is fp)
new_array = asarray(fp)
assert_(new_array.base is fp)
def test_ufunc_return_ndarray(self):
fp = memmap(self.tmpfp, dtype=self.dtype, shape=self.shape)
fp[:] = self.data
with suppress_warnings() as sup:
sup.filter(FutureWarning, "np.average currently does not preserve")
for unary_op in [sum, average, product]:
result = unary_op(fp)
assert_(isscalar(result))
assert_(result.__class__ is self.data[0, 0].__class__)
assert_(unary_op(fp, axis=0).__class__ is ndarray)
assert_(unary_op(fp, axis=1).__class__ is ndarray)
for binary_op in [add, subtract, multiply]:
assert_(binary_op(fp, self.data).__class__ is ndarray)
assert_(binary_op(self.data, fp).__class__ is ndarray)
assert_(binary_op(fp, fp).__class__ is ndarray)
fp += 1
assert(fp.__class__ is memmap)
add(fp, 1, out=fp)
assert(fp.__class__ is memmap)
def test_getitem(self):
fp = memmap(self.tmpfp, dtype=self.dtype, shape=self.shape)
fp[:] = self.data
assert_(fp[1:, :-1].__class__ is memmap)
# Fancy indexing returns a copy that is not memmapped
assert_(fp[[0, 1]].__class__ is ndarray)
def test_memmap_subclass(self):
class MemmapSubClass(memmap):
pass
fp = MemmapSubClass(self.tmpfp, dtype=self.dtype, shape=self.shape)
fp[:] = self.data
# We keep previous behavior for subclasses of memmap, i.e. the
# ufunc and __getitem__ output is never turned into a ndarray
assert_(sum(fp, axis=0).__class__ is MemmapSubClass)
assert_(sum(fp).__class__ is MemmapSubClass)
assert_(fp[1:, :-1].__class__ is MemmapSubClass)
assert(fp[[0, 1]].__class__ is MemmapSubClass)
def test_mmap_offset_greater_than_allocation_granularity(self):
size = 5 * mmap.ALLOCATIONGRANULARITY
offset = mmap.ALLOCATIONGRANULARITY + 1
fp = memmap(self.tmpfp, shape=size, mode='w+', offset=offset)
assert_(fp.offset == offset)
def test_no_shape(self):
self.tmpfp.write(b'a'*16)
mm = memmap(self.tmpfp, dtype='float64')
assert_equal(mm.shape, (2,))
def test_empty_array(self):
# gh-12653
with pytest.raises(ValueError, match='empty file'):
memmap(self.tmpfp, shape=(0,4), mode='w+')
self.tmpfp.write(b'\0')
# ok now the file is not empty
memmap(self.tmpfp, shape=(0,4), mode='w+')

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,554 @@
import sys
import itertools
import pytest
import numpy as np
from numpy.testing import assert_, assert_equal, assert_raises, IS_PYPY
# This is the structure of the table used for plain objects:
#
# +-+-+-+
# |x|y|z|
# +-+-+-+
# Structure of a plain array description:
Pdescr = [
('x', 'i4', (2,)),
('y', 'f8', (2, 2)),
('z', 'u1')]
# A plain list of tuples with values for testing:
PbufferT = [
# x y z
([3, 2], [[6., 4.], [6., 4.]], 8),
([4, 3], [[7., 5.], [7., 5.]], 9),
]
# This is the structure of the table used for nested objects (DON'T PANIC!):
#
# +-+---------------------------------+-----+----------+-+-+
# |x|Info |color|info |y|z|
# | +-----+--+----------------+----+--+ +----+-----+ | |
# | |value|y2|Info2 |name|z2| |Name|Value| | |
# | | | +----+-----+--+--+ | | | | | | |
# | | | |name|value|y3|z3| | | | | | | |
# +-+-----+--+----+-----+--+--+----+--+-----+----+-----+-+-+
#
# The corresponding nested array description:
Ndescr = [
('x', 'i4', (2,)),
('Info', [
('value', 'c16'),
('y2', 'f8'),
('Info2', [
('name', 'S2'),
('value', 'c16', (2,)),
('y3', 'f8', (2,)),
('z3', 'u4', (2,))]),
('name', 'S2'),
('z2', 'b1')]),
('color', 'S2'),
('info', [
('Name', 'U8'),
('Value', 'c16')]),
('y', 'f8', (2, 2)),
('z', 'u1')]
NbufferT = [
# x Info color info y z
# value y2 Info2 name z2 Name Value
# name value y3 z3
([3, 2], (6j, 6., (b'nn', [6j, 4j], [6., 4.], [1, 2]), b'NN', True), b'cc', (u'NN', 6j), [[6., 4.], [6., 4.]], 8),
([4, 3], (7j, 7., (b'oo', [7j, 5j], [7., 5.], [2, 1]), b'OO', False), b'dd', (u'OO', 7j), [[7., 5.], [7., 5.]], 9),
]
byteorder = {'little':'<', 'big':'>'}[sys.byteorder]
def normalize_descr(descr):
"Normalize a description adding the platform byteorder."
out = []
for item in descr:
dtype = item[1]
if isinstance(dtype, str):
if dtype[0] not in ['|', '<', '>']:
onebyte = dtype[1:] == "1"
if onebyte or dtype[0] in ['S', 'V', 'b']:
dtype = "|" + dtype
else:
dtype = byteorder + dtype
if len(item) > 2 and np.prod(item[2]) > 1:
nitem = (item[0], dtype, item[2])
else:
nitem = (item[0], dtype)
out.append(nitem)
elif isinstance(dtype, list):
l = normalize_descr(dtype)
out.append((item[0], l))
else:
raise ValueError("Expected a str or list and got %s" %
(type(item)))
return out
############################################################
# Creation tests
############################################################
class CreateZeros:
"""Check the creation of heterogeneous arrays zero-valued"""
def test_zeros0D(self):
"""Check creation of 0-dimensional objects"""
h = np.zeros((), dtype=self._descr)
assert_(normalize_descr(self._descr) == h.dtype.descr)
assert_(h.dtype.fields['x'][0].name[:4] == 'void')
assert_(h.dtype.fields['x'][0].char == 'V')
assert_(h.dtype.fields['x'][0].type == np.void)
# A small check that data is ok
assert_equal(h['z'], np.zeros((), dtype='u1'))
def test_zerosSD(self):
"""Check creation of single-dimensional objects"""
h = np.zeros((2,), dtype=self._descr)
assert_(normalize_descr(self._descr) == h.dtype.descr)
assert_(h.dtype['y'].name[:4] == 'void')
assert_(h.dtype['y'].char == 'V')
assert_(h.dtype['y'].type == np.void)
# A small check that data is ok
assert_equal(h['z'], np.zeros((2,), dtype='u1'))
def test_zerosMD(self):
"""Check creation of multi-dimensional objects"""
h = np.zeros((2, 3), dtype=self._descr)
assert_(normalize_descr(self._descr) == h.dtype.descr)
assert_(h.dtype['z'].name == 'uint8')
assert_(h.dtype['z'].char == 'B')
assert_(h.dtype['z'].type == np.uint8)
# A small check that data is ok
assert_equal(h['z'], np.zeros((2, 3), dtype='u1'))
class TestCreateZerosPlain(CreateZeros):
"""Check the creation of heterogeneous arrays zero-valued (plain)"""
_descr = Pdescr
class TestCreateZerosNested(CreateZeros):
"""Check the creation of heterogeneous arrays zero-valued (nested)"""
_descr = Ndescr
class CreateValues:
"""Check the creation of heterogeneous arrays with values"""
def test_tuple(self):
"""Check creation from tuples"""
h = np.array(self._buffer, dtype=self._descr)
assert_(normalize_descr(self._descr) == h.dtype.descr)
if self.multiple_rows:
assert_(h.shape == (2,))
else:
assert_(h.shape == ())
def test_list_of_tuple(self):
"""Check creation from list of tuples"""
h = np.array([self._buffer], dtype=self._descr)
assert_(normalize_descr(self._descr) == h.dtype.descr)
if self.multiple_rows:
assert_(h.shape == (1, 2))
else:
assert_(h.shape == (1,))
def test_list_of_list_of_tuple(self):
"""Check creation from list of list of tuples"""
h = np.array([[self._buffer]], dtype=self._descr)
assert_(normalize_descr(self._descr) == h.dtype.descr)
if self.multiple_rows:
assert_(h.shape == (1, 1, 2))
else:
assert_(h.shape == (1, 1))
class TestCreateValuesPlainSingle(CreateValues):
"""Check the creation of heterogeneous arrays (plain, single row)"""
_descr = Pdescr
multiple_rows = 0
_buffer = PbufferT[0]
class TestCreateValuesPlainMultiple(CreateValues):
"""Check the creation of heterogeneous arrays (plain, multiple rows)"""
_descr = Pdescr
multiple_rows = 1
_buffer = PbufferT
class TestCreateValuesNestedSingle(CreateValues):
"""Check the creation of heterogeneous arrays (nested, single row)"""
_descr = Ndescr
multiple_rows = 0
_buffer = NbufferT[0]
class TestCreateValuesNestedMultiple(CreateValues):
"""Check the creation of heterogeneous arrays (nested, multiple rows)"""
_descr = Ndescr
multiple_rows = 1
_buffer = NbufferT
############################################################
# Reading tests
############################################################
class ReadValuesPlain:
"""Check the reading of values in heterogeneous arrays (plain)"""
def test_access_fields(self):
h = np.array(self._buffer, dtype=self._descr)
if not self.multiple_rows:
assert_(h.shape == ())
assert_equal(h['x'], np.array(self._buffer[0], dtype='i4'))
assert_equal(h['y'], np.array(self._buffer[1], dtype='f8'))
assert_equal(h['z'], np.array(self._buffer[2], dtype='u1'))
else:
assert_(len(h) == 2)
assert_equal(h['x'], np.array([self._buffer[0][0],
self._buffer[1][0]], dtype='i4'))
assert_equal(h['y'], np.array([self._buffer[0][1],
self._buffer[1][1]], dtype='f8'))
assert_equal(h['z'], np.array([self._buffer[0][2],
self._buffer[1][2]], dtype='u1'))
class TestReadValuesPlainSingle(ReadValuesPlain):
"""Check the creation of heterogeneous arrays (plain, single row)"""
_descr = Pdescr
multiple_rows = 0
_buffer = PbufferT[0]
class TestReadValuesPlainMultiple(ReadValuesPlain):
"""Check the values of heterogeneous arrays (plain, multiple rows)"""
_descr = Pdescr
multiple_rows = 1
_buffer = PbufferT
class ReadValuesNested:
"""Check the reading of values in heterogeneous arrays (nested)"""
def test_access_top_fields(self):
"""Check reading the top fields of a nested array"""
h = np.array(self._buffer, dtype=self._descr)
if not self.multiple_rows:
assert_(h.shape == ())
assert_equal(h['x'], np.array(self._buffer[0], dtype='i4'))
assert_equal(h['y'], np.array(self._buffer[4], dtype='f8'))
assert_equal(h['z'], np.array(self._buffer[5], dtype='u1'))
else:
assert_(len(h) == 2)
assert_equal(h['x'], np.array([self._buffer[0][0],
self._buffer[1][0]], dtype='i4'))
assert_equal(h['y'], np.array([self._buffer[0][4],
self._buffer[1][4]], dtype='f8'))
assert_equal(h['z'], np.array([self._buffer[0][5],
self._buffer[1][5]], dtype='u1'))
def test_nested1_acessors(self):
"""Check reading the nested fields of a nested array (1st level)"""
h = np.array(self._buffer, dtype=self._descr)
if not self.multiple_rows:
assert_equal(h['Info']['value'],
np.array(self._buffer[1][0], dtype='c16'))
assert_equal(h['Info']['y2'],
np.array(self._buffer[1][1], dtype='f8'))
assert_equal(h['info']['Name'],
np.array(self._buffer[3][0], dtype='U2'))
assert_equal(h['info']['Value'],
np.array(self._buffer[3][1], dtype='c16'))
else:
assert_equal(h['Info']['value'],
np.array([self._buffer[0][1][0],
self._buffer[1][1][0]],
dtype='c16'))
assert_equal(h['Info']['y2'],
np.array([self._buffer[0][1][1],
self._buffer[1][1][1]],
dtype='f8'))
assert_equal(h['info']['Name'],
np.array([self._buffer[0][3][0],
self._buffer[1][3][0]],
dtype='U2'))
assert_equal(h['info']['Value'],
np.array([self._buffer[0][3][1],
self._buffer[1][3][1]],
dtype='c16'))
def test_nested2_acessors(self):
"""Check reading the nested fields of a nested array (2nd level)"""
h = np.array(self._buffer, dtype=self._descr)
if not self.multiple_rows:
assert_equal(h['Info']['Info2']['value'],
np.array(self._buffer[1][2][1], dtype='c16'))
assert_equal(h['Info']['Info2']['z3'],
np.array(self._buffer[1][2][3], dtype='u4'))
else:
assert_equal(h['Info']['Info2']['value'],
np.array([self._buffer[0][1][2][1],
self._buffer[1][1][2][1]],
dtype='c16'))
assert_equal(h['Info']['Info2']['z3'],
np.array([self._buffer[0][1][2][3],
self._buffer[1][1][2][3]],
dtype='u4'))
def test_nested1_descriptor(self):
"""Check access nested descriptors of a nested array (1st level)"""
h = np.array(self._buffer, dtype=self._descr)
assert_(h.dtype['Info']['value'].name == 'complex128')
assert_(h.dtype['Info']['y2'].name == 'float64')
assert_(h.dtype['info']['Name'].name == 'str256')
assert_(h.dtype['info']['Value'].name == 'complex128')
def test_nested2_descriptor(self):
"""Check access nested descriptors of a nested array (2nd level)"""
h = np.array(self._buffer, dtype=self._descr)
assert_(h.dtype['Info']['Info2']['value'].name == 'void256')
assert_(h.dtype['Info']['Info2']['z3'].name == 'void64')
class TestReadValuesNestedSingle(ReadValuesNested):
"""Check the values of heterogeneous arrays (nested, single row)"""
_descr = Ndescr
multiple_rows = False
_buffer = NbufferT[0]
class TestReadValuesNestedMultiple(ReadValuesNested):
"""Check the values of heterogeneous arrays (nested, multiple rows)"""
_descr = Ndescr
multiple_rows = True
_buffer = NbufferT
class TestEmptyField:
def test_assign(self):
a = np.arange(10, dtype=np.float32)
a.dtype = [("int", "<0i4"), ("float", "<2f4")]
assert_(a['int'].shape == (5, 0))
assert_(a['float'].shape == (5, 2))
class TestCommonType:
def test_scalar_loses1(self):
res = np.find_common_type(['f4', 'f4', 'i2'], ['f8'])
assert_(res == 'f4')
def test_scalar_loses2(self):
res = np.find_common_type(['f4', 'f4'], ['i8'])
assert_(res == 'f4')
def test_scalar_wins(self):
res = np.find_common_type(['f4', 'f4', 'i2'], ['c8'])
assert_(res == 'c8')
def test_scalar_wins2(self):
res = np.find_common_type(['u4', 'i4', 'i4'], ['f4'])
assert_(res == 'f8')
def test_scalar_wins3(self): # doesn't go up to 'f16' on purpose
res = np.find_common_type(['u8', 'i8', 'i8'], ['f8'])
assert_(res == 'f8')
class TestMultipleFields:
def setup(self):
self.ary = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype='i4,f4,i2,c8')
def _bad_call(self):
return self.ary['f0', 'f1']
def test_no_tuple(self):
assert_raises(IndexError, self._bad_call)
def test_return(self):
res = self.ary[['f0', 'f2']].tolist()
assert_(res == [(1, 3), (5, 7)])
class TestIsSubDType:
# scalar types can be promoted into dtypes
wrappers = [np.dtype, lambda x: x]
def test_both_abstract(self):
assert_(np.issubdtype(np.floating, np.inexact))
assert_(not np.issubdtype(np.inexact, np.floating))
def test_same(self):
for cls in (np.float32, np.int32):
for w1, w2 in itertools.product(self.wrappers, repeat=2):
assert_(np.issubdtype(w1(cls), w2(cls)))
def test_subclass(self):
# note we cannot promote floating to a dtype, as it would turn into a
# concrete type
for w in self.wrappers:
assert_(np.issubdtype(w(np.float32), np.floating))
assert_(np.issubdtype(w(np.float64), np.floating))
def test_subclass_backwards(self):
for w in self.wrappers:
assert_(not np.issubdtype(np.floating, w(np.float32)))
assert_(not np.issubdtype(np.floating, w(np.float64)))
def test_sibling_class(self):
for w1, w2 in itertools.product(self.wrappers, repeat=2):
assert_(not np.issubdtype(w1(np.float32), w2(np.float64)))
assert_(not np.issubdtype(w1(np.float64), w2(np.float32)))
def test_nondtype_nonscalartype(self):
# See gh-14619 and gh-9505 which introduced the deprecation to fix
# this. These tests are directly taken from gh-9505
assert not np.issubdtype(np.float32, 'float64')
assert not np.issubdtype(np.float32, 'f8')
assert not np.issubdtype(np.int32, str)
assert not np.issubdtype(np.int32, 'int64')
assert not np.issubdtype(np.str_, 'void')
# for the following the correct spellings are
# np.integer, np.floating, or np.complexfloating respectively:
assert not np.issubdtype(np.int8, int) # np.int8 is never np.int_
assert not np.issubdtype(np.float32, float)
assert not np.issubdtype(np.complex64, complex)
assert not np.issubdtype(np.float32, "float")
assert not np.issubdtype(np.float64, "f")
# Test the same for the correct first datatype and abstract one
# in the case of int, float, complex:
assert np.issubdtype(np.float64, 'float64')
assert np.issubdtype(np.float64, 'f8')
assert np.issubdtype(np.str_, str)
assert np.issubdtype(np.int64, 'int64')
assert np.issubdtype(np.void, 'void')
assert np.issubdtype(np.int8, np.integer)
assert np.issubdtype(np.float32, np.floating)
assert np.issubdtype(np.complex64, np.complexfloating)
assert np.issubdtype(np.float64, "float")
assert np.issubdtype(np.float32, "f")
class TestSctypeDict:
def test_longdouble(self):
assert_(np.sctypeDict['f8'] is not np.longdouble)
assert_(np.sctypeDict['c16'] is not np.clongdouble)
class TestBitName:
def test_abstract(self):
assert_raises(ValueError, np.core.numerictypes.bitname, np.floating)
class TestMaximumSctype:
# note that parametrizing with sctype['int'] and similar would skip types
# with the same size (gh-11923)
@pytest.mark.parametrize('t', [np.byte, np.short, np.intc, np.int_, np.longlong])
def test_int(self, t):
assert_equal(np.maximum_sctype(t), np.sctypes['int'][-1])
@pytest.mark.parametrize('t', [np.ubyte, np.ushort, np.uintc, np.uint, np.ulonglong])
def test_uint(self, t):
assert_equal(np.maximum_sctype(t), np.sctypes['uint'][-1])
@pytest.mark.parametrize('t', [np.half, np.single, np.double, np.longdouble])
def test_float(self, t):
assert_equal(np.maximum_sctype(t), np.sctypes['float'][-1])
@pytest.mark.parametrize('t', [np.csingle, np.cdouble, np.clongdouble])
def test_complex(self, t):
assert_equal(np.maximum_sctype(t), np.sctypes['complex'][-1])
@pytest.mark.parametrize('t', [np.bool_, np.object_, np.unicode_, np.bytes_, np.void])
def test_other(self, t):
assert_equal(np.maximum_sctype(t), t)
class Test_sctype2char:
# This function is old enough that we're really just documenting the quirks
# at this point.
def test_scalar_type(self):
assert_equal(np.sctype2char(np.double), 'd')
assert_equal(np.sctype2char(np.int_), 'l')
assert_equal(np.sctype2char(np.unicode_), 'U')
assert_equal(np.sctype2char(np.bytes_), 'S')
def test_other_type(self):
assert_equal(np.sctype2char(float), 'd')
assert_equal(np.sctype2char(list), 'O')
assert_equal(np.sctype2char(np.ndarray), 'O')
def test_third_party_scalar_type(self):
from numpy.core._rational_tests import rational
assert_raises(KeyError, np.sctype2char, rational)
assert_raises(KeyError, np.sctype2char, rational(1))
def test_array_instance(self):
assert_equal(np.sctype2char(np.array([1.0, 2.0])), 'd')
def test_abstract_type(self):
assert_raises(KeyError, np.sctype2char, np.floating)
def test_non_type(self):
assert_raises(ValueError, np.sctype2char, 1)
@pytest.mark.parametrize("rep, expected", [
(np.int32, True),
(list, False),
(1.1, False),
(str, True),
(np.dtype(np.float64), True),
(np.dtype((np.int16, (3, 4))), True),
(np.dtype([('a', np.int8)]), True),
])
def test_issctype(rep, expected):
# ensure proper identification of scalar
# data-types by issctype()
actual = np.issctype(rep)
assert_equal(actual, expected)
@pytest.mark.skipif(sys.flags.optimize > 1,
reason="no docstrings present to inspect when PYTHONOPTIMIZE/Py_OptimizeFlag > 1")
@pytest.mark.xfail(IS_PYPY,
reason="PyPy cannot modify tp_doc after PyType_Ready")
class TestDocStrings:
def test_platform_dependent_aliases(self):
if np.int64 is np.int_:
assert_('int64' in np.int_.__doc__)
elif np.int64 is np.longlong:
assert_('int64' in np.longlong.__doc__)
class TestScalarTypeNames:
# gh-9799
numeric_types = [
np.byte, np.short, np.intc, np.int_, np.longlong,
np.ubyte, np.ushort, np.uintc, np.uint, np.ulonglong,
np.half, np.single, np.double, np.longdouble,
np.csingle, np.cdouble, np.clongdouble,
]
def test_names_are_unique(self):
# none of the above may be aliases for each other
assert len(set(self.numeric_types)) == len(self.numeric_types)
# names must be unique
names = [t.__name__ for t in self.numeric_types]
assert len(set(names)) == len(names)
@pytest.mark.parametrize('t', numeric_types)
def test_names_reflect_attributes(self, t):
""" Test that names correspond to where the type is under ``np.`` """
assert getattr(np, t.__name__) is t
@pytest.mark.parametrize('t', numeric_types)
def test_names_are_undersood_by_dtype(self, t):
""" Test the dtype constructor maps names back to the type """
assert np.dtype(t.__name__).type is t

View file

@ -0,0 +1,427 @@
import inspect
import sys
from unittest import mock
import numpy as np
from numpy.testing import (
assert_, assert_equal, assert_raises, assert_raises_regex)
from numpy.core.overrides import (
_get_implementing_args, array_function_dispatch,
verify_matching_signatures, ARRAY_FUNCTION_ENABLED)
from numpy.compat import pickle
import pytest
requires_array_function = pytest.mark.skipif(
not ARRAY_FUNCTION_ENABLED,
reason="__array_function__ dispatch not enabled.")
def _return_not_implemented(self, *args, **kwargs):
return NotImplemented
# need to define this at the top level to test pickling
@array_function_dispatch(lambda array: (array,))
def dispatched_one_arg(array):
"""Docstring."""
return 'original'
@array_function_dispatch(lambda array1, array2: (array1, array2))
def dispatched_two_arg(array1, array2):
"""Docstring."""
return 'original'
class TestGetImplementingArgs:
def test_ndarray(self):
array = np.array(1)
args = _get_implementing_args([array])
assert_equal(list(args), [array])
args = _get_implementing_args([array, array])
assert_equal(list(args), [array])
args = _get_implementing_args([array, 1])
assert_equal(list(args), [array])
args = _get_implementing_args([1, array])
assert_equal(list(args), [array])
def test_ndarray_subclasses(self):
class OverrideSub(np.ndarray):
__array_function__ = _return_not_implemented
class NoOverrideSub(np.ndarray):
pass
array = np.array(1).view(np.ndarray)
override_sub = np.array(1).view(OverrideSub)
no_override_sub = np.array(1).view(NoOverrideSub)
args = _get_implementing_args([array, override_sub])
assert_equal(list(args), [override_sub, array])
args = _get_implementing_args([array, no_override_sub])
assert_equal(list(args), [no_override_sub, array])
args = _get_implementing_args(
[override_sub, no_override_sub])
assert_equal(list(args), [override_sub, no_override_sub])
def test_ndarray_and_duck_array(self):
class Other:
__array_function__ = _return_not_implemented
array = np.array(1)
other = Other()
args = _get_implementing_args([other, array])
assert_equal(list(args), [other, array])
args = _get_implementing_args([array, other])
assert_equal(list(args), [array, other])
def test_ndarray_subclass_and_duck_array(self):
class OverrideSub(np.ndarray):
__array_function__ = _return_not_implemented
class Other:
__array_function__ = _return_not_implemented
array = np.array(1)
subarray = np.array(1).view(OverrideSub)
other = Other()
assert_equal(_get_implementing_args([array, subarray, other]),
[subarray, array, other])
assert_equal(_get_implementing_args([array, other, subarray]),
[subarray, array, other])
def test_many_duck_arrays(self):
class A:
__array_function__ = _return_not_implemented
class B(A):
__array_function__ = _return_not_implemented
class C(A):
__array_function__ = _return_not_implemented
class D:
__array_function__ = _return_not_implemented
a = A()
b = B()
c = C()
d = D()
assert_equal(_get_implementing_args([1]), [])
assert_equal(_get_implementing_args([a]), [a])
assert_equal(_get_implementing_args([a, 1]), [a])
assert_equal(_get_implementing_args([a, a, a]), [a])
assert_equal(_get_implementing_args([a, d, a]), [a, d])
assert_equal(_get_implementing_args([a, b]), [b, a])
assert_equal(_get_implementing_args([b, a]), [b, a])
assert_equal(_get_implementing_args([a, b, c]), [b, c, a])
assert_equal(_get_implementing_args([a, c, b]), [c, b, a])
def test_too_many_duck_arrays(self):
namespace = dict(__array_function__=_return_not_implemented)
types = [type('A' + str(i), (object,), namespace) for i in range(33)]
relevant_args = [t() for t in types]
actual = _get_implementing_args(relevant_args[:32])
assert_equal(actual, relevant_args[:32])
with assert_raises_regex(TypeError, 'distinct argument types'):
_get_implementing_args(relevant_args)
class TestNDArrayArrayFunction:
@requires_array_function
def test_method(self):
class Other:
__array_function__ = _return_not_implemented
class NoOverrideSub(np.ndarray):
pass
class OverrideSub(np.ndarray):
__array_function__ = _return_not_implemented
array = np.array([1])
other = Other()
no_override_sub = array.view(NoOverrideSub)
override_sub = array.view(OverrideSub)
result = array.__array_function__(func=dispatched_two_arg,
types=(np.ndarray,),
args=(array, 1.), kwargs={})
assert_equal(result, 'original')
result = array.__array_function__(func=dispatched_two_arg,
types=(np.ndarray, Other),
args=(array, other), kwargs={})
assert_(result is NotImplemented)
result = array.__array_function__(func=dispatched_two_arg,
types=(np.ndarray, NoOverrideSub),
args=(array, no_override_sub),
kwargs={})
assert_equal(result, 'original')
result = array.__array_function__(func=dispatched_two_arg,
types=(np.ndarray, OverrideSub),
args=(array, override_sub),
kwargs={})
assert_equal(result, 'original')
with assert_raises_regex(TypeError, 'no implementation found'):
np.concatenate((array, other))
expected = np.concatenate((array, array))
result = np.concatenate((array, no_override_sub))
assert_equal(result, expected.view(NoOverrideSub))
result = np.concatenate((array, override_sub))
assert_equal(result, expected.view(OverrideSub))
def test_no_wrapper(self):
# This shouldn't happen unless a user intentionally calls
# __array_function__ with invalid arguments, but check that we raise
# an appropriate error all the same.
array = np.array(1)
func = lambda x: x
with assert_raises_regex(AttributeError, '_implementation'):
array.__array_function__(func=func, types=(np.ndarray,),
args=(array,), kwargs={})
@requires_array_function
class TestArrayFunctionDispatch:
def test_pickle(self):
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
roundtripped = pickle.loads(
pickle.dumps(dispatched_one_arg, protocol=proto))
assert_(roundtripped is dispatched_one_arg)
def test_name_and_docstring(self):
assert_equal(dispatched_one_arg.__name__, 'dispatched_one_arg')
if sys.flags.optimize < 2:
assert_equal(dispatched_one_arg.__doc__, 'Docstring.')
def test_interface(self):
class MyArray:
def __array_function__(self, func, types, args, kwargs):
return (self, func, types, args, kwargs)
original = MyArray()
(obj, func, types, args, kwargs) = dispatched_one_arg(original)
assert_(obj is original)
assert_(func is dispatched_one_arg)
assert_equal(set(types), {MyArray})
# assert_equal uses the overloaded np.iscomplexobj() internally
assert_(args == (original,))
assert_equal(kwargs, {})
def test_not_implemented(self):
class MyArray:
def __array_function__(self, func, types, args, kwargs):
return NotImplemented
array = MyArray()
with assert_raises_regex(TypeError, 'no implementation found'):
dispatched_one_arg(array)
@requires_array_function
class TestVerifyMatchingSignatures:
def test_verify_matching_signatures(self):
verify_matching_signatures(lambda x: 0, lambda x: 0)
verify_matching_signatures(lambda x=None: 0, lambda x=None: 0)
verify_matching_signatures(lambda x=1: 0, lambda x=None: 0)
with assert_raises(RuntimeError):
verify_matching_signatures(lambda a: 0, lambda b: 0)
with assert_raises(RuntimeError):
verify_matching_signatures(lambda x: 0, lambda x=None: 0)
with assert_raises(RuntimeError):
verify_matching_signatures(lambda x=None: 0, lambda y=None: 0)
with assert_raises(RuntimeError):
verify_matching_signatures(lambda x=1: 0, lambda y=1: 0)
def test_array_function_dispatch(self):
with assert_raises(RuntimeError):
@array_function_dispatch(lambda x: (x,))
def f(y):
pass
# should not raise
@array_function_dispatch(lambda x: (x,), verify=False)
def f(y):
pass
def _new_duck_type_and_implements():
"""Create a duck array type and implements functions."""
HANDLED_FUNCTIONS = {}
class MyArray:
def __array_function__(self, func, types, args, kwargs):
if func not in HANDLED_FUNCTIONS:
return NotImplemented
if not all(issubclass(t, MyArray) for t in types):
return NotImplemented
return HANDLED_FUNCTIONS[func](*args, **kwargs)
def implements(numpy_function):
"""Register an __array_function__ implementations."""
def decorator(func):
HANDLED_FUNCTIONS[numpy_function] = func
return func
return decorator
return (MyArray, implements)
@requires_array_function
class TestArrayFunctionImplementation:
def test_one_arg(self):
MyArray, implements = _new_duck_type_and_implements()
@implements(dispatched_one_arg)
def _(array):
return 'myarray'
assert_equal(dispatched_one_arg(1), 'original')
assert_equal(dispatched_one_arg(MyArray()), 'myarray')
def test_optional_args(self):
MyArray, implements = _new_duck_type_and_implements()
@array_function_dispatch(lambda array, option=None: (array,))
def func_with_option(array, option='default'):
return option
@implements(func_with_option)
def my_array_func_with_option(array, new_option='myarray'):
return new_option
# we don't need to implement every option on __array_function__
# implementations
assert_equal(func_with_option(1), 'default')
assert_equal(func_with_option(1, option='extra'), 'extra')
assert_equal(func_with_option(MyArray()), 'myarray')
with assert_raises(TypeError):
func_with_option(MyArray(), option='extra')
# but new options on implementations can't be used
result = my_array_func_with_option(MyArray(), new_option='yes')
assert_equal(result, 'yes')
with assert_raises(TypeError):
func_with_option(MyArray(), new_option='no')
def test_not_implemented(self):
MyArray, implements = _new_duck_type_and_implements()
@array_function_dispatch(lambda array: (array,), module='my')
def func(array):
return array
array = np.array(1)
assert_(func(array) is array)
assert_equal(func.__module__, 'my')
with assert_raises_regex(
TypeError, "no implementation found for 'my.func'"):
func(MyArray())
class TestNDArrayMethods:
def test_repr(self):
# gh-12162: should still be defined even if __array_function__ doesn't
# implement np.array_repr()
class MyArray(np.ndarray):
def __array_function__(*args, **kwargs):
return NotImplemented
array = np.array(1).view(MyArray)
assert_equal(repr(array), 'MyArray(1)')
assert_equal(str(array), '1')
class TestNumPyFunctions:
def test_set_module(self):
assert_equal(np.sum.__module__, 'numpy')
assert_equal(np.char.equal.__module__, 'numpy.char')
assert_equal(np.fft.fft.__module__, 'numpy.fft')
assert_equal(np.linalg.solve.__module__, 'numpy.linalg')
def test_inspect_sum(self):
signature = inspect.signature(np.sum)
assert_('axis' in signature.parameters)
@requires_array_function
def test_override_sum(self):
MyArray, implements = _new_duck_type_and_implements()
@implements(np.sum)
def _(array):
return 'yes'
assert_equal(np.sum(MyArray()), 'yes')
@requires_array_function
def test_sum_on_mock_array(self):
# We need a proxy for mocks because __array_function__ is only looked
# up in the class dict
class ArrayProxy:
def __init__(self, value):
self.value = value
def __array_function__(self, *args, **kwargs):
return self.value.__array_function__(*args, **kwargs)
def __array__(self, *args, **kwargs):
return self.value.__array__(*args, **kwargs)
proxy = ArrayProxy(mock.Mock(spec=ArrayProxy))
proxy.value.__array_function__.return_value = 1
result = np.sum(proxy)
assert_equal(result, 1)
proxy.value.__array_function__.assert_called_once_with(
np.sum, (ArrayProxy,), (proxy,), {})
proxy.value.__array__.assert_not_called()
@requires_array_function
def test_sum_forwarding_implementation(self):
class MyArray(np.ndarray):
def sum(self, axis, out):
return 'summed'
def __array_function__(self, func, types, args, kwargs):
return super().__array_function__(func, types, args, kwargs)
# note: the internal implementation of np.sum() calls the .sum() method
array = np.array(1).view(MyArray)
assert_equal(np.sum(array), 'summed')

View file

@ -0,0 +1,200 @@
import sys
import pytest
import numpy as np
from numpy.testing import assert_, assert_equal
from numpy.core.tests._locales import CommaDecimalPointLocale
from io import StringIO
_REF = {np.inf: 'inf', -np.inf: '-inf', np.nan: 'nan'}
@pytest.mark.parametrize('tp', [np.float32, np.double, np.longdouble])
def test_float_types(tp):
""" Check formatting.
This is only for the str function, and only for simple types.
The precision of np.float32 and np.longdouble aren't the same as the
python float precision.
"""
for x in [0, 1, -1, 1e20]:
assert_equal(str(tp(x)), str(float(x)),
err_msg='Failed str formatting for type %s' % tp)
if tp(1e16).itemsize > 4:
assert_equal(str(tp(1e16)), str(float('1e16')),
err_msg='Failed str formatting for type %s' % tp)
else:
ref = '1e+16'
assert_equal(str(tp(1e16)), ref,
err_msg='Failed str formatting for type %s' % tp)
@pytest.mark.parametrize('tp', [np.float32, np.double, np.longdouble])
def test_nan_inf_float(tp):
""" Check formatting of nan & inf.
This is only for the str function, and only for simple types.
The precision of np.float32 and np.longdouble aren't the same as the
python float precision.
"""
for x in [np.inf, -np.inf, np.nan]:
assert_equal(str(tp(x)), _REF[x],
err_msg='Failed str formatting for type %s' % tp)
@pytest.mark.parametrize('tp', [np.complex64, np.cdouble, np.clongdouble])
def test_complex_types(tp):
"""Check formatting of complex types.
This is only for the str function, and only for simple types.
The precision of np.float32 and np.longdouble aren't the same as the
python float precision.
"""
for x in [0, 1, -1, 1e20]:
assert_equal(str(tp(x)), str(complex(x)),
err_msg='Failed str formatting for type %s' % tp)
assert_equal(str(tp(x*1j)), str(complex(x*1j)),
err_msg='Failed str formatting for type %s' % tp)
assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j)),
err_msg='Failed str formatting for type %s' % tp)
if tp(1e16).itemsize > 8:
assert_equal(str(tp(1e16)), str(complex(1e16)),
err_msg='Failed str formatting for type %s' % tp)
else:
ref = '(1e+16+0j)'
assert_equal(str(tp(1e16)), ref,
err_msg='Failed str formatting for type %s' % tp)
@pytest.mark.parametrize('dtype', [np.complex64, np.cdouble, np.clongdouble])
def test_complex_inf_nan(dtype):
"""Check inf/nan formatting of complex types."""
TESTS = {
complex(np.inf, 0): "(inf+0j)",
complex(0, np.inf): "infj",
complex(-np.inf, 0): "(-inf+0j)",
complex(0, -np.inf): "-infj",
complex(np.inf, 1): "(inf+1j)",
complex(1, np.inf): "(1+infj)",
complex(-np.inf, 1): "(-inf+1j)",
complex(1, -np.inf): "(1-infj)",
complex(np.nan, 0): "(nan+0j)",
complex(0, np.nan): "nanj",
complex(-np.nan, 0): "(nan+0j)",
complex(0, -np.nan): "nanj",
complex(np.nan, 1): "(nan+1j)",
complex(1, np.nan): "(1+nanj)",
complex(-np.nan, 1): "(nan+1j)",
complex(1, -np.nan): "(1+nanj)",
}
for c, s in TESTS.items():
assert_equal(str(dtype(c)), s)
# print tests
def _test_redirected_print(x, tp, ref=None):
file = StringIO()
file_tp = StringIO()
stdout = sys.stdout
try:
sys.stdout = file_tp
print(tp(x))
sys.stdout = file
if ref:
print(ref)
else:
print(x)
finally:
sys.stdout = stdout
assert_equal(file.getvalue(), file_tp.getvalue(),
err_msg='print failed for type%s' % tp)
@pytest.mark.parametrize('tp', [np.float32, np.double, np.longdouble])
def test_float_type_print(tp):
"""Check formatting when using print """
for x in [0, 1, -1, 1e20]:
_test_redirected_print(float(x), tp)
for x in [np.inf, -np.inf, np.nan]:
_test_redirected_print(float(x), tp, _REF[x])
if tp(1e16).itemsize > 4:
_test_redirected_print(float(1e16), tp)
else:
ref = '1e+16'
_test_redirected_print(float(1e16), tp, ref)
@pytest.mark.parametrize('tp', [np.complex64, np.cdouble, np.clongdouble])
def test_complex_type_print(tp):
"""Check formatting when using print """
# We do not create complex with inf/nan directly because the feature is
# missing in python < 2.6
for x in [0, 1, -1, 1e20]:
_test_redirected_print(complex(x), tp)
if tp(1e16).itemsize > 8:
_test_redirected_print(complex(1e16), tp)
else:
ref = '(1e+16+0j)'
_test_redirected_print(complex(1e16), tp, ref)
_test_redirected_print(complex(np.inf, 1), tp, '(inf+1j)')
_test_redirected_print(complex(-np.inf, 1), tp, '(-inf+1j)')
_test_redirected_print(complex(-np.nan, 1), tp, '(nan+1j)')
def test_scalar_format():
"""Test the str.format method with NumPy scalar types"""
tests = [('{0}', True, np.bool_),
('{0}', False, np.bool_),
('{0:d}', 130, np.uint8),
('{0:d}', 50000, np.uint16),
('{0:d}', 3000000000, np.uint32),
('{0:d}', 15000000000000000000, np.uint64),
('{0:d}', -120, np.int8),
('{0:d}', -30000, np.int16),
('{0:d}', -2000000000, np.int32),
('{0:d}', -7000000000000000000, np.int64),
('{0:g}', 1.5, np.float16),
('{0:g}', 1.5, np.float32),
('{0:g}', 1.5, np.float64),
('{0:g}', 1.5, np.longdouble),
('{0:g}', 1.5+0.5j, np.complex64),
('{0:g}', 1.5+0.5j, np.complex128),
('{0:g}', 1.5+0.5j, np.clongdouble)]
for (fmat, val, valtype) in tests:
try:
assert_equal(fmat.format(val), fmat.format(valtype(val)),
"failed with val %s, type %s" % (val, valtype))
except ValueError as e:
assert_(False,
"format raised exception (fmt='%s', val=%s, type=%s, exc='%s')" %
(fmat, repr(val), repr(valtype), str(e)))
#
# Locale tests: scalar types formatting should be independent of the locale
#
class TestCommaDecimalPointLocale(CommaDecimalPointLocale):
def test_locale_single(self):
assert_equal(str(np.float32(1.2)), str(float(1.2)))
def test_locale_double(self):
assert_equal(str(np.double(1.2)), str(float(1.2)))
def test_locale_longdouble(self):
assert_equal(str(np.longdouble('1.2')), str(float(1.2)))

View file

@ -0,0 +1,44 @@
import pytest
import warnings
import numpy as np
@pytest.mark.filterwarnings("error")
def test_getattr_warning():
# issue gh-14735: make sure we clear only getattr errors, and let warnings
# through
class Wrapper:
def __init__(self, array):
self.array = array
def __len__(self):
return len(self.array)
def __getitem__(self, item):
return type(self)(self.array[item])
def __getattr__(self, name):
if name.startswith("__array_"):
warnings.warn("object got converted", UserWarning, stacklevel=1)
return getattr(self.array, name)
def __repr__(self):
return "<Wrapper({self.array})>".format(self=self)
array = Wrapper(np.arange(10))
with pytest.raises(UserWarning, match="object got converted"):
np.asarray(array)
def test_array_called():
class Wrapper:
val = '0' * 100
def __array__(self, result=None):
return np.array([self.val], dtype=object)
wrapped = Wrapper()
arr = np.array(wrapped, dtype=str)
assert arr.dtype == 'U100'
assert arr[0] == Wrapper.val

View file

@ -0,0 +1,504 @@
import collections.abc
import textwrap
from os import path
from pathlib import Path
import pytest
import numpy as np
from numpy.testing import (
assert_, assert_equal, assert_array_equal, assert_array_almost_equal,
assert_raises, temppath,
)
from numpy.compat import pickle
class TestFromrecords:
def test_fromrecords(self):
r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]],
names='col1,col2,col3')
assert_equal(r[0].item(), (456, 'dbe', 1.2))
assert_equal(r['col1'].dtype.kind, 'i')
assert_equal(r['col2'].dtype.kind, 'U')
assert_equal(r['col2'].dtype.itemsize, 12)
assert_equal(r['col3'].dtype.kind, 'f')
def test_fromrecords_0len(self):
""" Verify fromrecords works with a 0-length input """
dtype = [('a', float), ('b', float)]
r = np.rec.fromrecords([], dtype=dtype)
assert_equal(r.shape, (0,))
def test_fromrecords_2d(self):
data = [
[(1, 2), (3, 4), (5, 6)],
[(6, 5), (4, 3), (2, 1)]
]
expected_a = [[1, 3, 5], [6, 4, 2]]
expected_b = [[2, 4, 6], [5, 3, 1]]
# try with dtype
r1 = np.rec.fromrecords(data, dtype=[('a', int), ('b', int)])
assert_equal(r1['a'], expected_a)
assert_equal(r1['b'], expected_b)
# try with names
r2 = np.rec.fromrecords(data, names=['a', 'b'])
assert_equal(r2['a'], expected_a)
assert_equal(r2['b'], expected_b)
assert_equal(r1, r2)
def test_method_array(self):
r = np.rec.array(b'abcdefg' * 100, formats='i2,a3,i4', shape=3, byteorder='big')
assert_equal(r[1].item(), (25444, b'efg', 1633837924))
def test_method_array2(self):
r = np.rec.array([(1, 11, 'a'), (2, 22, 'b'), (3, 33, 'c'), (4, 44, 'd'), (5, 55, 'ex'),
(6, 66, 'f'), (7, 77, 'g')], formats='u1,f4,a1')
assert_equal(r[1].item(), (2, 22.0, b'b'))
def test_recarray_slices(self):
r = np.rec.array([(1, 11, 'a'), (2, 22, 'b'), (3, 33, 'c'), (4, 44, 'd'), (5, 55, 'ex'),
(6, 66, 'f'), (7, 77, 'g')], formats='u1,f4,a1')
assert_equal(r[1::2][1].item(), (4, 44.0, b'd'))
def test_recarray_fromarrays(self):
x1 = np.array([1, 2, 3, 4])
x2 = np.array(['a', 'dd', 'xyz', '12'])
x3 = np.array([1.1, 2, 3, 4])
r = np.rec.fromarrays([x1, x2, x3], names='a,b,c')
assert_equal(r[1].item(), (2, 'dd', 2.0))
x1[1] = 34
assert_equal(r.a, np.array([1, 2, 3, 4]))
def test_recarray_fromfile(self):
data_dir = path.join(path.dirname(__file__), 'data')
filename = path.join(data_dir, 'recarray_from_file.fits')
fd = open(filename, 'rb')
fd.seek(2880 * 2)
r1 = np.rec.fromfile(fd, formats='f8,i4,a5', shape=3, byteorder='big')
fd.seek(2880 * 2)
r2 = np.rec.array(fd, formats='f8,i4,a5', shape=3, byteorder='big')
fd.close()
assert_equal(r1, r2)
def test_recarray_from_obj(self):
count = 10
a = np.zeros(count, dtype='O')
b = np.zeros(count, dtype='f8')
c = np.zeros(count, dtype='f8')
for i in range(len(a)):
a[i] = list(range(1, 10))
mine = np.rec.fromarrays([a, b, c], names='date,data1,data2')
for i in range(len(a)):
assert_((mine.date[i] == list(range(1, 10))))
assert_((mine.data1[i] == 0.0))
assert_((mine.data2[i] == 0.0))
def test_recarray_repr(self):
a = np.array([(1, 0.1), (2, 0.2)],
dtype=[('foo', '<i4'), ('bar', '<f8')])
a = np.rec.array(a)
assert_equal(
repr(a),
textwrap.dedent("""\
rec.array([(1, 0.1), (2, 0.2)],
dtype=[('foo', '<i4'), ('bar', '<f8')])""")
)
# make sure non-structured dtypes also show up as rec.array
a = np.array(np.ones(4, dtype='f8'))
assert_(repr(np.rec.array(a)).startswith('rec.array'))
# check that the 'np.record' part of the dtype isn't shown
a = np.rec.array(np.ones(3, dtype='i4,i4'))
assert_equal(repr(a).find('numpy.record'), -1)
a = np.rec.array(np.ones(3, dtype='i4'))
assert_(repr(a).find('dtype=int32') != -1)
def test_0d_recarray_repr(self):
arr_0d = np.rec.array((1, 2.0, '2003'), dtype='<i4,<f8,<M8[Y]')
assert_equal(repr(arr_0d), textwrap.dedent("""\
rec.array((1, 2., '2003'),
dtype=[('f0', '<i4'), ('f1', '<f8'), ('f2', '<M8[Y]')])"""))
record = arr_0d[()]
assert_equal(repr(record), "(1, 2., '2003')")
# 1.13 converted to python scalars before the repr
try:
np.set_printoptions(legacy='1.13')
assert_equal(repr(record), '(1, 2.0, datetime.date(2003, 1, 1))')
finally:
np.set_printoptions(legacy=False)
def test_recarray_from_repr(self):
a = np.array([(1,'ABC'), (2, "DEF")],
dtype=[('foo', int), ('bar', 'S4')])
recordarr = np.rec.array(a)
recarr = a.view(np.recarray)
recordview = a.view(np.dtype((np.record, a.dtype)))
recordarr_r = eval("numpy." + repr(recordarr), {'numpy': np})
recarr_r = eval("numpy." + repr(recarr), {'numpy': np})
recordview_r = eval("numpy." + repr(recordview), {'numpy': np})
assert_equal(type(recordarr_r), np.recarray)
assert_equal(recordarr_r.dtype.type, np.record)
assert_equal(recordarr, recordarr_r)
assert_equal(type(recarr_r), np.recarray)
assert_equal(recarr_r.dtype.type, np.record)
assert_equal(recarr, recarr_r)
assert_equal(type(recordview_r), np.ndarray)
assert_equal(recordview.dtype.type, np.record)
assert_equal(recordview, recordview_r)
def test_recarray_views(self):
a = np.array([(1,'ABC'), (2, "DEF")],
dtype=[('foo', int), ('bar', 'S4')])
b = np.array([1,2,3,4,5], dtype=np.int64)
#check that np.rec.array gives right dtypes
assert_equal(np.rec.array(a).dtype.type, np.record)
assert_equal(type(np.rec.array(a)), np.recarray)
assert_equal(np.rec.array(b).dtype.type, np.int64)
assert_equal(type(np.rec.array(b)), np.recarray)
#check that viewing as recarray does the same
assert_equal(a.view(np.recarray).dtype.type, np.record)
assert_equal(type(a.view(np.recarray)), np.recarray)
assert_equal(b.view(np.recarray).dtype.type, np.int64)
assert_equal(type(b.view(np.recarray)), np.recarray)
#check that view to non-structured dtype preserves type=np.recarray
r = np.rec.array(np.ones(4, dtype="f4,i4"))
rv = r.view('f8').view('f4,i4')
assert_equal(type(rv), np.recarray)
assert_equal(rv.dtype.type, np.record)
#check that getitem also preserves np.recarray and np.record
r = np.rec.array(np.ones(4, dtype=[('a', 'i4'), ('b', 'i4'),
('c', 'i4,i4')]))
assert_equal(r['c'].dtype.type, np.record)
assert_equal(type(r['c']), np.recarray)
#and that it preserves subclasses (gh-6949)
class C(np.recarray):
pass
c = r.view(C)
assert_equal(type(c['c']), C)
# check that accessing nested structures keep record type, but
# not for subarrays, non-void structures, non-structured voids
test_dtype = [('a', 'f4,f4'), ('b', 'V8'), ('c', ('f4',2)),
('d', ('i8', 'i4,i4'))]
r = np.rec.array([((1,1), b'11111111', [1,1], 1),
((1,1), b'11111111', [1,1], 1)], dtype=test_dtype)
assert_equal(r.a.dtype.type, np.record)
assert_equal(r.b.dtype.type, np.void)
assert_equal(r.c.dtype.type, np.float32)
assert_equal(r.d.dtype.type, np.int64)
# check the same, but for views
r = np.rec.array(np.ones(4, dtype='i4,i4'))
assert_equal(r.view('f4,f4').dtype.type, np.record)
assert_equal(r.view(('i4',2)).dtype.type, np.int32)
assert_equal(r.view('V8').dtype.type, np.void)
assert_equal(r.view(('i8', 'i4,i4')).dtype.type, np.int64)
#check that we can undo the view
arrs = [np.ones(4, dtype='f4,i4'), np.ones(4, dtype='f8')]
for arr in arrs:
rec = np.rec.array(arr)
# recommended way to view as an ndarray:
arr2 = rec.view(rec.dtype.fields or rec.dtype, np.ndarray)
assert_equal(arr2.dtype.type, arr.dtype.type)
assert_equal(type(arr2), type(arr))
def test_recarray_from_names(self):
ra = np.rec.array([
(1, 'abc', 3.7000002861022949, 0),
(2, 'xy', 6.6999998092651367, 1),
(0, ' ', 0.40000000596046448, 0)],
names='c1, c2, c3, c4')
pa = np.rec.fromrecords([
(1, 'abc', 3.7000002861022949, 0),
(2, 'xy', 6.6999998092651367, 1),
(0, ' ', 0.40000000596046448, 0)],
names='c1, c2, c3, c4')
assert_(ra.dtype == pa.dtype)
assert_(ra.shape == pa.shape)
for k in range(len(ra)):
assert_(ra[k].item() == pa[k].item())
def test_recarray_conflict_fields(self):
ra = np.rec.array([(1, 'abc', 2.3), (2, 'xyz', 4.2),
(3, 'wrs', 1.3)],
names='field, shape, mean')
ra.mean = [1.1, 2.2, 3.3]
assert_array_almost_equal(ra['mean'], [1.1, 2.2, 3.3])
assert_(type(ra.mean) is type(ra.var))
ra.shape = (1, 3)
assert_(ra.shape == (1, 3))
ra.shape = ['A', 'B', 'C']
assert_array_equal(ra['shape'], [['A', 'B', 'C']])
ra.field = 5
assert_array_equal(ra['field'], [[5, 5, 5]])
assert_(isinstance(ra.field, collections.abc.Callable))
def test_fromrecords_with_explicit_dtype(self):
a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')],
dtype=[('a', int), ('b', object)])
assert_equal(a.a, [1, 2])
assert_equal(a[0].a, 1)
assert_equal(a.b, ['a', 'bbb'])
assert_equal(a[-1].b, 'bbb')
#
ndtype = np.dtype([('a', int), ('b', object)])
a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')], dtype=ndtype)
assert_equal(a.a, [1, 2])
assert_equal(a[0].a, 1)
assert_equal(a.b, ['a', 'bbb'])
assert_equal(a[-1].b, 'bbb')
def test_recarray_stringtypes(self):
# Issue #3993
a = np.array([('abc ', 1), ('abc', 2)],
dtype=[('foo', 'S4'), ('bar', int)])
a = a.view(np.recarray)
assert_equal(a.foo[0] == a.foo[1], False)
def test_recarray_returntypes(self):
qux_fields = {'C': (np.dtype('S5'), 0), 'D': (np.dtype('S5'), 6)}
a = np.rec.array([('abc ', (1,1), 1, ('abcde', 'fgehi')),
('abc', (2,3), 1, ('abcde', 'jklmn'))],
dtype=[('foo', 'S4'),
('bar', [('A', int), ('B', int)]),
('baz', int), ('qux', qux_fields)])
assert_equal(type(a.foo), np.ndarray)
assert_equal(type(a['foo']), np.ndarray)
assert_equal(type(a.bar), np.recarray)
assert_equal(type(a['bar']), np.recarray)
assert_equal(a.bar.dtype.type, np.record)
assert_equal(type(a['qux']), np.recarray)
assert_equal(a.qux.dtype.type, np.record)
assert_equal(dict(a.qux.dtype.fields), qux_fields)
assert_equal(type(a.baz), np.ndarray)
assert_equal(type(a['baz']), np.ndarray)
assert_equal(type(a[0].bar), np.record)
assert_equal(type(a[0]['bar']), np.record)
assert_equal(a[0].bar.A, 1)
assert_equal(a[0].bar['A'], 1)
assert_equal(a[0]['bar'].A, 1)
assert_equal(a[0]['bar']['A'], 1)
assert_equal(a[0].qux.D, b'fgehi')
assert_equal(a[0].qux['D'], b'fgehi')
assert_equal(a[0]['qux'].D, b'fgehi')
assert_equal(a[0]['qux']['D'], b'fgehi')
def test_zero_width_strings(self):
# Test for #6430, based on the test case from #1901
cols = [['test'] * 3, [''] * 3]
rec = np.rec.fromarrays(cols)
assert_equal(rec['f0'], ['test', 'test', 'test'])
assert_equal(rec['f1'], ['', '', ''])
dt = np.dtype([('f0', '|S4'), ('f1', '|S')])
rec = np.rec.fromarrays(cols, dtype=dt)
assert_equal(rec.itemsize, 4)
assert_equal(rec['f0'], [b'test', b'test', b'test'])
assert_equal(rec['f1'], [b'', b'', b''])
class TestPathUsage:
# Test that pathlib.Path can be used
def test_tofile_fromfile(self):
with temppath(suffix='.bin') as path:
path = Path(path)
np.random.seed(123)
a = np.random.rand(10).astype('f8,i4,a5')
a[5] = (0.5,10,'abcde')
with path.open("wb") as fd:
a.tofile(fd)
x = np.core.records.fromfile(path,
formats='f8,i4,a5',
shape=10)
assert_array_equal(x, a)
class TestRecord:
def setup(self):
self.data = np.rec.fromrecords([(1, 2, 3), (4, 5, 6)],
dtype=[("col1", "<i4"),
("col2", "<i4"),
("col3", "<i4")])
def test_assignment1(self):
a = self.data
assert_equal(a.col1[0], 1)
a[0].col1 = 0
assert_equal(a.col1[0], 0)
def test_assignment2(self):
a = self.data
assert_equal(a.col1[0], 1)
a.col1[0] = 0
assert_equal(a.col1[0], 0)
def test_invalid_assignment(self):
a = self.data
def assign_invalid_column(x):
x[0].col5 = 1
assert_raises(AttributeError, assign_invalid_column, a)
def test_nonwriteable_setfield(self):
# gh-8171
r = np.rec.array([(0,), (1,)], dtype=[('f', 'i4')])
r.flags.writeable = False
with assert_raises(ValueError):
r.f = [2, 3]
with assert_raises(ValueError):
r.setfield([2,3], *r.dtype.fields['f'])
def test_out_of_order_fields(self):
# names in the same order, padding added to descr
x = self.data[['col1', 'col2']]
assert_equal(x.dtype.names, ('col1', 'col2'))
assert_equal(x.dtype.descr,
[('col1', '<i4'), ('col2', '<i4'), ('', '|V4')])
# names change order to match indexing, as of 1.14 - descr can't
# represent that
y = self.data[['col2', 'col1']]
assert_equal(y.dtype.names, ('col2', 'col1'))
assert_raises(ValueError, lambda: y.dtype.descr)
def test_pickle_1(self):
# Issue #1529
a = np.array([(1, [])], dtype=[('a', np.int32), ('b', np.int32, 0)])
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
assert_equal(a, pickle.loads(pickle.dumps(a, protocol=proto)))
assert_equal(a[0], pickle.loads(pickle.dumps(a[0],
protocol=proto)))
def test_pickle_2(self):
a = self.data
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
assert_equal(a, pickle.loads(pickle.dumps(a, protocol=proto)))
assert_equal(a[0], pickle.loads(pickle.dumps(a[0],
protocol=proto)))
def test_pickle_3(self):
# Issue #7140
a = self.data
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
pa = pickle.loads(pickle.dumps(a[0], protocol=proto))
assert_(pa.flags.c_contiguous)
assert_(pa.flags.f_contiguous)
assert_(pa.flags.writeable)
assert_(pa.flags.aligned)
def test_pickle_void(self):
# issue gh-13593
dt = np.dtype([('obj', 'O'), ('int', 'i')])
a = np.empty(1, dtype=dt)
data = (bytearray(b'eman'),)
a['obj'] = data
a['int'] = 42
ctor, args = a[0].__reduce__()
# check the constructor is what we expect before interpreting the arguments
assert ctor is np.core.multiarray.scalar
dtype, obj = args
# make sure we did not pickle the address
assert not isinstance(obj, bytes)
assert_raises(TypeError, ctor, dtype, 13)
def test_objview_record(self):
# https://github.com/numpy/numpy/issues/2599
dt = np.dtype([('foo', 'i8'), ('bar', 'O')])
r = np.zeros((1,3), dtype=dt).view(np.recarray)
r.foo = np.array([1, 2, 3]) # TypeError?
# https://github.com/numpy/numpy/issues/3256
ra = np.recarray((2,), dtype=[('x', object), ('y', float), ('z', int)])
ra[['x','y']] # TypeError?
def test_record_scalar_setitem(self):
# https://github.com/numpy/numpy/issues/3561
rec = np.recarray(1, dtype=[('x', float, 5)])
rec[0].x = 1
assert_equal(rec[0].x, np.ones(5))
def test_missing_field(self):
# https://github.com/numpy/numpy/issues/4806
arr = np.zeros((3,), dtype=[('x', int), ('y', int)])
assert_raises(KeyError, lambda: arr[['nofield']])
def test_fromarrays_nested_structured_arrays(self):
arrays = [
np.arange(10),
np.ones(10, dtype=[('a', '<u2'), ('b', '<f4')]),
]
arr = np.rec.fromarrays(arrays) # ValueError?
@pytest.mark.parametrize('nfields', [0, 1, 2])
def test_assign_dtype_attribute(self, nfields):
dt = np.dtype([('a', np.uint8), ('b', np.uint8), ('c', np.uint8)][:nfields])
data = np.zeros(3, dt).view(np.recarray)
# the original and resulting dtypes differ on whether they are records
assert data.dtype.type == np.record
assert dt.type != np.record
# ensure that the dtype remains a record even when assigned
data.dtype = dt
assert data.dtype.type == np.record
@pytest.mark.parametrize('nfields', [0, 1, 2])
def test_nested_fields_are_records(self, nfields):
""" Test that nested structured types are treated as records too """
dt = np.dtype([('a', np.uint8), ('b', np.uint8), ('c', np.uint8)][:nfields])
dt_outer = np.dtype([('inner', dt)])
data = np.zeros(3, dt_outer).view(np.recarray)
assert isinstance(data, np.recarray)
assert isinstance(data['inner'], np.recarray)
data0 = data[0]
assert isinstance(data0, np.record)
assert isinstance(data0['inner'], np.record)
def test_nested_dtype_padding(self):
""" test that trailing padding is preserved """
# construct a dtype with padding at the end
dt = np.dtype([('a', np.uint8), ('b', np.uint8), ('c', np.uint8)])
dt_padded_end = dt[['a', 'b']]
assert dt_padded_end.itemsize == dt.itemsize
dt_outer = np.dtype([('inner', dt_padded_end)])
data = np.zeros(3, dt_outer).view(np.recarray)
assert_equal(data['inner'].dtype, dt_padded_end)
data0 = data[0]
assert_equal(data0['inner'].dtype, dt_padded_end)
def test_find_duplicate():
l1 = [1, 2, 3, 4, 5, 6]
assert_(np.rec.find_duplicate(l1) == [])
l2 = [1, 2, 1, 4, 5, 6]
assert_(np.rec.find_duplicate(l2) == [1])
l3 = [1, 2, 1, 4, 1, 6, 2, 3]
assert_(np.rec.find_duplicate(l3) == [1, 2])
l3 = [2, 2, 1, 4, 1, 6, 2, 3]
assert_(np.rec.find_duplicate(l3) == [2, 1])

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,81 @@
"""
Test the scalar constructors, which also do type-coercion
"""
import pytest
import numpy as np
from numpy.testing import (
assert_equal, assert_almost_equal, assert_warns,
)
class TestFromString:
def test_floating(self):
# Ticket #640, floats from string
fsingle = np.single('1.234')
fdouble = np.double('1.234')
flongdouble = np.longdouble('1.234')
assert_almost_equal(fsingle, 1.234)
assert_almost_equal(fdouble, 1.234)
assert_almost_equal(flongdouble, 1.234)
def test_floating_overflow(self):
""" Strings containing an unrepresentable float overflow """
fhalf = np.half('1e10000')
assert_equal(fhalf, np.inf)
fsingle = np.single('1e10000')
assert_equal(fsingle, np.inf)
fdouble = np.double('1e10000')
assert_equal(fdouble, np.inf)
flongdouble = assert_warns(RuntimeWarning, np.longdouble, '1e10000')
assert_equal(flongdouble, np.inf)
fhalf = np.half('-1e10000')
assert_equal(fhalf, -np.inf)
fsingle = np.single('-1e10000')
assert_equal(fsingle, -np.inf)
fdouble = np.double('-1e10000')
assert_equal(fdouble, -np.inf)
flongdouble = assert_warns(RuntimeWarning, np.longdouble, '-1e10000')
assert_equal(flongdouble, -np.inf)
class TestExtraArgs:
def test_superclass(self):
# try both positional and keyword arguments
s = np.str_(b'\\x61', encoding='unicode-escape')
assert s == 'a'
s = np.str_(b'\\x61', 'unicode-escape')
assert s == 'a'
# previously this would return '\\xx'
with pytest.raises(UnicodeDecodeError):
np.str_(b'\\xx', encoding='unicode-escape')
with pytest.raises(UnicodeDecodeError):
np.str_(b'\\xx', 'unicode-escape')
# superclass fails, but numpy succeeds
assert np.bytes_(-2) == b'-2'
def test_datetime(self):
dt = np.datetime64('2000-01', ('M', 2))
assert np.datetime_data(dt) == ('M', 2)
with pytest.raises(TypeError):
np.datetime64('2000', garbage=True)
def test_bool(self):
with pytest.raises(TypeError):
np.bool(False, garbage=True)
def test_void(self):
with pytest.raises(TypeError):
np.void(b'test', garbage=True)
class TestFromInt:
def test_intp(self):
# Ticket #99
assert_equal(1024, np.intp(1024))
def test_uint64_from_negative(self):
assert_equal(np.uint64(-2), np.uint64(18446744073709551614))

View file

@ -0,0 +1,103 @@
"""
Test the scalar constructors, which also do type-coercion
"""
import fractions
import platform
import pytest
import numpy as np
from numpy.testing import assert_equal, assert_raises
class TestAsIntegerRatio:
# derived in part from the cpython test "test_floatasratio"
@pytest.mark.parametrize("ftype", [
np.half, np.single, np.double, np.longdouble])
@pytest.mark.parametrize("f, ratio", [
(0.875, (7, 8)),
(-0.875, (-7, 8)),
(0.0, (0, 1)),
(11.5, (23, 2)),
])
def test_small(self, ftype, f, ratio):
assert_equal(ftype(f).as_integer_ratio(), ratio)
@pytest.mark.parametrize("ftype", [
np.half, np.single, np.double, np.longdouble])
def test_simple_fractions(self, ftype):
R = fractions.Fraction
assert_equal(R(0, 1),
R(*ftype(0.0).as_integer_ratio()))
assert_equal(R(5, 2),
R(*ftype(2.5).as_integer_ratio()))
assert_equal(R(1, 2),
R(*ftype(0.5).as_integer_ratio()))
assert_equal(R(-2100, 1),
R(*ftype(-2100.0).as_integer_ratio()))
@pytest.mark.parametrize("ftype", [
np.half, np.single, np.double, np.longdouble])
def test_errors(self, ftype):
assert_raises(OverflowError, ftype('inf').as_integer_ratio)
assert_raises(OverflowError, ftype('-inf').as_integer_ratio)
assert_raises(ValueError, ftype('nan').as_integer_ratio)
def test_against_known_values(self):
R = fractions.Fraction
assert_equal(R(1075, 512),
R(*np.half(2.1).as_integer_ratio()))
assert_equal(R(-1075, 512),
R(*np.half(-2.1).as_integer_ratio()))
assert_equal(R(4404019, 2097152),
R(*np.single(2.1).as_integer_ratio()))
assert_equal(R(-4404019, 2097152),
R(*np.single(-2.1).as_integer_ratio()))
assert_equal(R(4728779608739021, 2251799813685248),
R(*np.double(2.1).as_integer_ratio()))
assert_equal(R(-4728779608739021, 2251799813685248),
R(*np.double(-2.1).as_integer_ratio()))
# longdouble is platform dependent
@pytest.mark.parametrize("ftype, frac_vals, exp_vals", [
# dtype test cases generated using hypothesis
# first five generated cases per dtype
(np.half, [0.0, 0.01154830649280303, 0.31082276347447274,
0.527350517124794, 0.8308562335072596],
[0, 1, 0, -8, 12]),
(np.single, [0.0, 0.09248576989263226, 0.8160498218131407,
0.17389442853722373, 0.7956044195067877],
[0, 12, 10, 17, -26]),
(np.double, [0.0, 0.031066908499895136, 0.5214135908877832,
0.45780736035689296, 0.5906586745934036],
[0, -801, 51, 194, -653]),
pytest.param(
np.longdouble,
[0.0, 0.20492557202724854, 0.4277180662199366, 0.9888085019891495,
0.9620175814461964],
[0, -7400, 14266, -7822, -8721],
marks=[
pytest.mark.skipif(
np.finfo(np.double) == np.finfo(np.longdouble),
reason="long double is same as double"),
pytest.mark.skipif(
platform.machine().startswith("ppc"),
reason="IBM double double"),
]
)
])
def test_roundtrip(self, ftype, frac_vals, exp_vals):
for frac, exp in zip(frac_vals, exp_vals):
f = np.ldexp(frac, exp, dtype=ftype)
n, d = f.as_integer_ratio()
try:
# workaround for gh-9968
nf = np.longdouble(str(n))
df = np.longdouble(str(d))
except (OverflowError, RuntimeWarning):
# the values may not fit in any float type
pytest.skip("longdouble too small on this platform")
assert_equal(nf / df, f, "{}/{}".format(n, d))

View file

@ -0,0 +1,119 @@
"""
Test scalar buffer interface adheres to PEP 3118
"""
import numpy as np
import pytest
from numpy.testing import assert_, assert_equal, assert_raises
# PEP3118 format strings for native (standard alignment and byteorder) types
scalars_and_codes = [
(np.bool_, '?'),
(np.byte, 'b'),
(np.short, 'h'),
(np.intc, 'i'),
(np.int_, 'l'),
(np.longlong, 'q'),
(np.ubyte, 'B'),
(np.ushort, 'H'),
(np.uintc, 'I'),
(np.uint, 'L'),
(np.ulonglong, 'Q'),
(np.half, 'e'),
(np.single, 'f'),
(np.double, 'd'),
(np.longdouble, 'g'),
(np.csingle, 'Zf'),
(np.cdouble, 'Zd'),
(np.clongdouble, 'Zg'),
]
scalars_only, codes_only = zip(*scalars_and_codes)
class TestScalarPEP3118:
@pytest.mark.parametrize('scalar', scalars_only, ids=codes_only)
def test_scalar_match_array(self, scalar):
x = scalar()
a = np.array([], dtype=np.dtype(scalar))
mv_x = memoryview(x)
mv_a = memoryview(a)
assert_equal(mv_x.format, mv_a.format)
@pytest.mark.parametrize('scalar', scalars_only, ids=codes_only)
def test_scalar_dim(self, scalar):
x = scalar()
mv_x = memoryview(x)
assert_equal(mv_x.itemsize, np.dtype(scalar).itemsize)
assert_equal(mv_x.ndim, 0)
assert_equal(mv_x.shape, ())
assert_equal(mv_x.strides, ())
assert_equal(mv_x.suboffsets, ())
@pytest.mark.parametrize('scalar, code', scalars_and_codes, ids=codes_only)
def test_scalar_known_code(self, scalar, code):
x = scalar()
mv_x = memoryview(x)
assert_equal(mv_x.format, code)
def test_void_scalar_structured_data(self):
dt = np.dtype([('name', np.unicode_, 16), ('grades', np.float64, (2,))])
x = np.array(('ndarray_scalar', (1.2, 3.0)), dtype=dt)[()]
assert_(isinstance(x, np.void))
mv_x = memoryview(x)
expected_size = 16 * np.dtype((np.unicode_, 1)).itemsize
expected_size += 2 * np.dtype(np.float64).itemsize
assert_equal(mv_x.itemsize, expected_size)
assert_equal(mv_x.ndim, 0)
assert_equal(mv_x.shape, ())
assert_equal(mv_x.strides, ())
assert_equal(mv_x.suboffsets, ())
# check scalar format string against ndarray format string
a = np.array([('Sarah', (8.0, 7.0)), ('John', (6.0, 7.0))], dtype=dt)
assert_(isinstance(a, np.ndarray))
mv_a = memoryview(a)
assert_equal(mv_x.itemsize, mv_a.itemsize)
assert_equal(mv_x.format, mv_a.format)
def _as_dict(self, m):
return dict(strides=m.strides, shape=m.shape, itemsize=m.itemsize,
ndim=m.ndim, format=m.format)
def test_datetime_memoryview(self):
# gh-11656
# Values verified with v1.13.3, shape is not () as in test_scalar_dim
dt1 = np.datetime64('2016-01-01')
dt2 = np.datetime64('2017-01-01')
expected = dict(strides=(1,), itemsize=1, ndim=1, shape=(8,),
format='B')
v = memoryview(dt1)
assert self._as_dict(v) == expected
v = memoryview(dt2 - dt1)
assert self._as_dict(v) == expected
dt = np.dtype([('a', 'uint16'), ('b', 'M8[s]')])
a = np.empty(1, dt)
# Fails to create a PEP 3118 valid buffer
assert_raises((ValueError, BufferError), memoryview, a[0])
@pytest.mark.parametrize('s', [
pytest.param("\x32\x32", id="ascii"),
pytest.param("\uFE0F\uFE0F", id="basic multilingual"),
pytest.param("\U0001f4bb\U0001f4bb", id="non-BMP"),
])
def test_str_ucs4(self, s):
s = np.str_(s) # only our subclass implements the buffer protocol
# all the same, characters always encode as ucs4
expected = dict(strides=(), itemsize=8, ndim=0, shape=(), format='2w')
v = memoryview(s)
assert self._as_dict(v) == expected
# integers of the paltform-appropriate endianness
code_points = np.frombuffer(v, dtype='i4')
assert_equal(code_points, [ord(c) for c in s])

View file

@ -0,0 +1,91 @@
# -*- coding: utf-8 -*-
""" Test printing of scalar types.
"""
import pytest
import numpy as np
from numpy.testing import assert_
class A:
pass
class B(A, np.float64):
pass
class C(B):
pass
class D(C, B):
pass
class B0(np.float64, A):
pass
class C0(B0):
pass
class HasNew:
def __new__(cls, *args, **kwargs):
return cls, args, kwargs
class B1(np.float64, HasNew):
pass
class TestInherit:
def test_init(self):
x = B(1.0)
assert_(str(x) == '1.0')
y = C(2.0)
assert_(str(y) == '2.0')
z = D(3.0)
assert_(str(z) == '3.0')
def test_init2(self):
x = B0(1.0)
assert_(str(x) == '1.0')
y = C0(2.0)
assert_(str(y) == '2.0')
def test_gh_15395(self):
# HasNew is the second base, so `np.float64` should have priority
x = B1(1.0)
assert_(str(x) == '1.0')
# previously caused RecursionError!?
with pytest.raises(TypeError):
B1(1.0, 2.0)
class TestCharacter:
def test_char_radd(self):
# GH issue 9620, reached gentype_add and raise TypeError
np_s = np.string_('abc')
np_u = np.unicode_('abc')
s = b'def'
u = u'def'
assert_(np_s.__radd__(np_s) is NotImplemented)
assert_(np_s.__radd__(np_u) is NotImplemented)
assert_(np_s.__radd__(s) is NotImplemented)
assert_(np_s.__radd__(u) is NotImplemented)
assert_(np_u.__radd__(np_s) is NotImplemented)
assert_(np_u.__radd__(np_u) is NotImplemented)
assert_(np_u.__radd__(s) is NotImplemented)
assert_(np_u.__radd__(u) is NotImplemented)
assert_(s + np_s == b'defabc')
assert_(u + np_u == u'defabc')
class Mystr(str, np.generic):
# would segfault
pass
ret = s + Mystr('abc')
assert_(type(ret) is type(s))
def test_char_repeat(self):
np_s = np.string_('abc')
np_u = np.unicode_('abc')
res_s = b'abc' * 5
res_u = u'abc' * 5
assert_(np_s * 5 == res_s)
assert_(np_u * 5 == res_u)

View file

@ -0,0 +1,702 @@
import sys
import warnings
import itertools
import operator
import platform
import pytest
import numpy as np
from numpy.testing import (
assert_, assert_equal, assert_raises, assert_almost_equal,
assert_array_equal, IS_PYPY, suppress_warnings, _gen_alignment_data,
assert_warns, assert_raises_regex,
)
types = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, np.uintc,
np.int_, np.uint, np.longlong, np.ulonglong,
np.single, np.double, np.longdouble, np.csingle,
np.cdouble, np.clongdouble]
floating_types = np.floating.__subclasses__()
complex_floating_types = np.complexfloating.__subclasses__()
# This compares scalarmath against ufuncs.
class TestTypes:
def test_types(self):
for atype in types:
a = atype(1)
assert_(a == 1, "error with %r: got %r" % (atype, a))
def test_type_add(self):
# list of types
for k, atype in enumerate(types):
a_scalar = atype(3)
a_array = np.array([3], dtype=atype)
for l, btype in enumerate(types):
b_scalar = btype(1)
b_array = np.array([1], dtype=btype)
c_scalar = a_scalar + b_scalar
c_array = a_array + b_array
# It was comparing the type numbers, but the new ufunc
# function-finding mechanism finds the lowest function
# to which both inputs can be cast - which produces 'l'
# when you do 'q' + 'b'. The old function finding mechanism
# skipped ahead based on the first argument, but that
# does not produce properly symmetric results...
assert_equal(c_scalar.dtype, c_array.dtype,
"error with types (%d/'%c' + %d/'%c')" %
(k, np.dtype(atype).char, l, np.dtype(btype).char))
def test_type_create(self):
for k, atype in enumerate(types):
a = np.array([1, 2, 3], atype)
b = atype([1, 2, 3])
assert_equal(a, b)
def test_leak(self):
# test leak of scalar objects
# a leak would show up in valgrind as still-reachable of ~2.6MB
for i in range(200000):
np.add(1, 1)
class TestBaseMath:
def test_blocked(self):
# test alignments offsets for simd instructions
# alignments for vz + 2 * (vs - 1) + 1
for dt, sz in [(np.float32, 11), (np.float64, 7), (np.int32, 11)]:
for out, inp1, inp2, msg in _gen_alignment_data(dtype=dt,
type='binary',
max_size=sz):
exp1 = np.ones_like(inp1)
inp1[...] = np.ones_like(inp1)
inp2[...] = np.zeros_like(inp2)
assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg)
assert_almost_equal(np.add(inp1, 2), exp1 + 2, err_msg=msg)
assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg)
np.add(inp1, inp2, out=out)
assert_almost_equal(out, exp1, err_msg=msg)
inp2[...] += np.arange(inp2.size, dtype=dt) + 1
assert_almost_equal(np.square(inp2),
np.multiply(inp2, inp2), err_msg=msg)
# skip true divide for ints
if dt != np.int32:
assert_almost_equal(np.reciprocal(inp2),
np.divide(1, inp2), err_msg=msg)
inp1[...] = np.ones_like(inp1)
np.add(inp1, 2, out=out)
assert_almost_equal(out, exp1 + 2, err_msg=msg)
inp2[...] = np.ones_like(inp2)
np.add(2, inp2, out=out)
assert_almost_equal(out, exp1 + 2, err_msg=msg)
def test_lower_align(self):
# check data that is not aligned to element size
# i.e doubles are aligned to 4 bytes on i386
d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
o = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
assert_almost_equal(d + d, d * 2)
np.add(d, d, out=o)
np.add(np.ones_like(d), d, out=o)
np.add(d, np.ones_like(d), out=o)
np.add(np.ones_like(d), d)
np.add(d, np.ones_like(d))
class TestPower:
def test_small_types(self):
for t in [np.int8, np.int16, np.float16]:
a = t(3)
b = a ** 4
assert_(b == 81, "error with %r: got %r" % (t, b))
def test_large_types(self):
for t in [np.int32, np.int64, np.float32, np.float64, np.longdouble]:
a = t(51)
b = a ** 4
msg = "error with %r: got %r" % (t, b)
if np.issubdtype(t, np.integer):
assert_(b == 6765201, msg)
else:
assert_almost_equal(b, 6765201, err_msg=msg)
def test_integers_to_negative_integer_power(self):
# Note that the combination of uint64 with a signed integer
# has common type np.float64. The other combinations should all
# raise a ValueError for integer ** negative integer.
exp = [np.array(-1, dt)[()] for dt in 'bhilq']
# 1 ** -1 possible special case
base = [np.array(1, dt)[()] for dt in 'bhilqBHILQ']
for i1, i2 in itertools.product(base, exp):
if i1.dtype != np.uint64:
assert_raises(ValueError, operator.pow, i1, i2)
else:
res = operator.pow(i1, i2)
assert_(res.dtype.type is np.float64)
assert_almost_equal(res, 1.)
# -1 ** -1 possible special case
base = [np.array(-1, dt)[()] for dt in 'bhilq']
for i1, i2 in itertools.product(base, exp):
if i1.dtype != np.uint64:
assert_raises(ValueError, operator.pow, i1, i2)
else:
res = operator.pow(i1, i2)
assert_(res.dtype.type is np.float64)
assert_almost_equal(res, -1.)
# 2 ** -1 perhaps generic
base = [np.array(2, dt)[()] for dt in 'bhilqBHILQ']
for i1, i2 in itertools.product(base, exp):
if i1.dtype != np.uint64:
assert_raises(ValueError, operator.pow, i1, i2)
else:
res = operator.pow(i1, i2)
assert_(res.dtype.type is np.float64)
assert_almost_equal(res, .5)
def test_mixed_types(self):
typelist = [np.int8, np.int16, np.float16,
np.float32, np.float64, np.int8,
np.int16, np.int32, np.int64]
for t1 in typelist:
for t2 in typelist:
a = t1(3)
b = t2(2)
result = a**b
msg = ("error with %r and %r:"
"got %r, expected %r") % (t1, t2, result, 9)
if np.issubdtype(np.dtype(result), np.integer):
assert_(result == 9, msg)
else:
assert_almost_equal(result, 9, err_msg=msg)
def test_modular_power(self):
# modular power is not implemented, so ensure it errors
a = 5
b = 4
c = 10
expected = pow(a, b, c) # noqa: F841
for t in (np.int32, np.float32, np.complex64):
# note that 3-operand power only dispatches on the first argument
assert_raises(TypeError, operator.pow, t(a), b, c)
assert_raises(TypeError, operator.pow, np.array(t(a)), b, c)
def floordiv_and_mod(x, y):
return (x // y, x % y)
def _signs(dt):
if dt in np.typecodes['UnsignedInteger']:
return (+1,)
else:
return (+1, -1)
class TestModulus:
def test_modulus_basic(self):
dt = np.typecodes['AllInteger'] + np.typecodes['Float']
for op in [floordiv_and_mod, divmod]:
for dt1, dt2 in itertools.product(dt, dt):
for sg1, sg2 in itertools.product(_signs(dt1), _signs(dt2)):
fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s'
msg = fmt % (op.__name__, dt1, dt2, sg1, sg2)
a = np.array(sg1*71, dtype=dt1)[()]
b = np.array(sg2*19, dtype=dt2)[()]
div, rem = op(a, b)
assert_equal(div*b + rem, a, err_msg=msg)
if sg2 == -1:
assert_(b < rem <= 0, msg)
else:
assert_(b > rem >= 0, msg)
def test_float_modulus_exact(self):
# test that float results are exact for small integers. This also
# holds for the same integers scaled by powers of two.
nlst = list(range(-127, 0))
plst = list(range(1, 128))
dividend = nlst + [0] + plst
divisor = nlst + plst
arg = list(itertools.product(dividend, divisor))
tgt = list(divmod(*t) for t in arg)
a, b = np.array(arg, dtype=int).T
# convert exact integer results from Python to float so that
# signed zero can be used, it is checked.
tgtdiv, tgtrem = np.array(tgt, dtype=float).T
tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv)
tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem)
for op in [floordiv_and_mod, divmod]:
for dt in np.typecodes['Float']:
msg = 'op: %s, dtype: %s' % (op.__name__, dt)
fa = a.astype(dt)
fb = b.astype(dt)
# use list comprehension so a_ and b_ are scalars
div, rem = zip(*[op(a_, b_) for a_, b_ in zip(fa, fb)])
assert_equal(div, tgtdiv, err_msg=msg)
assert_equal(rem, tgtrem, err_msg=msg)
def test_float_modulus_roundoff(self):
# gh-6127
dt = np.typecodes['Float']
for op in [floordiv_and_mod, divmod]:
for dt1, dt2 in itertools.product(dt, dt):
for sg1, sg2 in itertools.product((+1, -1), (+1, -1)):
fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s'
msg = fmt % (op.__name__, dt1, dt2, sg1, sg2)
a = np.array(sg1*78*6e-8, dtype=dt1)[()]
b = np.array(sg2*6e-8, dtype=dt2)[()]
div, rem = op(a, b)
# Equal assertion should hold when fmod is used
assert_equal(div*b + rem, a, err_msg=msg)
if sg2 == -1:
assert_(b < rem <= 0, msg)
else:
assert_(b > rem >= 0, msg)
def test_float_modulus_corner_cases(self):
# Check remainder magnitude.
for dt in np.typecodes['Float']:
b = np.array(1.0, dtype=dt)
a = np.nextafter(np.array(0.0, dtype=dt), -b)
rem = operator.mod(a, b)
assert_(rem <= b, 'dt: %s' % dt)
rem = operator.mod(-a, -b)
assert_(rem >= -b, 'dt: %s' % dt)
# Check nans, inf
with suppress_warnings() as sup:
sup.filter(RuntimeWarning, "invalid value encountered in remainder")
for dt in np.typecodes['Float']:
fone = np.array(1.0, dtype=dt)
fzer = np.array(0.0, dtype=dt)
finf = np.array(np.inf, dtype=dt)
fnan = np.array(np.nan, dtype=dt)
rem = operator.mod(fone, fzer)
assert_(np.isnan(rem), 'dt: %s' % dt)
# MSVC 2008 returns NaN here, so disable the check.
#rem = operator.mod(fone, finf)
#assert_(rem == fone, 'dt: %s' % dt)
rem = operator.mod(fone, fnan)
assert_(np.isnan(rem), 'dt: %s' % dt)
rem = operator.mod(finf, fone)
assert_(np.isnan(rem), 'dt: %s' % dt)
def test_inplace_floordiv_handling(self):
# issue gh-12927
# this only applies to in-place floordiv //=, because the output type
# promotes to float which does not fit
a = np.array([1, 2], np.int64)
b = np.array([1, 2], np.uint64)
pattern = 'could not be coerced to provided output parameter'
with assert_raises_regex(TypeError, pattern):
a //= b
class TestComplexDivision:
def test_zero_division(self):
with np.errstate(all="ignore"):
for t in [np.complex64, np.complex128]:
a = t(0.0)
b = t(1.0)
assert_(np.isinf(b/a))
b = t(complex(np.inf, np.inf))
assert_(np.isinf(b/a))
b = t(complex(np.inf, np.nan))
assert_(np.isinf(b/a))
b = t(complex(np.nan, np.inf))
assert_(np.isinf(b/a))
b = t(complex(np.nan, np.nan))
assert_(np.isnan(b/a))
b = t(0.)
assert_(np.isnan(b/a))
def test_signed_zeros(self):
with np.errstate(all="ignore"):
for t in [np.complex64, np.complex128]:
# tupled (numerator, denominator, expected)
# for testing as expected == numerator/denominator
data = (
(( 0.0,-1.0), ( 0.0, 1.0), (-1.0,-0.0)),
(( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)),
(( 0.0,-1.0), (-0.0,-1.0), ( 1.0, 0.0)),
(( 0.0,-1.0), (-0.0, 1.0), (-1.0, 0.0)),
(( 0.0, 1.0), ( 0.0,-1.0), (-1.0, 0.0)),
(( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)),
((-0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)),
((-0.0, 1.0), ( 0.0,-1.0), (-1.0,-0.0))
)
for cases in data:
n = cases[0]
d = cases[1]
ex = cases[2]
result = t(complex(n[0], n[1])) / t(complex(d[0], d[1]))
# check real and imag parts separately to avoid comparison
# in array context, which does not account for signed zeros
assert_equal(result.real, ex[0])
assert_equal(result.imag, ex[1])
def test_branches(self):
with np.errstate(all="ignore"):
for t in [np.complex64, np.complex128]:
# tupled (numerator, denominator, expected)
# for testing as expected == numerator/denominator
data = list()
# trigger branch: real(fabs(denom)) > imag(fabs(denom))
# followed by else condition as neither are == 0
data.append((( 2.0, 1.0), ( 2.0, 1.0), (1.0, 0.0)))
# trigger branch: real(fabs(denom)) > imag(fabs(denom))
# followed by if condition as both are == 0
# is performed in test_zero_division(), so this is skipped
# trigger else if branch: real(fabs(denom)) < imag(fabs(denom))
data.append((( 1.0, 2.0), ( 1.0, 2.0), (1.0, 0.0)))
for cases in data:
n = cases[0]
d = cases[1]
ex = cases[2]
result = t(complex(n[0], n[1])) / t(complex(d[0], d[1]))
# check real and imag parts separately to avoid comparison
# in array context, which does not account for signed zeros
assert_equal(result.real, ex[0])
assert_equal(result.imag, ex[1])
class TestConversion:
def test_int_from_long(self):
l = [1e6, 1e12, 1e18, -1e6, -1e12, -1e18]
li = [10**6, 10**12, 10**18, -10**6, -10**12, -10**18]
for T in [None, np.float64, np.int64]:
a = np.array(l, dtype=T)
assert_equal([int(_m) for _m in a], li)
a = np.array(l[:3], dtype=np.uint64)
assert_equal([int(_m) for _m in a], li[:3])
def test_iinfo_long_values(self):
for code in 'bBhH':
res = np.array(np.iinfo(code).max + 1, dtype=code)
tgt = np.iinfo(code).min
assert_(res == tgt)
for code in np.typecodes['AllInteger']:
res = np.array(np.iinfo(code).max, dtype=code)
tgt = np.iinfo(code).max
assert_(res == tgt)
for code in np.typecodes['AllInteger']:
res = np.typeDict[code](np.iinfo(code).max)
tgt = np.iinfo(code).max
assert_(res == tgt)
def test_int_raise_behaviour(self):
def overflow_error_func(dtype):
np.typeDict[dtype](np.iinfo(dtype).max + 1)
for code in 'lLqQ':
assert_raises(OverflowError, overflow_error_func, code)
def test_int_from_infinite_longdouble(self):
# gh-627
x = np.longdouble(np.inf)
assert_raises(OverflowError, int, x)
with suppress_warnings() as sup:
sup.record(np.ComplexWarning)
x = np.clongdouble(np.inf)
assert_raises(OverflowError, int, x)
assert_equal(len(sup.log), 1)
@pytest.mark.skipif(not IS_PYPY, reason="Test is PyPy only (gh-9972)")
def test_int_from_infinite_longdouble___int__(self):
x = np.longdouble(np.inf)
assert_raises(OverflowError, x.__int__)
with suppress_warnings() as sup:
sup.record(np.ComplexWarning)
x = np.clongdouble(np.inf)
assert_raises(OverflowError, x.__int__)
assert_equal(len(sup.log), 1)
@pytest.mark.skipif(np.finfo(np.double) == np.finfo(np.longdouble),
reason="long double is same as double")
@pytest.mark.skipif(platform.machine().startswith("ppc"),
reason="IBM double double")
def test_int_from_huge_longdouble(self):
# Produce a longdouble that would overflow a double,
# use exponent that avoids bug in Darwin pow function.
exp = np.finfo(np.double).maxexp - 1
huge_ld = 2 * 1234 * np.longdouble(2) ** exp
huge_i = 2 * 1234 * 2 ** exp
assert_(huge_ld != np.inf)
assert_equal(int(huge_ld), huge_i)
def test_int_from_longdouble(self):
x = np.longdouble(1.5)
assert_equal(int(x), 1)
x = np.longdouble(-10.5)
assert_equal(int(x), -10)
def test_numpy_scalar_relational_operators(self):
# All integer
for dt1 in np.typecodes['AllInteger']:
assert_(1 > np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,))
assert_(not 1 < np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,))
for dt2 in np.typecodes['AllInteger']:
assert_(np.array(1, dtype=dt1)[()] > np.array(0, dtype=dt2)[()],
"type %s and %s failed" % (dt1, dt2))
assert_(not np.array(1, dtype=dt1)[()] < np.array(0, dtype=dt2)[()],
"type %s and %s failed" % (dt1, dt2))
#Unsigned integers
for dt1 in 'BHILQP':
assert_(-1 < np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,))
assert_(not -1 > np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,))
assert_(-1 != np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,))
#unsigned vs signed
for dt2 in 'bhilqp':
assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()],
"type %s and %s failed" % (dt1, dt2))
assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()],
"type %s and %s failed" % (dt1, dt2))
assert_(np.array(1, dtype=dt1)[()] != np.array(-1, dtype=dt2)[()],
"type %s and %s failed" % (dt1, dt2))
#Signed integers and floats
for dt1 in 'bhlqp' + np.typecodes['Float']:
assert_(1 > np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,))
assert_(not 1 < np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,))
assert_(-1 == np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,))
for dt2 in 'bhlqp' + np.typecodes['Float']:
assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()],
"type %s and %s failed" % (dt1, dt2))
assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()],
"type %s and %s failed" % (dt1, dt2))
assert_(np.array(-1, dtype=dt1)[()] == np.array(-1, dtype=dt2)[()],
"type %s and %s failed" % (dt1, dt2))
def test_scalar_comparison_to_none(self):
# Scalars should just return False and not give a warnings.
# The comparisons are flagged by pep8, ignore that.
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', FutureWarning)
assert_(not np.float32(1) == None)
assert_(not np.str_('test') == None)
# This is dubious (see below):
assert_(not np.datetime64('NaT') == None)
assert_(np.float32(1) != None)
assert_(np.str_('test') != None)
# This is dubious (see below):
assert_(np.datetime64('NaT') != None)
assert_(len(w) == 0)
# For documentation purposes, this is why the datetime is dubious.
# At the time of deprecation this was no behaviour change, but
# it has to be considered when the deprecations are done.
assert_(np.equal(np.datetime64('NaT'), None))
#class TestRepr:
# def test_repr(self):
# for t in types:
# val = t(1197346475.0137341)
# val_repr = repr(val)
# val2 = eval(val_repr)
# assert_equal( val, val2 )
class TestRepr:
def _test_type_repr(self, t):
finfo = np.finfo(t)
last_fraction_bit_idx = finfo.nexp + finfo.nmant
last_exponent_bit_idx = finfo.nexp
storage_bytes = np.dtype(t).itemsize*8
# could add some more types to the list below
for which in ['small denorm', 'small norm']:
# Values from https://en.wikipedia.org/wiki/IEEE_754
constr = np.array([0x00]*storage_bytes, dtype=np.uint8)
if which == 'small denorm':
byte = last_fraction_bit_idx // 8
bytebit = 7-(last_fraction_bit_idx % 8)
constr[byte] = 1 << bytebit
elif which == 'small norm':
byte = last_exponent_bit_idx // 8
bytebit = 7-(last_exponent_bit_idx % 8)
constr[byte] = 1 << bytebit
else:
raise ValueError('hmm')
val = constr.view(t)[0]
val_repr = repr(val)
val2 = t(eval(val_repr))
if not (val2 == 0 and val < 1e-100):
assert_equal(val, val2)
def test_float_repr(self):
# long double test cannot work, because eval goes through a python
# float
for t in [np.float32, np.float64]:
self._test_type_repr(t)
if not IS_PYPY:
# sys.getsizeof() is not valid on PyPy
class TestSizeOf:
def test_equal_nbytes(self):
for type in types:
x = type(0)
assert_(sys.getsizeof(x) > x.nbytes)
def test_error(self):
d = np.float32()
assert_raises(TypeError, d.__sizeof__, "a")
class TestMultiply:
def test_seq_repeat(self):
# Test that basic sequences get repeated when multiplied with
# numpy integers. And errors are raised when multiplied with others.
# Some of this behaviour may be controversial and could be open for
# change.
accepted_types = set(np.typecodes["AllInteger"])
deprecated_types = {'?'}
forbidden_types = (
set(np.typecodes["All"]) - accepted_types - deprecated_types)
forbidden_types -= {'V'} # can't default-construct void scalars
for seq_type in (list, tuple):
seq = seq_type([1, 2, 3])
for numpy_type in accepted_types:
i = np.dtype(numpy_type).type(2)
assert_equal(seq * i, seq * int(i))
assert_equal(i * seq, int(i) * seq)
for numpy_type in deprecated_types:
i = np.dtype(numpy_type).type()
assert_equal(
assert_warns(DeprecationWarning, operator.mul, seq, i),
seq * int(i))
assert_equal(
assert_warns(DeprecationWarning, operator.mul, i, seq),
int(i) * seq)
for numpy_type in forbidden_types:
i = np.dtype(numpy_type).type()
assert_raises(TypeError, operator.mul, seq, i)
assert_raises(TypeError, operator.mul, i, seq)
def test_no_seq_repeat_basic_array_like(self):
# Test that an array-like which does not know how to be multiplied
# does not attempt sequence repeat (raise TypeError).
# See also gh-7428.
class ArrayLike:
def __init__(self, arr):
self.arr = arr
def __array__(self):
return self.arr
# Test for simple ArrayLike above and memoryviews (original report)
for arr_like in (ArrayLike(np.ones(3)), memoryview(np.ones(3))):
assert_array_equal(arr_like * np.float32(3.), np.full(3, 3.))
assert_array_equal(np.float32(3.) * arr_like, np.full(3, 3.))
assert_array_equal(arr_like * np.int_(3), np.full(3, 3))
assert_array_equal(np.int_(3) * arr_like, np.full(3, 3))
class TestNegative:
def test_exceptions(self):
a = np.ones((), dtype=np.bool_)[()]
assert_raises(TypeError, operator.neg, a)
def test_result(self):
types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
with suppress_warnings() as sup:
sup.filter(RuntimeWarning)
for dt in types:
a = np.ones((), dtype=dt)[()]
assert_equal(operator.neg(a) + a, 0)
class TestSubtract:
def test_exceptions(self):
a = np.ones((), dtype=np.bool_)[()]
assert_raises(TypeError, operator.sub, a, a)
def test_result(self):
types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
with suppress_warnings() as sup:
sup.filter(RuntimeWarning)
for dt in types:
a = np.ones((), dtype=dt)[()]
assert_equal(operator.sub(a, a), 0)
class TestAbs:
def _test_abs_func(self, absfunc):
for tp in floating_types + complex_floating_types:
x = tp(-1.5)
assert_equal(absfunc(x), 1.5)
x = tp(0.0)
res = absfunc(x)
# assert_equal() checks zero signedness
assert_equal(res, 0.0)
x = tp(-0.0)
res = absfunc(x)
assert_equal(res, 0.0)
x = tp(np.finfo(tp).max)
assert_equal(absfunc(x), x.real)
x = tp(np.finfo(tp).tiny)
assert_equal(absfunc(x), x.real)
x = tp(np.finfo(tp).min)
assert_equal(absfunc(x), -x.real)
def test_builtin_abs(self):
self._test_abs_func(abs)
def test_numpy_abs(self):
self._test_abs_func(np.abs)
class TestBitShifts:
@pytest.mark.parametrize('type_code', np.typecodes['AllInteger'])
@pytest.mark.parametrize('op',
[operator.rshift, operator.lshift], ids=['>>', '<<'])
def test_shift_all_bits(self, type_code, op):
""" Shifts where the shift amount is the width of the type or wider """
# gh-2449
dt = np.dtype(type_code)
nbits = dt.itemsize * 8
for val in [5, -5]:
for shift in [nbits, nbits + 4]:
val_scl = dt.type(val)
shift_scl = dt.type(shift)
res_scl = op(val_scl, shift_scl)
if val_scl < 0 and op is operator.rshift:
# sign bit is preserved
assert_equal(res_scl, -1)
else:
assert_equal(res_scl, 0)
# Result on scalars should be the same as on arrays
val_arr = np.array([val]*32, dtype=dt)
shift_arr = np.array([shift]*32, dtype=dt)
res_arr = op(val_arr, shift_arr)
assert_equal(res_arr, res_scl)

View file

@ -0,0 +1,322 @@
# -*- coding: utf-8 -*-
""" Test printing of scalar types.
"""
import code
import platform
import pytest
import sys
from tempfile import TemporaryFile
import numpy as np
from numpy.testing import assert_, assert_equal
class TestRealScalars:
def test_str(self):
svals = [0.0, -0.0, 1, -1, np.inf, -np.inf, np.nan]
styps = [np.float16, np.float32, np.float64, np.longdouble]
wanted = [
['0.0', '0.0', '0.0', '0.0' ],
['-0.0', '-0.0', '-0.0', '-0.0'],
['1.0', '1.0', '1.0', '1.0' ],
['-1.0', '-1.0', '-1.0', '-1.0'],
['inf', 'inf', 'inf', 'inf' ],
['-inf', '-inf', '-inf', '-inf'],
['nan', 'nan', 'nan', 'nan']]
for wants, val in zip(wanted, svals):
for want, styp in zip(wants, styps):
msg = 'for str({}({}))'.format(np.dtype(styp).name, repr(val))
assert_equal(str(styp(val)), want, err_msg=msg)
def test_scalar_cutoffs(self):
# test that both the str and repr of np.float64 behaves
# like python floats in python3.
def check(v):
assert_equal(str(np.float64(v)), str(v))
assert_equal(str(np.float64(v)), repr(v))
assert_equal(repr(np.float64(v)), repr(v))
assert_equal(repr(np.float64(v)), str(v))
# check we use the same number of significant digits
check(1.12345678901234567890)
check(0.0112345678901234567890)
# check switch from scientific output to positional and back
check(1e-5)
check(1e-4)
check(1e15)
check(1e16)
def test_py2_float_print(self):
# gh-10753
# In python2, the python float type implements an obsolete method
# tp_print, which overrides tp_repr and tp_str when using "print" to
# output to a "real file" (ie, not a StringIO). Make sure we don't
# inherit it.
x = np.double(0.1999999999999)
with TemporaryFile('r+t') as f:
print(x, file=f)
f.seek(0)
output = f.read()
assert_equal(output, str(x) + '\n')
# In python2 the value float('0.1999999999999') prints with reduced
# precision as '0.2', but we want numpy's np.double('0.1999999999999')
# to print the unique value, '0.1999999999999'.
# gh-11031
# Only in the python2 interactive shell and when stdout is a "real"
# file, the output of the last command is printed to stdout without
# Py_PRINT_RAW (unlike the print statement) so `>>> x` and `>>> print
# x` are potentially different. Make sure they are the same. The only
# way I found to get prompt-like output is using an actual prompt from
# the 'code' module. Again, must use tempfile to get a "real" file.
# dummy user-input which enters one line and then ctrl-Ds.
def userinput():
yield 'np.sqrt(2)'
raise EOFError
gen = userinput()
input_func = lambda prompt="": next(gen)
with TemporaryFile('r+t') as fo, TemporaryFile('r+t') as fe:
orig_stdout, orig_stderr = sys.stdout, sys.stderr
sys.stdout, sys.stderr = fo, fe
code.interact(local={'np': np}, readfunc=input_func, banner='')
sys.stdout, sys.stderr = orig_stdout, orig_stderr
fo.seek(0)
capture = fo.read().strip()
assert_equal(capture, repr(np.sqrt(2)))
def test_dragon4(self):
# these tests are adapted from Ryan Juckett's dragon4 implementation,
# see dragon4.c for details.
fpos32 = lambda x, **k: np.format_float_positional(np.float32(x), **k)
fsci32 = lambda x, **k: np.format_float_scientific(np.float32(x), **k)
fpos64 = lambda x, **k: np.format_float_positional(np.float64(x), **k)
fsci64 = lambda x, **k: np.format_float_scientific(np.float64(x), **k)
preckwd = lambda prec: {'unique': False, 'precision': prec}
assert_equal(fpos32('1.0'), "1.")
assert_equal(fsci32('1.0'), "1.e+00")
assert_equal(fpos32('10.234'), "10.234")
assert_equal(fpos32('-10.234'), "-10.234")
assert_equal(fsci32('10.234'), "1.0234e+01")
assert_equal(fsci32('-10.234'), "-1.0234e+01")
assert_equal(fpos32('1000.0'), "1000.")
assert_equal(fpos32('1.0', precision=0), "1.")
assert_equal(fsci32('1.0', precision=0), "1.e+00")
assert_equal(fpos32('10.234', precision=0), "10.")
assert_equal(fpos32('-10.234', precision=0), "-10.")
assert_equal(fsci32('10.234', precision=0), "1.e+01")
assert_equal(fsci32('-10.234', precision=0), "-1.e+01")
assert_equal(fpos32('10.234', precision=2), "10.23")
assert_equal(fsci32('-10.234', precision=2), "-1.02e+01")
assert_equal(fsci64('9.9999999999999995e-08', **preckwd(16)),
'9.9999999999999995e-08')
assert_equal(fsci64('9.8813129168249309e-324', **preckwd(16)),
'9.8813129168249309e-324')
assert_equal(fsci64('9.9999999999999694e-311', **preckwd(16)),
'9.9999999999999694e-311')
# test rounding
# 3.1415927410 is closest float32 to np.pi
assert_equal(fpos32('3.14159265358979323846', **preckwd(10)),
"3.1415927410")
assert_equal(fsci32('3.14159265358979323846', **preckwd(10)),
"3.1415927410e+00")
assert_equal(fpos64('3.14159265358979323846', **preckwd(10)),
"3.1415926536")
assert_equal(fsci64('3.14159265358979323846', **preckwd(10)),
"3.1415926536e+00")
# 299792448 is closest float32 to 299792458
assert_equal(fpos32('299792458.0', **preckwd(5)), "299792448.00000")
assert_equal(fsci32('299792458.0', **preckwd(5)), "2.99792e+08")
assert_equal(fpos64('299792458.0', **preckwd(5)), "299792458.00000")
assert_equal(fsci64('299792458.0', **preckwd(5)), "2.99792e+08")
assert_equal(fpos32('3.14159265358979323846', **preckwd(25)),
"3.1415927410125732421875000")
assert_equal(fpos64('3.14159265358979323846', **preckwd(50)),
"3.14159265358979311599796346854418516159057617187500")
assert_equal(fpos64('3.14159265358979323846'), "3.141592653589793")
# smallest numbers
assert_equal(fpos32(0.5**(126 + 23), unique=False, precision=149),
"0.00000000000000000000000000000000000000000000140129846432"
"4817070923729583289916131280261941876515771757068283889791"
"08268586060148663818836212158203125")
assert_equal(fpos64(0.5**(1022 + 52), unique=False, precision=1074),
"0.00000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000049406564584124654417656"
"8792868221372365059802614324764425585682500675507270208751"
"8652998363616359923797965646954457177309266567103559397963"
"9877479601078187812630071319031140452784581716784898210368"
"8718636056998730723050006387409153564984387312473397273169"
"6151400317153853980741262385655911710266585566867681870395"
"6031062493194527159149245532930545654440112748012970999954"
"1931989409080416563324524757147869014726780159355238611550"
"1348035264934720193790268107107491703332226844753335720832"
"4319360923828934583680601060115061698097530783422773183292"
"4790498252473077637592724787465608477820373446969953364701"
"7972677717585125660551199131504891101451037862738167250955"
"8373897335989936648099411642057026370902792427675445652290"
"87538682506419718265533447265625")
# largest numbers
assert_equal(fpos32(np.finfo(np.float32).max, **preckwd(0)),
"340282346638528859811704183484516925440.")
assert_equal(fpos64(np.finfo(np.float64).max, **preckwd(0)),
"1797693134862315708145274237317043567980705675258449965989"
"1747680315726078002853876058955863276687817154045895351438"
"2464234321326889464182768467546703537516986049910576551282"
"0762454900903893289440758685084551339423045832369032229481"
"6580855933212334827479782620414472316873817718091929988125"
"0404026184124858368.")
# Warning: In unique mode only the integer digits necessary for
# uniqueness are computed, the rest are 0. Should we change this?
assert_equal(fpos32(np.finfo(np.float32).max, precision=0),
"340282350000000000000000000000000000000.")
# test trailing zeros
assert_equal(fpos32('1.0', unique=False, precision=3), "1.000")
assert_equal(fpos64('1.0', unique=False, precision=3), "1.000")
assert_equal(fsci32('1.0', unique=False, precision=3), "1.000e+00")
assert_equal(fsci64('1.0', unique=False, precision=3), "1.000e+00")
assert_equal(fpos32('1.5', unique=False, precision=3), "1.500")
assert_equal(fpos64('1.5', unique=False, precision=3), "1.500")
assert_equal(fsci32('1.5', unique=False, precision=3), "1.500e+00")
assert_equal(fsci64('1.5', unique=False, precision=3), "1.500e+00")
# gh-10713
assert_equal(fpos64('324', unique=False, precision=5, fractional=False), "324.00")
def test_dragon4_interface(self):
tps = [np.float16, np.float32, np.float64]
if hasattr(np, 'float128'):
tps.append(np.float128)
fpos = np.format_float_positional
fsci = np.format_float_scientific
for tp in tps:
# test padding
assert_equal(fpos(tp('1.0'), pad_left=4, pad_right=4), " 1. ")
assert_equal(fpos(tp('-1.0'), pad_left=4, pad_right=4), " -1. ")
assert_equal(fpos(tp('-10.2'),
pad_left=4, pad_right=4), " -10.2 ")
# test exp_digits
assert_equal(fsci(tp('1.23e1'), exp_digits=5), "1.23e+00001")
# test fixed (non-unique) mode
assert_equal(fpos(tp('1.0'), unique=False, precision=4), "1.0000")
assert_equal(fsci(tp('1.0'), unique=False, precision=4),
"1.0000e+00")
# test trimming
# trim of 'k' or '.' only affects non-unique mode, since unique
# mode will not output trailing 0s.
assert_equal(fpos(tp('1.'), unique=False, precision=4, trim='k'),
"1.0000")
assert_equal(fpos(tp('1.'), unique=False, precision=4, trim='.'),
"1.")
assert_equal(fpos(tp('1.2'), unique=False, precision=4, trim='.'),
"1.2" if tp != np.float16 else "1.2002")
assert_equal(fpos(tp('1.'), unique=False, precision=4, trim='0'),
"1.0")
assert_equal(fpos(tp('1.2'), unique=False, precision=4, trim='0'),
"1.2" if tp != np.float16 else "1.2002")
assert_equal(fpos(tp('1.'), trim='0'), "1.0")
assert_equal(fpos(tp('1.'), unique=False, precision=4, trim='-'),
"1")
assert_equal(fpos(tp('1.2'), unique=False, precision=4, trim='-'),
"1.2" if tp != np.float16 else "1.2002")
assert_equal(fpos(tp('1.'), trim='-'), "1")
@pytest.mark.skipif(not platform.machine().startswith("ppc64"),
reason="only applies to ppc float128 values")
def test_ppc64_ibm_double_double128(self):
# check that the precision decreases once we get into the subnormal
# range. Unlike float64, this starts around 1e-292 instead of 1e-308,
# which happens when the first double is normal and the second is
# subnormal.
x = np.float128('2.123123123123123123123123123123123e-286')
got = [str(x/np.float128('2e' + str(i))) for i in range(0,40)]
expected = [
"1.06156156156156156156156156156157e-286",
"1.06156156156156156156156156156158e-287",
"1.06156156156156156156156156156159e-288",
"1.0615615615615615615615615615616e-289",
"1.06156156156156156156156156156157e-290",
"1.06156156156156156156156156156156e-291",
"1.0615615615615615615615615615616e-292",
"1.0615615615615615615615615615615e-293",
"1.061561561561561561561561561562e-294",
"1.06156156156156156156156156155e-295",
"1.0615615615615615615615615616e-296",
"1.06156156156156156156156156e-297",
"1.06156156156156156156156157e-298",
"1.0615615615615615615615616e-299",
"1.06156156156156156156156e-300",
"1.06156156156156156156155e-301",
"1.0615615615615615615616e-302",
"1.061561561561561561562e-303",
"1.06156156156156156156e-304",
"1.0615615615615615618e-305",
"1.06156156156156156e-306",
"1.06156156156156157e-307",
"1.0615615615615616e-308",
"1.06156156156156e-309",
"1.06156156156157e-310",
"1.0615615615616e-311",
"1.06156156156e-312",
"1.06156156154e-313",
"1.0615615616e-314",
"1.06156156e-315",
"1.06156155e-316",
"1.061562e-317",
"1.06156e-318",
"1.06155e-319",
"1.0617e-320",
"1.06e-321",
"1.04e-322",
"1e-323",
"0.0",
"0.0"]
assert_equal(got, expected)
# Note: we follow glibc behavior, but it (or gcc) might not be right.
# In particular we can get two values that print the same but are not
# equal:
a = np.float128('2')/np.float128('3')
b = np.float128(str(a))
assert_equal(str(a), str(b))
assert_(a != b)
def float32_roundtrip(self):
# gh-9360
x = np.float32(1024 - 2**-14)
y = np.float32(1024 - 2**-13)
assert_(repr(x) != repr(y))
assert_equal(np.float32(repr(x)), x)
assert_equal(np.float32(repr(y)), y)
def float64_vs_python(self):
# gh-2643, gh-6136, gh-6908
assert_equal(repr(np.float64(0.1)), repr(0.1))
assert_(repr(np.float64(0.20000000000000004)) != repr(0.2))

View file

@ -0,0 +1,713 @@
import pytest
import numpy as np
from numpy.core import (
array, arange, atleast_1d, atleast_2d, atleast_3d, block, vstack, hstack,
newaxis, concatenate, stack
)
from numpy.core.shape_base import (_block_dispatcher, _block_setup,
_block_concatenate, _block_slicing)
from numpy.testing import (
assert_, assert_raises, assert_array_equal, assert_equal,
assert_raises_regex, assert_warns
)
class TestAtleast1d:
def test_0D_array(self):
a = array(1)
b = array(2)
res = [atleast_1d(a), atleast_1d(b)]
desired = [array([1]), array([2])]
assert_array_equal(res, desired)
def test_1D_array(self):
a = array([1, 2])
b = array([2, 3])
res = [atleast_1d(a), atleast_1d(b)]
desired = [array([1, 2]), array([2, 3])]
assert_array_equal(res, desired)
def test_2D_array(self):
a = array([[1, 2], [1, 2]])
b = array([[2, 3], [2, 3]])
res = [atleast_1d(a), atleast_1d(b)]
desired = [a, b]
assert_array_equal(res, desired)
def test_3D_array(self):
a = array([[1, 2], [1, 2]])
b = array([[2, 3], [2, 3]])
a = array([a, a])
b = array([b, b])
res = [atleast_1d(a), atleast_1d(b)]
desired = [a, b]
assert_array_equal(res, desired)
def test_r1array(self):
""" Test to make sure equivalent Travis O's r1array function
"""
assert_(atleast_1d(3).shape == (1,))
assert_(atleast_1d(3j).shape == (1,))
assert_(atleast_1d(3.0).shape == (1,))
assert_(atleast_1d([[2, 3], [4, 5]]).shape == (2, 2))
class TestAtleast2d:
def test_0D_array(self):
a = array(1)
b = array(2)
res = [atleast_2d(a), atleast_2d(b)]
desired = [array([[1]]), array([[2]])]
assert_array_equal(res, desired)
def test_1D_array(self):
a = array([1, 2])
b = array([2, 3])
res = [atleast_2d(a), atleast_2d(b)]
desired = [array([[1, 2]]), array([[2, 3]])]
assert_array_equal(res, desired)
def test_2D_array(self):
a = array([[1, 2], [1, 2]])
b = array([[2, 3], [2, 3]])
res = [atleast_2d(a), atleast_2d(b)]
desired = [a, b]
assert_array_equal(res, desired)
def test_3D_array(self):
a = array([[1, 2], [1, 2]])
b = array([[2, 3], [2, 3]])
a = array([a, a])
b = array([b, b])
res = [atleast_2d(a), atleast_2d(b)]
desired = [a, b]
assert_array_equal(res, desired)
def test_r2array(self):
""" Test to make sure equivalent Travis O's r2array function
"""
assert_(atleast_2d(3).shape == (1, 1))
assert_(atleast_2d([3j, 1]).shape == (1, 2))
assert_(atleast_2d([[[3, 1], [4, 5]], [[3, 5], [1, 2]]]).shape == (2, 2, 2))
class TestAtleast3d:
def test_0D_array(self):
a = array(1)
b = array(2)
res = [atleast_3d(a), atleast_3d(b)]
desired = [array([[[1]]]), array([[[2]]])]
assert_array_equal(res, desired)
def test_1D_array(self):
a = array([1, 2])
b = array([2, 3])
res = [atleast_3d(a), atleast_3d(b)]
desired = [array([[[1], [2]]]), array([[[2], [3]]])]
assert_array_equal(res, desired)
def test_2D_array(self):
a = array([[1, 2], [1, 2]])
b = array([[2, 3], [2, 3]])
res = [atleast_3d(a), atleast_3d(b)]
desired = [a[:,:, newaxis], b[:,:, newaxis]]
assert_array_equal(res, desired)
def test_3D_array(self):
a = array([[1, 2], [1, 2]])
b = array([[2, 3], [2, 3]])
a = array([a, a])
b = array([b, b])
res = [atleast_3d(a), atleast_3d(b)]
desired = [a, b]
assert_array_equal(res, desired)
class TestHstack:
def test_non_iterable(self):
assert_raises(TypeError, hstack, 1)
def test_empty_input(self):
assert_raises(ValueError, hstack, ())
def test_0D_array(self):
a = array(1)
b = array(2)
res = hstack([a, b])
desired = array([1, 2])
assert_array_equal(res, desired)
def test_1D_array(self):
a = array([1])
b = array([2])
res = hstack([a, b])
desired = array([1, 2])
assert_array_equal(res, desired)
def test_2D_array(self):
a = array([[1], [2]])
b = array([[1], [2]])
res = hstack([a, b])
desired = array([[1, 1], [2, 2]])
assert_array_equal(res, desired)
def test_generator(self):
with assert_warns(FutureWarning):
hstack((np.arange(3) for _ in range(2)))
with assert_warns(FutureWarning):
hstack(map(lambda x: x, np.ones((3, 2))))
class TestVstack:
def test_non_iterable(self):
assert_raises(TypeError, vstack, 1)
def test_empty_input(self):
assert_raises(ValueError, vstack, ())
def test_0D_array(self):
a = array(1)
b = array(2)
res = vstack([a, b])
desired = array([[1], [2]])
assert_array_equal(res, desired)
def test_1D_array(self):
a = array([1])
b = array([2])
res = vstack([a, b])
desired = array([[1], [2]])
assert_array_equal(res, desired)
def test_2D_array(self):
a = array([[1], [2]])
b = array([[1], [2]])
res = vstack([a, b])
desired = array([[1], [2], [1], [2]])
assert_array_equal(res, desired)
def test_2D_array2(self):
a = array([1, 2])
b = array([1, 2])
res = vstack([a, b])
desired = array([[1, 2], [1, 2]])
assert_array_equal(res, desired)
def test_generator(self):
with assert_warns(FutureWarning):
vstack((np.arange(3) for _ in range(2)))
class TestConcatenate:
def test_returns_copy(self):
a = np.eye(3)
b = np.concatenate([a])
b[0, 0] = 2
assert b[0, 0] != a[0, 0]
def test_exceptions(self):
# test axis must be in bounds
for ndim in [1, 2, 3]:
a = np.ones((1,)*ndim)
np.concatenate((a, a), axis=0) # OK
assert_raises(np.AxisError, np.concatenate, (a, a), axis=ndim)
assert_raises(np.AxisError, np.concatenate, (a, a), axis=-(ndim + 1))
# Scalars cannot be concatenated
assert_raises(ValueError, concatenate, (0,))
assert_raises(ValueError, concatenate, (np.array(0),))
# dimensionality must match
assert_raises_regex(
ValueError,
r"all the input arrays must have same number of dimensions, but "
r"the array at index 0 has 1 dimension\(s\) and the array at "
r"index 1 has 2 dimension\(s\)",
np.concatenate, (np.zeros(1), np.zeros((1, 1))))
# test shapes must match except for concatenation axis
a = np.ones((1, 2, 3))
b = np.ones((2, 2, 3))
axis = list(range(3))
for i in range(3):
np.concatenate((a, b), axis=axis[0]) # OK
assert_raises_regex(
ValueError,
"all the input array dimensions for the concatenation axis "
"must match exactly, but along dimension {}, the array at "
"index 0 has size 1 and the array at index 1 has size 2"
.format(i),
np.concatenate, (a, b), axis=axis[1])
assert_raises(ValueError, np.concatenate, (a, b), axis=axis[2])
a = np.moveaxis(a, -1, 0)
b = np.moveaxis(b, -1, 0)
axis.append(axis.pop(0))
# No arrays to concatenate raises ValueError
assert_raises(ValueError, concatenate, ())
def test_concatenate_axis_None(self):
a = np.arange(4, dtype=np.float64).reshape((2, 2))
b = list(range(3))
c = ['x']
r = np.concatenate((a, a), axis=None)
assert_equal(r.dtype, a.dtype)
assert_equal(r.ndim, 1)
r = np.concatenate((a, b), axis=None)
assert_equal(r.size, a.size + len(b))
assert_equal(r.dtype, a.dtype)
r = np.concatenate((a, b, c), axis=None)
d = array(['0.0', '1.0', '2.0', '3.0',
'0', '1', '2', 'x'])
assert_array_equal(r, d)
out = np.zeros(a.size + len(b))
r = np.concatenate((a, b), axis=None)
rout = np.concatenate((a, b), axis=None, out=out)
assert_(out is rout)
assert_equal(r, rout)
def test_large_concatenate_axis_None(self):
# When no axis is given, concatenate uses flattened versions.
# This also had a bug with many arrays (see gh-5979).
x = np.arange(1, 100)
r = np.concatenate(x, None)
assert_array_equal(x, r)
# This should probably be deprecated:
r = np.concatenate(x, 100) # axis is >= MAXDIMS
assert_array_equal(x, r)
def test_concatenate(self):
# Test concatenate function
# One sequence returns unmodified (but as array)
r4 = list(range(4))
assert_array_equal(concatenate((r4,)), r4)
# Any sequence
assert_array_equal(concatenate((tuple(r4),)), r4)
assert_array_equal(concatenate((array(r4),)), r4)
# 1D default concatenation
r3 = list(range(3))
assert_array_equal(concatenate((r4, r3)), r4 + r3)
# Mixed sequence types
assert_array_equal(concatenate((tuple(r4), r3)), r4 + r3)
assert_array_equal(concatenate((array(r4), r3)), r4 + r3)
# Explicit axis specification
assert_array_equal(concatenate((r4, r3), 0), r4 + r3)
# Including negative
assert_array_equal(concatenate((r4, r3), -1), r4 + r3)
# 2D
a23 = array([[10, 11, 12], [13, 14, 15]])
a13 = array([[0, 1, 2]])
res = array([[10, 11, 12], [13, 14, 15], [0, 1, 2]])
assert_array_equal(concatenate((a23, a13)), res)
assert_array_equal(concatenate((a23, a13), 0), res)
assert_array_equal(concatenate((a23.T, a13.T), 1), res.T)
assert_array_equal(concatenate((a23.T, a13.T), -1), res.T)
# Arrays much match shape
assert_raises(ValueError, concatenate, (a23.T, a13.T), 0)
# 3D
res = arange(2 * 3 * 7).reshape((2, 3, 7))
a0 = res[..., :4]
a1 = res[..., 4:6]
a2 = res[..., 6:]
assert_array_equal(concatenate((a0, a1, a2), 2), res)
assert_array_equal(concatenate((a0, a1, a2), -1), res)
assert_array_equal(concatenate((a0.T, a1.T, a2.T), 0), res.T)
out = res.copy()
rout = concatenate((a0, a1, a2), 2, out=out)
assert_(out is rout)
assert_equal(res, rout)
def test_bad_out_shape(self):
a = array([1, 2])
b = array([3, 4])
assert_raises(ValueError, concatenate, (a, b), out=np.empty(5))
assert_raises(ValueError, concatenate, (a, b), out=np.empty((4,1)))
assert_raises(ValueError, concatenate, (a, b), out=np.empty((1,4)))
concatenate((a, b), out=np.empty(4))
def test_out_dtype(self):
out = np.empty(4, np.float32)
res = concatenate((array([1, 2]), array([3, 4])), out=out)
assert_(out is res)
out = np.empty(4, np.complex64)
res = concatenate((array([0.1, 0.2]), array([0.3, 0.4])), out=out)
assert_(out is res)
# invalid cast
out = np.empty(4, np.int32)
assert_raises(TypeError, concatenate,
(array([0.1, 0.2]), array([0.3, 0.4])), out=out)
def test_stack():
# non-iterable input
assert_raises(TypeError, stack, 1)
# 0d input
for input_ in [(1, 2, 3),
[np.int32(1), np.int32(2), np.int32(3)],
[np.array(1), np.array(2), np.array(3)]]:
assert_array_equal(stack(input_), [1, 2, 3])
# 1d input examples
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
r1 = array([[1, 2, 3], [4, 5, 6]])
assert_array_equal(np.stack((a, b)), r1)
assert_array_equal(np.stack((a, b), axis=1), r1.T)
# all input types
assert_array_equal(np.stack(list([a, b])), r1)
assert_array_equal(np.stack(array([a, b])), r1)
# all shapes for 1d input
arrays = [np.random.randn(3) for _ in range(10)]
axes = [0, 1, -1, -2]
expected_shapes = [(10, 3), (3, 10), (3, 10), (10, 3)]
for axis, expected_shape in zip(axes, expected_shapes):
assert_equal(np.stack(arrays, axis).shape, expected_shape)
assert_raises_regex(np.AxisError, 'out of bounds', stack, arrays, axis=2)
assert_raises_regex(np.AxisError, 'out of bounds', stack, arrays, axis=-3)
# all shapes for 2d input
arrays = [np.random.randn(3, 4) for _ in range(10)]
axes = [0, 1, 2, -1, -2, -3]
expected_shapes = [(10, 3, 4), (3, 10, 4), (3, 4, 10),
(3, 4, 10), (3, 10, 4), (10, 3, 4)]
for axis, expected_shape in zip(axes, expected_shapes):
assert_equal(np.stack(arrays, axis).shape, expected_shape)
# empty arrays
assert_(stack([[], [], []]).shape == (3, 0))
assert_(stack([[], [], []], axis=1).shape == (0, 3))
# out
out = np.zeros_like(r1)
np.stack((a, b), out=out)
assert_array_equal(out, r1)
# edge cases
assert_raises_regex(ValueError, 'need at least one array', stack, [])
assert_raises_regex(ValueError, 'must have the same shape',
stack, [1, np.arange(3)])
assert_raises_regex(ValueError, 'must have the same shape',
stack, [np.arange(3), 1])
assert_raises_regex(ValueError, 'must have the same shape',
stack, [np.arange(3), 1], axis=1)
assert_raises_regex(ValueError, 'must have the same shape',
stack, [np.zeros((3, 3)), np.zeros(3)], axis=1)
assert_raises_regex(ValueError, 'must have the same shape',
stack, [np.arange(2), np.arange(3)])
# generator is deprecated
with assert_warns(FutureWarning):
result = stack((x for x in range(3)))
assert_array_equal(result, np.array([0, 1, 2]))
class TestBlock:
@pytest.fixture(params=['block', 'force_concatenate', 'force_slicing'])
def block(self, request):
# blocking small arrays and large arrays go through different paths.
# the algorithm is triggered depending on the number of element
# copies required.
# We define a test fixture that forces most tests to go through
# both code paths.
# Ultimately, this should be removed if a single algorithm is found
# to be faster for both small and large arrays.
def _block_force_concatenate(arrays):
arrays, list_ndim, result_ndim, _ = _block_setup(arrays)
return _block_concatenate(arrays, list_ndim, result_ndim)
def _block_force_slicing(arrays):
arrays, list_ndim, result_ndim, _ = _block_setup(arrays)
return _block_slicing(arrays, list_ndim, result_ndim)
if request.param == 'force_concatenate':
return _block_force_concatenate
elif request.param == 'force_slicing':
return _block_force_slicing
elif request.param == 'block':
return block
else:
raise ValueError('Unknown blocking request. There is a typo in the tests.')
def test_returns_copy(self, block):
a = np.eye(3)
b = block(a)
b[0, 0] = 2
assert b[0, 0] != a[0, 0]
def test_block_total_size_estimate(self, block):
_, _, _, total_size = _block_setup([1])
assert total_size == 1
_, _, _, total_size = _block_setup([[1]])
assert total_size == 1
_, _, _, total_size = _block_setup([[1, 1]])
assert total_size == 2
_, _, _, total_size = _block_setup([[1], [1]])
assert total_size == 2
_, _, _, total_size = _block_setup([[1, 2], [3, 4]])
assert total_size == 4
def test_block_simple_row_wise(self, block):
a_2d = np.ones((2, 2))
b_2d = 2 * a_2d
desired = np.array([[1, 1, 2, 2],
[1, 1, 2, 2]])
result = block([a_2d, b_2d])
assert_equal(desired, result)
def test_block_simple_column_wise(self, block):
a_2d = np.ones((2, 2))
b_2d = 2 * a_2d
expected = np.array([[1, 1],
[1, 1],
[2, 2],
[2, 2]])
result = block([[a_2d], [b_2d]])
assert_equal(expected, result)
def test_block_with_1d_arrays_row_wise(self, block):
# # # 1-D vectors are treated as row arrays
a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
expected = np.array([1, 2, 3, 2, 3, 4])
result = block([a, b])
assert_equal(expected, result)
def test_block_with_1d_arrays_multiple_rows(self, block):
a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
expected = np.array([[1, 2, 3, 2, 3, 4],
[1, 2, 3, 2, 3, 4]])
result = block([[a, b], [a, b]])
assert_equal(expected, result)
def test_block_with_1d_arrays_column_wise(self, block):
# # # 1-D vectors are treated as row arrays
a_1d = np.array([1, 2, 3])
b_1d = np.array([2, 3, 4])
expected = np.array([[1, 2, 3],
[2, 3, 4]])
result = block([[a_1d], [b_1d]])
assert_equal(expected, result)
def test_block_mixed_1d_and_2d(self, block):
a_2d = np.ones((2, 2))
b_1d = np.array([2, 2])
result = block([[a_2d], [b_1d]])
expected = np.array([[1, 1],
[1, 1],
[2, 2]])
assert_equal(expected, result)
def test_block_complicated(self, block):
# a bit more complicated
one_2d = np.array([[1, 1, 1]])
two_2d = np.array([[2, 2, 2]])
three_2d = np.array([[3, 3, 3, 3, 3, 3]])
four_1d = np.array([4, 4, 4, 4, 4, 4])
five_0d = np.array(5)
six_1d = np.array([6, 6, 6, 6, 6])
zero_2d = np.zeros((2, 6))
expected = np.array([[1, 1, 1, 2, 2, 2],
[3, 3, 3, 3, 3, 3],
[4, 4, 4, 4, 4, 4],
[5, 6, 6, 6, 6, 6],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
result = block([[one_2d, two_2d],
[three_2d],
[four_1d],
[five_0d, six_1d],
[zero_2d]])
assert_equal(result, expected)
def test_nested(self, block):
one = np.array([1, 1, 1])
two = np.array([[2, 2, 2], [2, 2, 2], [2, 2, 2]])
three = np.array([3, 3, 3])
four = np.array([4, 4, 4])
five = np.array(5)
six = np.array([6, 6, 6, 6, 6])
zero = np.zeros((2, 6))
result = block([
[
block([
[one],
[three],
[four]
]),
two
],
[five, six],
[zero]
])
expected = np.array([[1, 1, 1, 2, 2, 2],
[3, 3, 3, 2, 2, 2],
[4, 4, 4, 2, 2, 2],
[5, 6, 6, 6, 6, 6],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
assert_equal(result, expected)
def test_3d(self, block):
a000 = np.ones((2, 2, 2), int) * 1
a100 = np.ones((3, 2, 2), int) * 2
a010 = np.ones((2, 3, 2), int) * 3
a001 = np.ones((2, 2, 3), int) * 4
a011 = np.ones((2, 3, 3), int) * 5
a101 = np.ones((3, 2, 3), int) * 6
a110 = np.ones((3, 3, 2), int) * 7
a111 = np.ones((3, 3, 3), int) * 8
result = block([
[
[a000, a001],
[a010, a011],
],
[
[a100, a101],
[a110, a111],
]
])
expected = array([[[1, 1, 4, 4, 4],
[1, 1, 4, 4, 4],
[3, 3, 5, 5, 5],
[3, 3, 5, 5, 5],
[3, 3, 5, 5, 5]],
[[1, 1, 4, 4, 4],
[1, 1, 4, 4, 4],
[3, 3, 5, 5, 5],
[3, 3, 5, 5, 5],
[3, 3, 5, 5, 5]],
[[2, 2, 6, 6, 6],
[2, 2, 6, 6, 6],
[7, 7, 8, 8, 8],
[7, 7, 8, 8, 8],
[7, 7, 8, 8, 8]],
[[2, 2, 6, 6, 6],
[2, 2, 6, 6, 6],
[7, 7, 8, 8, 8],
[7, 7, 8, 8, 8],
[7, 7, 8, 8, 8]],
[[2, 2, 6, 6, 6],
[2, 2, 6, 6, 6],
[7, 7, 8, 8, 8],
[7, 7, 8, 8, 8],
[7, 7, 8, 8, 8]]])
assert_array_equal(result, expected)
def test_block_with_mismatched_shape(self, block):
a = np.array([0, 0])
b = np.eye(2)
assert_raises(ValueError, block, [a, b])
assert_raises(ValueError, block, [b, a])
to_block = [[np.ones((2,3)), np.ones((2,2))],
[np.ones((2,2)), np.ones((2,2))]]
assert_raises(ValueError, block, to_block)
def test_no_lists(self, block):
assert_equal(block(1), np.array(1))
assert_equal(block(np.eye(3)), np.eye(3))
def test_invalid_nesting(self, block):
msg = 'depths are mismatched'
assert_raises_regex(ValueError, msg, block, [1, [2]])
assert_raises_regex(ValueError, msg, block, [1, []])
assert_raises_regex(ValueError, msg, block, [[1], 2])
assert_raises_regex(ValueError, msg, block, [[], 2])
assert_raises_regex(ValueError, msg, block, [
[[1], [2]],
[[3, 4]],
[5] # missing brackets
])
def test_empty_lists(self, block):
assert_raises_regex(ValueError, 'empty', block, [])
assert_raises_regex(ValueError, 'empty', block, [[]])
assert_raises_regex(ValueError, 'empty', block, [[1], []])
def test_tuple(self, block):
assert_raises_regex(TypeError, 'tuple', block, ([1, 2], [3, 4]))
assert_raises_regex(TypeError, 'tuple', block, [(1, 2), (3, 4)])
def test_different_ndims(self, block):
a = 1.
b = 2 * np.ones((1, 2))
c = 3 * np.ones((1, 1, 3))
result = block([a, b, c])
expected = np.array([[[1., 2., 2., 3., 3., 3.]]])
assert_equal(result, expected)
def test_different_ndims_depths(self, block):
a = 1.
b = 2 * np.ones((1, 2))
c = 3 * np.ones((1, 2, 3))
result = block([[a, b], [c]])
expected = np.array([[[1., 2., 2.],
[3., 3., 3.],
[3., 3., 3.]]])
assert_equal(result, expected)
def test_block_memory_order(self, block):
# 3D
arr_c = np.zeros((3,)*3, order='C')
arr_f = np.zeros((3,)*3, order='F')
b_c = [[[arr_c, arr_c],
[arr_c, arr_c]],
[[arr_c, arr_c],
[arr_c, arr_c]]]
b_f = [[[arr_f, arr_f],
[arr_f, arr_f]],
[[arr_f, arr_f],
[arr_f, arr_f]]]
assert block(b_c).flags['C_CONTIGUOUS']
assert block(b_f).flags['F_CONTIGUOUS']
arr_c = np.zeros((3, 3), order='C')
arr_f = np.zeros((3, 3), order='F')
# 2D
b_c = [[arr_c, arr_c],
[arr_c, arr_c]]
b_f = [[arr_f, arr_f],
[arr_f, arr_f]]
assert block(b_c).flags['C_CONTIGUOUS']
assert block(b_f).flags['F_CONTIGUOUS']
def test_block_dispatcher():
class ArrayLike:
pass
a = ArrayLike()
b = ArrayLike()
c = ArrayLike()
assert_equal(list(_block_dispatcher(a)), [a])
assert_equal(list(_block_dispatcher([a])), [a])
assert_equal(list(_block_dispatcher([a, b])), [a, b])
assert_equal(list(_block_dispatcher([[a], [b, [c]]])), [a, b, c])
# don't recurse into non-lists
assert_equal(list(_block_dispatcher((a, b))), [(a, b)])

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,59 @@
import numpy as np
import platform
from os import path
import sys
import pytest
from ctypes import c_longlong, c_double, c_float, c_int, cast, pointer, POINTER
from numpy.testing import assert_array_max_ulp
from numpy.core._multiarray_umath import __cpu_features__
IS_AVX = __cpu_features__.get('AVX512F', False) or \
(__cpu_features__.get('FMA3', False) and __cpu_features__.get('AVX2', False))
runtest = sys.platform.startswith('linux') and IS_AVX
platform_skip = pytest.mark.skipif(not runtest,
reason="avoid testing inconsistent platform "
"library implementations")
# convert string to hex function taken from:
# https://stackoverflow.com/questions/1592158/convert-hex-to-float #
def convert(s, datatype="np.float32"):
i = int(s, 16) # convert from hex to a Python int
if (datatype == "np.float64"):
cp = pointer(c_longlong(i)) # make this into a c long long integer
fp = cast(cp, POINTER(c_double)) # cast the int pointer to a double pointer
else:
cp = pointer(c_int(i)) # make this into a c integer
fp = cast(cp, POINTER(c_float)) # cast the int pointer to a float pointer
return fp.contents.value # dereference the pointer, get the float
str_to_float = np.vectorize(convert)
files = ['umath-validation-set-exp',
'umath-validation-set-log',
'umath-validation-set-sin',
'umath-validation-set-cos']
class TestAccuracy:
@platform_skip
def test_validate_transcendentals(self):
with np.errstate(all='ignore'):
for filename in files:
data_dir = path.join(path.dirname(__file__), 'data')
filepath = path.join(data_dir, filename)
with open(filepath) as fid:
file_without_comments = (r for r in fid if not r[0] in ('$', '#'))
data = np.genfromtxt(file_without_comments,
dtype=('|S39','|S39','|S39',int),
names=('type','input','output','ulperr'),
delimiter=',',
skip_header=1)
npfunc = getattr(np, filename.split('-')[3])
for datatype in np.unique(data['type']):
data_subset = data[data['type'] == datatype]
inval = np.array(str_to_float(data_subset['input'].astype(str), data_subset['type'].astype(str)), dtype=eval(datatype))
outval = np.array(str_to_float(data_subset['output'].astype(str), data_subset['type'].astype(str)), dtype=eval(datatype))
perm = np.random.permutation(len(inval))
inval = inval[perm]
outval = outval[perm]
maxulperr = data_subset['ulperr'].max()
assert_array_max_ulp(npfunc(inval), outval, maxulperr)

View file

@ -0,0 +1,610 @@
import sys
import platform
import pytest
import numpy as np
# import the c-extension module directly since _arg is not exported via umath
import numpy.core._multiarray_umath as ncu
from numpy.testing import (
assert_raises, assert_equal, assert_array_equal, assert_almost_equal, assert_array_max_ulp
)
# TODO: branch cuts (use Pauli code)
# TODO: conj 'symmetry'
# TODO: FPU exceptions
# At least on Windows the results of many complex functions are not conforming
# to the C99 standard. See ticket 1574.
# Ditto for Solaris (ticket 1642) and OS X on PowerPC.
#FIXME: this will probably change when we require full C99 campatibility
with np.errstate(all='ignore'):
functions_seem_flaky = ((np.exp(complex(np.inf, 0)).imag != 0)
or (np.log(complex(np.NZERO, 0)).imag != np.pi))
# TODO: replace with a check on whether platform-provided C99 funcs are used
xfail_complex_tests = (not sys.platform.startswith('linux') or functions_seem_flaky)
# TODO This can be xfail when the generator functions are got rid of.
platform_skip = pytest.mark.skipif(xfail_complex_tests,
reason="Inadequate C99 complex support")
class TestCexp:
def test_simple(self):
check = check_complex_value
f = np.exp
check(f, 1, 0, np.exp(1), 0, False)
check(f, 0, 1, np.cos(1), np.sin(1), False)
ref = np.exp(1) * complex(np.cos(1), np.sin(1))
check(f, 1, 1, ref.real, ref.imag, False)
@platform_skip
def test_special_values(self):
# C99: Section G 6.3.1
check = check_complex_value
f = np.exp
# cexp(+-0 + 0i) is 1 + 0i
check(f, np.PZERO, 0, 1, 0, False)
check(f, np.NZERO, 0, 1, 0, False)
# cexp(x + infi) is nan + nani for finite x and raises 'invalid' FPU
# exception
check(f, 1, np.inf, np.nan, np.nan)
check(f, -1, np.inf, np.nan, np.nan)
check(f, 0, np.inf, np.nan, np.nan)
# cexp(inf + 0i) is inf + 0i
check(f, np.inf, 0, np.inf, 0)
# cexp(-inf + yi) is +0 * (cos(y) + i sin(y)) for finite y
check(f, -np.inf, 1, np.PZERO, np.PZERO)
check(f, -np.inf, 0.75 * np.pi, np.NZERO, np.PZERO)
# cexp(inf + yi) is +inf * (cos(y) + i sin(y)) for finite y
check(f, np.inf, 1, np.inf, np.inf)
check(f, np.inf, 0.75 * np.pi, -np.inf, np.inf)
# cexp(-inf + inf i) is +-0 +- 0i (signs unspecified)
def _check_ninf_inf(dummy):
msgform = "cexp(-inf, inf) is (%f, %f), expected (+-0, +-0)"
with np.errstate(invalid='ignore'):
z = f(np.array(complex(-np.inf, np.inf)))
if z.real != 0 or z.imag != 0:
raise AssertionError(msgform % (z.real, z.imag))
_check_ninf_inf(None)
# cexp(inf + inf i) is +-inf + NaNi and raised invalid FPU ex.
def _check_inf_inf(dummy):
msgform = "cexp(inf, inf) is (%f, %f), expected (+-inf, nan)"
with np.errstate(invalid='ignore'):
z = f(np.array(complex(np.inf, np.inf)))
if not np.isinf(z.real) or not np.isnan(z.imag):
raise AssertionError(msgform % (z.real, z.imag))
_check_inf_inf(None)
# cexp(-inf + nan i) is +-0 +- 0i
def _check_ninf_nan(dummy):
msgform = "cexp(-inf, nan) is (%f, %f), expected (+-0, +-0)"
with np.errstate(invalid='ignore'):
z = f(np.array(complex(-np.inf, np.nan)))
if z.real != 0 or z.imag != 0:
raise AssertionError(msgform % (z.real, z.imag))
_check_ninf_nan(None)
# cexp(inf + nan i) is +-inf + nan
def _check_inf_nan(dummy):
msgform = "cexp(-inf, nan) is (%f, %f), expected (+-inf, nan)"
with np.errstate(invalid='ignore'):
z = f(np.array(complex(np.inf, np.nan)))
if not np.isinf(z.real) or not np.isnan(z.imag):
raise AssertionError(msgform % (z.real, z.imag))
_check_inf_nan(None)
# cexp(nan + yi) is nan + nani for y != 0 (optional: raises invalid FPU
# ex)
check(f, np.nan, 1, np.nan, np.nan)
check(f, np.nan, -1, np.nan, np.nan)
check(f, np.nan, np.inf, np.nan, np.nan)
check(f, np.nan, -np.inf, np.nan, np.nan)
# cexp(nan + nani) is nan + nani
check(f, np.nan, np.nan, np.nan, np.nan)
# TODO This can be xfail when the generator functions are got rid of.
@pytest.mark.skip(reason="cexp(nan + 0I) is wrong on most platforms")
def test_special_values2(self):
# XXX: most implementations get it wrong here (including glibc <= 2.10)
# cexp(nan + 0i) is nan + 0i
check = check_complex_value
f = np.exp
check(f, np.nan, 0, np.nan, 0)
class TestClog:
def test_simple(self):
x = np.array([1+0j, 1+2j])
y_r = np.log(np.abs(x)) + 1j * np.angle(x)
y = np.log(x)
for i in range(len(x)):
assert_almost_equal(y[i], y_r[i])
@platform_skip
@pytest.mark.skipif(platform.machine() == "armv5tel", reason="See gh-413.")
def test_special_values(self):
xl = []
yl = []
# From C99 std (Sec 6.3.2)
# XXX: check exceptions raised
# --- raise for invalid fails.
# clog(-0 + i0) returns -inf + i pi and raises the 'divide-by-zero'
# floating-point exception.
with np.errstate(divide='raise'):
x = np.array([np.NZERO], dtype=complex)
y = complex(-np.inf, np.pi)
assert_raises(FloatingPointError, np.log, x)
with np.errstate(divide='ignore'):
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
# clog(+0 + i0) returns -inf + i0 and raises the 'divide-by-zero'
# floating-point exception.
with np.errstate(divide='raise'):
x = np.array([0], dtype=complex)
y = complex(-np.inf, 0)
assert_raises(FloatingPointError, np.log, x)
with np.errstate(divide='ignore'):
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
# clog(x + i inf returns +inf + i pi /2, for finite x.
x = np.array([complex(1, np.inf)], dtype=complex)
y = complex(np.inf, 0.5 * np.pi)
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
x = np.array([complex(-1, np.inf)], dtype=complex)
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
# clog(x + iNaN) returns NaN + iNaN and optionally raises the
# 'invalid' floating- point exception, for finite x.
with np.errstate(invalid='raise'):
x = np.array([complex(1., np.nan)], dtype=complex)
y = complex(np.nan, np.nan)
#assert_raises(FloatingPointError, np.log, x)
with np.errstate(invalid='ignore'):
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
with np.errstate(invalid='raise'):
x = np.array([np.inf + 1j * np.nan], dtype=complex)
#assert_raises(FloatingPointError, np.log, x)
with np.errstate(invalid='ignore'):
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
# clog(- inf + iy) returns +inf + ipi , for finite positive-signed y.
x = np.array([-np.inf + 1j], dtype=complex)
y = complex(np.inf, np.pi)
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
# clog(+ inf + iy) returns +inf + i0, for finite positive-signed y.
x = np.array([np.inf + 1j], dtype=complex)
y = complex(np.inf, 0)
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
# clog(- inf + i inf) returns +inf + i3pi /4.
x = np.array([complex(-np.inf, np.inf)], dtype=complex)
y = complex(np.inf, 0.75 * np.pi)
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
# clog(+ inf + i inf) returns +inf + ipi /4.
x = np.array([complex(np.inf, np.inf)], dtype=complex)
y = complex(np.inf, 0.25 * np.pi)
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
# clog(+/- inf + iNaN) returns +inf + iNaN.
x = np.array([complex(np.inf, np.nan)], dtype=complex)
y = complex(np.inf, np.nan)
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
x = np.array([complex(-np.inf, np.nan)], dtype=complex)
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
# clog(NaN + iy) returns NaN + iNaN and optionally raises the
# 'invalid' floating-point exception, for finite y.
x = np.array([complex(np.nan, 1)], dtype=complex)
y = complex(np.nan, np.nan)
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
# clog(NaN + i inf) returns +inf + iNaN.
x = np.array([complex(np.nan, np.inf)], dtype=complex)
y = complex(np.inf, np.nan)
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
# clog(NaN + iNaN) returns NaN + iNaN.
x = np.array([complex(np.nan, np.nan)], dtype=complex)
y = complex(np.nan, np.nan)
assert_almost_equal(np.log(x), y)
xl.append(x)
yl.append(y)
# clog(conj(z)) = conj(clog(z)).
xa = np.array(xl, dtype=complex)
ya = np.array(yl, dtype=complex)
with np.errstate(divide='ignore'):
for i in range(len(xa)):
assert_almost_equal(np.log(xa[i].conj()), ya[i].conj())
class TestCsqrt:
def test_simple(self):
# sqrt(1)
check_complex_value(np.sqrt, 1, 0, 1, 0)
# sqrt(1i)
rres = 0.5*np.sqrt(2)
ires = rres
check_complex_value(np.sqrt, 0, 1, rres, ires, False)
# sqrt(-1)
check_complex_value(np.sqrt, -1, 0, 0, 1)
def test_simple_conjugate(self):
ref = np.conj(np.sqrt(complex(1, 1)))
def f(z):
return np.sqrt(np.conj(z))
check_complex_value(f, 1, 1, ref.real, ref.imag, False)
#def test_branch_cut(self):
# _check_branch_cut(f, -1, 0, 1, -1)
@platform_skip
def test_special_values(self):
# C99: Sec G 6.4.2
check = check_complex_value
f = np.sqrt
# csqrt(+-0 + 0i) is 0 + 0i
check(f, np.PZERO, 0, 0, 0)
check(f, np.NZERO, 0, 0, 0)
# csqrt(x + infi) is inf + infi for any x (including NaN)
check(f, 1, np.inf, np.inf, np.inf)
check(f, -1, np.inf, np.inf, np.inf)
check(f, np.PZERO, np.inf, np.inf, np.inf)
check(f, np.NZERO, np.inf, np.inf, np.inf)
check(f, np.inf, np.inf, np.inf, np.inf)
check(f, -np.inf, np.inf, np.inf, np.inf)
check(f, -np.nan, np.inf, np.inf, np.inf)
# csqrt(x + nani) is nan + nani for any finite x
check(f, 1, np.nan, np.nan, np.nan)
check(f, -1, np.nan, np.nan, np.nan)
check(f, 0, np.nan, np.nan, np.nan)
# csqrt(-inf + yi) is +0 + infi for any finite y > 0
check(f, -np.inf, 1, np.PZERO, np.inf)
# csqrt(inf + yi) is +inf + 0i for any finite y > 0
check(f, np.inf, 1, np.inf, np.PZERO)
# csqrt(-inf + nani) is nan +- infi (both +i infi are valid)
def _check_ninf_nan(dummy):
msgform = "csqrt(-inf, nan) is (%f, %f), expected (nan, +-inf)"
z = np.sqrt(np.array(complex(-np.inf, np.nan)))
#Fixme: ugly workaround for isinf bug.
with np.errstate(invalid='ignore'):
if not (np.isnan(z.real) and np.isinf(z.imag)):
raise AssertionError(msgform % (z.real, z.imag))
_check_ninf_nan(None)
# csqrt(+inf + nani) is inf + nani
check(f, np.inf, np.nan, np.inf, np.nan)
# csqrt(nan + yi) is nan + nani for any finite y (infinite handled in x
# + nani)
check(f, np.nan, 0, np.nan, np.nan)
check(f, np.nan, 1, np.nan, np.nan)
check(f, np.nan, np.nan, np.nan, np.nan)
# XXX: check for conj(csqrt(z)) == csqrt(conj(z)) (need to fix branch
# cuts first)
class TestCpow:
def setup(self):
self.olderr = np.seterr(invalid='ignore')
def teardown(self):
np.seterr(**self.olderr)
def test_simple(self):
x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan])
y_r = x ** 2
y = np.power(x, 2)
for i in range(len(x)):
assert_almost_equal(y[i], y_r[i])
def test_scalar(self):
x = np.array([1, 1j, 2, 2.5+.37j, np.inf, np.nan])
y = np.array([1, 1j, -0.5+1.5j, -0.5+1.5j, 2, 3])
lx = list(range(len(x)))
# Compute the values for complex type in python
p_r = [complex(x[i]) ** complex(y[i]) for i in lx]
# Substitute a result allowed by C99 standard
p_r[4] = complex(np.inf, np.nan)
# Do the same with numpy complex scalars
n_r = [x[i] ** y[i] for i in lx]
for i in lx:
assert_almost_equal(n_r[i], p_r[i], err_msg='Loop %d\n' % i)
def test_array(self):
x = np.array([1, 1j, 2, 2.5+.37j, np.inf, np.nan])
y = np.array([1, 1j, -0.5+1.5j, -0.5+1.5j, 2, 3])
lx = list(range(len(x)))
# Compute the values for complex type in python
p_r = [complex(x[i]) ** complex(y[i]) for i in lx]
# Substitute a result allowed by C99 standard
p_r[4] = complex(np.inf, np.nan)
# Do the same with numpy arrays
n_r = x ** y
for i in lx:
assert_almost_equal(n_r[i], p_r[i], err_msg='Loop %d\n' % i)
class TestCabs:
def setup(self):
self.olderr = np.seterr(invalid='ignore')
def teardown(self):
np.seterr(**self.olderr)
def test_simple(self):
x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan])
y_r = np.array([np.sqrt(2.), 2, np.sqrt(5), np.inf, np.nan])
y = np.abs(x)
for i in range(len(x)):
assert_almost_equal(y[i], y_r[i])
def test_fabs(self):
# Test that np.abs(x +- 0j) == np.abs(x) (as mandated by C99 for cabs)
x = np.array([1+0j], dtype=complex)
assert_array_equal(np.abs(x), np.real(x))
x = np.array([complex(1, np.NZERO)], dtype=complex)
assert_array_equal(np.abs(x), np.real(x))
x = np.array([complex(np.inf, np.NZERO)], dtype=complex)
assert_array_equal(np.abs(x), np.real(x))
x = np.array([complex(np.nan, np.NZERO)], dtype=complex)
assert_array_equal(np.abs(x), np.real(x))
def test_cabs_inf_nan(self):
x, y = [], []
# cabs(+-nan + nani) returns nan
x.append(np.nan)
y.append(np.nan)
check_real_value(np.abs, np.nan, np.nan, np.nan)
x.append(np.nan)
y.append(-np.nan)
check_real_value(np.abs, -np.nan, np.nan, np.nan)
# According to C99 standard, if exactly one of the real/part is inf and
# the other nan, then cabs should return inf
x.append(np.inf)
y.append(np.nan)
check_real_value(np.abs, np.inf, np.nan, np.inf)
x.append(-np.inf)
y.append(np.nan)
check_real_value(np.abs, -np.inf, np.nan, np.inf)
# cabs(conj(z)) == conj(cabs(z)) (= cabs(z))
def f(a):
return np.abs(np.conj(a))
def g(a, b):
return np.abs(complex(a, b))
xa = np.array(x, dtype=complex)
for i in range(len(xa)):
ref = g(x[i], y[i])
check_real_value(f, x[i], y[i], ref)
class TestCarg:
def test_simple(self):
check_real_value(ncu._arg, 1, 0, 0, False)
check_real_value(ncu._arg, 0, 1, 0.5*np.pi, False)
check_real_value(ncu._arg, 1, 1, 0.25*np.pi, False)
check_real_value(ncu._arg, np.PZERO, np.PZERO, np.PZERO)
# TODO This can be xfail when the generator functions are got rid of.
@pytest.mark.skip(
reason="Complex arithmetic with signed zero fails on most platforms")
def test_zero(self):
# carg(-0 +- 0i) returns +- pi
check_real_value(ncu._arg, np.NZERO, np.PZERO, np.pi, False)
check_real_value(ncu._arg, np.NZERO, np.NZERO, -np.pi, False)
# carg(+0 +- 0i) returns +- 0
check_real_value(ncu._arg, np.PZERO, np.PZERO, np.PZERO)
check_real_value(ncu._arg, np.PZERO, np.NZERO, np.NZERO)
# carg(x +- 0i) returns +- 0 for x > 0
check_real_value(ncu._arg, 1, np.PZERO, np.PZERO, False)
check_real_value(ncu._arg, 1, np.NZERO, np.NZERO, False)
# carg(x +- 0i) returns +- pi for x < 0
check_real_value(ncu._arg, -1, np.PZERO, np.pi, False)
check_real_value(ncu._arg, -1, np.NZERO, -np.pi, False)
# carg(+- 0 + yi) returns pi/2 for y > 0
check_real_value(ncu._arg, np.PZERO, 1, 0.5 * np.pi, False)
check_real_value(ncu._arg, np.NZERO, 1, 0.5 * np.pi, False)
# carg(+- 0 + yi) returns -pi/2 for y < 0
check_real_value(ncu._arg, np.PZERO, -1, 0.5 * np.pi, False)
check_real_value(ncu._arg, np.NZERO, -1, -0.5 * np.pi, False)
#def test_branch_cuts(self):
# _check_branch_cut(ncu._arg, -1, 1j, -1, 1)
def test_special_values(self):
# carg(-np.inf +- yi) returns +-pi for finite y > 0
check_real_value(ncu._arg, -np.inf, 1, np.pi, False)
check_real_value(ncu._arg, -np.inf, -1, -np.pi, False)
# carg(np.inf +- yi) returns +-0 for finite y > 0
check_real_value(ncu._arg, np.inf, 1, np.PZERO, False)
check_real_value(ncu._arg, np.inf, -1, np.NZERO, False)
# carg(x +- np.infi) returns +-pi/2 for finite x
check_real_value(ncu._arg, 1, np.inf, 0.5 * np.pi, False)
check_real_value(ncu._arg, 1, -np.inf, -0.5 * np.pi, False)
# carg(-np.inf +- np.infi) returns +-3pi/4
check_real_value(ncu._arg, -np.inf, np.inf, 0.75 * np.pi, False)
check_real_value(ncu._arg, -np.inf, -np.inf, -0.75 * np.pi, False)
# carg(np.inf +- np.infi) returns +-pi/4
check_real_value(ncu._arg, np.inf, np.inf, 0.25 * np.pi, False)
check_real_value(ncu._arg, np.inf, -np.inf, -0.25 * np.pi, False)
# carg(x + yi) returns np.nan if x or y is nan
check_real_value(ncu._arg, np.nan, 0, np.nan, False)
check_real_value(ncu._arg, 0, np.nan, np.nan, False)
check_real_value(ncu._arg, np.nan, np.inf, np.nan, False)
check_real_value(ncu._arg, np.inf, np.nan, np.nan, False)
def check_real_value(f, x1, y1, x, exact=True):
z1 = np.array([complex(x1, y1)])
if exact:
assert_equal(f(z1), x)
else:
assert_almost_equal(f(z1), x)
def check_complex_value(f, x1, y1, x2, y2, exact=True):
z1 = np.array([complex(x1, y1)])
z2 = complex(x2, y2)
with np.errstate(invalid='ignore'):
if exact:
assert_equal(f(z1), z2)
else:
assert_almost_equal(f(z1), z2)
class TestSpecialComplexAVX(object):
@pytest.mark.parametrize("stride", [-4,-2,-1,1,2,4])
@pytest.mark.parametrize("astype", [np.complex64, np.complex128])
def test_array(self, stride, astype):
arr = np.array([np.complex(np.nan , np.nan),
np.complex(np.nan , np.inf),
np.complex(np.inf , np.nan),
np.complex(np.inf , np.inf),
np.complex(0. , np.inf),
np.complex(np.inf , 0.),
np.complex(0. , 0.),
np.complex(0. , np.nan),
np.complex(np.nan , 0.)], dtype=astype)
abs_true = np.array([np.nan, np.inf, np.inf, np.inf, np.inf, np.inf, 0., np.nan, np.nan], dtype=arr.real.dtype)
sq_true = np.array([np.complex(np.nan, np.nan),
np.complex(np.nan, np.nan),
np.complex(np.nan, np.nan),
np.complex(np.nan, np.inf),
np.complex(-np.inf, np.nan),
np.complex(np.inf, np.nan),
np.complex(0., 0.),
np.complex(np.nan, np.nan),
np.complex(np.nan, np.nan)], dtype=astype)
assert_equal(np.abs(arr[::stride]), abs_true[::stride])
with np.errstate(invalid='ignore'):
assert_equal(np.square(arr[::stride]), sq_true[::stride])
class TestComplexAbsoluteAVX(object):
@pytest.mark.parametrize("arraysize", [1,2,3,4,5,6,7,8,9,10,11,13,15,17,18,19])
@pytest.mark.parametrize("stride", [-4,-3,-2,-1,1,2,3,4])
@pytest.mark.parametrize("astype", [np.complex64, np.complex128])
# test to ensure masking and strides work as intended in the AVX implementation
def test_array(self, arraysize, stride, astype):
arr = np.ones(arraysize, dtype=astype)
abs_true = np.ones(arraysize, dtype=arr.real.dtype)
assert_equal(np.abs(arr[::stride]), abs_true[::stride])
# Testcase taken as is from https://github.com/numpy/numpy/issues/16660
class TestComplexAbsoluteMixedDTypes(object):
@pytest.mark.parametrize("stride", [-4,-3,-2,-1,1,2,3,4])
@pytest.mark.parametrize("astype", [np.complex64, np.complex128])
@pytest.mark.parametrize("func", ['abs', 'square', 'conjugate'])
def test_array(self, stride, astype, func):
dtype = [('template_id', '<i8'), ('bank_chisq','<f4'),
('bank_chisq_dof','<i8'), ('chisq', '<f4'), ('chisq_dof','<i8'),
('cont_chisq', '<f4'), ('psd_var_val', '<f4'), ('sg_chisq','<f4'),
('mycomplex', astype), ('time_index', '<i8')]
vec = np.array([
(0, 0., 0, -31.666483, 200, 0., 0., 1. , 3.0+4.0j , 613090),
(1, 0., 0, 260.91525 , 42, 0., 0., 1. , 5.0+12.0j , 787315),
(1, 0., 0, 52.15155 , 42, 0., 0., 1. , 8.0+15.0j , 806641),
(1, 0., 0, 52.430195, 42, 0., 0., 1. , 7.0+24.0j , 1363540),
(2, 0., 0, 304.43646 , 58, 0., 0., 1. , 20.0+21.0j , 787323),
(3, 0., 0, 299.42108 , 52, 0., 0., 1. , 12.0+35.0j , 787332),
(4, 0., 0, 39.4836 , 28, 0., 0., 9.182192, 9.0+40.0j , 787304),
(4, 0., 0, 76.83787 , 28, 0., 0., 1. , 28.0+45.0j, 1321869),
(5, 0., 0, 143.26366 , 24, 0., 0., 10.996129, 11.0+60.0j , 787299)], dtype=dtype)
myfunc = getattr(np, func)
a = vec['mycomplex']
g = myfunc(a[::stride])
b = vec['mycomplex'].copy()
h = myfunc(b[::stride])
assert_array_max_ulp(h.real, g.real, 1)
assert_array_max_ulp(h.imag, g.imag, 1)

View file

@ -0,0 +1,362 @@
import numpy as np
from numpy.testing import assert_, assert_equal, assert_array_equal
def buffer_length(arr):
if isinstance(arr, str):
if not arr:
charmax = 0
else:
charmax = max([ord(c) for c in arr])
if charmax < 256:
size = 1
elif charmax < 65536:
size = 2
else:
size = 4
return size * len(arr)
v = memoryview(arr)
if v.shape is None:
return len(v) * v.itemsize
else:
return np.prod(v.shape) * v.itemsize
# In both cases below we need to make sure that the byte swapped value (as
# UCS4) is still a valid unicode:
# Value that can be represented in UCS2 interpreters
ucs2_value = u'\u0900'
# Value that cannot be represented in UCS2 interpreters (but can in UCS4)
ucs4_value = u'\U00100900'
def test_string_cast():
str_arr = np.array(["1234", "1234\0\0"], dtype='S')
uni_arr1 = str_arr.astype('>U')
uni_arr2 = str_arr.astype('<U')
assert_(str_arr != uni_arr1)
assert_(str_arr != uni_arr2)
assert_array_equal(uni_arr1, uni_arr2)
############################################################
# Creation tests
############################################################
class CreateZeros:
"""Check the creation of zero-valued arrays"""
def content_check(self, ua, ua_scalar, nbytes):
# Check the length of the unicode base type
assert_(int(ua.dtype.str[2:]) == self.ulen)
# Check the length of the data buffer
assert_(buffer_length(ua) == nbytes)
# Small check that data in array element is ok
assert_(ua_scalar == u'')
# Encode to ascii and double check
assert_(ua_scalar.encode('ascii') == b'')
# Check buffer lengths for scalars
assert_(buffer_length(ua_scalar) == 0)
def test_zeros0D(self):
# Check creation of 0-dimensional objects
ua = np.zeros((), dtype='U%s' % self.ulen)
self.content_check(ua, ua[()], 4*self.ulen)
def test_zerosSD(self):
# Check creation of single-dimensional objects
ua = np.zeros((2,), dtype='U%s' % self.ulen)
self.content_check(ua, ua[0], 4*self.ulen*2)
self.content_check(ua, ua[1], 4*self.ulen*2)
def test_zerosMD(self):
# Check creation of multi-dimensional objects
ua = np.zeros((2, 3, 4), dtype='U%s' % self.ulen)
self.content_check(ua, ua[0, 0, 0], 4*self.ulen*2*3*4)
self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4)
class TestCreateZeros_1(CreateZeros):
"""Check the creation of zero-valued arrays (size 1)"""
ulen = 1
class TestCreateZeros_2(CreateZeros):
"""Check the creation of zero-valued arrays (size 2)"""
ulen = 2
class TestCreateZeros_1009(CreateZeros):
"""Check the creation of zero-valued arrays (size 1009)"""
ulen = 1009
class CreateValues:
"""Check the creation of unicode arrays with values"""
def content_check(self, ua, ua_scalar, nbytes):
# Check the length of the unicode base type
assert_(int(ua.dtype.str[2:]) == self.ulen)
# Check the length of the data buffer
assert_(buffer_length(ua) == nbytes)
# Small check that data in array element is ok
assert_(ua_scalar == self.ucs_value*self.ulen)
# Encode to UTF-8 and double check
assert_(ua_scalar.encode('utf-8') ==
(self.ucs_value*self.ulen).encode('utf-8'))
# Check buffer lengths for scalars
if self.ucs_value == ucs4_value:
# In UCS2, the \U0010FFFF will be represented using a
# surrogate *pair*
assert_(buffer_length(ua_scalar) == 2*2*self.ulen)
else:
# In UCS2, the \uFFFF will be represented using a
# regular 2-byte word
assert_(buffer_length(ua_scalar) == 2*self.ulen)
def test_values0D(self):
# Check creation of 0-dimensional objects with values
ua = np.array(self.ucs_value*self.ulen, dtype='U%s' % self.ulen)
self.content_check(ua, ua[()], 4*self.ulen)
def test_valuesSD(self):
# Check creation of single-dimensional objects with values
ua = np.array([self.ucs_value*self.ulen]*2, dtype='U%s' % self.ulen)
self.content_check(ua, ua[0], 4*self.ulen*2)
self.content_check(ua, ua[1], 4*self.ulen*2)
def test_valuesMD(self):
# Check creation of multi-dimensional objects with values
ua = np.array([[[self.ucs_value*self.ulen]*2]*3]*4, dtype='U%s' % self.ulen)
self.content_check(ua, ua[0, 0, 0], 4*self.ulen*2*3*4)
self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4)
class TestCreateValues_1_UCS2(CreateValues):
"""Check the creation of valued arrays (size 1, UCS2 values)"""
ulen = 1
ucs_value = ucs2_value
class TestCreateValues_1_UCS4(CreateValues):
"""Check the creation of valued arrays (size 1, UCS4 values)"""
ulen = 1
ucs_value = ucs4_value
class TestCreateValues_2_UCS2(CreateValues):
"""Check the creation of valued arrays (size 2, UCS2 values)"""
ulen = 2
ucs_value = ucs2_value
class TestCreateValues_2_UCS4(CreateValues):
"""Check the creation of valued arrays (size 2, UCS4 values)"""
ulen = 2
ucs_value = ucs4_value
class TestCreateValues_1009_UCS2(CreateValues):
"""Check the creation of valued arrays (size 1009, UCS2 values)"""
ulen = 1009
ucs_value = ucs2_value
class TestCreateValues_1009_UCS4(CreateValues):
"""Check the creation of valued arrays (size 1009, UCS4 values)"""
ulen = 1009
ucs_value = ucs4_value
############################################################
# Assignment tests
############################################################
class AssignValues:
"""Check the assignment of unicode arrays with values"""
def content_check(self, ua, ua_scalar, nbytes):
# Check the length of the unicode base type
assert_(int(ua.dtype.str[2:]) == self.ulen)
# Check the length of the data buffer
assert_(buffer_length(ua) == nbytes)
# Small check that data in array element is ok
assert_(ua_scalar == self.ucs_value*self.ulen)
# Encode to UTF-8 and double check
assert_(ua_scalar.encode('utf-8') ==
(self.ucs_value*self.ulen).encode('utf-8'))
# Check buffer lengths for scalars
if self.ucs_value == ucs4_value:
# In UCS2, the \U0010FFFF will be represented using a
# surrogate *pair*
assert_(buffer_length(ua_scalar) == 2*2*self.ulen)
else:
# In UCS2, the \uFFFF will be represented using a
# regular 2-byte word
assert_(buffer_length(ua_scalar) == 2*self.ulen)
def test_values0D(self):
# Check assignment of 0-dimensional objects with values
ua = np.zeros((), dtype='U%s' % self.ulen)
ua[()] = self.ucs_value*self.ulen
self.content_check(ua, ua[()], 4*self.ulen)
def test_valuesSD(self):
# Check assignment of single-dimensional objects with values
ua = np.zeros((2,), dtype='U%s' % self.ulen)
ua[0] = self.ucs_value*self.ulen
self.content_check(ua, ua[0], 4*self.ulen*2)
ua[1] = self.ucs_value*self.ulen
self.content_check(ua, ua[1], 4*self.ulen*2)
def test_valuesMD(self):
# Check assignment of multi-dimensional objects with values
ua = np.zeros((2, 3, 4), dtype='U%s' % self.ulen)
ua[0, 0, 0] = self.ucs_value*self.ulen
self.content_check(ua, ua[0, 0, 0], 4*self.ulen*2*3*4)
ua[-1, -1, -1] = self.ucs_value*self.ulen
self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4)
class TestAssignValues_1_UCS2(AssignValues):
"""Check the assignment of valued arrays (size 1, UCS2 values)"""
ulen = 1
ucs_value = ucs2_value
class TestAssignValues_1_UCS4(AssignValues):
"""Check the assignment of valued arrays (size 1, UCS4 values)"""
ulen = 1
ucs_value = ucs4_value
class TestAssignValues_2_UCS2(AssignValues):
"""Check the assignment of valued arrays (size 2, UCS2 values)"""
ulen = 2
ucs_value = ucs2_value
class TestAssignValues_2_UCS4(AssignValues):
"""Check the assignment of valued arrays (size 2, UCS4 values)"""
ulen = 2
ucs_value = ucs4_value
class TestAssignValues_1009_UCS2(AssignValues):
"""Check the assignment of valued arrays (size 1009, UCS2 values)"""
ulen = 1009
ucs_value = ucs2_value
class TestAssignValues_1009_UCS4(AssignValues):
"""Check the assignment of valued arrays (size 1009, UCS4 values)"""
ulen = 1009
ucs_value = ucs4_value
############################################################
# Byteorder tests
############################################################
class ByteorderValues:
"""Check the byteorder of unicode arrays in round-trip conversions"""
def test_values0D(self):
# Check byteorder of 0-dimensional objects
ua = np.array(self.ucs_value*self.ulen, dtype='U%s' % self.ulen)
ua2 = ua.newbyteorder()
# This changes the interpretation of the data region (but not the
# actual data), therefore the returned scalars are not
# the same (they are byte-swapped versions of each other).
assert_(ua[()] != ua2[()])
ua3 = ua2.newbyteorder()
# Arrays must be equal after the round-trip
assert_equal(ua, ua3)
def test_valuesSD(self):
# Check byteorder of single-dimensional objects
ua = np.array([self.ucs_value*self.ulen]*2, dtype='U%s' % self.ulen)
ua2 = ua.newbyteorder()
assert_((ua != ua2).all())
assert_(ua[-1] != ua2[-1])
ua3 = ua2.newbyteorder()
# Arrays must be equal after the round-trip
assert_equal(ua, ua3)
def test_valuesMD(self):
# Check byteorder of multi-dimensional objects
ua = np.array([[[self.ucs_value*self.ulen]*2]*3]*4,
dtype='U%s' % self.ulen)
ua2 = ua.newbyteorder()
assert_((ua != ua2).all())
assert_(ua[-1, -1, -1] != ua2[-1, -1, -1])
ua3 = ua2.newbyteorder()
# Arrays must be equal after the round-trip
assert_equal(ua, ua3)
def test_values_cast(self):
# Check byteorder of when casting the array for a strided and
# contiguous array:
test1 = np.array([self.ucs_value*self.ulen]*2, dtype='U%s' % self.ulen)
test2 = np.repeat(test1, 2)[::2]
for ua in (test1, test2):
ua2 = ua.astype(dtype=ua.dtype.newbyteorder())
assert_((ua == ua2).all())
assert_(ua[-1] == ua2[-1])
ua3 = ua2.astype(dtype=ua.dtype)
# Arrays must be equal after the round-trip
assert_equal(ua, ua3)
def test_values_updowncast(self):
# Check byteorder of when casting the array to a longer and shorter
# string length for strided and contiguous arrays
test1 = np.array([self.ucs_value*self.ulen]*2, dtype='U%s' % self.ulen)
test2 = np.repeat(test1, 2)[::2]
for ua in (test1, test2):
# Cast to a longer type with zero padding
longer_type = np.dtype('U%s' % (self.ulen+1)).newbyteorder()
ua2 = ua.astype(dtype=longer_type)
assert_((ua == ua2).all())
assert_(ua[-1] == ua2[-1])
# Cast back again with truncating:
ua3 = ua2.astype(dtype=ua.dtype)
# Arrays must be equal after the round-trip
assert_equal(ua, ua3)
class TestByteorder_1_UCS2(ByteorderValues):
"""Check the byteorder in unicode (size 1, UCS2 values)"""
ulen = 1
ucs_value = ucs2_value
class TestByteorder_1_UCS4(ByteorderValues):
"""Check the byteorder in unicode (size 1, UCS4 values)"""
ulen = 1
ucs_value = ucs4_value
class TestByteorder_2_UCS2(ByteorderValues):
"""Check the byteorder in unicode (size 2, UCS2 values)"""
ulen = 2
ucs_value = ucs2_value
class TestByteorder_2_UCS4(ByteorderValues):
"""Check the byteorder in unicode (size 2, UCS4 values)"""
ulen = 2
ucs_value = ucs4_value
class TestByteorder_1009_UCS2(ByteorderValues):
"""Check the byteorder in unicode (size 1009, UCS2 values)"""
ulen = 1009
ucs_value = ucs2_value
class TestByteorder_1009_UCS4(ByteorderValues):
"""Check the byteorder in unicode (size 1009, UCS4 values)"""
ulen = 1009
ucs_value = ucs4_value