text stringlengths 1 262k | target_text stringlengths 1 3.1k | context_documents listlengths 0 8 | repo stringlengths 7 93 | path stringlengths 5 228 |
|---|---|---|---|---|
"""
Standalone script for writing release doc::
python tools/write_release <version>
Example::
python tools/write_release.py 1.7.0
Needs to be run from the root of the repository and assumes
that the output is in `release` and wheels and sdist in
`release/installers`.
Translation from rst to md markdown requires Pandoc, you
will need to rely on your distribution to provide that.
"""
import argparse
import os
import subprocess
from pathlib import Path
# Name of the notes directory
NOTES_DIR = "doc/source/release"
# Name of the output directory
OUTPUT_DIR = "release"
# Output base name, `.rst` or `.md` will be appended
OUTPUT_FILE = "README"
def write_release(version):
"""
Copy the <version>-notes.rst file to the OUTPUT_DIR and use
pandoc to translate it to markdown. That results in both
README.rst and README.md files that can be used for on
github for the release.
Parameters
----------
version: str
Release version, e.g., '2.3.2', etc.
Returns
-------
None.
"""
notes = Path(NOTES_DIR) / f"{version}-notes.rst"
outdir = Path(OUTPUT_DIR)
outdir.mkdir(exist_ok=True)
target_md = outdir / f"{OUTPUT_FILE}.md"
target_rst = outdir / f"{OUTPUT_FILE}.rst"
# translate README.rst to md for posting on GitHub
os.system(f"cp {notes} {target_rst}")
subprocess.run(
["pandoc", "-s", "-o", str(target_md), str(target_rst), "--wrap=preserve"],
check=True,
)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
"version",
help="NumPy version of the release, e.g. 2.3.2, etc.")
args = parser.parse_args()
write_release(args.version)
| """
Standalone script for writing release doc::
python tools/write_release <version>
Example::
python tools/write_release.py 1.7.0
Needs to be run from the root of the repository and assumes
that the output is in `release` and wheels and sdist in
`release/installers`.
Translation from rst to md markdown requires Pandoc, you
will need to rely on your distribution to provide that.
"""
import argparse
import os
import subprocess
from pathlib import Path
# Name of the notes directory
NOTES_DIR = "doc/source/release"
# Name of the output directory
OUTPUT_DIR = "release"
# Output base name, `.rst` or `.md` will be appended
OUTPUT_FILE = "README"
def write_release(version):
"""
Copy the <version>-notes.rst file to the OUTPUT_DIR and use
pandoc to translate it to markdown. That results in both
README.rst and README.md files that can be used for on
github for the release.
Parameters
----------
version: str
Release version, e.g., '2.3.2', etc.
Returns
-------
None.
"""
notes = Path(NOTES_DIR) / f"{version}-notes.rst"
outdir = Path(OUTPUT_DIR)
outdir.mkdir(exist_ok=True)
target_md = outdir / f"{OUTPUT_FILE}.md"
target_rst = outdir / f"{OUTPUT_FILE}.rst"
# translate README.rst to md for posting on GitHub
os.system(f"cp {notes} {target_rst}")
subprocess.run(
["pandoc", "-s", "-o", | [] | numpy/numpy | tools/write_release.py |
#!/usr/bin/env python3
import sys
import unittest
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
import Vector
######################################################################
class VectorTestCase(unittest.TestCase):
def __init__(self, methodName="runTest"):
unittest.TestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
# Test the (type IN_ARRAY1[ANY]) typemap
def testLength(self):
"Test length function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
length = Vector.__dict__[self.typeStr + "Length"]
self.assertEqual(length([5, 12, 0]), 13)
# Test the (type IN_ARRAY1[ANY]) typemap
def testLengthBadList(self):
"Test length function with bad list"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
length = Vector.__dict__[self.typeStr + "Length"]
self.assertRaises(BadListError, length, [5, "twelve", 0])
# Test the (type IN_ARRAY1[ANY]) typemap
def testLengthWrongSize(self):
"Test length function with wrong size"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
length = Vector.__dict__[self.typeStr + "Length"]
self.assertRaises(TypeError, length, [5, 12])
# Test the (type IN_ARRAY1[ANY]) typemap
def testLengthWrongDim(self):
"Test length function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
length = Vector.__dict__[self.typeStr + "Length"]
self.assertRaises(TypeError, length, [[1, 2], [3, 4]])
# Test the (type IN_ARRAY1[ANY]) typemap
def testLengthNonContainer(self):
"Test length function with non-container"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
length = Vector.__dict__[self.typeStr + "Length"]
self.assertRaises(TypeError, length, None)
# Test the (type* IN_ARRAY1, int DIM1) typemap
def testProd(self):
"Test prod function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
prod = Vector.__dict__[self.typeStr + "Prod"]
self.assertEqual(prod([1, 2, 3, 4]), 24)
# Test the (type* IN_ARRAY1, int DIM1) typemap
def testProdBadList(self):
"Test prod function with bad list"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
prod = Vector.__dict__[self.typeStr + "Prod"]
self.assertRaises(BadListError, prod, [[1, "two"], ["e", "pi"]])
# Test the (type* IN_ARRAY1, int DIM1) typemap
def testProdWrongDim(self):
"Test prod function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
prod = Vector.__dict__[self.typeStr + "Prod"]
self.assertRaises(TypeError, prod, [[1, 2], [8, 9]])
# Test the (type* IN_ARRAY1, int DIM1) typemap
def testProdNonContainer(self):
"Test prod function with non-container"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
prod = Vector.__dict__[self.typeStr + "Prod"]
self.assertRaises(TypeError, prod, None)
# Test the (int DIM1, type* IN_ARRAY1) typemap
def testSum(self):
"Test sum function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
sum = Vector.__dict__[self.typeStr + "Sum"]
self.assertEqual(sum([5, 6, 7, 8]), 26)
# Test the (int DIM1, type* IN_ARRAY1) typemap
def testSumBadList(self):
"Test sum function with bad list"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
sum = Vector.__dict__[self.typeStr + "Sum"]
self.assertRaises(BadListError, sum, [3, 4, 5, "pi"])
# Test the (int DIM1, type* IN_ARRAY1) typemap
def testSumWrongDim(self):
"Test sum function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
sum = Vector.__dict__[self.typeStr + "Sum"]
self.assertRaises(TypeError, sum, [[3, 4], [5, 6]])
# Test the (int DIM1, type* IN_ARRAY1) typemap
def testSumNonContainer(self):
"Test sum function with non-container"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
sum = Vector.__dict__[self.typeStr + "Sum"]
self.assertRaises(TypeError, sum, True)
# Test the (type INPLACE_ARRAY1[ANY]) typemap
def testReverse(self):
"Test reverse function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
reverse = Vector.__dict__[self.typeStr + "Reverse"]
vector = np.array([1, 2, 4], self.typeCode)
reverse(vector)
self.assertEqual((vector == [4, 2, 1]).all(), True)
# Test the (type INPLACE_ARRAY1[ANY]) typemap
def testReverseWrongDim(self):
"Test reverse function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
reverse = Vector.__dict__[self.typeStr + "Reverse"]
vector = np.array([[1, 2], [3, 4]], self.typeCode)
self.assertRaises(TypeError, reverse, vector)
# Test the (type INPLACE_ARRAY1[ANY]) typemap
def testReverseWrongSize(self):
"Test reverse function with wrong size"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
reverse = Vector.__dict__[self.typeStr + "Reverse"]
vector = np.array([9, 8, 7, 6, 5, 4], self.typeCode)
self.assertRaises(TypeError, reverse, vector)
# Test the (type INPLACE_ARRAY1[ANY]) typemap
def testReverseWrongType(self):
"Test reverse function with wrong type"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
reverse = Vector.__dict__[self.typeStr + "Reverse"]
vector = np.array([1, 2, 4], 'c')
self.assertRaises(TypeError, reverse, vector)
# Test the (type INPLACE_ARRAY1[ANY]) typemap
def testReverseNonArray(self):
"Test reverse function with non-array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
reverse = Vector.__dict__[self.typeStr + "Reverse"]
self.assertRaises(TypeError, reverse, [2, 4, 6])
# Test the (type* INPLACE_ARRAY1, int DIM1) typemap
def testOnes(self):
"Test ones function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ones = Vector.__dict__[self.typeStr + "Ones"]
vector = np.zeros(5, self.typeCode)
ones(vector)
np.testing.assert_array_equal(vector, np.array([1, 1, 1, 1, 1]))
# Test the (type* INPLACE_ARRAY1, int DIM1) typemap
def testOnesWrongDim(self):
"Test ones function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ones = Vector.__dict__[self.typeStr + "Ones"]
vector = np.zeros((5, 5), self.typeCode)
self.assertRaises(TypeError, ones, vector)
# Test the (type* INPLACE_ARRAY1, int DIM1) typemap
def testOnesWrongType(self):
"Test ones function with wrong type"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ones = Vector.__dict__[self.typeStr + "Ones"]
vector = np.zeros((5, 5), 'c')
self.assertRaises(TypeError, ones, vector)
# Test the (type* INPLACE_ARRAY1, int DIM1) typemap
def testOnesNonArray(self):
"Test ones function with non-array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ones = Vector.__dict__[self.typeStr + "Ones"]
self.assertRaises(TypeError, ones, [2, 4, 6, 8])
# Test the (int DIM1, type* INPLACE_ARRAY1) typemap
def testZeros(self):
"Test zeros function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
zeros = Vector.__dict__[self.typeStr + "Zeros"]
vector = np.ones(5, self.typeCode)
zeros(vector)
np.testing.assert_array_equal(vector, np.array([0, 0, 0, 0, 0]))
# Test the (int DIM1, type* INPLACE_ARRAY1) typemap
def testZerosWrongDim(self):
"Test zeros function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
zeros = Vector.__dict__[self.typeStr + "Zeros"]
vector = np.ones((5, 5), self.typeCode)
self.assertRaises(TypeError, zeros, vector)
# Test the (int DIM1, type* INPLACE_ARRAY1) typemap
def testZerosWrongType(self):
"Test zeros function with wrong type"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
zeros = Vector.__dict__[self.typeStr + "Zeros"]
vector = np.ones(6, 'c')
self.assertRaises(TypeError, zeros, vector)
# Test the (int DIM1, type* INPLACE_ARRAY1) typemap
def testZerosNonArray(self):
"Test zeros function with non-array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
zeros = Vector.__dict__[self.typeStr + "Zeros"]
self.assertRaises(TypeError, zeros, [1, 3, 5, 7, 9])
# Test the (type ARGOUT_ARRAY1[ANY]) typemap
def testEOSplit(self):
"Test eoSplit function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
eoSplit = Vector.__dict__[self.typeStr + "EOSplit"]
even, odd = eoSplit([1, 2, 3])
self.assertEqual((even == [1, 0, 3]).all(), True)
self.assertEqual((odd == [0, 2, 0]).all(), True)
# Test the (type* ARGOUT_ARRAY1, int DIM1) typemap
def testTwos(self):
"Test twos function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
twos = Vector.__dict__[self.typeStr + "Twos"]
vector = twos(5)
self.assertEqual((vector == [2, 2, 2, 2, 2]).all(), True)
# Test the (type* ARGOUT_ARRAY1, int DIM1) typemap
def testTwosNonInt(self):
"Test twos function with non-integer dimension"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
twos = Vector.__dict__[self.typeStr + "Twos"]
self.assertRaises(TypeError, twos, 5.0)
# Test the (int DIM1, type* ARGOUT_ARRAY1) typemap
def testThrees(self):
"Test threes function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
threes = Vector.__dict__[self.typeStr + "Threes"]
vector = threes(6)
self.assertEqual((vector == [3, 3, 3, 3, 3, 3]).all(), True)
# Test the (type* ARGOUT_ARRAY1, int DIM1) typemap
def testThreesNonInt(self):
"Test threes function with non-integer dimension"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
threes = Vector.__dict__[self.typeStr + "Threes"]
self.assertRaises(TypeError, threes, "threes")
######################################################################
class scharTestCase(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "schar"
self.typeCode = "b"
######################################################################
class ucharTestCase(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "uchar"
self.typeCode = "B"
######################################################################
class shortTestCase(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "short"
self.typeCode = "h"
######################################################################
class ushortTestCase(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "ushort"
self.typeCode = "H"
######################################################################
class intTestCase(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "int"
self.typeCode = "i"
######################################################################
class uintTestCase(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "uint"
self.typeCode = "I"
######################################################################
class longTestCase(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "long"
self.typeCode = "l"
######################################################################
class ulongTestCase(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "ulong"
self.typeCode = "L"
######################################################################
class longLongTestCase(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "longLong"
self.typeCode = "q"
######################################################################
class ulongLongTestCase(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "ulongLong"
self.typeCode = "Q"
######################################################################
class floatTestCase(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "float"
self.typeCode = "f"
######################################################################
class doubleTestCase(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
######################################################################
if __name__ == "__main__":
# Build the test suite
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( scharTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ucharTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( shortTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ushortTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( intTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( uintTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( longTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ulongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( longLongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(ulongLongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( floatTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( doubleTestCase))
# Execute the test suite
print("Testing 1D Functions of Module Vector")
print("NumPy version", np.__version__)
print()
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(bool(result.errors + result.failures))
| #!/usr/bin/env python3
import sys
import unittest
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
import Vector
######################################################################
class VectorTestCase(unittest.TestCase):
def __init__(self, methodName="runTest"):
unittest.TestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
# Test the (type IN_ARRAY1[ANY]) typemap
def testLength(self):
"Test length function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
length = Vector.__dict__[self.typeStr + "Length"]
self.assertEqual(length([5, 12, 0]), 13)
# Test the (type IN_ARRAY1[ANY]) typemap
def testLengthBadList(self):
"Test length function with bad list"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
length = Vector.__dict__[self.typeStr + "Length"]
self.assertRaises(BadListError, length, [5, "twelve", 0])
# Test the (type IN_ARRAY1[ANY]) typemap
def testLengthWrongSize(self):
"Test length function with wrong size"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
length | [] | numpy/numpy | tools/swig/test/testVector.py |
#!/usr/bin/env python3
import sys
import unittest
from math import sqrt
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
import Tensor
######################################################################
class TensorTestCase(unittest.TestCase):
def __init__(self, methodName="runTests"):
unittest.TestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
self.result = sqrt(28.0 / 8)
# Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap
def testNorm(self):
"Test norm function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
norm = Tensor.__dict__[self.typeStr + "Norm"]
tensor = [[[0, 1], [2, 3]],
[[3, 2], [1, 0]]]
if isinstance(self.result, int):
self.assertEqual(norm(tensor), self.result)
else:
self.assertAlmostEqual(norm(tensor), self.result, 6)
# Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap
def testNormBadList(self):
"Test norm function with bad list"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
norm = Tensor.__dict__[self.typeStr + "Norm"]
tensor = [[[0, "one"], [2, 3]],
[[3, "two"], [1, 0]]]
self.assertRaises(BadListError, norm, tensor)
# Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap
def testNormWrongDim(self):
"Test norm function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
norm = Tensor.__dict__[self.typeStr + "Norm"]
tensor = [[0, 1, 2, 3],
[3, 2, 1, 0]]
self.assertRaises(TypeError, norm, tensor)
# Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap
def testNormWrongSize(self):
"Test norm function with wrong size"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
norm = Tensor.__dict__[self.typeStr + "Norm"]
tensor = [[[0, 1, 0], [2, 3, 2]],
[[3, 2, 3], [1, 0, 1]]]
self.assertRaises(TypeError, norm, tensor)
# Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap
def testNormNonContainer(self):
"Test norm function with non-container"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
norm = Tensor.__dict__[self.typeStr + "Norm"]
self.assertRaises(TypeError, norm, None)
# Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testMax(self):
"Test max function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
max = Tensor.__dict__[self.typeStr + "Max"]
tensor = [[[1, 2], [3, 4]],
[[5, 6], [7, 8]]]
self.assertEqual(max(tensor), 8)
# Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testMaxBadList(self):
"Test max function with bad list"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
max = Tensor.__dict__[self.typeStr + "Max"]
tensor = [[[1, "two"], [3, 4]],
[[5, "six"], [7, 8]]]
self.assertRaises(BadListError, max, tensor)
# Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testMaxNonContainer(self):
"Test max function with non-container"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
max = Tensor.__dict__[self.typeStr + "Max"]
self.assertRaises(TypeError, max, None)
# Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testMaxWrongDim(self):
"Test max function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
max = Tensor.__dict__[self.typeStr + "Max"]
self.assertRaises(TypeError, max, [0, 1, 2, 3])
# Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap
def testMin(self):
"Test min function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
min = Tensor.__dict__[self.typeStr + "Min"]
tensor = [[[9, 8], [7, 6]],
[[5, 4], [3, 2]]]
self.assertEqual(min(tensor), 2)
# Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap
def testMinBadList(self):
"Test min function with bad list"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
min = Tensor.__dict__[self.typeStr + "Min"]
tensor = [[["nine", 8], [7, 6]],
[["five", 4], [3, 2]]]
self.assertRaises(BadListError, min, tensor)
# Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap
def testMinNonContainer(self):
"Test min function with non-container"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
min = Tensor.__dict__[self.typeStr + "Min"]
self.assertRaises(TypeError, min, True)
# Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap
def testMinWrongDim(self):
"Test min function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
min = Tensor.__dict__[self.typeStr + "Min"]
self.assertRaises(TypeError, min, [[1, 3], [5, 7]])
# Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap
def testScale(self):
"Test scale function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
scale = Tensor.__dict__[self.typeStr + "Scale"]
tensor = np.array([[[1, 0, 1], [0, 1, 0], [1, 0, 1]],
[[0, 1, 0], [1, 0, 1], [0, 1, 0]],
[[1, 0, 1], [0, 1, 0], [1, 0, 1]]], self.typeCode)
scale(tensor, 4)
self.assertEqual((tensor == [[[4, 0, 4], [0, 4, 0], [4, 0, 4]],
[[0, 4, 0], [4, 0, 4], [0, 4, 0]],
[[4, 0, 4], [0, 4, 0], [4, 0, 4]]]).all(), True)
# Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap
def testScaleWrongType(self):
"Test scale function with wrong type"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
scale = Tensor.__dict__[self.typeStr + "Scale"]
tensor = np.array([[[1, 0, 1], [0, 1, 0], [1, 0, 1]],
[[0, 1, 0], [1, 0, 1], [0, 1, 0]],
[[1, 0, 1], [0, 1, 0], [1, 0, 1]]], 'c')
self.assertRaises(TypeError, scale, tensor)
# Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap
def testScaleWrongDim(self):
"Test scale function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
scale = Tensor.__dict__[self.typeStr + "Scale"]
tensor = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1],
[0, 1, 0], [1, 0, 1], [0, 1, 0]], self.typeCode)
self.assertRaises(TypeError, scale, tensor)
# Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap
def testScaleWrongSize(self):
"Test scale function with wrong size"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
scale = Tensor.__dict__[self.typeStr + "Scale"]
tensor = np.array([[[1, 0], [0, 1], [1, 0]],
[[0, 1], [1, 0], [0, 1]],
[[1, 0], [0, 1], [1, 0]]], self.typeCode)
self.assertRaises(TypeError, scale, tensor)
# Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap
def testScaleNonArray(self):
"Test scale function with non-array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
scale = Tensor.__dict__[self.typeStr + "Scale"]
self.assertRaises(TypeError, scale, True)
# Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testFloor(self):
"Test floor function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
floor = Tensor.__dict__[self.typeStr + "Floor"]
tensor = np.array([[[1, 2], [3, 4]],
[[5, 6], [7, 8]]], self.typeCode)
floor(tensor, 4)
np.testing.assert_array_equal(tensor, np.array([[[4, 4], [4, 4]],
[[5, 6], [7, 8]]]))
# Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testFloorWrongType(self):
"Test floor function with wrong type"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
floor = Tensor.__dict__[self.typeStr + "Floor"]
tensor = np.array([[[1, 2], [3, 4]],
[[5, 6], [7, 8]]], 'c')
self.assertRaises(TypeError, floor, tensor)
# Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testFloorWrongDim(self):
"Test floor function with wrong type"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
floor = Tensor.__dict__[self.typeStr + "Floor"]
tensor = np.array([[1, 2], [3, 4], [5, 6], [7, 8]], self.typeCode)
self.assertRaises(TypeError, floor, tensor)
# Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testFloorNonArray(self):
"Test floor function with non-array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
floor = Tensor.__dict__[self.typeStr + "Floor"]
self.assertRaises(TypeError, floor, object)
# Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap
def testCeil(self):
"Test ceil function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ceil = Tensor.__dict__[self.typeStr + "Ceil"]
tensor = np.array([[[9, 8], [7, 6]],
[[5, 4], [3, 2]]], self.typeCode)
ceil(tensor, 5)
np.testing.assert_array_equal(tensor, np.array([[[5, 5], [5, 5]],
[[5, 4], [3, 2]]]))
# Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap
def testCeilWrongType(self):
"Test ceil function with wrong type"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ceil = Tensor.__dict__[self.typeStr + "Ceil"]
tensor = np.array([[[9, 8], [7, 6]],
[[5, 4], [3, 2]]], 'c')
self.assertRaises(TypeError, ceil, tensor)
# Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap
def testCeilWrongDim(self):
"Test ceil function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ceil = Tensor.__dict__[self.typeStr + "Ceil"]
tensor = np.array([[9, 8], [7, 6], [5, 4], [3, 2]], self.typeCode)
self.assertRaises(TypeError, ceil, tensor)
# Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap
def testCeilNonArray(self):
"Test ceil function with non-array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ceil = Tensor.__dict__[self.typeStr + "Ceil"]
tensor = [[[9, 8], [7, 6]],
[[5, 4], [3, 2]]]
self.assertRaises(TypeError, ceil, tensor)
# Test (type ARGOUT_ARRAY3[ANY][ANY][ANY]) typemap
def testLUSplit(self):
"Test luSplit function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
luSplit = Tensor.__dict__[self.typeStr + "LUSplit"]
lower, upper = luSplit([[[1, 1], [1, 1]],
[[1, 1], [1, 1]]])
self.assertEqual((lower == [[[1, 1], [1, 0]],
[[1, 0], [0, 0]]]).all(), True)
self.assertEqual((upper == [[[0, 0], [0, 1]],
[[0, 1], [1, 1]]]).all(), True)
######################################################################
class scharTestCase(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "schar"
self.typeCode = "b"
self.result = int(self.result)
######################################################################
class ucharTestCase(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "uchar"
self.typeCode = "B"
self.result = int(self.result)
######################################################################
class shortTestCase(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "short"
self.typeCode = "h"
self.result = int(self.result)
######################################################################
class ushortTestCase(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "ushort"
self.typeCode = "H"
self.result = int(self.result)
######################################################################
class intTestCase(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "int"
self.typeCode = "i"
self.result = int(self.result)
######################################################################
class uintTestCase(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "uint"
self.typeCode = "I"
self.result = int(self.result)
######################################################################
class longTestCase(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "long"
self.typeCode = "l"
self.result = int(self.result)
######################################################################
class ulongTestCase(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "ulong"
self.typeCode = "L"
self.result = int(self.result)
######################################################################
class longLongTestCase(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "longLong"
self.typeCode = "q"
self.result = int(self.result)
######################################################################
class ulongLongTestCase(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "ulongLong"
self.typeCode = "Q"
self.result = int(self.result)
######################################################################
class floatTestCase(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "float"
self.typeCode = "f"
######################################################################
class doubleTestCase(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
######################################################################
if __name__ == "__main__":
# Build the test suite
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( scharTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ucharTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( shortTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ushortTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( intTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( uintTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( longTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ulongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( longLongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(ulongLongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( floatTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( doubleTestCase))
# Execute the test suite
print("Testing 3D Functions of Module Tensor")
print("NumPy version", np.__version__)
print()
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(bool(result.errors + result.failures))
| #!/usr/bin/env python3
import sys
import unittest
from math import sqrt
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
import Tensor
######################################################################
class TensorTestCase(unittest.TestCase):
def __init__(self, methodName="runTests"):
unittest.TestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
self.result = sqrt(28.0 / 8)
# Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap
def testNorm(self):
"Test norm function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
norm = Tensor.__dict__[self.typeStr + "Norm"]
tensor = [[[0, 1], [2, 3]],
[[3, 2], [1, 0]]]
if isinstance(self.result, int):
self.assertEqual(norm(tensor), self.result)
else:
self.assertAlmostEqual(norm(tensor), self.result, 6)
# Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap
def testNormBadList(self):
"Test norm function with bad list"
print(self.typeStr, "... ", | [] | numpy/numpy | tools/swig/test/testTensor.py |
#!/usr/bin/env python3
import sys
import unittest
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
import SuperTensor
######################################################################
class SuperTensorTestCase(unittest.TestCase):
def __init__(self, methodName="runTests"):
unittest.TestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
# Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap
def testNorm(self):
"Test norm function"
print(self.typeStr, "... ", file=sys.stderr)
norm = SuperTensor.__dict__[self.typeStr + "Norm"]
supertensor = np.arange(2 * 2 * 2 * 2,
dtype=self.typeCode).reshape((2, 2, 2, 2))
# Note: cludge to get an answer of the same type as supertensor.
# Answer is simply sqrt(sum(supertensor*supertensor)/16)
answer = np.array([np.sqrt(np.sum(supertensor.astype('d') * supertensor) / 16.)], dtype=self.typeCode)[0] # noqa: E501
self.assertAlmostEqual(norm(supertensor), answer, 6)
# Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap
def testNormBadList(self):
"Test norm function with bad list"
print(self.typeStr, "... ", file=sys.stderr)
norm = SuperTensor.__dict__[self.typeStr + "Norm"]
supertensor = [[[[0, "one"], [2, 3]], [[3, "two"], [1, 0]]],
[[[0, "one"], [2, 3]], [[3, "two"], [1, 0]]]]
self.assertRaises(BadListError, norm, supertensor)
# Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap
def testNormWrongDim(self):
"Test norm function with wrong dimensions"
print(self.typeStr, "... ", file=sys.stderr)
norm = SuperTensor.__dict__[self.typeStr + "Norm"]
supertensor = np.arange(2 * 2 * 2, dtype=self.typeCode).reshape((2, 2, 2))
self.assertRaises(TypeError, norm, supertensor)
# Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap
def testNormWrongSize(self):
"Test norm function with wrong size"
print(self.typeStr, "... ", file=sys.stderr)
norm = SuperTensor.__dict__[self.typeStr + "Norm"]
supertensor = np.arange(3 * 2 * 2, dtype=self.typeCode).reshape((3, 2, 2))
self.assertRaises(TypeError, norm, supertensor)
# Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap
def testNormNonContainer(self):
"Test norm function with non-container"
print(self.typeStr, "... ", file=sys.stderr)
norm = SuperTensor.__dict__[self.typeStr + "Norm"]
self.assertRaises(TypeError, norm, None)
# Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testMax(self):
"Test max function"
print(self.typeStr, "... ", file=sys.stderr)
max = SuperTensor.__dict__[self.typeStr + "Max"]
supertensor = [[[[1, 2], [3, 4]], [[5, 6], [7, 8]]],
[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]]
self.assertEqual(max(supertensor), 8)
# Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testMaxBadList(self):
"Test max function with bad list"
print(self.typeStr, "... ", file=sys.stderr)
max = SuperTensor.__dict__[self.typeStr + "Max"]
supertensor = [[[[1, "two"], [3, 4]], [[5, "six"], [7, 8]]],
[[[1, "two"], [3, 4]], [[5, "six"], [7, 8]]]]
self.assertRaises(BadListError, max, supertensor)
# Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testMaxNonContainer(self):
"Test max function with non-container"
print(self.typeStr, "... ", file=sys.stderr)
max = SuperTensor.__dict__[self.typeStr + "Max"]
self.assertRaises(TypeError, max, None)
# Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testMaxWrongDim(self):
"Test max function with wrong dimensions"
print(self.typeStr, "... ", file=sys.stderr)
max = SuperTensor.__dict__[self.typeStr + "Max"]
self.assertRaises(TypeError, max, [0, -1, 2, -3])
# Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap
def testMin(self):
"Test min function"
print(self.typeStr, "... ", file=sys.stderr)
min = SuperTensor.__dict__[self.typeStr + "Min"]
supertensor = [[[[9, 8], [7, 6]], [[5, 4], [3, 2]]],
[[[9, 8], [7, 6]], [[5, 4], [3, 2]]]]
self.assertEqual(min(supertensor), 2)
# Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap
def testMinBadList(self):
"Test min function with bad list"
print(self.typeStr, "... ", file=sys.stderr)
min = SuperTensor.__dict__[self.typeStr + "Min"]
supertensor = [[[["nine", 8], [7, 6]], [["five", 4], [3, 2]]],
[[["nine", 8], [7, 6]], [["five", 4], [3, 2]]]]
self.assertRaises(BadListError, min, supertensor)
# Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap
def testMinNonContainer(self):
"Test min function with non-container"
print(self.typeStr, "... ", file=sys.stderr)
min = SuperTensor.__dict__[self.typeStr + "Min"]
self.assertRaises(TypeError, min, True)
# Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap
def testMinWrongDim(self):
"Test min function with wrong dimensions"
print(self.typeStr, "... ", file=sys.stderr)
min = SuperTensor.__dict__[self.typeStr + "Min"]
self.assertRaises(TypeError, min, [[1, 3], [5, 7]])
# Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap
def testScale(self):
"Test scale function"
print(self.typeStr, "... ", file=sys.stderr)
scale = SuperTensor.__dict__[self.typeStr + "Scale"]
supertensor = np.arange(3 * 3 * 3 * 3,
dtype=self.typeCode).reshape((3, 3, 3, 3))
answer = supertensor.copy() * 4
scale(supertensor, 4)
self.assertEqual((supertensor == answer).all(), True)
# Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap
def testScaleWrongType(self):
"Test scale function with wrong type"
print(self.typeStr, "... ", file=sys.stderr)
scale = SuperTensor.__dict__[self.typeStr + "Scale"]
supertensor = np.array([[[1, 0, 1], [0, 1, 0], [1, 0, 1]],
[[0, 1, 0], [1, 0, 1], [0, 1, 0]],
[[1, 0, 1], [0, 1, 0], [1, 0, 1]]], 'c')
self.assertRaises(TypeError, scale, supertensor)
# Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap
def testScaleWrongDim(self):
"Test scale function with wrong dimensions"
print(self.typeStr, "... ", file=sys.stderr)
scale = SuperTensor.__dict__[self.typeStr + "Scale"]
supertensor = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1],
[0, 1, 0], [1, 0, 1], [0, 1, 0]], self.typeCode)
self.assertRaises(TypeError, scale, supertensor)
# Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap
def testScaleWrongSize(self):
"Test scale function with wrong size"
print(self.typeStr, "... ", file=sys.stderr)
scale = SuperTensor.__dict__[self.typeStr + "Scale"]
supertensor = np.array([[[1, 0], [0, 1], [1, 0]],
[[0, 1], [1, 0], [0, 1]],
[[1, 0], [0, 1], [1, 0]]], self.typeCode)
self.assertRaises(TypeError, scale, supertensor)
# Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap
def testScaleNonArray(self):
"Test scale function with non-array"
print(self.typeStr, "... ", file=sys.stderr)
scale = SuperTensor.__dict__[self.typeStr + "Scale"]
self.assertRaises(TypeError, scale, True)
# Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testFloor(self):
"Test floor function"
print(self.typeStr, "... ", file=sys.stderr)
supertensor = np.arange(2 * 2 * 2 * 2,
dtype=self.typeCode).reshape((2, 2, 2, 2))
answer = supertensor.copy()
answer[answer < 4] = 4
floor = SuperTensor.__dict__[self.typeStr + "Floor"]
floor(supertensor, 4)
np.testing.assert_array_equal(supertensor, answer)
# Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testFloorWrongType(self):
"Test floor function with wrong type"
print(self.typeStr, "... ", file=sys.stderr)
floor = SuperTensor.__dict__[self.typeStr + "Floor"]
supertensor = np.ones(2 * 2 * 2 * 2, dtype='c').reshape((2, 2, 2, 2))
self.assertRaises(TypeError, floor, supertensor)
# Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testFloorWrongDim(self):
"Test floor function with wrong type"
print(self.typeStr, "... ", file=sys.stderr)
floor = SuperTensor.__dict__[self.typeStr + "Floor"]
supertensor = np.arange(2 * 2 * 2, dtype=self.typeCode).reshape((2, 2, 2))
self.assertRaises(TypeError, floor, supertensor)
# Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap
def testFloorNonArray(self):
"Test floor function with non-array"
print(self.typeStr, "... ", file=sys.stderr)
floor = SuperTensor.__dict__[self.typeStr + "Floor"]
self.assertRaises(TypeError, floor, object)
# Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap
def testCeil(self):
"Test ceil function"
print(self.typeStr, "... ", file=sys.stderr)
supertensor = np.arange(2 * 2 * 2 * 2,
dtype=self.typeCode).reshape((2, 2, 2, 2))
answer = supertensor.copy()
answer[answer > 5] = 5
ceil = SuperTensor.__dict__[self.typeStr + "Ceil"]
ceil(supertensor, 5)
np.testing.assert_array_equal(supertensor, answer)
# Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap
def testCeilWrongType(self):
"Test ceil function with wrong type"
print(self.typeStr, "... ", file=sys.stderr)
ceil = SuperTensor.__dict__[self.typeStr + "Ceil"]
supertensor = np.ones(2 * 2 * 2 * 2, 'c').reshape((2, 2, 2, 2))
self.assertRaises(TypeError, ceil, supertensor)
# Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap
def testCeilWrongDim(self):
"Test ceil function with wrong dimensions"
print(self.typeStr, "... ", file=sys.stderr)
ceil = SuperTensor.__dict__[self.typeStr + "Ceil"]
supertensor = np.arange(2 * 2 * 2, dtype=self.typeCode).reshape((2, 2, 2))
self.assertRaises(TypeError, ceil, supertensor)
# Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap
def testCeilNonArray(self):
"Test ceil function with non-array"
print(self.typeStr, "... ", file=sys.stderr)
ceil = SuperTensor.__dict__[self.typeStr + "Ceil"]
supertensor = np.arange(2 * 2 * 2 * 2,
dtype=self.typeCode).reshape((2, 2, 2, 2)).tolist()
self.assertRaises(TypeError, ceil, supertensor)
# Test (type ARGOUT_ARRAY3[ANY][ANY][ANY]) typemap
def testLUSplit(self):
"Test luSplit function"
print(self.typeStr, "... ", file=sys.stderr)
luSplit = SuperTensor.__dict__[self.typeStr + "LUSplit"]
supertensor = np.ones(2 * 2 * 2 * 2, dtype=self.typeCode).reshape((2, 2, 2, 2))
answer_upper = [[[[0, 0], [0, 1]], [[0, 1], [1, 1]]], [[[0, 1], [1, 1]], [[1, 1], [1, 1]]]] # noqa: E501
answer_lower = [[[[1, 1], [1, 0]], [[1, 0], [0, 0]]], [[[1, 0], [0, 0]], [[0, 0], [0, 0]]]] # noqa: E501
lower, upper = luSplit(supertensor)
self.assertEqual((lower == answer_lower).all(), True)
self.assertEqual((upper == answer_upper).all(), True)
######################################################################
class scharTestCase(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "schar"
self.typeCode = "b"
#self.result = int(self.result)
######################################################################
class ucharTestCase(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "uchar"
self.typeCode = "B"
#self.result = int(self.result)
######################################################################
class shortTestCase(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "short"
self.typeCode = "h"
#self.result = int(self.result)
######################################################################
class ushortTestCase(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "ushort"
self.typeCode = "H"
#self.result = int(self.result)
######################################################################
class intTestCase(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "int"
self.typeCode = "i"
#self.result = int(self.result)
######################################################################
class uintTestCase(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "uint"
self.typeCode = "I"
#self.result = int(self.result)
######################################################################
class longTestCase(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "long"
self.typeCode = "l"
#self.result = int(self.result)
######################################################################
class ulongTestCase(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "ulong"
self.typeCode = "L"
#self.result = int(self.result)
######################################################################
class longLongTestCase(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "longLong"
self.typeCode = "q"
#self.result = int(self.result)
######################################################################
class ulongLongTestCase(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "ulongLong"
self.typeCode = "Q"
#self.result = int(self.result)
######################################################################
class floatTestCase(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "float"
self.typeCode = "f"
######################################################################
class doubleTestCase(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
######################################################################
if __name__ == "__main__":
# Build the test suite
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( scharTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ucharTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( shortTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ushortTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( intTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( uintTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( longTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ulongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( longLongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(ulongLongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( floatTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( doubleTestCase))
# Execute the test suite
print("Testing 4D Functions of Module SuperTensor")
print("NumPy version", np.__version__)
print()
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(bool(result.errors + result.failures))
| #!/usr/bin/env python3
import sys
import unittest
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
import SuperTensor
######################################################################
class SuperTensorTestCase(unittest.TestCase):
def __init__(self, methodName="runTests"):
unittest.TestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
# Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap
def testNorm(self):
"Test norm function"
print(self.typeStr, "... ", file=sys.stderr)
norm = SuperTensor.__dict__[self.typeStr + "Norm"]
supertensor = np.arange(2 * 2 * 2 * 2,
dtype=self.typeCode).reshape((2, 2, 2, 2))
# Note: cludge to get an answer of the same type as supertensor.
# Answer is simply sqrt(sum(supertensor*supertensor)/16)
answer = np.array([np.sqrt(np.sum(supertensor.astype('d') * supertensor) / 16.)], dtype=self.typeCode)[0] # noqa: E501
self.assertAlmostEqual(norm(supertensor), answer, 6)
# Test (type IN_ARRAY3[ANY][ANY][ANY]) | [] | numpy/numpy | tools/swig/test/testSuperTensor.py |
#!/usr/bin/env python3
import sys
import unittest
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
import Matrix
######################################################################
class MatrixTestCase(unittest.TestCase):
def __init__(self, methodName="runTests"):
unittest.TestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
# Test (type IN_ARRAY2[ANY][ANY]) typemap
def testDet(self):
"Test det function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
det = Matrix.__dict__[self.typeStr + "Det"]
matrix = [[8, 7], [6, 9]]
self.assertEqual(det(matrix), 30)
# Test (type IN_ARRAY2[ANY][ANY]) typemap
def testDetBadList(self):
"Test det function with bad list"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
det = Matrix.__dict__[self.typeStr + "Det"]
matrix = [[8, 7], ["e", "pi"]]
self.assertRaises(BadListError, det, matrix)
# Test (type IN_ARRAY2[ANY][ANY]) typemap
def testDetWrongDim(self):
"Test det function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
det = Matrix.__dict__[self.typeStr + "Det"]
matrix = [8, 7]
self.assertRaises(TypeError, det, matrix)
# Test (type IN_ARRAY2[ANY][ANY]) typemap
def testDetWrongSize(self):
"Test det function with wrong size"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
det = Matrix.__dict__[self.typeStr + "Det"]
matrix = [[8, 7, 6], [5, 4, 3], [2, 1, 0]]
self.assertRaises(TypeError, det, matrix)
# Test (type IN_ARRAY2[ANY][ANY]) typemap
def testDetNonContainer(self):
"Test det function with non-container"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
det = Matrix.__dict__[self.typeStr + "Det"]
self.assertRaises(TypeError, det, None)
# Test (type* IN_ARRAY2, int DIM1, int DIM2) typemap
def testMax(self):
"Test max function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
max = Matrix.__dict__[self.typeStr + "Max"]
matrix = [[6, 5, 4], [3, 2, 1]]
self.assertEqual(max(matrix), 6)
# Test (type* IN_ARRAY2, int DIM1, int DIM2) typemap
def testMaxBadList(self):
"Test max function with bad list"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
max = Matrix.__dict__[self.typeStr + "Max"]
matrix = [[6, "five", 4], ["three", 2, "one"]]
self.assertRaises(BadListError, max, matrix)
# Test (type* IN_ARRAY2, int DIM1, int DIM2) typemap
def testMaxNonContainer(self):
"Test max function with non-container"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
max = Matrix.__dict__[self.typeStr + "Max"]
self.assertRaises(TypeError, max, None)
# Test (type* IN_ARRAY2, int DIM1, int DIM2) typemap
def testMaxWrongDim(self):
"Test max function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
max = Matrix.__dict__[self.typeStr + "Max"]
self.assertRaises(TypeError, max, [0, 1, 2, 3])
# Test (int DIM1, int DIM2, type* IN_ARRAY2) typemap
def testMin(self):
"Test min function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
min = Matrix.__dict__[self.typeStr + "Min"]
matrix = [[9, 8], [7, 6], [5, 4]]
self.assertEqual(min(matrix), 4)
# Test (int DIM1, int DIM2, type* IN_ARRAY2) typemap
def testMinBadList(self):
"Test min function with bad list"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
min = Matrix.__dict__[self.typeStr + "Min"]
matrix = [["nine", "eight"], ["seven", "six"]]
self.assertRaises(BadListError, min, matrix)
# Test (int DIM1, int DIM2, type* IN_ARRAY2) typemap
def testMinWrongDim(self):
"Test min function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
min = Matrix.__dict__[self.typeStr + "Min"]
self.assertRaises(TypeError, min, [1, 3, 5, 7, 9])
# Test (int DIM1, int DIM2, type* IN_ARRAY2) typemap
def testMinNonContainer(self):
"Test min function with non-container"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
min = Matrix.__dict__[self.typeStr + "Min"]
self.assertRaises(TypeError, min, False)
# Test (type INPLACE_ARRAY2[ANY][ANY]) typemap
def testScale(self):
"Test scale function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
scale = Matrix.__dict__[self.typeStr + "Scale"]
matrix = np.array([[1, 2, 3], [2, 1, 2], [3, 2, 1]], self.typeCode)
scale(matrix, 4)
self.assertEqual((matrix == [[4, 8, 12], [8, 4, 8], [12, 8, 4]]).all(), True)
# Test (type INPLACE_ARRAY2[ANY][ANY]) typemap
def testScaleWrongDim(self):
"Test scale function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
scale = Matrix.__dict__[self.typeStr + "Scale"]
matrix = np.array([1, 2, 2, 1], self.typeCode)
self.assertRaises(TypeError, scale, matrix)
# Test (type INPLACE_ARRAY2[ANY][ANY]) typemap
def testScaleWrongSize(self):
"Test scale function with wrong size"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
scale = Matrix.__dict__[self.typeStr + "Scale"]
matrix = np.array([[1, 2], [2, 1]], self.typeCode)
self.assertRaises(TypeError, scale, matrix)
# Test (type INPLACE_ARRAY2[ANY][ANY]) typemap
def testScaleWrongType(self):
"Test scale function with wrong type"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
scale = Matrix.__dict__[self.typeStr + "Scale"]
matrix = np.array([[1, 2, 3], [2, 1, 2], [3, 2, 1]], 'c')
self.assertRaises(TypeError, scale, matrix)
# Test (type INPLACE_ARRAY2[ANY][ANY]) typemap
def testScaleNonArray(self):
"Test scale function with non-array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
scale = Matrix.__dict__[self.typeStr + "Scale"]
matrix = [[1, 2, 3], [2, 1, 2], [3, 2, 1]]
self.assertRaises(TypeError, scale, matrix)
# Test (type* INPLACE_ARRAY2, int DIM1, int DIM2) typemap
def testFloor(self):
"Test floor function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
floor = Matrix.__dict__[self.typeStr + "Floor"]
matrix = np.array([[6, 7], [8, 9]], self.typeCode)
floor(matrix, 7)
np.testing.assert_array_equal(matrix, np.array([[7, 7], [8, 9]]))
# Test (type* INPLACE_ARRAY2, int DIM1, int DIM2) typemap
def testFloorWrongDim(self):
"Test floor function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
floor = Matrix.__dict__[self.typeStr + "Floor"]
matrix = np.array([6, 7, 8, 9], self.typeCode)
self.assertRaises(TypeError, floor, matrix)
# Test (type* INPLACE_ARRAY2, int DIM1, int DIM2) typemap
def testFloorWrongType(self):
"Test floor function with wrong type"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
floor = Matrix.__dict__[self.typeStr + "Floor"]
matrix = np.array([[6, 7], [8, 9]], 'c')
self.assertRaises(TypeError, floor, matrix)
# Test (type* INPLACE_ARRAY2, int DIM1, int DIM2) typemap
def testFloorNonArray(self):
"Test floor function with non-array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
floor = Matrix.__dict__[self.typeStr + "Floor"]
matrix = [[6, 7], [8, 9]]
self.assertRaises(TypeError, floor, matrix)
# Test (int DIM1, int DIM2, type* INPLACE_ARRAY2) typemap
def testCeil(self):
"Test ceil function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ceil = Matrix.__dict__[self.typeStr + "Ceil"]
matrix = np.array([[1, 2], [3, 4]], self.typeCode)
ceil(matrix, 3)
np.testing.assert_array_equal(matrix, np.array([[1, 2], [3, 3]]))
# Test (int DIM1, int DIM2, type* INPLACE_ARRAY2) typemap
def testCeilWrongDim(self):
"Test ceil function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ceil = Matrix.__dict__[self.typeStr + "Ceil"]
matrix = np.array([1, 2, 3, 4], self.typeCode)
self.assertRaises(TypeError, ceil, matrix)
# Test (int DIM1, int DIM2, type* INPLACE_ARRAY2) typemap
def testCeilWrongType(self):
"Test ceil function with wrong dimensions"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ceil = Matrix.__dict__[self.typeStr + "Ceil"]
matrix = np.array([[1, 2], [3, 4]], 'c')
self.assertRaises(TypeError, ceil, matrix)
# Test (int DIM1, int DIM2, type* INPLACE_ARRAY2) typemap
def testCeilNonArray(self):
"Test ceil function with non-array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
ceil = Matrix.__dict__[self.typeStr + "Ceil"]
matrix = [[1, 2], [3, 4]]
self.assertRaises(TypeError, ceil, matrix)
# Test (type ARGOUT_ARRAY2[ANY][ANY]) typemap
def testLUSplit(self):
"Test luSplit function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
luSplit = Matrix.__dict__[self.typeStr + "LUSplit"]
lower, upper = luSplit([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
self.assertEqual((lower == [[1, 0, 0], [4, 5, 0], [7, 8, 9]]).all(), True)
self.assertEqual((upper == [[0, 2, 3], [0, 0, 6], [0, 0, 0]]).all(), True)
######################################################################
class scharTestCase(MatrixTestCase):
def __init__(self, methodName="runTest"):
MatrixTestCase.__init__(self, methodName)
self.typeStr = "schar"
self.typeCode = "b"
######################################################################
class ucharTestCase(MatrixTestCase):
def __init__(self, methodName="runTest"):
MatrixTestCase.__init__(self, methodName)
self.typeStr = "uchar"
self.typeCode = "B"
######################################################################
class shortTestCase(MatrixTestCase):
def __init__(self, methodName="runTest"):
MatrixTestCase.__init__(self, methodName)
self.typeStr = "short"
self.typeCode = "h"
######################################################################
class ushortTestCase(MatrixTestCase):
def __init__(self, methodName="runTest"):
MatrixTestCase.__init__(self, methodName)
self.typeStr = "ushort"
self.typeCode = "H"
######################################################################
class intTestCase(MatrixTestCase):
def __init__(self, methodName="runTest"):
MatrixTestCase.__init__(self, methodName)
self.typeStr = "int"
self.typeCode = "i"
######################################################################
class uintTestCase(MatrixTestCase):
def __init__(self, methodName="runTest"):
MatrixTestCase.__init__(self, methodName)
self.typeStr = "uint"
self.typeCode = "I"
######################################################################
class longTestCase(MatrixTestCase):
def __init__(self, methodName="runTest"):
MatrixTestCase.__init__(self, methodName)
self.typeStr = "long"
self.typeCode = "l"
######################################################################
class ulongTestCase(MatrixTestCase):
def __init__(self, methodName="runTest"):
MatrixTestCase.__init__(self, methodName)
self.typeStr = "ulong"
self.typeCode = "L"
######################################################################
class longLongTestCase(MatrixTestCase):
def __init__(self, methodName="runTest"):
MatrixTestCase.__init__(self, methodName)
self.typeStr = "longLong"
self.typeCode = "q"
######################################################################
class ulongLongTestCase(MatrixTestCase):
def __init__(self, methodName="runTest"):
MatrixTestCase.__init__(self, methodName)
self.typeStr = "ulongLong"
self.typeCode = "Q"
######################################################################
class floatTestCase(MatrixTestCase):
def __init__(self, methodName="runTest"):
MatrixTestCase.__init__(self, methodName)
self.typeStr = "float"
self.typeCode = "f"
######################################################################
class doubleTestCase(MatrixTestCase):
def __init__(self, methodName="runTest"):
MatrixTestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
######################################################################
if __name__ == "__main__":
# Build the test suite
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( scharTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ucharTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( shortTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ushortTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( intTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( uintTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( longTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ulongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( longLongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(ulongLongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( floatTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( doubleTestCase))
# Execute the test suite
print("Testing 2D Functions of Module Matrix")
print("NumPy version", np.__version__)
print()
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(bool(result.errors + result.failures))
| #!/usr/bin/env python3
import sys
import unittest
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
import Matrix
######################################################################
class MatrixTestCase(unittest.TestCase):
def __init__(self, methodName="runTests"):
unittest.TestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
# Test (type IN_ARRAY2[ANY][ANY]) typemap
def testDet(self):
"Test det function"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
det = Matrix.__dict__[self.typeStr + "Det"]
matrix = [[8, 7], [6, 9]]
self.assertEqual(det(matrix), 30)
# Test (type IN_ARRAY2[ANY][ANY]) typemap
def testDetBadList(self):
"Test det function with bad list"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
det = Matrix.__dict__[self.typeStr + "Det"]
matrix = [[8, 7], ["e", "pi"]]
self.assertRaises(BadListError, det, matrix)
# Test (type IN_ARRAY2[ANY][ANY]) typemap
def testDetWrongDim(self):
"Test det function with wrong dimensions"
| [] | numpy/numpy | tools/swig/test/testMatrix.py |
#!/usr/bin/env python3
import sys
import unittest
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
import Fortran
######################################################################
class FortranTestCase(unittest.TestCase):
def __init__(self, methodName="runTests"):
unittest.TestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
# Test (type* IN_FARRAY2, int DIM1, int DIM2) typemap
def testSecondElementFortran(self):
"Test Fortran matrix initialized from reshaped NumPy fortranarray"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
second = Fortran.__dict__[self.typeStr + "SecondElement"]
matrix = np.asfortranarray(np.arange(9).reshape(3, 3),
self.typeCode)
self.assertEqual(second(matrix), 3)
def testSecondElementObject(self):
"Test Fortran matrix initialized from nested list fortranarray"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
second = Fortran.__dict__[self.typeStr + "SecondElement"]
matrix = np.asfortranarray([[0, 1, 2], [3, 4, 5], [6, 7, 8]], self.typeCode)
self.assertEqual(second(matrix), 3)
######################################################################
class scharTestCase(FortranTestCase):
def __init__(self, methodName="runTest"):
FortranTestCase.__init__(self, methodName)
self.typeStr = "schar"
self.typeCode = "b"
######################################################################
class ucharTestCase(FortranTestCase):
def __init__(self, methodName="runTest"):
FortranTestCase.__init__(self, methodName)
self.typeStr = "uchar"
self.typeCode = "B"
######################################################################
class shortTestCase(FortranTestCase):
def __init__(self, methodName="runTest"):
FortranTestCase.__init__(self, methodName)
self.typeStr = "short"
self.typeCode = "h"
######################################################################
class ushortTestCase(FortranTestCase):
def __init__(self, methodName="runTest"):
FortranTestCase.__init__(self, methodName)
self.typeStr = "ushort"
self.typeCode = "H"
######################################################################
class intTestCase(FortranTestCase):
def __init__(self, methodName="runTest"):
FortranTestCase.__init__(self, methodName)
self.typeStr = "int"
self.typeCode = "i"
######################################################################
class uintTestCase(FortranTestCase):
def __init__(self, methodName="runTest"):
FortranTestCase.__init__(self, methodName)
self.typeStr = "uint"
self.typeCode = "I"
######################################################################
class longTestCase(FortranTestCase):
def __init__(self, methodName="runTest"):
FortranTestCase.__init__(self, methodName)
self.typeStr = "long"
self.typeCode = "l"
######################################################################
class ulongTestCase(FortranTestCase):
def __init__(self, methodName="runTest"):
FortranTestCase.__init__(self, methodName)
self.typeStr = "ulong"
self.typeCode = "L"
######################################################################
class longLongTestCase(FortranTestCase):
def __init__(self, methodName="runTest"):
FortranTestCase.__init__(self, methodName)
self.typeStr = "longLong"
self.typeCode = "q"
######################################################################
class ulongLongTestCase(FortranTestCase):
def __init__(self, methodName="runTest"):
FortranTestCase.__init__(self, methodName)
self.typeStr = "ulongLong"
self.typeCode = "Q"
######################################################################
class floatTestCase(FortranTestCase):
def __init__(self, methodName="runTest"):
FortranTestCase.__init__(self, methodName)
self.typeStr = "float"
self.typeCode = "f"
######################################################################
class doubleTestCase(FortranTestCase):
def __init__(self, methodName="runTest"):
FortranTestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
######################################################################
if __name__ == "__main__":
# Build the test suite
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( scharTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ucharTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( shortTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ushortTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( intTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( uintTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( longTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ulongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( longLongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(ulongLongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( floatTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( doubleTestCase))
# Execute the test suite
print("Testing 2D Functions of Module Matrix")
print("NumPy version", np.__version__)
print()
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(bool(result.errors + result.failures))
| #!/usr/bin/env python3
import sys
import unittest
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
import Fortran
######################################################################
class FortranTestCase(unittest.TestCase):
def __init__(self, methodName="runTests"):
unittest.TestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
# Test (type* IN_FARRAY2, int DIM1, int DIM2) typemap
def testSecondElementFortran(self):
"Test Fortran matrix initialized from reshaped NumPy fortranarray"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
second = Fortran.__dict__[self.typeStr + "SecondElement"]
matrix = np.asfortranarray(np.arange(9).reshape(3, 3),
self.typeCode)
self.assertEqual(second(matrix), 3)
def testSecondElementObject(self):
"Test Fortran matrix initialized from nested list fortranarray"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
second = Fortran.__dict__[self.typeStr + "SecondElement"]
matrix = np.asfortranarray([[0, 1, 2], [3, 4, 5], | [] | numpy/numpy | tools/swig/test/testFortran.py |
#!/usr/bin/env python3
import struct
import sys
import unittest
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
import Flat
######################################################################
class FlatTestCase(unittest.TestCase):
def __init__(self, methodName="runTest"):
unittest.TestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
# Test the (type* INPLACE_ARRAY_FLAT, int DIM_FLAT) typemap
def testProcess1D(self):
"Test Process function 1D array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
process = Flat.__dict__[self.typeStr + "Process"]
pack_output = b''
for i in range(10):
pack_output += struct.pack(self.typeCode, i)
x = np.frombuffer(pack_output, dtype=self.typeCode)
y = x.copy()
process(y)
self.assertEqual(np.all((x + 1) == y), True)
def testProcess3D(self):
"Test Process function 3D array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
process = Flat.__dict__[self.typeStr + "Process"]
pack_output = b''
for i in range(24):
pack_output += struct.pack(self.typeCode, i)
x = np.frombuffer(pack_output, dtype=self.typeCode)
x = x.reshape((2, 3, 4))
y = x.copy()
process(y)
self.assertEqual(np.all((x + 1) == y), True)
def testProcess3DTranspose(self):
"Test Process function 3D array, FORTRAN order"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
process = Flat.__dict__[self.typeStr + "Process"]
pack_output = b''
for i in range(24):
pack_output += struct.pack(self.typeCode, i)
x = np.frombuffer(pack_output, dtype=self.typeCode)
x = x.reshape((2, 3, 4))
y = x.copy()
process(y.T)
self.assertEqual(np.all((x.T + 1) == y.T), True)
def testProcessNoncontiguous(self):
"Test Process function with non-contiguous array, which should raise an error"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
process = Flat.__dict__[self.typeStr + "Process"]
pack_output = b''
for i in range(24):
pack_output += struct.pack(self.typeCode, i)
x = np.frombuffer(pack_output, dtype=self.typeCode)
x = x.reshape((2, 3, 4))
self.assertRaises(TypeError, process, x[:, :, 0])
######################################################################
class scharTestCase(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "schar"
self.typeCode = "b"
######################################################################
class ucharTestCase(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "uchar"
self.typeCode = "B"
######################################################################
class shortTestCase(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "short"
self.typeCode = "h"
######################################################################
class ushortTestCase(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "ushort"
self.typeCode = "H"
######################################################################
class intTestCase(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "int"
self.typeCode = "i"
######################################################################
class uintTestCase(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "uint"
self.typeCode = "I"
######################################################################
class longTestCase(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "long"
self.typeCode = "l"
######################################################################
class ulongTestCase(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "ulong"
self.typeCode = "L"
######################################################################
class longLongTestCase(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "longLong"
self.typeCode = "q"
######################################################################
class ulongLongTestCase(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "ulongLong"
self.typeCode = "Q"
######################################################################
class floatTestCase(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "float"
self.typeCode = "f"
######################################################################
class doubleTestCase(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
######################################################################
if __name__ == "__main__":
# Build the test suite
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( scharTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ucharTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( shortTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ushortTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( intTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( uintTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( longTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( ulongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( longLongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(ulongLongTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( floatTestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase( doubleTestCase))
# Execute the test suite
print("Testing 1D Functions of Module Flat")
print("NumPy version", np.__version__)
print()
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(bool(result.errors + result.failures))
| #!/usr/bin/env python3
import struct
import sys
import unittest
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
import Flat
######################################################################
class FlatTestCase(unittest.TestCase):
def __init__(self, methodName="runTest"):
unittest.TestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
# Test the (type* INPLACE_ARRAY_FLAT, int DIM_FLAT) typemap
def testProcess1D(self):
"Test Process function 1D array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
process = Flat.__dict__[self.typeStr + "Process"]
pack_output = b''
for i in range(10):
pack_output += struct.pack(self.typeCode, i)
x = np.frombuffer(pack_output, dtype=self.typeCode)
y = x.copy()
process(y)
self.assertEqual(np.all((x + 1) == y), True)
def testProcess3D(self):
"Test Process function 3D array"
print(self.typeStr, "... ", end=' ', file=sys.stderr)
process = Flat.__dict__[self.typeStr + "Process"]
| [] | numpy/numpy | tools/swig/test/testFlat.py |
#!/usr/bin/env python3
import os
import sys
import unittest
from distutils.util import get_platform
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
# Add the distutils-generated build directory to the python search path and then
# import the extension module
libDir = f"lib.{get_platform()}-{sys.version_info[0]}.{sys.version_info[1]}"
sys.path.insert(0, os.path.join("build", libDir))
import Farray
######################################################################
class FarrayTestCase(unittest.TestCase):
def setUp(self):
self.nrows = 5
self.ncols = 4
self.array = Farray.Farray(self.nrows, self.ncols)
def testConstructor1(self):
"Test Farray size constructor"
self.assertTrue(isinstance(self.array, Farray.Farray))
def testConstructor2(self):
"Test Farray copy constructor"
for i in range(self.nrows):
for j in range(self.ncols):
self.array[i, j] = i + j
arrayCopy = Farray.Farray(self.array)
self.assertTrue(arrayCopy == self.array)
def testConstructorBad1(self):
"Test Farray size constructor, negative nrows"
self.assertRaises(ValueError, Farray.Farray, -4, 4)
def testConstructorBad2(self):
"Test Farray size constructor, negative ncols"
self.assertRaises(ValueError, Farray.Farray, 4, -4)
def testNrows(self):
"Test Farray nrows method"
self.assertTrue(self.array.nrows() == self.nrows)
def testNcols(self):
"Test Farray ncols method"
self.assertTrue(self.array.ncols() == self.ncols)
def testLen(self):
"Test Farray __len__ method"
self.assertTrue(len(self.array) == self.nrows * self.ncols)
def testSetGet(self):
"Test Farray __setitem__, __getitem__ methods"
m = self.nrows
n = self.ncols
for i in range(m):
for j in range(n):
self.array[i, j] = i * j
for i in range(m):
for j in range(n):
self.assertTrue(self.array[i, j] == i * j)
def testSetBad1(self):
"Test Farray __setitem__ method, negative row"
self.assertRaises(IndexError, self.array.__setitem__, (-1, 3), 0)
def testSetBad2(self):
"Test Farray __setitem__ method, negative col"
self.assertRaises(IndexError, self.array.__setitem__, (1, -3), 0)
def testSetBad3(self):
"Test Farray __setitem__ method, out-of-range row"
self.assertRaises(IndexError, self.array.__setitem__, (self.nrows + 1, 0), 0)
def testSetBad4(self):
"Test Farray __setitem__ method, out-of-range col"
self.assertRaises(IndexError, self.array.__setitem__, (0, self.ncols + 1), 0)
def testGetBad1(self):
"Test Farray __getitem__ method, negative row"
self.assertRaises(IndexError, self.array.__getitem__, (-1, 3))
def testGetBad2(self):
"Test Farray __getitem__ method, negative col"
self.assertRaises(IndexError, self.array.__getitem__, (1, -3))
def testGetBad3(self):
"Test Farray __getitem__ method, out-of-range row"
self.assertRaises(IndexError, self.array.__getitem__, (self.nrows + 1, 0))
def testGetBad4(self):
"Test Farray __getitem__ method, out-of-range col"
self.assertRaises(IndexError, self.array.__getitem__, (0, self.ncols + 1))
def testAsString(self):
"Test Farray asString method"
result = """\
[ [ 0, 1, 2, 3 ],
[ 1, 2, 3, 4 ],
[ 2, 3, 4, 5 ],
[ 3, 4, 5, 6 ],
[ 4, 5, 6, 7 ] ]
"""
for i in range(self.nrows):
for j in range(self.ncols):
self.array[i, j] = i + j
self.assertTrue(self.array.asString() == result)
def testStr(self):
"Test Farray __str__ method"
result = """\
[ [ 0, -1, -2, -3 ],
[ 1, 0, -1, -2 ],
[ 2, 1, 0, -1 ],
[ 3, 2, 1, 0 ],
[ 4, 3, 2, 1 ] ]
"""
for i in range(self.nrows):
for j in range(self.ncols):
self.array[i, j] = i - j
self.assertTrue(str(self.array) == result)
def testView(self):
"Test Farray view method"
for i in range(self.nrows):
for j in range(self.ncols):
self.array[i, j] = i + j
a = self.array.view()
self.assertTrue(isinstance(a, np.ndarray))
self.assertTrue(a.flags.f_contiguous)
for i in range(self.nrows):
for j in range(self.ncols):
self.assertTrue(a[i, j] == i + j)
######################################################################
if __name__ == "__main__":
# Build the test suite
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(FarrayTestCase))
# Execute the test suite
print("Testing Classes of Module Farray")
print("NumPy version", np.__version__)
print()
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(bool(result.errors + result.failures))
| #!/usr/bin/env python3
import os
import sys
import unittest
from distutils.util import get_platform
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
# Add the distutils-generated build directory to the python search path and then
# import the extension module
libDir = f"lib.{get_platform()}-{sys.version_info[0]}.{sys.version_info[1]}"
sys.path.insert(0, os.path.join("build", libDir))
import Farray
######################################################################
class FarrayTestCase(unittest.TestCase):
def setUp(self):
self.nrows = 5
self.ncols = 4
self.array = Farray.Farray(self.nrows, self.ncols)
def testConstructor1(self):
"Test Farray size constructor"
self.assertTrue(isinstance(self.array, Farray.Farray))
def testConstructor2(self):
"Test Farray copy constructor"
for i in range(self.nrows):
for j in range(self.ncols):
self.array[i, j] = i + j
arrayCopy = Farray.Farray(self.array)
self.assertTrue(arrayCopy == self.array)
def testConstructorBad1(self):
"Test Farray size constructor, negative nrows"
self.assertRaises(ValueError, Farray.Farray, - | [] | numpy/numpy | tools/swig/test/testFarray.py |
#!/usr/bin/env python3
import sys
import unittest
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
import Array
######################################################################
class Array1TestCase(unittest.TestCase):
def setUp(self):
self.length = 5
self.array1 = Array.Array1(self.length)
def testConstructor0(self):
"Test Array1 default constructor"
a = Array.Array1()
self.assertTrue(isinstance(a, Array.Array1))
self.assertTrue(len(a) == 0)
def testConstructor1(self):
"Test Array1 length constructor"
self.assertTrue(isinstance(self.array1, Array.Array1))
def testConstructor2(self):
"Test Array1 array constructor"
na = np.arange(self.length)
aa = Array.Array1(na)
self.assertTrue(isinstance(aa, Array.Array1))
def testConstructor3(self):
"Test Array1 copy constructor"
for i in range(self.array1.length()):
self.array1[i] = i
arrayCopy = Array.Array1(self.array1)
self.assertTrue(arrayCopy == self.array1)
def testConstructorBad(self):
"Test Array1 length constructor, negative"
self.assertRaises(ValueError, Array.Array1, -4)
def testLength(self):
"Test Array1 length method"
self.assertTrue(self.array1.length() == self.length)
def testLen(self):
"Test Array1 __len__ method"
self.assertTrue(len(self.array1) == self.length)
def testResize0(self):
"Test Array1 resize method, length"
newLen = 2 * self.length
self.array1.resize(newLen)
self.assertTrue(len(self.array1) == newLen)
def testResize1(self):
"Test Array1 resize method, array"
a = np.zeros((2 * self.length,), dtype='l')
self.array1.resize(a)
self.assertTrue(len(self.array1) == a.size)
def testResizeBad(self):
"Test Array1 resize method, negative length"
self.assertRaises(ValueError, self.array1.resize, -5)
def testSetGet(self):
"Test Array1 __setitem__, __getitem__ methods"
n = self.length
for i in range(n):
self.array1[i] = i * i
for i in range(n):
self.assertTrue(self.array1[i] == i * i)
def testSetBad1(self):
"Test Array1 __setitem__ method, negative index"
self.assertRaises(IndexError, self.array1.__setitem__, -1, 0)
def testSetBad2(self):
"Test Array1 __setitem__ method, out-of-range index"
self.assertRaises(IndexError, self.array1.__setitem__, self.length + 1, 0)
def testGetBad1(self):
"Test Array1 __getitem__ method, negative index"
self.assertRaises(IndexError, self.array1.__getitem__, -1)
def testGetBad2(self):
"Test Array1 __getitem__ method, out-of-range index"
self.assertRaises(IndexError, self.array1.__getitem__, self.length + 1)
def testAsString(self):
"Test Array1 asString method"
for i in range(self.array1.length()):
self.array1[i] = i + 1
self.assertTrue(self.array1.asString() == "[ 1, 2, 3, 4, 5 ]")
def testStr(self):
"Test Array1 __str__ method"
for i in range(self.array1.length()):
self.array1[i] = i - 2
self.assertTrue(str(self.array1) == "[ -2, -1, 0, 1, 2 ]")
def testView(self):
"Test Array1 view method"
for i in range(self.array1.length()):
self.array1[i] = i + 1
a = self.array1.view()
self.assertTrue(isinstance(a, np.ndarray))
self.assertTrue(len(a) == self.length)
self.assertTrue((a == [1, 2, 3, 4, 5]).all())
######################################################################
class Array2TestCase(unittest.TestCase):
def setUp(self):
self.nrows = 5
self.ncols = 4
self.array2 = Array.Array2(self.nrows, self.ncols)
def testConstructor0(self):
"Test Array2 default constructor"
a = Array.Array2()
self.assertTrue(isinstance(a, Array.Array2))
self.assertTrue(len(a) == 0)
def testConstructor1(self):
"Test Array2 nrows, ncols constructor"
self.assertTrue(isinstance(self.array2, Array.Array2))
def testConstructor2(self):
"Test Array2 array constructor"
na = np.zeros((3, 4), dtype="l")
aa = Array.Array2(na)
self.assertTrue(isinstance(aa, Array.Array2))
def testConstructor3(self):
"Test Array2 copy constructor"
for i in range(self.nrows):
for j in range(self.ncols):
self.array2[i][j] = i * j
arrayCopy = Array.Array2(self.array2)
self.assertTrue(arrayCopy == self.array2)
def testConstructorBad1(self):
"Test Array2 nrows, ncols constructor, negative nrows"
self.assertRaises(ValueError, Array.Array2, -4, 4)
def testConstructorBad2(self):
"Test Array2 nrows, ncols constructor, negative ncols"
self.assertRaises(ValueError, Array.Array2, 4, -4)
def testNrows(self):
"Test Array2 nrows method"
self.assertTrue(self.array2.nrows() == self.nrows)
def testNcols(self):
"Test Array2 ncols method"
self.assertTrue(self.array2.ncols() == self.ncols)
def testLen(self):
"Test Array2 __len__ method"
self.assertTrue(len(self.array2) == self.nrows * self.ncols)
def testResize0(self):
"Test Array2 resize method, size"
newRows = 2 * self.nrows
newCols = 2 * self.ncols
self.array2.resize(newRows, newCols)
self.assertTrue(len(self.array2) == newRows * newCols)
def testResize1(self):
"Test Array2 resize method, array"
a = np.zeros((2 * self.nrows, 2 * self.ncols), dtype='l')
self.array2.resize(a)
self.assertTrue(len(self.array2) == a.size)
def testResizeBad1(self):
"Test Array2 resize method, negative nrows"
self.assertRaises(ValueError, self.array2.resize, -5, 5)
def testResizeBad2(self):
"Test Array2 resize method, negative ncols"
self.assertRaises(ValueError, self.array2.resize, 5, -5)
def testSetGet1(self):
"Test Array2 __setitem__, __getitem__ methods"
m = self.nrows
n = self.ncols
array1 = []
a = np.arange(n, dtype="l")
for i in range(m):
array1.append(Array.Array1(i * a))
for i in range(m):
self.array2[i] = array1[i]
for i in range(m):
self.assertTrue(self.array2[i] == array1[i])
def testSetGet2(self):
"Test Array2 chained __setitem__, __getitem__ methods"
m = self.nrows
n = self.ncols
for i in range(m):
for j in range(n):
self.array2[i][j] = i * j
for i in range(m):
for j in range(n):
self.assertTrue(self.array2[i][j] == i * j)
def testSetBad1(self):
"Test Array2 __setitem__ method, negative index"
a = Array.Array1(self.ncols)
self.assertRaises(IndexError, self.array2.__setitem__, -1, a)
def testSetBad2(self):
"Test Array2 __setitem__ method, out-of-range index"
a = Array.Array1(self.ncols)
self.assertRaises(IndexError, self.array2.__setitem__, self.nrows + 1, a)
def testGetBad1(self):
"Test Array2 __getitem__ method, negative index"
self.assertRaises(IndexError, self.array2.__getitem__, -1)
def testGetBad2(self):
"Test Array2 __getitem__ method, out-of-range index"
self.assertRaises(IndexError, self.array2.__getitem__, self.nrows + 1)
def testAsString(self):
"Test Array2 asString method"
result = """\
[ [ 0, 1, 2, 3 ],
[ 1, 2, 3, 4 ],
[ 2, 3, 4, 5 ],
[ 3, 4, 5, 6 ],
[ 4, 5, 6, 7 ] ]
"""
for i in range(self.nrows):
for j in range(self.ncols):
self.array2[i][j] = i + j
self.assertTrue(self.array2.asString() == result)
def testStr(self):
"Test Array2 __str__ method"
result = """\
[ [ 0, -1, -2, -3 ],
[ 1, 0, -1, -2 ],
[ 2, 1, 0, -1 ],
[ 3, 2, 1, 0 ],
[ 4, 3, 2, 1 ] ]
"""
for i in range(self.nrows):
for j in range(self.ncols):
self.array2[i][j] = i - j
self.assertTrue(str(self.array2) == result)
def testView(self):
"Test Array2 view method"
a = self.array2.view()
self.assertTrue(isinstance(a, np.ndarray))
self.assertTrue(len(a) == self.nrows)
######################################################################
class ArrayZTestCase(unittest.TestCase):
def setUp(self):
self.length = 5
self.array3 = Array.ArrayZ(self.length)
def testConstructor0(self):
"Test ArrayZ default constructor"
a = Array.ArrayZ()
self.assertTrue(isinstance(a, Array.ArrayZ))
self.assertTrue(len(a) == 0)
def testConstructor1(self):
"Test ArrayZ length constructor"
self.assertTrue(isinstance(self.array3, Array.ArrayZ))
def testConstructor2(self):
"Test ArrayZ array constructor"
na = np.arange(self.length, dtype=np.complex128)
aa = Array.ArrayZ(na)
self.assertTrue(isinstance(aa, Array.ArrayZ))
def testConstructor3(self):
"Test ArrayZ copy constructor"
for i in range(self.array3.length()):
self.array3[i] = complex(i, -i)
arrayCopy = Array.ArrayZ(self.array3)
self.assertTrue(arrayCopy == self.array3)
def testConstructorBad(self):
"Test ArrayZ length constructor, negative"
self.assertRaises(ValueError, Array.ArrayZ, -4)
def testLength(self):
"Test ArrayZ length method"
self.assertTrue(self.array3.length() == self.length)
def testLen(self):
"Test ArrayZ __len__ method"
self.assertTrue(len(self.array3) == self.length)
def testResize0(self):
"Test ArrayZ resize method, length"
newLen = 2 * self.length
self.array3.resize(newLen)
self.assertTrue(len(self.array3) == newLen)
def testResize1(self):
"Test ArrayZ resize method, array"
a = np.zeros((2 * self.length,), dtype=np.complex128)
self.array3.resize(a)
self.assertTrue(len(self.array3) == a.size)
def testResizeBad(self):
"Test ArrayZ resize method, negative length"
self.assertRaises(ValueError, self.array3.resize, -5)
def testSetGet(self):
"Test ArrayZ __setitem__, __getitem__ methods"
n = self.length
for i in range(n):
self.array3[i] = i * i
for i in range(n):
self.assertTrue(self.array3[i] == i * i)
def testSetBad1(self):
"Test ArrayZ __setitem__ method, negative index"
self.assertRaises(IndexError, self.array3.__setitem__, -1, 0)
def testSetBad2(self):
"Test ArrayZ __setitem__ method, out-of-range index"
self.assertRaises(IndexError, self.array3.__setitem__, self.length + 1, 0)
def testGetBad1(self):
"Test ArrayZ __getitem__ method, negative index"
self.assertRaises(IndexError, self.array3.__getitem__, -1)
def testGetBad2(self):
"Test ArrayZ __getitem__ method, out-of-range index"
self.assertRaises(IndexError, self.array3.__getitem__, self.length + 1)
def testAsString(self):
"Test ArrayZ asString method"
for i in range(self.array3.length()):
self.array3[i] = complex(i + 1, -i - 1)
self.assertTrue(self.array3.asString() ==
"[ (1,-1), (2,-2), (3,-3), (4,-4), (5,-5) ]")
def testStr(self):
"Test ArrayZ __str__ method"
for i in range(self.array3.length()):
self.array3[i] = complex(i - 2, (i - 2) * 2)
self.assertTrue(str(self.array3) == "[ (-2,-4), (-1,-2), (0,0), (1,2), (2,4) ]")
def testView(self):
"Test ArrayZ view method"
for i in range(self.array3.length()):
self.array3[i] = complex(i + 1, i + 2)
a = self.array3.view()
self.assertTrue(isinstance(a, np.ndarray))
self.assertTrue(len(a) == self.length)
self.assertTrue((a == [1 + 2j, 2 + 3j, 3 + 4j, 4 + 5j, 5 + 6j]).all())
######################################################################
if __name__ == "__main__":
# Build the test suite
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(Array1TestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(Array2TestCase))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(ArrayZTestCase))
# Execute the test suite
print("Testing Classes of Module Array")
print("NumPy version", np.__version__)
print()
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(bool(result.errors + result.failures))
| #!/usr/bin/env python3
import sys
import unittest
import numpy as np
major, minor = [int(d) for d in np.__version__.split(".")[:2]]
if major == 0:
BadListError = TypeError
else:
BadListError = ValueError
import Array
######################################################################
class Array1TestCase(unittest.TestCase):
def setUp(self):
self.length = 5
self.array1 = Array.Array1(self.length)
def testConstructor0(self):
"Test Array1 default constructor"
a = Array.Array1()
self.assertTrue(isinstance(a, Array.Array1))
self.assertTrue(len(a) == 0)
def testConstructor1(self):
"Test Array1 length constructor"
self.assertTrue(isinstance(self.array1, Array.Array1))
def testConstructor2(self):
"Test Array1 array constructor"
na = np.arange(self.length)
aa = Array.Array1(na)
self.assertTrue(isinstance(aa, Array.Array1))
def testConstructor3(self):
"Test Array1 copy constructor"
for i in range(self.array1.length()):
self.array1[i] = i
arrayCopy = Array.Array1(self.array1)
self.assertTrue(arrayCopy == self.array1)
def testConstructorBad(self):
"Test Array1 length constructor | [] | numpy/numpy | tools/swig/test/testArray.py |
#!/usr/bin/env python3
from distutils.core import Extension, setup
import numpy
# Obtain the numpy include directory.
numpy_include = numpy.get_include()
# Array extension module
_Array = Extension("_Array",
["Array_wrap.cxx",
"Array1.cxx",
"Array2.cxx",
"ArrayZ.cxx"],
include_dirs=[numpy_include],
)
# Farray extension module
_Farray = Extension("_Farray",
["Farray_wrap.cxx",
"Farray.cxx"],
include_dirs=[numpy_include],
)
# _Vector extension module
_Vector = Extension("_Vector",
["Vector_wrap.cxx",
"Vector.cxx"],
include_dirs=[numpy_include],
)
# _Matrix extension module
_Matrix = Extension("_Matrix",
["Matrix_wrap.cxx",
"Matrix.cxx"],
include_dirs=[numpy_include],
)
# _Tensor extension module
_Tensor = Extension("_Tensor",
["Tensor_wrap.cxx",
"Tensor.cxx"],
include_dirs=[numpy_include],
)
_Fortran = Extension("_Fortran",
["Fortran_wrap.cxx",
"Fortran.cxx"],
include_dirs=[numpy_include],
)
_Flat = Extension("_Flat",
["Flat_wrap.cxx",
"Flat.cxx"],
include_dirs=[numpy_include],
)
# NumyTypemapTests setup
setup(name="NumpyTypemapTests",
description="Functions that work on arrays",
author="Bill Spotz",
py_modules=["Array", "Farray", "Vector", "Matrix", "Tensor",
"Fortran", "Flat"],
ext_modules=[_Array, _Farray, _Vector, _Matrix, _Tensor,
_Fortran, _Flat]
)
| #!/usr/bin/env python3
from distutils.core import Extension, setup
import numpy
# Obtain the numpy include directory.
numpy_include = numpy.get_include()
# Array extension module
_Array = Extension("_Array",
["Array_wrap.cxx",
"Array1.cxx",
"Array2.cxx",
"ArrayZ.cxx"],
include_dirs=[numpy_include],
)
# Farray extension module
_Farray = Extension("_Farray",
["Farray_wrap.cxx",
"Farray.cxx"],
include_dirs=[numpy_include],
)
# _Vector extension module
_Vector = Extension("_Vector",
["Vector_wrap.cxx",
"Vector.cxx"],
include_dirs=[numpy_include],
)
# _Matrix extension module
_Matrix = Extension("_Matrix",
["Matrix_wrap.cxx", | [] | numpy/numpy | tools/swig/test/setup.py |
#!/usr/bin/env python3
"""
refguide_check.py [OPTIONS] [-- ARGS]
- Check for a NumPy submodule whether the objects in its __all__ dict
correspond to the objects included in the reference guide.
- Check docstring examples
- Check example blocks in RST files
Example of usage::
$ python tools/refguide_check.py
Note that this is a helper script to be able to check if things are missing;
the output of this script does need to be checked manually. In some cases
objects are left out of the refguide for a good reason (it's an alias of
another function, or deprecated, or ...)
Another use of this helper script is to check validity of code samples
in docstrings::
$ python tools/refguide_check.py --doctests ma
or in RST-based documentations::
$ python tools/refguide_check.py --rst doc/source
"""
import copy
import inspect
import io
import os
import re
import sys
import warnings
from argparse import ArgumentParser
import docutils.core
from docutils.parsers.rst import directives
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'doc', 'sphinxext'))
from numpydoc.docscrape_sphinx import get_doc_object
# Enable specific Sphinx directives
from sphinx.directives.other import Only, SeeAlso
directives.register_directive('seealso', SeeAlso)
directives.register_directive('only', Only)
BASE_MODULE = "numpy"
PUBLIC_SUBMODULES = [
"f2py",
"linalg",
"lib",
"lib.format",
"lib.mixins",
"lib.recfunctions",
"lib.scimath",
"lib.stride_tricks",
"lib.npyio",
"lib.introspect",
"lib.array_utils",
"fft",
"char",
"rec",
"ma",
"ma.extras",
"ma.mrecords",
"polynomial",
"polynomial.chebyshev",
"polynomial.hermite",
"polynomial.hermite_e",
"polynomial.laguerre",
"polynomial.legendre",
"polynomial.polynomial",
"matrixlib",
"random",
"strings",
"testing",
]
# Docs for these modules are included in the parent module
OTHER_MODULE_DOCS = {
'fftpack.convolve': 'fftpack',
'io.wavfile': 'io',
'io.arff': 'io',
}
# these names are not required to be present in ALL despite being in
# autosummary:: listing
REFGUIDE_ALL_SKIPLIST = [
r'scipy\.sparse\.linalg',
r'scipy\.spatial\.distance',
r'scipy\.linalg\.blas\.[sdczi].*',
r'scipy\.linalg\.lapack\.[sdczi].*',
]
# these names are not required to be in an autosummary:: listing
# despite being in ALL
REFGUIDE_AUTOSUMMARY_SKIPLIST = [
# NOTE: should NumPy have a better match between autosummary
# listings and __all__? For now, TR isn't convinced this is a
# priority -- focus on just getting docstrings executed / correct
r'numpy\.*',
]
def short_path(path, cwd=None):
"""
Return relative or absolute path name, whichever is shortest.
Parameters
----------
path : str or None
cwd : str or None
Returns
-------
str
Relative path or absolute path based on current working directory
"""
if not isinstance(path, str):
return path
if cwd is None:
cwd = os.getcwd()
abspath = os.path.abspath(path)
relpath = os.path.relpath(path, cwd)
if len(abspath) <= len(relpath):
return abspath
return relpath
def find_names(module, names_dict):
"""
Finds the occurrences of function names, special directives like data
and functions and scipy constants in the docstrings of `module`. The
following patterns are searched for:
* 3 spaces followed by function name, and maybe some spaces, some
dashes, and an explanation; only function names listed in
refguide are formatted like this (mostly, there may be some false
positives
* special directives, such as data and function
* (scipy.constants only): quoted list
The `names_dict` is updated by reference and accessible in calling method
Parameters
----------
module : ModuleType
The module, whose docstrings is to be searched
names_dict : dict
Dictionary which contains module name as key and a set of found
function names and directives as value
Returns
-------
None
"""
patterns = [
r"^\s\s\s([a-z_0-9A-Z]+)(\s+-+.*)?$",
r"^\.\. (?:data|function)::\s*([a-z_0-9A-Z]+)\s*$"
]
if module.__name__ == 'scipy.constants':
patterns += ["^``([a-z_0-9A-Z]+)``"]
patterns = [re.compile(pattern) for pattern in patterns]
module_name = module.__name__
for line in module.__doc__.splitlines():
res = re.search(r"^\s*\.\. (?:currentmodule|module):: ([a-z0-9A-Z_.]+)\s*$",
line)
if res:
module_name = res.group(1)
continue
for pattern in patterns:
res = re.match(pattern, line)
if res is not None:
name = res.group(1)
entry = f'{module_name}.{name}'
names_dict.setdefault(module_name, set()).add(name)
break
def get_all_dict(module):
"""
Return a copy of the __all__ dict with irrelevant items removed.
Parameters
----------
module : ModuleType
The module whose __all__ dict has to be processed
Returns
-------
deprecated : list
List of callable and deprecated sub modules
not_deprecated : list
List of non callable or non deprecated sub modules
others : list
List of remaining types of sub modules
"""
if hasattr(module, "__all__"):
all_dict = copy.deepcopy(module.__all__)
else:
all_dict = copy.deepcopy(dir(module))
all_dict = [name for name in all_dict
if not name.startswith("_")]
for name in ['absolute_import', 'division', 'print_function']:
try:
all_dict.remove(name)
except ValueError:
pass
if not all_dict:
# Must be a pure documentation module
all_dict.append('__doc__')
# Modules are almost always private; real submodules need a separate
# run of refguide_check.
all_dict = [name for name in all_dict
if not inspect.ismodule(getattr(module, name, None))]
deprecated = []
not_deprecated = []
for name in all_dict:
f = getattr(module, name, None)
if callable(f) and is_deprecated(f):
deprecated.append(name)
else:
not_deprecated.append(name)
others = set(dir(module)).difference(set(deprecated)).difference(set(not_deprecated)) # noqa: E501
return not_deprecated, deprecated, others
def compare(all_dict, others, names, module_name):
"""
Return sets of objects from all_dict.
Will return three sets:
{in module_name.__all__},
{in REFGUIDE*},
and {missing from others}
Parameters
----------
all_dict : list
List of non deprecated sub modules for module_name
others : list
List of sub modules for module_name
names : set
Set of function names or special directives present in
docstring of module_name
module_name : ModuleType
Returns
-------
only_all : set
only_ref : set
missing : set
"""
only_all = set()
for name in all_dict:
if name not in names:
for pat in REFGUIDE_AUTOSUMMARY_SKIPLIST:
if re.match(pat, module_name + '.' + name):
break
else:
only_all.add(name)
only_ref = set()
missing = set()
for name in names:
if name not in all_dict:
for pat in REFGUIDE_ALL_SKIPLIST:
if re.match(pat, module_name + '.' + name):
if name not in others:
missing.add(name)
break
else:
only_ref.add(name)
return only_all, only_ref, missing
def is_deprecated(f):
"""
Check if module `f` is deprecated
Parameters
----------
f : ModuleType
Returns
-------
bool
"""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("error")
try:
f(**{"not a kwarg": None})
except DeprecationWarning:
return True
except Exception:
pass
return False
def check_items(all_dict, names, deprecated, others, module_name, dots=True):
"""
Check that `all_dict` is consistent with the `names` in `module_name`
For instance, that there are no deprecated or extra objects.
Parameters
----------
all_dict : list
names : set
deprecated : list
others : list
module_name : ModuleType
dots : bool
Whether to print a dot for each check
Returns
-------
list
List of [(name, success_flag, output)...]
"""
num_all = len(all_dict)
num_ref = len(names)
output = ""
output += f"Non-deprecated objects in __all__: {num_all}\n"
output += f"Objects in refguide: {num_ref}\n\n"
only_all, only_ref, missing = compare(all_dict, others, names, module_name)
dep_in_ref = only_ref.intersection(deprecated)
only_ref = only_ref.difference(deprecated)
if len(dep_in_ref) > 0:
output += "Deprecated objects in refguide::\n\n"
for name in sorted(deprecated):
output += " " + name + "\n"
if len(only_all) == len(only_ref) == len(missing) == 0:
if dots:
output_dot('.')
return [(None, True, output)]
else:
if len(only_all) > 0:
output += f"ERROR: objects in {module_name}.__all__ but not in refguide::\n\n" # noqa: E501
for name in sorted(only_all):
output += " " + name + "\n"
output += "\nThis issue can be fixed by adding these objects to\n"
output += "the function listing in __init__.py for this module\n"
if len(only_ref) > 0:
output += f"ERROR: objects in refguide but not in {module_name}.__all__::\n\n" # noqa: E501
for name in sorted(only_ref):
output += " " + name + "\n"
output += "\nThis issue should likely be fixed by removing these objects\n"
output += "from the function listing in __init__.py for this module\n"
output += "or adding them to __all__.\n"
if len(missing) > 0:
output += "ERROR: missing objects::\n\n"
for name in sorted(missing):
output += " " + name + "\n"
if dots:
output_dot('F')
return [(None, False, output)]
def validate_rst_syntax(text, name, dots=True):
"""
Validates the doc string in a snippet of documentation
`text` from file `name`
Parameters
----------
text : str
Docstring text
name : str
File name for which the doc string is to be validated
dots : bool
Whether to print a dot symbol for each check
Returns
-------
(bool, str)
"""
if text is None:
if dots:
output_dot('E')
return False, f"ERROR: {name}: no documentation"
ok_unknown_items = {
'mod', 'doc', 'currentmodule', 'autosummary', 'data', 'attr',
'obj', 'versionadded', 'versionchanged', 'module', 'class',
'ref', 'func', 'toctree', 'moduleauthor', 'term', 'c:member',
'sectionauthor', 'codeauthor', 'eq', 'doi', 'DOI', 'arXiv', 'arxiv'
}
# Run through docutils
error_stream = io.StringIO()
def resolve(name, is_label=False):
return ("http://foo", name)
token = '<RST-VALIDATE-SYNTAX-CHECK>'
docutils.core.publish_doctree(
text, token,
settings_overrides={'halt_level': 5,
'traceback': True,
'default_reference_context': 'title-reference',
'default_role': 'emphasis',
'link_base': '',
'resolve_name': resolve,
'stylesheet_path': '',
'raw_enabled': 0,
'file_insertion_enabled': 0,
'warning_stream': error_stream})
# Print errors, disregarding unimportant ones
error_msg = error_stream.getvalue()
errors = error_msg.split(token)
success = True
output = ""
for error in errors:
lines = error.splitlines()
if not lines:
continue
m = re.match(r'.*Unknown (?:interpreted text role|directive type) "(.*)".*$', lines[0]) # noqa: E501
if m:
if m.group(1) in ok_unknown_items:
continue
m = re.match(r'.*Error in "math" directive:.*unknown option: "label"', " ".join(lines), re.S) # noqa: E501
if m:
continue
output += name + lines[0] + "::\n " + "\n ".join(lines[1:]).rstrip() + "\n" # noqa: E501
success = False
if not success:
output += " " + "-" * 72 + "\n"
for lineno, line in enumerate(text.splitlines()):
output += " %-4d %s\n" % (lineno + 1, line)
output += " " + "-" * 72 + "\n\n"
if dots:
output_dot('.' if success else 'F')
return success, output
def output_dot(msg='.', stream=sys.stderr):
stream.write(msg)
stream.flush()
def check_rest(module, names, dots=True):
"""
Check reStructuredText formatting of docstrings
Parameters
----------
module : ModuleType
names : set
Returns
-------
result : list
List of [(module_name, success_flag, output),...]
"""
skip_types = (dict, str, float, int)
results = []
if module.__name__[6:] not in OTHER_MODULE_DOCS:
results += [(module.__name__,) +
validate_rst_syntax(inspect.getdoc(module),
module.__name__, dots=dots)]
for name in names:
full_name = module.__name__ + '.' + name
obj = getattr(module, name, None)
if obj is None:
results.append((full_name, False, f"{full_name} has no docstring"))
continue
elif isinstance(obj, skip_types):
continue
if inspect.ismodule(obj):
text = inspect.getdoc(obj)
else:
try:
text = str(get_doc_object(obj))
except Exception:
import traceback
results.append((full_name, False,
"Error in docstring format!\n" +
traceback.format_exc()))
continue
m = re.search("([\x00-\x09\x0b-\x1f])", text)
if m:
msg = ("Docstring contains a non-printable character %r! "
"Maybe forgot r\"\"\"?" % (m.group(1),))
results.append((full_name, False, msg))
continue
try:
src_file = short_path(inspect.getsourcefile(obj))
except TypeError:
src_file = None
if src_file:
file_full_name = src_file + ':' + full_name
else:
file_full_name = full_name
results.append((full_name,) +
validate_rst_syntax(text, file_full_name, dots=dots))
return results
def main(argv):
"""
Validates the docstrings of all the pre decided set of
modules for errors and docstring standards.
"""
parser = ArgumentParser(usage=__doc__.lstrip())
parser.add_argument("module_names", metavar="SUBMODULES", default=[],
nargs='*', help="Submodules to check (default: all public)")
parser.add_argument("-v", "--verbose", action="count", default=0)
args = parser.parse_args(argv)
modules = []
names_dict = {}
if not args.module_names:
args.module_names = list(PUBLIC_SUBMODULES) + [BASE_MODULE]
module_names = args.module_names + [
OTHER_MODULE_DOCS[name]
for name in args.module_names
if name in OTHER_MODULE_DOCS
]
# remove duplicates while maintaining order
module_names = list(dict.fromkeys(module_names))
dots = True
success = True
results = []
errormsgs = []
for submodule_name in module_names:
prefix = BASE_MODULE + '.'
if not (
submodule_name.startswith(prefix) or
submodule_name == BASE_MODULE
):
module_name = prefix + submodule_name
else:
module_name = submodule_name
__import__(module_name)
module = sys.modules[module_name]
if submodule_name not in OTHER_MODULE_DOCS:
find_names(module, names_dict)
if submodule_name in args.module_names:
modules.append(module)
if modules:
print(f"Running checks for {len(modules)} modules:")
for module in modules:
if dots:
sys.stderr.write(module.__name__ + ' ')
sys.stderr.flush()
all_dict, deprecated, others = get_all_dict(module)
names = names_dict.get(module.__name__, set())
mod_results = []
mod_results += check_items(all_dict, names, deprecated, others,
module.__name__)
mod_results += check_rest(module, set(names).difference(deprecated),
dots=dots)
for v in mod_results:
assert isinstance(v, tuple), v
results.append((module, mod_results))
if dots:
sys.stderr.write('\n')
sys.stderr.flush()
# Report results
for module, mod_results in results:
success = all(x[1] for x in mod_results)
if not success:
errormsgs.append(f'failed checking {module.__name__}')
if success and args.verbose == 0:
continue
print("")
print("=" * len(module.__name__))
print(module.__name__)
print("=" * len(module.__name__))
print("")
for name, success, output in mod_results:
if name is None:
if not success or args.verbose >= 1:
print(output.strip())
print("")
elif not success or (args.verbose >= 2 and output.strip()):
print(name)
print("-" * len(name))
print("")
print(output.strip())
print("")
if len(errormsgs) == 0:
print("\nOK: all checks passed!")
sys.exit(0)
else:
print('\nERROR: ', '\n '.join(errormsgs))
sys.exit(1)
if __name__ == '__main__':
main(argv=sys.argv[1:])
| #!/usr/bin/env python3
"""
refguide_check.py [OPTIONS] [-- ARGS]
- Check for a NumPy submodule whether the objects in its __all__ dict
correspond to the objects included in the reference guide.
- Check docstring examples
- Check example blocks in RST files
Example of usage::
$ python tools/refguide_check.py
Note that this is a helper script to be able to check if things are missing;
the output of this script does need to be checked manually. In some cases
objects are left out of the refguide for a good reason (it's an alias of
another function, or deprecated, or ...)
Another use of this helper script is to check validity of code samples
in docstrings::
$ python tools/refguide_check.py --doctests ma
or in RST-based documentations::
$ python tools/refguide_check.py --rst doc/source
"""
import copy
import inspect
import io
import os
import re
import sys
import warnings
from argparse import ArgumentParser
import docutils.core
from docutils.parsers.rst import directives
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'doc', 'sphinxext'))
from numpydoc.docscrape_sphinx import get_doc_object
# Enable specific Sphinx directives
from sphinx.directives.other import Only, SeeAlso
directives.register_directive('seealso', SeeAlso)
directives.register_directive('only', Only)
BASE_MODULE = "numpy"
PUBLIC_SUBMODULES = [
"f2py",
"linalg",
"lib",
"lib.format",
"lib.mixins",
"lib.recfunctions",
"lib.scimath",
"lib.stride_tricks",
"lib.npyio",
" | [
"# sphinx-doc/sphinx:sphinx/directives/other.py\nOnly",
"# sphinx-doc/sphinx:sphinx/directives/admonitions.py\nSeeAlso"
] | numpy/numpy | tools/refguide_check.py |
"""
Run PyRight's `--verifytypes` and check that its reported type completeness is above
a minimum threshold.
Requires `basedpyright` to be installed in the environment.
Example usage:
spin run python tools/pyright_completeness.py --verifytypes numpy --ignoreexternal \
--exclude-like '*.tests.*' '*.conftest.*'
We use `--ignoreexternal` to avoid "partially unknown" reports coming from the stdlib
`numbers` module, see https://github.com/microsoft/pyright/discussions/9911.
"""
import argparse
import fnmatch
import json
import subprocess
import sys
from collections.abc import Sequence
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
"--exclude-like",
required=False,
nargs="*",
type=str,
help="Exclude symbols whose names matches this glob pattern",
)
args, unknownargs = parser.parse_known_args(argv)
pyright_args = list(unknownargs)
if "--outputjson" not in pyright_args:
pyright_args.append("--outputjson")
return run_pyright_with_coverage(pyright_args, args.exclude_like)
def run_pyright_with_coverage(
pyright_args: list[str],
exclude_like: Sequence[str],
) -> int:
result = subprocess.run(
["basedpyright", *pyright_args],
capture_output=True,
text=True,
)
try:
data = json.loads(result.stdout)
except json.decoder.JSONDecodeError:
sys.stdout.write(result.stdout)
sys.stderr.write(result.stderr)
return 1
if exclude_like:
symbols = data["typeCompleteness"]["symbols"]
matched_symbols = [
x
for x in symbols
if not any(fnmatch.fnmatch(x["name"], pattern) for pattern in exclude_like)
and x["isExported"]
]
covered = sum(x["isTypeKnown"] for x in matched_symbols) / len(matched_symbols)
else:
covered = data["typeCompleteness"]["completenessScore"]
sys.stderr.write(result.stderr)
if covered < 1:
sys.stdout.write(f"Coverage {covered:.1%} is below minimum required 100%\n")
return 1
sys.stdout.write("Coverage is at 100%\n")
return 0
if __name__ == "__main__":
sys.exit(main())
| """
Run PyRight's `--verifytypes` and check that its reported type completeness is above
a minimum threshold.
Requires `basedpyright` to be installed in the environment.
Example usage:
spin run python tools/pyright_completeness.py --verifytypes numpy --ignoreexternal \
--exclude-like '*.tests.*' '*.conftest.*'
We use `--ignoreexternal` to avoid "partially unknown" reports coming from the stdlib
`numbers` module, see https://github.com/microsoft/pyright/discussions/9911.
"""
import argparse
import fnmatch
import json
import subprocess
import sys
from collections.abc import Sequence
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
"--exclude-like",
required=False,
nargs="*",
type=str,
help="Exclude symbols whose names matches this glob pattern",
)
args, unknownargs = parser.parse_known_args(argv)
pyright_args = list(unknownargs)
if "--outputjson" not in pyright_args:
pyright_args.append("--outputjson")
return run_pyright_with_coverage(pyright_args, args.exclude_like)
def run_pyright_with_coverage(
pyright_args: list[str],
exclude_like: Sequence[str],
) -> int:
result = subprocess.run(
["basedpyright", *pyright_args],
capture_output=True,
text=True,
)
try:
data = json | [] | numpy/numpy | tools/pyright_completeness.py |
import os
import subprocess
import sys
from argparse import ArgumentParser
CWD = os.path.abspath(os.path.dirname(__file__))
class DiffLinter:
def __init__(self) -> None:
self.repository_root = os.path.realpath(os.path.join(CWD, ".."))
def run_ruff(self, fix: bool) -> tuple[int, str]:
"""
Original Author: Josh Wilson (@person142)
Source:
https://github.com/scipy/scipy/blob/main/tools/lint_diff.py
Unlike pycodestyle, ruff by itself is not capable of limiting
its output to the given diff.
"""
print("Running Ruff Check...")
command = ["ruff", "check"]
if fix:
command.append("--fix")
res = subprocess.run(
command,
stdout=subprocess.PIPE,
cwd=self.repository_root,
encoding="utf-8",
)
return res.returncode, res.stdout
def run_cython_lint(self) -> tuple[int, str]:
print("Running cython-lint...")
command = ["cython-lint", "--no-pycodestyle", "numpy"]
res = subprocess.run(
command,
stdout=subprocess.PIPE,
cwd=self.repository_root,
encoding="utf-8",
)
return res.returncode, res.stdout
def run_lint(self, fix: bool) -> None:
# Ruff Linter
retcode, ruff_errors = self.run_ruff(fix)
ruff_errors and print(ruff_errors)
if retcode:
sys.exit(retcode)
# C API Borrowed-ref Linter
retcode, c_API_errors = self.run_check_c_api()
c_API_errors and print(c_API_errors)
if retcode:
sys.exit(retcode)
# Cython Linter
retcode, cython_errors = self.run_cython_lint()
cython_errors and print(cython_errors)
sys.exit(retcode)
def run_check_c_api(self) -> tuple[int, str]:
"""Run C-API borrowed-ref checker"""
print("Running C API borrow-reference linter...")
borrowed_ref_script = os.path.join(
self.repository_root, "tools", "ci", "check_c_api_usage.py"
)
borrowed_res = subprocess.run(
[sys.executable, borrowed_ref_script],
cwd=self.repository_root,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
check=False,
)
# Exit with non-zero if C API Check fails
return borrowed_res.returncode, borrowed_res.stdout
if __name__ == "__main__":
parser = ArgumentParser()
args = parser.parse_args()
DiffLinter().run_lint(fix=False)
| import os
import subprocess
import sys
from argparse import ArgumentParser
CWD = os.path.abspath(os.path.dirname(__file__))
class DiffLinter:
def __init__(self) -> None:
self.repository_root = os.path.realpath(os.path.join(CWD, ".."))
def run_ruff(self, fix: bool) -> tuple[int, str]:
"""
Original Author: Josh Wilson (@person142)
Source:
https://github.com/scipy/scipy/blob/main/tools/lint_diff.py
Unlike pycodestyle, ruff by itself is not capable of limiting
its output to the given diff.
"""
print("Running Ruff Check...")
command = ["ruff", "check"]
if fix:
command.append("--fix")
res = subprocess.run(
command,
stdout=subprocess.PIPE,
cwd=self.repository_root,
encoding="utf-8",
)
return res.returncode, res.stdout
def run_cython_lint(self) -> tuple[int, str]:
print("Running cython-lint...")
command = ["cython-lint", "--no-pycodestyle", "numpy"]
res = subprocess.run(
| [] | numpy/numpy | tools/linter.py |
import glob
import os.path
def get_submodule_paths():
'''
Get paths to submodules so that we can exclude them from things like
check_test_name.py, check_unicode.py, etc.
'''
root_directory = os.path.dirname(os.path.dirname(__file__))
gitmodule_file = os.path.join(root_directory, '.gitmodules')
with open(gitmodule_file) as gitmodules:
data = gitmodules.read().split('\n')
submodule_paths = [datum.split(' = ')[1] for datum in data if
datum.startswith('\tpath = ')]
submodule_paths = [os.path.join(root_directory, path) for path in
submodule_paths]
# vendored with a script rather than via gitmodules
with open(
os.path.join(root_directory, ".gitattributes"), "r"
) as attr_file:
for line in attr_file:
if "vendored" in line:
pattern = line.split(" ", 1)[0]
submodule_paths.extend(glob.glob(pattern))
return submodule_paths
if __name__ == "__main__":
print('\n'.join(get_submodule_paths()))
| import glob
import os.path
def get_submodule_paths():
'''
Get paths to submodules so that we can exclude them from things like
check_test_name.py, check_unicode.py, etc.
'''
root_directory = os.path.dirname(os.path.dirname(__file__))
gitmodule_file = os.path.join(root_directory, '.gitmodules')
with open(gitmodule_file) as gitmodules:
data = gitmodules.read().split('\n')
submodule_paths = [datum.split(' = ')[1] for datum in data if
datum.startswith('\tpath = ')]
submodule_paths = [os.path.join(root_directory, path) for path in
submodule_paths]
# vendored with a script rather than via gitmodules
with open(
os.path.join(root_directory, ".gitattributes"), "r"
) as attr_file:
for line in attr_file:
if "vendored" in line:
pattern = line.split(" ", 1)[0]
submodule_paths.extend(glob.glob(pattern))
return submodule_paths
if __name__ == "__main__":
print('\n'.join(get_submodule_paths()))
| [] | numpy/numpy | tools/get_submodule_paths.py |
#!/usr/bin/env python
"""Find the functions in a module missing type annotations.
To use it run
./functions_missing_types.py <module>
and it will print out a list of functions in the module that don't
have types.
"""
import argparse
import ast
import importlib
import os
NUMPY_ROOT = os.path.dirname(os.path.join(
os.path.abspath(__file__), "..",
))
# Technically "public" functions (they don't start with an underscore)
# that we don't want to include.
EXCLUDE_LIST = {
"numpy": {
# Stdlib modules in the namespace by accident
"absolute_import",
"division",
"print_function",
"warnings",
"sys",
"os",
"math",
# Accidentally public, deprecated, or shouldn't be used
"Tester",
"_core",
"int_asbuffer",
"numarray",
"oldnumeric",
"test",
"typeDict",
# Builtins
"bool",
"complex",
"float",
"int",
"long",
"object",
"str",
"unicode",
# More standard names should be preferred
"alltrue", # all
"sometrue", # any
}
}
class FindAttributes(ast.NodeVisitor):
"""Find top-level attributes/functions/classes in stubs files.
Do this by walking the stubs ast. See e.g.
https://greentreesnakes.readthedocs.io/en/latest/index.html
for more information on working with Python's ast.
"""
def __init__(self):
self.attributes = set()
def visit_FunctionDef(self, node):
if node.name == "__getattr__":
# Not really a module member.
return
self.attributes.add(node.name)
# Do not call self.generic_visit; we are only interested in
# top-level functions.
return
def visit_ClassDef(self, node):
if not node.name.startswith("_"):
self.attributes.add(node.name)
def visit_AnnAssign(self, node):
self.attributes.add(node.target.id)
def find_missing(module_name):
module_path = os.path.join(
NUMPY_ROOT,
module_name.replace(".", os.sep),
"__init__.pyi",
)
module = importlib.import_module(module_name)
module_attributes = {
attribute for attribute in dir(module) if not attribute.startswith("_")
}
if os.path.isfile(module_path):
with open(module_path) as f:
tree = ast.parse(f.read())
ast_visitor = FindAttributes()
ast_visitor.visit(tree)
stubs_attributes = ast_visitor.attributes
else:
# No stubs for this module yet.
stubs_attributes = set()
exclude_list = EXCLUDE_LIST.get(module_name, set())
missing = module_attributes - stubs_attributes - exclude_list
print("\n".join(sorted(missing)))
def main():
parser = argparse.ArgumentParser()
parser.add_argument("module")
args = parser.parse_args()
find_missing(args.module)
if __name__ == "__main__":
main()
| #!/usr/bin/env python
"""Find the functions in a module missing type annotations.
To use it run
./functions_missing_types.py <module>
and it will print out a list of functions in the module that don't
have types.
"""
import argparse
import ast
import importlib
import os
NUMPY_ROOT = os.path.dirname(os.path.join(
os.path.abspath(__file__), "..",
))
# Technically "public" functions (they don't start with an underscore)
# that we don't want to include.
EXCLUDE_LIST = {
"numpy": {
# Stdlib modules in the namespace by accident
"absolute_import",
"division",
"print_function",
"warnings",
"sys",
"os",
"math",
# Accidentally public, deprecated, or shouldn't be used
"Tester",
"_core",
"int_asbuffer",
"numarray",
"oldnumeric",
"test",
"typeDict",
# Builtins
"bool",
"complex",
"float",
"int",
"long",
"object",
"str",
"unicode",
# More standard names should be preferred
"alltrue", # all
" | [] | numpy/numpy | tools/functions_missing_types.py |
#!/usr/bin/env python3
import os
import sys
import toml
def main():
path = toml.load("pyproject.toml")["tool"]["towncrier"]["directory"]
fragments = os.listdir(path)
fragments.remove("README.rst")
fragments.remove("template.rst")
if fragments:
print("The following files were not found by towncrier:")
print(" " + "\n ".join(fragments))
sys.exit(1)
if __name__ == "__main__":
main()
| #!/usr/bin/env python3
import os
import sys
import toml
def main():
path = toml.load("pyproject.toml")["tool"]["towncrier"]["directory"]
fragments = os.listdir(path)
fragments.remove("README.rst")
fragments.remove("template.rst")
if fragments:
print("The following files were not found by towncrier:")
print(" " + "\n ".join(fragments))
sys.exit(1)
if __name__ == "__main__":
main()
| [] | numpy/numpy | tools/ci/test_all_newsfragments_used.py |
#!/usr/bin/env python3
import argparse
import os
import shutil
import subprocess
import sys
import tempfile
parser = argparse.ArgumentParser(
description='Upload files to a remote repo, replacing existing content'
)
parser.add_argument('dir', help='directory of which content will be uploaded')
parser.add_argument('remote', help='remote to which content will be pushed')
parser.add_argument('--message', default='Commit bot upload',
help='commit message to use')
parser.add_argument('--committer', default='numpy-commit-bot',
help='Name of the git committer')
parser.add_argument('--email', default='numpy-commit-bot@nomail',
help='Email of the git committer')
parser.add_argument('--count', default=1, type=int,
help="minimum number of expected files, defaults to 1")
parser.add_argument(
'--force', action='store_true',
help='hereby acknowledge that remote repo content will be overwritten'
)
args = parser.parse_args()
args.dir = os.path.abspath(args.dir)
if not os.path.exists(args.dir):
print('Content directory does not exist')
sys.exit(1)
count = len([name for name in os.listdir(args.dir)
if os.path.isfile(os.path.join(args.dir, name))])
if count < args.count:
print(f"Expected {args.count} top-directory files to upload, got {count}")
sys.exit(1)
def run(cmd, stdout=True):
pipe = None if stdout else subprocess.DEVNULL
try:
subprocess.check_call(cmd, stdout=pipe, stderr=pipe)
except subprocess.CalledProcessError:
print(f"\n! Error executing: `{' '.join(cmd)};` aborting")
sys.exit(1)
workdir = tempfile.mkdtemp()
os.chdir(workdir)
run(['git', 'init'])
# ensure the working branch is called "main"
# (`--initial-branch=main` appeared to have failed on older git versions):
run(['git', 'checkout', '-b', 'main'])
run(['git', 'remote', 'add', 'origin', args.remote])
run(['git', 'config', '--local', 'user.name', args.committer])
run(['git', 'config', '--local', 'user.email', args.email])
print(f'- committing new content: "{args.message}"')
run(['cp', '-R', os.path.join(args.dir, '.'), '.'])
run(['git', 'add', '.'], stdout=False)
run(['git', 'commit', '--allow-empty', '-m', args.message], stdout=False)
print(f'- uploading as {args.committer} <{args.email}>')
if args.force:
run(['git', 'push', 'origin', 'main', '--force'])
else:
print('\n!! No `--force` argument specified; aborting')
print('!! Before enabling that flag, make sure you know what it does\n')
sys.exit(1)
shutil.rmtree(workdir)
| #!/usr/bin/env python3
import argparse
import os
import shutil
import subprocess
import sys
import tempfile
parser = argparse.ArgumentParser(
description='Upload files to a remote repo, replacing existing content'
)
parser.add_argument('dir', help='directory of which content will be uploaded')
parser.add_argument('remote', help='remote to which content will be pushed')
parser.add_argument('--message', default='Commit bot upload',
help='commit message to use')
parser.add_argument('--committer', default='numpy-commit-bot',
help='Name of the git committer')
parser.add_argument('--email', default='numpy-commit-bot@nomail',
help='Email of the git committer')
parser.add_argument('--count', default=1, type=int,
help="minimum number of expected files, defaults to 1")
parser.add_argument(
'--force', action='store_true',
help='hereby acknowledge that remote repo content will be overwritten'
)
args = parser.parse_args()
args.dir = os.path.abspath(args.dir)
if not os.path.exists(args.dir):
print('Content directory does not exist')
sys.exit(1)
count = len([name for name in os.listdir(args.dir)
if os.path.isfile(os.path.join(args.dir, name))])
if count < args.count:
print(f"Expected {args.count} top-directory files to upload, got {count}")
sys.exit(1)
def run(cmd, stdout=True):
| [] | numpy/numpy | tools/ci/push_docs_to_repo.py |
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import os
import re
import sys
import tempfile
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from re import Pattern
"""
Borrow-ref C API linter (Python version).
- Recursively scans source files under --root (default: numpy)
- Matches suspicious CPython C-API calls as whole identifiers
- Skips:
- lines with '// noqa: borrowed-ref OK' or
'// noqa: borrowed-ref - manual fix needed'
- line comments (// ...)
- block comments (/* ... */), even when they span lines
- Prints findings and exits 1 if any issues found, else 0
"""
def strip_comments(line: str, in_block: bool) -> tuple[str, bool]:
"""
Return (code_without_comments, updated_in_block).
Removes // line comments and /* ... */ block comments (non-nesting, C-style).
"""
i = 0
out_parts: list[str] = []
n = len(line)
while i < n:
if in_block:
end = line.find("*/", i)
if end == -1:
# Entire remainder is inside a block comment.
return ("".join(out_parts), True)
i = end + 2
in_block = False
continue
# Not in block: look for next // or /* from current i
sl = line.find("//", i)
bl = line.find("/*", i)
if sl != -1 and (bl == -1 or sl < bl):
# Line comment starts first: take code up to '//' and stop
out_parts.append(line[i:sl])
return ("".join(out_parts), in_block)
if bl != -1:
# Block comment starts: take code up to '/*', then enter block
out_parts.append(line[i:bl])
i = bl + 2
in_block = True
continue
# No more comments
out_parts.append(line[i:])
break
return ("".join(out_parts), in_block)
def iter_source_files(root: Path, exts: set[str], excludes: set[str]) -> list[Path]:
"""
Return a list of source files under 'root', where filenames end with any of the
extensions in 'exts' (e.g., '.c.src', '.c', '.h').
Excludes directories whose names are in 'excludes'.
"""
results: list[Path] = []
for dirpath, dirnames, filenames in os.walk(root):
# Prune excluded directories
dirnames[:] = [d for d in dirnames if d not in excludes]
for fn in filenames:
# endswith handles mult-suffice patterns, e.g., .c.src
if any(fn.endswith(ext) for ext in exts):
results.append(Path(dirpath) / fn)
return results
def build_func_rx(funcs: tuple[str, ...]) -> Pattern[str]:
return re.compile(r"(?<!\w)(?:" + "|".join(map(re.escape, funcs)) + r")(?!\w)")
def scan_file(
path: Path,
func_rx: Pattern[str],
noqa_markers: tuple[str, ...]
) -> list[tuple[str, int, str, str]]:
"""
Scan a single file.
Returns list of (func_name, line_number, path_str, raw_line_str).
"""
hits: list[tuple[str, int, str, str]] = []
in_block = False
noqa_set = set(noqa_markers)
try:
with path.open("r", encoding="utf-8", errors="ignore") as f:
for lineno, raw in enumerate(f, 1):
# Skip if approved by noqa markers
if any(mark in raw for mark in noqa_set):
continue
# Remove comments; if nothing remains, skip
code, in_block = strip_comments(raw.rstrip("\n"), in_block)
if not code.strip():
continue
# Find all suspicious calls in non-comment code
for m in func_rx.finditer(code):
hits.append((m.group(0), lineno, str(path), raw.rstrip("\n")))
except FileNotFoundError:
# File may have disappeared; ignore gracefully
pass
return hits
def main(argv: list[str] | None = None) -> int:
# List of suspicious function calls:
suspicious_funcs: tuple[str, ...] = (
"PyList_GetItem",
"PyDict_GetItem",
"PyDict_GetItemWithError",
"PyDict_GetItemString",
"PyDict_SetDefault",
"PyDict_Next",
"PyWeakref_GetObject",
"PyWeakref_GET_OBJECT",
"PyList_GET_ITEM",
"_PyDict_GetItemStringWithError",
"PySequence_Fast"
)
func_rx = build_func_rx(suspicious_funcs)
noqa_markers = (
"noqa: borrowed-ref OK",
"noqa: borrowed-ref - manual fix needed"
)
default_exts = {".c", ".h", ".c.src", ".cpp"}
default_excludes = {"pythoncapi-compat"}
ap = argparse.ArgumentParser(description="Borrow-ref C API linter (Python).")
ap.add_argument(
"--quiet",
action="store_true",
help="Suppress normal output; exit status alone indicates result (useful\
for CI).",
)
ap.add_argument(
"-j", "--jobs",
type=int,
default=0,
help="Number of worker threads (0=auto, 1=sequential).",
)
ap.add_argument(
"--root",
default="numpy",
type=str,
help="Root directory to scan (default: numpy)"
)
ap.add_argument(
"--ext",
action="append",
default=None,
help=f"File extension(s) to include (repeatable). Defaults to {default_exts}",
)
ap.add_argument(
"--exclude",
action="append",
default=None,
help=f"Directory name(s) to exclude (repeatable). Default: {default_excludes}",
)
args = ap.parse_args(argv)
if args.ext:
exts = {e if e.startswith(".") else f".{e}" for e in args.ext}
else:
exts = set(default_exts)
excludes = set(args.exclude) if args.exclude else set(default_excludes)
root = Path(args.root)
if not root.exists():
print(f"error: root '{root}' does not exist", file=sys.stderr)
return 2
files = sorted(iter_source_files(root, exts, excludes), key=str)
# Determine concurrency: auto picks a reasonable cap for I/O-bound work
if args.jobs is None or args.jobs <= 0:
max_workers = min(32, (os.cpu_count() or 1) * 5)
else:
max_workers = max(1, args.jobs)
print(f'Scanning {len(files)} C/C++ source files...\n')
# Output file (mirrors your shell behavior)
tmpdir = Path(".tmp")
tmpdir.mkdir(exist_ok=True)
findings = 0
# Run the scanning in parallel; only the main thread writes the report
all_hits: list[tuple[str, int, str, str]] = []
if max_workers == 1:
for p in files:
all_hits.extend(scan_file(p, func_rx, noqa_markers))
else:
with ThreadPoolExecutor(max_workers=max_workers) as ex:
fut_to_file = {ex.submit(scan_file, p, func_rx, noqa_markers):
p for p in files}
for fut in as_completed(fut_to_file):
try:
all_hits.extend(fut.result())
except Exception as e:
print(f'Failed to scan {fut_to_file[fut]}: {e}')
# Sort for deterministic output: by path, then line number
all_hits.sort(key=lambda t: (t[2], t[1]))
# There no hits, linter passed
if not all_hits:
if not args.quiet:
print("All checks passed! C API borrow-ref linter found no issues.\n")
return 0
# There are some linter failures: create a log file
with tempfile.NamedTemporaryFile(
prefix="c_api_usage_report.",
suffix=".txt",
dir=tmpdir,
mode="w+",
encoding="utf-8",
delete=False,
) as out:
report_path = Path(out.name)
out.write("Running Suspicious C API usage report workflow...\n\n")
for func, lineo, pstr, raw in all_hits:
findings += 1
out.write(f"Found suspicious call to {func} in file: {pstr}\n")
out.write(f" -> {pstr}:{lineo}a:{raw}\n")
out.write("Recommendation:\n")
out.write(
"If this use is intentional and safe, add "
"'// noqa: borrowed-ref OK' on the same line "
"to silence this warning.\n"
)
out.write(
"Otherwise, consider replacing the call "
"with a thread-safe API function.\n\n"
)
out.flush()
if not args.quiet:
out.seek(0)
sys.stdout.write(out.read())
print(f"Report written to: {report_path}\n\n\
C API borrow-ref linter FAILED.")
return 1
if __name__ == "__main__":
sys.exit(main())
| #!/usr/bin/env python3
from __future__ import annotations
import argparse
import os
import re
import sys
import tempfile
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from re import Pattern
"""
Borrow-ref C API linter (Python version).
- Recursively scans source files under --root (default: numpy)
- Matches suspicious CPython C-API calls as whole identifiers
- Skips:
- lines with '// noqa: borrowed-ref OK' or
'// noqa: borrowed-ref - manual fix needed'
- line comments (// ...)
- block comments (/* ... */), even when they span lines
- Prints findings and exits 1 if any issues found, else 0
"""
def strip_comments(line: str, in_block: bool) -> tuple[str, bool]:
"""
Return (code_without_comments, updated_in_block).
Removes // line comments and /* ... */ block comments (non-nesting, C-style).
"""
i = 0
out_parts: list[str] = []
n = len(line)
while i < n:
if in_block:
end = line.find("*/", i)
if end == -1:
# Entire remainder is inside a block comment.
return ("".join(out_parts), True)
i = end + 2
in_block = False
continue
# Not in block: look for next // or /* from current i
sl = line.find("//", i)
bl = line.find | [] | numpy/numpy | tools/ci/check_c_api_usage.py |
#!/usr/bin/env python
"""Check that Python.h is included before any stdlib headers.
May be a bit overzealous, but it should get the job done.
"""
import argparse
import fnmatch
import os.path
import re
import subprocess
import sys
from get_submodule_paths import get_submodule_paths
HEADER_PATTERN = re.compile(
r'^\s*#\s*include\s*[<"]((?:\w+/)*\w+(?:\.h[hp+]{0,2})?)[>"]\s*$'
)
PYTHON_INCLUDING_HEADERS = [
"Python.h",
# This isn't all of Python.h, but it is the visibility macros
"pyconfig.h",
"numpy/npy_common.h",
"numpy/npy_math.h",
"numpy/arrayobject.h",
"numpy/ndarrayobject.h",
"numpy/ndarraytypes.h",
"numpy/random/distributions.h",
"npy_sort.h",
"npy_config.h",
"common.h",
"npy_cpu_features.h",
# Boost::Python
"boost/python.hpp",
]
LEAF_HEADERS = [
"numpy/numpyconfig.h",
"numpy/npy_os.h",
"numpy/npy_cpu.h",
"numpy/utils.h",
]
C_CPP_EXTENSIONS = (".c", ".h", ".cpp", ".hpp", ".cc", ".hh", ".cxx", ".hxx")
# check against list in diff_files
PARSER = argparse.ArgumentParser(description=__doc__)
PARSER.add_argument(
"files",
nargs="*",
help="Lint these files or directories; use **/*.c to lint all files\n"
"Expects relative paths",
)
def check_python_h_included_first(name_to_check: str) -> int:
"""Check that the passed file includes Python.h first if it does at all.
Perhaps overzealous, but that should work around concerns with
recursion.
Parameters
----------
name_to_check : str
The name of the file to check.
Returns
-------
int
The number of headers before Python.h
"""
included_python = False
included_non_python_header = []
warned_python_construct = False
basename_to_check = os.path.basename(name_to_check)
in_comment = False
includes_headers = False
with open(name_to_check) as in_file:
for i, line in enumerate(in_file, 1):
# Very basic comment parsing
# Assumes /*...*/ comments are on their own lines
if "/*" in line:
if "*/" not in line:
in_comment = True
# else-branch could use regex to remove comment and continue
continue
if in_comment:
if "*/" in line:
in_comment = False
continue
line = line.split("//", 1)[0].strip()
match = HEADER_PATTERN.match(line)
if match:
includes_headers = True
this_header = match.group(1)
if this_header in PYTHON_INCLUDING_HEADERS:
if included_non_python_header and not included_python:
# Headers before python-including header
print(
f"Header before Python.h in file {name_to_check:s}\n"
f"Python.h on line {i:d}, other header(s) on line(s)"
f" {included_non_python_header}",
file=sys.stderr,
)
# else: # no headers before python-including header
included_python = True
PYTHON_INCLUDING_HEADERS.append(basename_to_check)
if os.path.dirname(name_to_check).endswith("include/numpy"):
PYTHON_INCLUDING_HEADERS.append(f"numpy/{basename_to_check:s}")
# We just found out where Python.h comes in this file
break
elif this_header in LEAF_HEADERS:
# This header is just defines, so it won't include
# the system headers that cause problems
continue
elif not included_python and (
"numpy/" in this_header
and this_header not in LEAF_HEADERS
or "python" in this_header.lower()
):
print(
f"Python.h not included before python-including header "
f"in file {name_to_check:s}\n"
f"{this_header:s} on line {i:d}",
file=sys.stderr,
)
included_python = True
PYTHON_INCLUDING_HEADERS.append(basename_to_check)
elif not included_python and this_header not in LEAF_HEADERS:
included_non_python_header.append(i)
elif (
not included_python
and not warned_python_construct
and ".h" not in basename_to_check
) and ("py::" in line or "PYBIND11_" in line):
print(
"Python-including header not used before python constructs "
f"in file {name_to_check:s}\nConstruct on line {i:d}",
file=sys.stderr,
)
warned_python_construct = True
if not includes_headers:
LEAF_HEADERS.append(basename_to_check)
return included_python and len(included_non_python_header)
def sort_order(path: str) -> tuple[int, str]:
if "include/numpy" in path:
# Want to process numpy/*.h first, to work out which of those
# include Python.h directly
priority = 0x00
elif "h" in os.path.splitext(path)[1].lower():
# Then other headers, which tend to include numpy/*.h
priority = 0x10
else:
# Source files after headers, to give the best chance of
# properly checking whether they include Python.h
priority = 0x20
if "common" in path:
priority -= 8
path_basename = os.path.basename(path)
if path_basename.startswith("npy_"):
priority -= 4
elif path_basename.startswith("npy"):
priority -= 3
elif path_basename.startswith("np"):
priority -= 2
if "config" in path_basename:
priority -= 1
return priority, path
def process_files(file_list: list[str]) -> int:
n_out_of_order = 0
submodule_paths = get_submodule_paths()
root_directory = os.path.dirname(os.path.dirname(__file__))
for name_to_check in sorted(file_list, key=sort_order):
name_to_check = os.path.join(root_directory, name_to_check)
if any(submodule_path in name_to_check for submodule_path in submodule_paths):
continue
if ".dispatch." in name_to_check:
continue
try:
n_out_of_order += check_python_h_included_first(name_to_check)
except UnicodeDecodeError:
print(f"File {name_to_check:s} not utf-8", sys.stdout)
return n_out_of_order
def find_c_cpp_files(root: str) -> list[str]:
result = []
for dirpath, dirnames, filenames in os.walk(root):
# I'm assuming other people have checked boost
for name in ("build", ".git", "boost"):
try:
dirnames.remove(name)
except ValueError:
pass
for name in fnmatch.filter(dirnames, "*.p"):
dirnames.remove(name)
result.extend(
[
os.path.join(dirpath, name)
for name in filenames
if os.path.splitext(name)[1].lower() in C_CPP_EXTENSIONS
]
)
# Check the headers before the source files
result.sort(key=lambda path: "h" in os.path.splitext(path)[1], reverse=True)
return result
def diff_files(sha: str) -> list[str]:
"""Find the diff since the given SHA.
Adapted from lint.py
"""
res = subprocess.run(
[
"git",
"diff",
"--name-only",
"--diff-filter=ACMR",
"-z",
sha,
"--",
# Check against C_CPP_EXTENSIONS
"*.[chCH]",
"*.[ch]pp",
"*.[ch]xx",
"*.cc",
"*.hh",
],
stdout=subprocess.PIPE,
encoding="utf-8",
)
res.check_returncode()
return [f for f in res.stdout.split("\0") if f]
if __name__ == "__main__":
args = PARSER.parse_args()
if len(args.files) == 0:
files = find_c_cpp_files("numpy")
else:
files = args.files
if len(files) == 1 and os.path.isdir(files[0]):
files = find_c_cpp_files(files[0])
# See which of the headers include Python.h and add them to the list
n_out_of_order = process_files(files)
sys.exit(n_out_of_order)
| #!/usr/bin/env python
"""Check that Python.h is included before any stdlib headers.
May be a bit overzealous, but it should get the job done.
"""
import argparse
import fnmatch
import os.path
import re
import subprocess
import sys
from get_submodule_paths import get_submodule_paths
HEADER_PATTERN = re.compile(
r'^\s*#\s*include\s*[<"]((?:\w+/)*\w+(?:\.h[hp+]{0,2})?)[>"]\s*$'
)
PYTHON_INCLUDING_HEADERS = [
"Python.h",
# This isn't all of Python.h, but it is the visibility macros
"pyconfig.h",
"numpy/npy_common.h",
"numpy/npy_math.h",
"numpy/arrayobject.h",
"numpy/ndarrayobject.h",
"numpy/ndarraytypes.h",
"numpy/random/distributions.h",
"npy_sort.h",
"npy_config.h",
"common.h",
"npy_cpu_features.h",
# Boost::Python
"boost/python.hpp",
]
LEAF_HEADERS = [
"numpy/numpyconfig.h",
"numpy/npy_os.h",
"numpy/npy_cpu.h",
"numpy/utils.h",
]
C_CPP_EXTENSIONS = (".c", ".h", ".cpp", ".hpp", ".cc", ".hh", ".cxx", ".hxx")
# check against list in diff_files
PARSER = argparse.ArgumentParser(description=__doc__)
PARSER.add_argument(
"files",
| [] | numpy/numpy | tools/check_python_h_first.py |
"""
Checks related to the OpenBLAS version used in CI.
Options:
1. Check that the BLAS used at build time is (a) scipy-openblas, and (b) its version is
higher than a given minimum version. Note: this method only seems to give
the first 3 version components, so 0.3.30.0.7 gets translated to 0.3.30 when reading
it back out from `scipy.show_config()`.
2. Check requirements files in the main numpy repo and compare with the numpy-release
repo. Goal is to ensure that `numpy-release` is not behind.
Both of these checks are primarily useful in a CI job.
Examples:
# Requires install numpy
$ python check_openblas_version.py --min-version 0.3.30
# Only needs the requirements files
$ python check_openblas_version.py --req-files \
../numpy-release/requirements/openblas_requirements.txt
"""
import argparse
import os.path
import pprint
def check_built_version(min_version):
import numpy
deps = numpy.show_config('dicts')['Build Dependencies']
assert "blas" in deps
print("Build Dependencies: blas")
pprint.pprint(deps["blas"])
assert deps["blas"]["version"].split(".") >= min_version.split(".")
assert deps["blas"]["name"] == "scipy-openblas"
def check_requirements_files(reqfile):
if not os.path.exists(reqfile):
print(f"Path does not exist: {reqfile}")
def get_version(line):
req = line.split(";")[0].split("==")[1].split(".")[:5]
return tuple(int(s) for s in req)
def parse_reqs(reqfile):
with open(reqfile) as f:
lines = f.readlines()
v32 = None
v64 = None
for line in lines:
if "scipy-openblas32" in line:
v32 = get_version(line)
if "scipy-openblas64" in line:
v64 = get_version(line)
if v32 is None or v64 is None:
raise AssertionError("Expected `scipy-openblas32` and "
"`scipy-openblas64` in `ci_requirements.txt`, "
f"got:\n {' '.join(lines)}")
return v32, v64
this_dir = os.path.abspath(os.path.dirname(__file__))
reqfile_thisrepo = os.path.join(this_dir, '..', 'requirements',
'ci_requirements.txt')
v32_thisrepo, v64_thisrepo = parse_reqs(reqfile_thisrepo)
v32_rel, v64_rel = parse_reqs(reqfile)
def compare_versions(v_rel, v_thisrepo, bits):
if not v_rel >= v_thisrepo:
raise AssertionError(f"`numpy-release` version of scipy-openblas{bits} "
f"{v_rel} is behind this repo: {v_thisrepo}")
compare_versions(v64_rel, v64_thisrepo, "64")
compare_versions(v32_rel, v32_thisrepo, "32")
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--req-files",
type=str,
help="Path to the requirements file to compare with the one in this repo"
)
parser.add_argument(
"--min-version",
type=str,
help="The minimum version that should have been used at build time for "
"installed `numpy` package"
)
args = parser.parse_args()
if args.min_version is None and args.req_files is None:
raise ValueError("One of `--req-files` or `--min-version` needs to be "
"specified")
if args.min_version:
check_built_version(args.min_version)
if args.req_files:
check_requirements_files(args.req_files)
if __name__ == '__main__':
main()
| """
Checks related to the OpenBLAS version used in CI.
Options:
1. Check that the BLAS used at build time is (a) scipy-openblas, and (b) its version is
higher than a given minimum version. Note: this method only seems to give
the first 3 version components, so 0.3.30.0.7 gets translated to 0.3.30 when reading
it back out from `scipy.show_config()`.
2. Check requirements files in the main numpy repo and compare with the numpy-release
repo. Goal is to ensure that `numpy-release` is not behind.
Both of these checks are primarily useful in a CI job.
Examples:
# Requires install numpy
$ python check_openblas_version.py --min-version 0.3.30
# Only needs the requirements files
$ python check_openblas_version.py --req-files \
../numpy-release/requirements/openblas_requirements.txt
"""
import argparse
import os.path
import pprint
def check_built_version(min_version):
import numpy
deps = numpy.show_config('dicts')['Build Dependencies']
assert "blas" in deps
print("Build Dependencies: blas")
pprint.pprint(deps["blas"])
assert deps["blas"]["version"].split(".") >= min_version.split(".")
assert deps["blas"]["name"] == "scipy-openblas"
def check_requirements_files(reqfile):
if not os.path.exists(reqfile):
print(f"Path does not exist: {reqfile}")
def get_version(line):
req = line.split(";")[0].split("==")[1].split(".")[:5] | [] | numpy/numpy | tools/check_openblas_version.py |
"""
Check if all the test and .pyi files are installed after building.
Examples::
$ python check_installed_files.py install_dirname
install_dirname:
the relative path to the directory where NumPy is installed after
building and running `meson install`.
Notes
=====
The script will stop on encountering the first missing file in the install dir,
it will not give a full listing. This should be okay, because the script is
meant for use in CI so it's not like many files will be missing at once.
"""
import glob
import json
import os
import sys
CUR_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__)))
ROOT_DIR = os.path.dirname(CUR_DIR)
NUMPY_DIR = os.path.join(ROOT_DIR, 'numpy')
# Files whose installation path will be different from original one
changed_installed_path = {
#'numpy/_build_utils/some_file.py': 'numpy/lib/some_file.py'
}
def main(install_dir, tests_check):
INSTALLED_DIR = os.path.join(ROOT_DIR, install_dir)
if not os.path.exists(INSTALLED_DIR):
raise ValueError(
f"Provided install dir {INSTALLED_DIR} does not exist"
)
numpy_test_files = get_files(NUMPY_DIR, kind='test')
installed_test_files = get_files(INSTALLED_DIR, kind='test')
if tests_check == "--no-tests":
if len(installed_test_files) > 0:
raise Exception("Test files aren't expected to be installed in %s"
", found %s" % (INSTALLED_DIR, installed_test_files))
print("----------- No test files were installed --------------")
else:
# Check test files detected in repo are installed
for test_file in numpy_test_files.keys():
if test_file not in installed_test_files.keys():
raise Exception(
f"{numpy_test_files[test_file]} is not installed"
)
print("----------- All the test files were installed --------------")
numpy_pyi_files = get_files(NUMPY_DIR, kind='stub')
installed_pyi_files = get_files(INSTALLED_DIR, kind='stub')
# Check *.pyi files detected in repo are installed
for pyi_file in numpy_pyi_files.keys():
if pyi_file not in installed_pyi_files.keys():
if (tests_check == "--no-tests" and
"tests" in numpy_pyi_files[pyi_file]):
continue
raise Exception(f"{numpy_pyi_files[pyi_file]} is not installed")
print("----------- All the necessary .pyi files "
"were installed --------------")
def get_files(dir_to_check, kind='test'):
files = {}
patterns = {
'test': f'{dir_to_check}/**/test_*.py',
'stub': f'{dir_to_check}/**/*.pyi',
}
for path in glob.glob(patterns[kind], recursive=True):
relpath = os.path.relpath(path, dir_to_check)
files[relpath] = path
# ignore python files in vendored pythoncapi-compat submodule
files = {
k: v for k, v in files.items() if 'pythoncapi-compat' not in k
}
return files
if __name__ == '__main__':
if len(sys.argv) < 2:
raise ValueError("Incorrect number of input arguments, need "
"check_installation.py relpath/to/installed/numpy")
install_dir = sys.argv[1]
tests_check = ""
if len(sys.argv) >= 3:
tests_check = sys.argv[2]
main(install_dir, tests_check)
all_tags = set()
with open(os.path.join('build', 'meson-info',
'intro-install_plan.json'), 'r') as f:
targets = json.load(f)
for key in targets.keys():
for values in list(targets[key].values()):
if values['tag'] not in all_tags:
all_tags.add(values['tag'])
if all_tags != {'runtime', 'python-runtime', 'devel', 'tests'}:
raise AssertionError(f"Found unexpected install tag: {all_tags}")
| """
Check if all the test and .pyi files are installed after building.
Examples::
$ python check_installed_files.py install_dirname
install_dirname:
the relative path to the directory where NumPy is installed after
building and running `meson install`.
Notes
=====
The script will stop on encountering the first missing file in the install dir,
it will not give a full listing. This should be okay, because the script is
meant for use in CI so it's not like many files will be missing at once.
"""
import glob
import json
import os
import sys
CUR_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__)))
ROOT_DIR = os.path.dirname(CUR_DIR)
NUMPY_DIR = os.path.join(ROOT_DIR, 'numpy')
# Files whose installation path will be different from original one
changed_installed_path = {
#'numpy/_build_utils/some_file.py': 'numpy/lib/some_file.py'
}
def main(install_dir, tests_check):
INSTALLED_DIR = os.path.join(ROOT_DIR, install_dir)
if not os.path.exists(INSTALLED_DIR):
raise ValueError(
f"Provided install dir {INSTALLED_DIR} does not exist"
)
numpy_test_files = get_files(NUMPY_DIR, kind='test')
installed_test_files = get_files(INSTALLED_DIR, kind='test')
if tests_check == "--no-tests":
if len(installed_test_files) > 0:
raise Exception("Test files aren't expected to be installed | [] | numpy/numpy | tools/check_installed_files.py |
#!/usr/bin/env python3
"""
Script to generate contributor and pull request lists
This script generates contributor and pull request lists for release
changelogs using Github v3 protocol. Use requires an authentication token in
order to have sufficient bandwidth, you can get one following the directions at
`<https://help.github.com/articles/creating-an-access-token-for-command-line-use/>_
Don't add any scope, as the default is read access to public information. The
token may be stored in an environment variable as you only get one chance to
see it.
Usage::
$ ./tools/announce.py <token> <revision range>
The output is utf8 rst.
Dependencies
------------
- gitpython
- pygithub
- git >= 2.29.0
Some code was copied from scipy `tools/gh_list.py` and `tools/authors.py`.
Examples
--------
From the bash command line with $GITHUB token::
$ ./tools/announce $GITHUB v1.13.0..v1.14.0 > 1.14.0-changelog.rst
"""
import os
import re
from git import Repo
from github import Github
this_repo = Repo(os.path.join(os.path.dirname(__file__), ".."))
author_msg =\
"""
A total of %d people contributed to this release. People with a "+" by their
names contributed a patch for the first time.
"""
pull_request_msg =\
"""
A total of %d pull requests were merged for this release.
"""
def get_authors(revision_range):
lst_release, cur_release = [r.strip() for r in revision_range.split('..')]
authors_pat = r'^.*\t(.*)$'
# authors and co-authors in current and previous releases.
grp1 = '--group=author'
grp2 = '--group=trailer:co-authored-by'
cur = this_repo.git.shortlog('-s', grp1, grp2, revision_range)
pre = this_repo.git.shortlog('-s', grp1, grp2, lst_release)
authors_cur = set(re.findall(authors_pat, cur, re.M))
authors_pre = set(re.findall(authors_pat, pre, re.M))
# Ignore the bot Homu.
authors_cur.discard('Homu')
authors_pre.discard('Homu')
# Ignore the bot dependabot-preview
authors_cur.discard('dependabot-preview')
authors_pre.discard('dependabot-preview')
# Append '+' to new authors.
authors_new = [s + ' +' for s in authors_cur - authors_pre]
authors_old = list(authors_cur & authors_pre)
authors = authors_new + authors_old
authors.sort()
return authors
def get_pull_requests(repo, revision_range):
prnums = []
# From regular merges
merges = this_repo.git.log(
'--oneline', '--merges', revision_range)
issues = re.findall(r"Merge pull request \#(\d*)", merges)
prnums.extend(int(s) for s in issues)
# From Homu merges (Auto merges)
issues = re. findall(r"Auto merge of \#(\d*)", merges)
prnums.extend(int(s) for s in issues)
# From fast forward squash-merges
commits = this_repo.git.log(
'--oneline', '--no-merges', '--first-parent', revision_range)
issues = re.findall(r'^.*\((\#|gh-|gh-\#)(\d+)\)$', commits, re.M)
prnums.extend(int(s[1]) for s in issues)
# get PR data from github repo
prnums.sort()
prs = [repo.get_pull(n) for n in prnums]
return prs
def main(token, revision_range):
lst_release, cur_release = [r.strip() for r in revision_range.split('..')]
github = Github(token)
github_repo = github.get_repo('numpy/numpy')
# document authors
authors = get_authors(revision_range)
heading = "Contributors"
print()
print(heading)
print("=" * len(heading))
print(author_msg % len(authors))
for s in authors:
print('* ' + s)
# document pull requests
pull_requests = get_pull_requests(github_repo, revision_range)
heading = "Pull requests merged"
pull_msg = "* `#{0} <{1}>`__: {2}"
print()
print(heading)
print("=" * len(heading))
print(pull_request_msg % len(pull_requests))
def backtick_repl(matchobj):
"""repl to add an escaped space following a code block if needed"""
if matchobj.group(2) != ' ':
post = r'\ ' + matchobj.group(2)
else:
post = matchobj.group(2)
return '``' + matchobj.group(1) + '``' + post
for pull in pull_requests:
# sanitize whitespace
title = re.sub(r"\s+", " ", pull.title.strip())
# substitute any single backtick not adjacent to a backtick
# for a double backtick
title = re.sub(
r"(?P<pre>(?:^|(?<=[^`])))`(?P<post>(?=[^`]|$))",
r"\g<pre>``\g<post>",
title
)
# add an escaped space if code block is not followed by a space
title = re.sub(r"``(.*?)``(.)", backtick_repl, title)
# sanitize asterisks
title = title.replace('*', '\\*')
if len(title) > 60:
remainder = re.sub(r"\s.*$", "...", title[60:])
if len(remainder) > 20:
# just use the first 80 characters, with ellipses.
# note: this was previously bugged,
# assigning to `remainder` rather than `title`
title = title[:80] + "..."
else:
# use the first 60 characters and the next word
title = title[:60] + remainder
if title.count('`') % 4 != 0:
# ellipses have cut in the middle of a code block,
# so finish the code block before the ellipses
title = title[:-3] + '``...'
print(pull_msg.format(pull.number, pull.html_url, title))
if __name__ == "__main__":
from argparse import ArgumentParser
parser = ArgumentParser(description="Generate author/pr lists for release")
parser.add_argument('token', help='github access token')
parser.add_argument('revision_range', help='<revision>..<revision>')
args = parser.parse_args()
main(args.token, args.revision_range)
| #!/usr/bin/env python3
"""
Script to generate contributor and pull request lists
This script generates contributor and pull request lists for release
changelogs using Github v3 protocol. Use requires an authentication token in
order to have sufficient bandwidth, you can get one following the directions at
`<https://help.github.com/articles/creating-an-access-token-for-command-line-use/>_
Don't add any scope, as the default is read access to public information. The
token may be stored in an environment variable as you only get one chance to
see it.
Usage::
$ ./tools/announce.py <token> <revision range>
The output is utf8 rst.
Dependencies
------------
- gitpython
- pygithub
- git >= 2.29.0
Some code was copied from scipy `tools/gh_list.py` and `tools/authors.py`.
Examples
--------
From the bash command line with $GITHUB token::
$ ./tools/announce $GITHUB v1.13.0..v1.14.0 > 1.14.0-changelog.rst
"""
import os
import re
from git import Repo
from github import Github
this_repo = Repo(os.path.join(os.path.dirname(__file__), ".."))
author_msg =\
"""
A total of %d people contributed to this release. People with a "+" by their
names contributed a patch for the first time.
"""
pull_request_msg =\
"""
A total of %d pull requests were merged for this release.
"""
def get_authors(revision_range):
lst_release, cur_release = [r.strip() for r in revision_range.split('..')]
authors_pat = r'^.*\t(.*)$'
# authors and co-authors in current and previous releases.
grp1 = '--group=author'
grp2 = '--group=trailer:co-authored-by'
| [] | numpy/numpy | tools/changelog.py |
#!/usr/bin/env python3
"""
A script to create C code-coverage reports based on the output of
valgrind's callgrind tool.
"""
import os
import re
import sys
from xml.sax.saxutils import escape, quoteattr
try:
import pygments
if tuple(int(x) for x in pygments.__version__.split('.')) < (0, 11):
raise ImportError
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import CLexer
has_pygments = True
except ImportError:
print("This script requires pygments 0.11 or greater to generate HTML")
has_pygments = False
class FunctionHtmlFormatter(HtmlFormatter):
"""Custom HTML formatter to insert extra information with the lines."""
def __init__(self, lines, **kwargs):
HtmlFormatter.__init__(self, **kwargs)
self.lines = lines
def wrap(self, source, outfile):
for i, (c, t) in enumerate(HtmlFormatter.wrap(self, source, outfile)):
as_functions = self.lines.get(i - 1, None)
if as_functions is not None:
yield 0, ('<div title=%s style="background: #ccffcc">[%2d]' %
(quoteattr('as ' + ', '.join(as_functions)),
len(as_functions)))
else:
yield 0, ' '
yield c, t
if as_functions is not None:
yield 0, '</div>'
class SourceFile:
def __init__(self, path):
self.path = path
self.lines = {}
def mark_line(self, lineno, as_func=None):
line = self.lines.setdefault(lineno, set())
if as_func is not None:
as_func = as_func.split("'", 1)[0]
line.add(as_func)
def write_text(self, fd):
with open(self.path, "r") as source:
for i, line in enumerate(source):
if i + 1 in self.lines:
fd.write("> ")
else:
fd.write("! ")
fd.write(line)
def write_html(self, fd):
with open(self.path, 'r') as source:
code = source.read()
lexer = CLexer()
formatter = FunctionHtmlFormatter(
self.lines,
full=True,
linenos='inline')
fd.write(highlight(code, lexer, formatter))
class SourceFiles:
def __init__(self):
self.files = {}
self.prefix = None
def get_file(self, path):
if path not in self.files:
self.files[path] = SourceFile(path)
if self.prefix is None:
self.prefix = path
else:
self.prefix = os.path.commonpath([self.prefix, path])
return self.files[path]
def clean_path(self, path):
path = path[len(self.prefix):]
return re.sub(r"[^A-Za-z0-9\.]", '_', path)
def write_text(self, root):
for path, source in self.files.items():
with open(os.path.join(root, self.clean_path(path)), "w") as fd:
source.write_text(fd)
def write_html(self, root):
for path, source in self.files.items():
with open(
os.path.join(root, self.clean_path(path) + ".html"), "w"
) as fd:
source.write_html(fd)
with open(os.path.join(root, 'index.html'), 'w') as fd:
fd.write("<html>")
paths = sorted(self.files.keys())
for path in paths:
fd.write('<p><a href="%s.html">%s</a></p>' %
(self.clean_path(path),
escape(path[len(self.prefix):])))
fd.write("</html>")
def collect_stats(files, fd, pattern):
# TODO: Handle compressed callgrind files
line_regexs = [
re.compile(r"(?P<lineno>[0-9]+)(\s[0-9]+)+"),
re.compile(r"((jump)|(jcnd))=([0-9]+)\s(?P<lineno>[0-9]+)")
]
current_file = None
current_function = None
for line in fd:
if re.match(r"f[lie]=.+", line):
path = line.split('=', 2)[1].strip()
if os.path.exists(path) and re.search(pattern, path):
current_file = files.get_file(path)
else:
current_file = None
elif re.match(r"fn=.+", line):
current_function = line.split('=', 2)[1].strip()
elif current_file is not None:
for regex in line_regexs:
match = regex.match(line)
if match:
lineno = int(match.group('lineno'))
current_file.mark_line(lineno, current_function)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'callgrind_file', nargs='+',
help='One or more callgrind files')
parser.add_argument(
'-d', '--directory', default='coverage',
help='Destination directory for output (default: %(default)s)')
parser.add_argument(
'-p', '--pattern', default='numpy',
help='Regex pattern to match against source file paths '
'(default: %(default)s)')
parser.add_argument(
'-f', '--format', action='append', default=[],
choices=['text', 'html'],
help="Output format(s) to generate. "
"If option not provided, both will be generated.")
args = parser.parse_args()
files = SourceFiles()
for log_file in args.callgrind_file:
with open(log_file, 'r') as log_fd:
collect_stats(files, log_fd, args.pattern)
if not os.path.exists(args.directory):
os.makedirs(args.directory)
if args.format == []:
formats = ['text', 'html']
else:
formats = args.format
if 'text' in formats:
files.write_text(args.directory)
if 'html' in formats:
if not has_pygments:
print("Pygments 0.11 or later is required to generate HTML")
sys.exit(1)
files.write_html(args.directory)
| #!/usr/bin/env python3
"""
A script to create C code-coverage reports based on the output of
valgrind's callgrind tool.
"""
import os
import re
import sys
from xml.sax.saxutils import escape, quoteattr
try:
import pygments
if tuple(int(x) for x in pygments.__version__.split('.')) < (0, 11):
raise ImportError
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import CLexer
has_pygments = True
except ImportError:
print("This script requires pygments 0.11 or greater to generate HTML")
has_pygments = False
class FunctionHtmlFormatter(HtmlFormatter):
"""Custom HTML formatter to insert extra information with the lines."""
def __init__(self, lines, **kwargs):
HtmlFormatter.__init__(self, **kwargs)
self.lines = lines
def wrap(self, source, outfile):
for i, (c, t) in enumerate(HtmlFormatter.wrap(self, source, outfile)):
as_functions = self.lines.get(i - 1, None)
if as_functions is not None:
yield 0, ('<div title=%s style="background: #ccffcc">[%2d]' %
(quoteattr('as ' + ', '.join(as_functions)),
len(as_functions)))
| [] | numpy/numpy | tools/c_coverage/c_coverage_report.py |
import importlib.util
import os
import re
import shutil
import textwrap
from collections import defaultdict
from typing import TYPE_CHECKING
import pytest
# Only trigger a full `mypy` run if this environment variable is set
# Note that these tests tend to take over a minute even on a macOS M1 CPU,
# and more than that in CI.
RUN_MYPY = "NPY_RUN_MYPY_IN_TESTSUITE" in os.environ
if RUN_MYPY and RUN_MYPY not in ('0', '', 'false'):
RUN_MYPY = True
# Skips all functions in this file
pytestmark = pytest.mark.skipif(
not RUN_MYPY,
reason="`NPY_RUN_MYPY_IN_TESTSUITE` not set"
)
try:
from mypy import api
except ImportError:
NO_MYPY = True
else:
NO_MYPY = False
if TYPE_CHECKING:
from collections.abc import Iterator
# We need this as annotation, but it's located in a private namespace.
# As a compromise, do *not* import it during runtime
from _pytest.mark.structures import ParameterSet
DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
PASS_DIR = os.path.join(DATA_DIR, "pass")
FAIL_DIR = os.path.join(DATA_DIR, "fail")
REVEAL_DIR = os.path.join(DATA_DIR, "reveal")
MISC_DIR = os.path.join(DATA_DIR, "misc")
MYPY_INI = os.path.join(DATA_DIR, "mypy.ini")
CACHE_DIR = os.path.join(DATA_DIR, ".mypy_cache")
#: A dictionary with file names as keys and lists of the mypy stdout as values.
#: To-be populated by `run_mypy`.
OUTPUT_MYPY: defaultdict[str, list[str]] = defaultdict(list)
def _key_func(key: str) -> str:
"""Split at the first occurrence of the ``:`` character.
Windows drive-letters (*e.g.* ``C:``) are ignored herein.
"""
drive, tail = os.path.splitdrive(key)
return os.path.join(drive, tail.split(":", 1)[0])
def _strip_filename(msg: str) -> tuple[int, str]:
"""Strip the filename and line number from a mypy message."""
_, tail = os.path.splitdrive(msg)
_, lineno, msg = tail.split(":", 2)
return int(lineno), msg.strip()
def strip_func(match: re.Match[str]) -> str:
"""`re.sub` helper function for stripping module names."""
return match.groups()[1]
@pytest.fixture(scope="module", autouse=True)
def run_mypy() -> None:
"""Clears the cache and run mypy before running any of the typing tests.
The mypy results are cached in `OUTPUT_MYPY` for further use.
The cache refresh can be skipped using
NUMPY_TYPING_TEST_CLEAR_CACHE=0 pytest numpy/typing/tests
"""
if (
os.path.isdir(CACHE_DIR)
and bool(os.environ.get("NUMPY_TYPING_TEST_CLEAR_CACHE", True))
):
shutil.rmtree(CACHE_DIR)
split_pattern = re.compile(r"(\s+)?\^(\~+)?")
for directory in (PASS_DIR, REVEAL_DIR, FAIL_DIR, MISC_DIR):
# Run mypy
stdout, stderr, exit_code = api.run([
"--config-file",
MYPY_INI,
"--cache-dir",
CACHE_DIR,
directory,
])
if stderr:
pytest.fail(f"Unexpected mypy standard error\n\n{stderr}", False)
elif exit_code not in {0, 1}:
pytest.fail(f"Unexpected mypy exit code: {exit_code}\n\n{stdout}", False)
str_concat = ""
filename: str | None = None
for i in stdout.split("\n"):
if "note:" in i:
continue
if filename is None:
filename = _key_func(i)
str_concat += f"{i}\n"
if split_pattern.match(i) is not None:
OUTPUT_MYPY[filename].append(str_concat)
str_concat = ""
filename = None
def get_test_cases(*directories: str) -> "Iterator[ParameterSet]":
for directory in directories:
for root, _, files in os.walk(directory):
for fname in files:
short_fname, ext = os.path.splitext(fname)
if ext not in (".pyi", ".py"):
continue
fullpath = os.path.join(root, fname)
yield pytest.param(fullpath, id=short_fname)
_FAIL_INDENT = " " * 4
_FAIL_SEP = "\n" + "_" * 79 + "\n\n"
_FAIL_MSG_REVEAL = """{}:{} - reveal mismatch:
{}"""
@pytest.mark.slow
@pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
@pytest.mark.parametrize("path", get_test_cases(PASS_DIR, FAIL_DIR))
def test_pass(path) -> None:
# Alias `OUTPUT_MYPY` so that it appears in the local namespace
output_mypy = OUTPUT_MYPY
if path not in output_mypy:
return
relpath = os.path.relpath(path)
# collect any reported errors, and clean up the output
messages = []
for message in output_mypy[path]:
lineno, content = _strip_filename(message)
content = content.removeprefix("error:").lstrip()
messages.append(f"{relpath}:{lineno} - {content}")
if messages:
pytest.fail("\n".join(messages), pytrace=False)
@pytest.mark.slow
@pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
@pytest.mark.parametrize("path", get_test_cases(REVEAL_DIR))
def test_reveal(path: str) -> None:
"""Validate that mypy correctly infers the return-types of
the expressions in `path`.
"""
__tracebackhide__ = True
output_mypy = OUTPUT_MYPY
if path not in output_mypy:
return
relpath = os.path.relpath(path)
# collect any reported errors, and clean up the output
failures = []
for error_line in output_mypy[path]:
lineno, error_msg = _strip_filename(error_line)
error_msg = textwrap.indent(error_msg, _FAIL_INDENT)
reason = _FAIL_MSG_REVEAL.format(relpath, lineno, error_msg)
failures.append(reason)
if failures:
reasons = _FAIL_SEP.join(failures)
pytest.fail(reasons, pytrace=False)
@pytest.mark.filterwarnings("ignore::DeprecationWarning")
@pytest.mark.slow
@pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
@pytest.mark.filterwarnings("ignore:numpy.fix is deprecated:DeprecationWarning")
@pytest.mark.parametrize("path", get_test_cases(PASS_DIR))
def test_code_runs(path: str) -> None:
"""Validate that the code in `path` properly during runtime."""
path_without_extension, _ = os.path.splitext(path)
dirname, filename = path.split(os.sep)[-2:]
spec = importlib.util.spec_from_file_location(
f"{dirname}.{filename}", path
)
assert spec is not None
assert spec.loader is not None
test_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(test_module)
| import importlib.util
import os
import re
import shutil
import textwrap
from collections import defaultdict
from typing import TYPE_CHECKING
import pytest
# Only trigger a full `mypy` run if this environment variable is set
# Note that these tests tend to take over a minute even on a macOS M1 CPU,
# and more than that in CI.
RUN_MYPY = "NPY_RUN_MYPY_IN_TESTSUITE" in os.environ
if RUN_MYPY and RUN_MYPY not in ('0', '', 'false'):
RUN_MYPY = True
# Skips all functions in this file
pytestmark = pytest.mark.skipif(
not RUN_MYPY,
reason="`NPY_RUN_MYPY_IN_TESTSUITE` not set"
)
try:
from mypy import api
except ImportError:
NO_MYPY = True
else:
NO_MYPY = False
if TYPE_CHECKING:
from collections.abc import Iterator
# We need this as annotation, but it's located in a private namespace.
# As a compromise, do *not* import it during runtime
from _pytest.mark.structures import ParameterSet
DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
PASS_DIR = os.path.join(DATA_DIR, "pass")
FAIL_DIR = os.path.join(DATA_DIR, "fail")
REVEAL_DIR = os.path.join(DATA_DIR, "reveal")
MISC_DIR = os.path.join(DATA_DIR, "misc")
MYPY_INI = os.path.join(DATA_DIR, "mypy.ini")
CACHE_DIR = os.path.join(DATA_DIR, ".mypy_cache")
#: A dictionary with file names as keys and lists of the mypy stdout as values.
#: To-be populated by | [] | numpy/numpy | numpy/typing/tests/test_typing.py |
"""Test the runtime usage of `numpy.typing`."""
from typing import (
Any,
NamedTuple,
Self,
TypeAliasType,
get_args,
get_origin,
get_type_hints,
)
import pytest
import numpy as np
import numpy._typing as _npt
import numpy.typing as npt
class TypeTup(NamedTuple):
typ: type # type expression
args: tuple[type, ...] # generic type parameters or arguments
origin: type | None # e.g. `UnionType` or `GenericAlias`
@classmethod
def from_type_alias(cls, alias: TypeAliasType, /) -> Self:
# PEP 695 `type _ = ...` aliases wrap the type expression as a
# `types.TypeAliasType` instance with a `__value__` attribute.
tp = alias.__value__
return cls(typ=tp, args=get_args(tp), origin=get_origin(tp))
TYPES = {
"ArrayLike": TypeTup.from_type_alias(npt.ArrayLike),
"DTypeLike": TypeTup.from_type_alias(npt.DTypeLike),
"NBitBase": TypeTup(npt.NBitBase, (), None), # type: ignore[deprecated] # pyright: ignore[reportDeprecated]
"NDArray": TypeTup.from_type_alias(npt.NDArray),
}
@pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
def test_get_args(name: type, tup: TypeTup) -> None:
"""Test `typing.get_args`."""
typ, ref = tup.typ, tup.args
out = get_args(typ)
assert out == ref
@pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
def test_get_origin(name: type, tup: TypeTup) -> None:
"""Test `typing.get_origin`."""
typ, ref = tup.typ, tup.origin
out = get_origin(typ)
assert out == ref
@pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
def test_get_type_hints(name: type, tup: TypeTup) -> None:
"""Test `typing.get_type_hints`."""
typ = tup.typ
def func(a: typ) -> None: pass
out = get_type_hints(func)
ref = {"a": typ, "return": type(None)}
assert out == ref
@pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
def test_get_type_hints_str(name: type, tup: TypeTup) -> None:
"""Test `typing.get_type_hints` with string-representation of types."""
typ_str, typ = f"npt.{name}", tup.typ
def func(a: typ_str) -> None: pass
out = get_type_hints(func)
ref = {"a": getattr(npt, str(name)), "return": type(None)}
assert out == ref
def test_keys() -> None:
"""Test that ``TYPES.keys()`` and ``numpy.typing.__all__`` are synced."""
keys = TYPES.keys()
ref = set(npt.__all__)
assert keys == ref
PROTOCOLS: dict[str, tuple[type[Any], object]] = {
"_SupportsArray": (_npt._SupportsArray, np.arange(10)),
"_SupportsArrayFunc": (_npt._SupportsArrayFunc, np.arange(10)),
"_NestedSequence": (_npt._NestedSequence, [1]),
}
@pytest.mark.parametrize("cls,obj", PROTOCOLS.values(), ids=PROTOCOLS.keys())
class TestRuntimeProtocol:
def test_isinstance(self, cls: type[Any], obj: object) -> None:
assert isinstance(obj, cls)
assert not isinstance(None, cls)
def test_issubclass(self, cls: type[Any], obj: object) -> None:
assert issubclass(type(obj), cls)
assert not issubclass(type(None), cls)
| """Test the runtime usage of `numpy.typing`."""
from typing import (
Any,
NamedTuple,
Self,
TypeAliasType,
get_args,
get_origin,
get_type_hints,
)
import pytest
import numpy as np
import numpy._typing as _npt
import numpy.typing as npt
class TypeTup(NamedTuple):
typ: type # type expression
args: tuple[type, ...] # generic type parameters or arguments
origin: type | None # e.g. `UnionType` or `GenericAlias`
@classmethod
def from_type_alias(cls, alias: TypeAliasType, /) -> Self:
# PEP 695 `type _ = ...` aliases wrap the type expression as a
# `types.TypeAliasType` instance with a `__value__` attribute.
tp = alias.__value__
return cls(typ=tp, args=get_args(tp), origin=get_origin(tp))
TYPES = {
"ArrayLike": TypeTup.from_type_alias(npt.ArrayLike),
"DTypeLike": TypeTup.from_type_alias(npt.DTypeLike),
"NBitBase": TypeTup(npt.NBitBase, (), None), # type: ignore[deprecated] # pyright: ignore[reportDeprecated]
"NDArray": TypeTup.from_type_alias(npt.NDArray),
}
@pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
def test_get_args(name: type, tup: TypeTup) -> None:
"""Test `typing.get_args`."""
typ, | [] | numpy/numpy | numpy/typing/tests/test_runtime.py |
import os
from pathlib import Path
import pytest
import numpy as np
from numpy.testing import assert_
ROOT = Path(np.__file__).parents[0]
FILES = [
ROOT / "py.typed",
ROOT / "__init__.pyi",
ROOT / "ctypeslib" / "__init__.pyi",
ROOT / "_core" / "__init__.pyi",
ROOT / "f2py" / "__init__.pyi",
ROOT / "fft" / "__init__.pyi",
ROOT / "lib" / "__init__.pyi",
ROOT / "linalg" / "__init__.pyi",
ROOT / "ma" / "__init__.pyi",
ROOT / "matrixlib" / "__init__.pyi",
ROOT / "polynomial" / "__init__.pyi",
ROOT / "random" / "__init__.pyi",
ROOT / "testing" / "__init__.pyi",
]
@pytest.mark.thread_unsafe(
reason="os.path has a thread-safety bug (python/cpython#140054). "
"Expected to only be a problem in 3.14.0"
)
class TestIsFile:
def test_isfile(self):
"""Test if all ``.pyi`` files are properly installed."""
for file in FILES:
assert_(os.path.isfile(file))
| import os
from pathlib import Path
import pytest
import numpy as np
from numpy.testing import assert_
ROOT = Path(np.__file__).parents[0]
FILES = [
ROOT / "py.typed",
ROOT / "__init__.pyi",
ROOT / "ctypeslib" / "__init__.pyi",
ROOT / "_core" / "__init__.pyi",
ROOT / "f2py" / "__init__.pyi",
ROOT / "fft" / "__init__.pyi",
ROOT / "lib" / "__init__.pyi",
ROOT / "linalg" / "__init__.pyi",
ROOT / "ma" / "__init__.pyi",
ROOT / "matrixlib" / "__init__.pyi",
ROOT / "polynomial" / "__init__.pyi",
ROOT / "random" / "__init__.pyi",
ROOT / "testing" / "__init__.pyi",
]
@pytest.mark.thread_unsafe(
reason="os.path has a thread-safety bug (python/cpython#140054). "
"Expected to only be a problem in 3.14.0"
)
class TestIsFile:
def test_isfile(self):
"""Test if all ``.pyi`` files are properly installed."""
for file in FILES:
assert_(os.path.isfile(file))
| [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_"
] | numpy/numpy | numpy/typing/tests/test_isfile.py |
import numpy.exceptions as ex
ex.AxisError("test")
ex.AxisError(1, ndim=2)
ex.AxisError(1, ndim=2, msg_prefix="error")
ex.AxisError(1, ndim=2, msg_prefix=None)
| import numpy.exceptions as ex
ex.AxisError("test")
ex.AxisError(1, ndim=2)
ex.AxisError(1, ndim=2, msg_prefix="error")
ex.AxisError(1, ndim=2, msg_prefix=None)
| [] | numpy/numpy | numpy/typing/tests/data/pass/warnings_and_errors.py |
import numpy as np
np.sin(1)
np.sin([1, 2, 3])
np.sin(1, out=np.empty(1))
np.matmul(np.ones((2, 2, 2)), np.ones((2, 2, 2)), axes=[(0, 1), (0, 1), (0, 1)])
np.sin(1, signature="D->D")
# NOTE: `np.generic` subclasses are not guaranteed to support addition;
# re-enable this we can infer the exact return type of `np.sin(...)`.
#
# np.sin(1) + np.sin(1)
np.sin.types[0]
np.sin.__name__
np.sin.__doc__
np.abs(np.array([1]))
| import numpy as np
np.sin(1)
np.sin([1, 2, 3])
np.sin(1, out=np.empty(1))
np.matmul(np.ones((2, 2, 2)), np.ones((2, 2, 2)), axes=[(0, 1), (0, 1), (0, 1)])
np.sin(1, signature="D->D")
# NOTE: `np.generic` subclasses are not guaranteed to support addition;
# re-enable this we can infer the exact return type of `np.sin(...)`.
#
# np.sin(1) + np.sin(1)
np.sin.types[0]
np.sin.__name__
np.sin.__doc__
np.abs(np.array([1]))
| [] | numpy/numpy | numpy/typing/tests/data/pass/ufuncs.py |
from __future__ import annotations
from typing import Any
import numpy as np
class Object:
def __ceil__(self) -> Object:
return self
def __floor__(self) -> Object:
return self
def __trunc__(self) -> Object:
return self
def __ge__(self, value: object) -> bool:
return True
def __array__(self, dtype: np.typing.DTypeLike | None = None,
copy: bool | None = None) -> np.ndarray[Any, np.dtype[np.object_]]:
ret = np.empty((), dtype=object)
ret[()] = self
return ret
AR_LIKE_b = [True, True, False]
AR_LIKE_u = [np.uint32(1), np.uint32(2), np.uint32(3)]
AR_LIKE_i = [1, 2, 3]
AR_LIKE_f = [1.0, 2.0, 3.0]
AR_LIKE_O = [Object(), Object(), Object()]
AR_U: np.ndarray[Any, np.dtype[np.str_]] = np.zeros(3, dtype="U5")
np.fix(AR_LIKE_b) # type: ignore[deprecated]
np.fix(AR_LIKE_u) # type: ignore[deprecated]
np.fix(AR_LIKE_i) # type: ignore[deprecated]
np.fix(AR_LIKE_f) # type: ignore[deprecated]
np.fix(AR_LIKE_O) # type: ignore[deprecated]
np.fix(AR_LIKE_f, out=AR_U) # type: ignore[deprecated]
np.isposinf(AR_LIKE_b)
np.isposinf(AR_LIKE_u)
np.isposinf(AR_LIKE_i)
np.isposinf(AR_LIKE_f)
np.isposinf(AR_LIKE_f, out=AR_U)
np.isneginf(AR_LIKE_b)
np.isneginf(AR_LIKE_u)
np.isneginf(AR_LIKE_i)
np.isneginf(AR_LIKE_f)
np.isneginf(AR_LIKE_f, out=AR_U)
| from __future__ import annotations
from typing import Any
import numpy as np
class Object:
def __ceil__(self) -> Object:
return self
def __floor__(self) -> Object:
return self
def __trunc__(self) -> Object:
return self
def __ge__(self, value: object) -> bool:
return True
def __array__(self, dtype: np.typing.DTypeLike | None = None,
copy: bool | None = None) -> np.ndarray[Any, np.dtype[np.object_]]:
ret = np.empty((), dtype=object)
ret[()] = self
return ret
AR_LIKE_b = [True, True, False]
AR_LIKE_u = [np.uint32(1), np.uint32(2), np.uint32(3)]
AR_LIKE_i = [1, 2, 3]
AR_LIKE_f = [1.0, 2.0, 3.0]
AR_LIKE_O = [Object(), Object(), Object()]
AR_U: np.ndarray[Any, np.dtype[np.str_]] = np.zeros(3, dtype="U5")
np.fix(AR_LIKE_b) # type: ignore[deprecated]
np.fix(AR_LIKE_u) # type: ignore[deprecated]
np.fix(AR_LIKE_i) # type: ignore[deprecated]
np.fix(AR_LIKE_f) # type: ignore[deprecated]
np.fix(AR_LIKE_O) # type: ignore[deprecated]
np.fix(AR_LIKE_f, out=AR_U) # type: ignore[deprecated]
np | [] | numpy/numpy | numpy/typing/tests/data/pass/ufunclike.py |
"""Typing tests for `numpy._core._ufunc_config`."""
import numpy as np
def func1(a: str, b: int) -> None:
return None
def func2(a: str, b: int, c: float = 1.0) -> None:
return None
def func3(a: str, b: int) -> int:
return 0
class Write1:
def write(self, a: str) -> None:
return None
class Write2:
def write(self, a: str, b: int = 1) -> None:
return None
class Write3:
def write(self, a: str) -> int:
return 0
_err_default = np.geterr()
_bufsize_default = np.getbufsize()
_errcall_default = np.geterrcall()
try:
np.seterr(all=None)
np.seterr(divide="ignore")
np.seterr(over="warn")
np.seterr(under="call")
np.seterr(invalid="raise")
np.geterr()
np.setbufsize(4096)
np.getbufsize()
np.seterrcall(func1)
np.seterrcall(func2)
np.seterrcall(func3)
np.seterrcall(Write1())
np.seterrcall(Write2())
np.seterrcall(Write3())
np.geterrcall()
with np.errstate(call=func1, all="call"):
pass
with np.errstate(call=Write1(), divide="log", over="log"):
pass
finally:
np.seterr(**_err_default)
np.setbufsize(_bufsize_default)
np.seterrcall(_errcall_default)
| """Typing tests for `numpy._core._ufunc_config`."""
import numpy as np
def func1(a: str, b: int) -> None:
return None
def func2(a: str, b: int, c: float = 1.0) -> None:
return None
def func3(a: str, b: int) -> int:
return 0
class Write1:
def write(self, a: str) -> None:
return None
class Write2:
def write(self, a: str, b: int = 1) -> None:
return None
class Write3:
def write(self, a: str) -> int:
return 0
_err_default = np.geterr()
_bufsize_default = np.getbufsize()
_errcall_default = np.geterrcall()
try:
np.seterr(all=None)
np.seterr(divide="ignore")
np.seterr(over="warn")
np.seterr(under="call")
np.seterr(invalid="raise")
np.geterr()
np.setbufsize(4096)
np.getbufsize()
np.seterrcall(func1)
np.seterrcall(func2)
np.seterrcall(func3)
np.seterrcall(Write1())
np.seterrcall(Write2())
np.seterrcall(Write3())
np.geterrcall()
with np.errstate(call=func1, all="call"):
pass
with np.errstate(call=Write1(), divide="log", over="log"):
pass
f | [] | numpy/numpy | numpy/typing/tests/data/pass/ufunc_config.py |
"""Simple expression that should pass with mypy."""
import operator
from collections.abc import Iterable
import numpy as np
import numpy.typing as npt
# Basic checks
array = np.array([1, 2])
def ndarray_func(x: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]:
return x
ndarray_func(np.array([1, 2], dtype=np.float64))
array == 1
array.dtype == float
# Dtype construction
np.dtype(float)
np.dtype(np.float64)
np.dtype(None)
np.dtype("float64")
np.dtype(np.dtype(float))
np.dtype(("U", 10))
np.dtype((np.int32, (2, 2)))
# Define the arguments on the previous line to prevent bidirectional
# type inference in mypy from broadening the types.
two_tuples_dtype = [("R", "u1"), ("G", "u1"), ("B", "u1")]
np.dtype(two_tuples_dtype)
three_tuples_dtype = [("R", "u1", 2)]
np.dtype(three_tuples_dtype)
mixed_tuples_dtype = [("R", "u1"), ("G", np.str_, 1)]
np.dtype(mixed_tuples_dtype)
shape_tuple_dtype = [("R", "u1", (2, 2))]
np.dtype(shape_tuple_dtype)
shape_like_dtype = [("R", "u1", (2, 2)), ("G", np.str_, 1)]
np.dtype(shape_like_dtype)
object_dtype = [("field1", object)]
np.dtype(object_dtype)
np.dtype((np.int32, (np.int8, 4)))
# Dtype comparison
np.dtype(float) == float
np.dtype(float) != np.float64
np.dtype(float) < None
np.dtype(float) <= "float64"
np.dtype(float) > np.dtype(float)
np.dtype(float) >= np.dtype(("U", 10))
# Iteration and indexing
def iterable_func(x: Iterable[object]) -> Iterable[object]:
return x
iterable_func(array)
list(array)
iter(array)
zip(array, array)
array[1]
array[:]
array[...]
array[:] = 0
array_2d = np.ones((3, 3))
array_2d[:2, :2]
array_2d[:2, :2] = 0
array_2d[..., 0]
array_2d[..., 0] = 2
array_2d[-1, -1] = None
array_obj = np.zeros(1, dtype=np.object_)
array_obj[0] = slice(None)
# Other special methods
len(array)
str(array)
array_scalar = np.array(1)
int(array_scalar)
float(array_scalar)
complex(array_scalar)
bytes(array_scalar)
operator.index(array_scalar)
bool(array_scalar)
# comparisons
array < 1
array <= 1
array == 1
array != 1
array > 1
array >= 1
1 < array
1 <= array
1 == array
1 != array
1 > array
1 >= array
# binary arithmetic
array + 1
1 + array
array += 1
array - 1
1 - array
array -= 1
array * 1
1 * array
array *= 1
nonzero_array = np.array([1, 2])
array / 1
1 / nonzero_array
float_array = np.array([1.0, 2.0])
float_array /= 1
array // 1
1 // nonzero_array
array //= 1
array % 1
1 % nonzero_array
array %= 1
divmod(array, 1)
divmod(1, nonzero_array)
array ** 1
1 ** array
array **= 1
array << 1
1 << array
array <<= 1
array >> 1
1 >> array
array >>= 1
array & 1
1 & array
array &= 1
array ^ 1
1 ^ array
array ^= 1
array | 1
1 | array
array |= 1
# unary arithmetic
-array
+array
abs(array)
~array
# Other methods
array.transpose()
array @ array
| """Simple expression that should pass with mypy."""
import operator
from collections.abc import Iterable
import numpy as np
import numpy.typing as npt
# Basic checks
array = np.array([1, 2])
def ndarray_func(x: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]:
return x
ndarray_func(np.array([1, 2], dtype=np.float64))
array == 1
array.dtype == float
# Dtype construction
np.dtype(float)
np.dtype(np.float64)
np.dtype(None)
np.dtype("float64")
np.dtype(np.dtype(float))
np.dtype(("U", 10))
np.dtype((np.int32, (2, 2)))
# Define the arguments on the previous line to prevent bidirectional
# type inference in mypy from broadening the types.
two_tuples_dtype = [("R", "u1"), ("G", "u1"), ("B", "u1")]
np.dtype(two_tuples_dtype)
three_tuples_dtype = [("R", "u1", 2)]
np.dtype(three_tuples_dtype)
mixed_tuples_dtype = [("R", "u1"), ("G", np.str_, 1)]
np.dtype(mixed_tuples_dtype)
shape_tuple_dtype = [("R", "u1", (2, 2))]
np.dtype(shape_tuple_dtype)
shape_like_dtype = [("R", "u1", (2, 2)), ("G", np.str_, 1)]
np.dtype(shape_like_dtype)
object_dtype = [("field1", object)]
np.dtype(object_dtype)
np.dtype((np.int32, (np.int8, 4)))
# Dtype comparison
np.dtype(float) == float
np.dtype | [] | numpy/numpy | numpy/typing/tests/data/pass/simple.py |
from typing import Any, NamedTuple
import numpy as np
# Subtype of tuple[int, int]
class XYGrid(NamedTuple):
x_axis: int
y_axis: int
# Test variance of _ShapeT_co
def accepts_2d(a: np.ndarray[tuple[int, int], Any]) -> None:
return None
accepts_2d(np.empty(XYGrid(2, 2)))
accepts_2d(np.zeros(XYGrid(2, 2), dtype=int))
accepts_2d(np.ones(XYGrid(2, 2), dtype=int))
accepts_2d(np.full(XYGrid(2, 2), fill_value=5, dtype=int))
| from typing import Any, NamedTuple
import numpy as np
# Subtype of tuple[int, int]
class XYGrid(NamedTuple):
x_axis: int
y_axis: int
# Test variance of _ShapeT_co
def accepts_2d(a: np.ndarray[tuple[int, int], Any]) -> None:
return None
accepts_2d(np.empty(XYGrid(2, 2)))
accepts_2d(np.zeros(XYGrid(2, 2), dtype=int))
accepts_2d(np.ones(XYGrid(2, 2), dtype=int))
accepts_2d(np.full(XYGrid(2, 2), fill_value=5, dtype=int))
| [] | numpy/numpy | numpy/typing/tests/data/pass/shape.py |
import datetime as dt
import pytest
import numpy as np
b = np.bool()
b_ = np.bool_()
u8 = np.uint64()
i8 = np.int64()
f8 = np.float64()
c16 = np.complex128()
U = np.str_()
S = np.bytes_()
# Construction
class D:
def __index__(self) -> int:
return 0
class C:
def __complex__(self) -> complex:
return 3j
class B:
def __int__(self) -> int:
return 4
class A:
def __float__(self) -> float:
return 4.0
np.complex64(3j)
np.complex64(A())
np.complex64(C())
np.complex128(3j)
np.complex128(C())
np.complex128(None)
np.complex64("1.2")
np.complex128(b"2j")
np.int8(4)
np.int16(3.4)
np.int32(4)
np.int64(-1)
np.uint8(B())
np.uint32()
np.int32("1")
np.int64(b"2")
np.float16(A())
np.float32(16)
np.float64(3.0)
np.float64(None)
np.float32("1")
np.float16(b"2.5")
np.uint64(D())
np.float32(D())
np.complex64(D())
np.bytes_(b"hello")
np.bytes_("hello", 'utf-8')
np.bytes_("hello", encoding='utf-8')
np.str_("hello")
np.str_(b"hello", 'utf-8')
np.str_(b"hello", encoding='utf-8')
# Array-ish semantics
np.int8().real
np.int16().imag
np.int32().data
np.int64().flags
np.uint8().itemsize * 2
np.uint16().ndim + 1
np.uint32().strides
np.uint64().shape
# Time structures
np.datetime64()
np.datetime64(0, "D")
np.datetime64(0, b"D")
np.datetime64(0, ('ms', 3))
np.datetime64("2019")
np.datetime64(b"2019")
np.datetime64("2019", "D")
np.datetime64("2019", "us")
np.datetime64("2019", "as")
np.datetime64(np.datetime64())
np.datetime64(np.datetime64())
np.datetime64(dt.datetime(2000, 5, 3))
np.datetime64(dt.datetime(2000, 5, 3), "D")
np.datetime64(dt.datetime(2000, 5, 3), "us")
np.datetime64(dt.datetime(2000, 5, 3), "as")
np.datetime64(dt.date(2000, 5, 3))
np.datetime64(dt.date(2000, 5, 3), "D")
np.datetime64(dt.date(2000, 5, 3), "us")
np.datetime64(dt.date(2000, 5, 3), "as")
np.datetime64(None)
np.datetime64(None, "D")
np.timedelta64()
np.timedelta64(0)
np.timedelta64(0, "D")
np.timedelta64(0, ('ms', 3))
np.timedelta64(0, b"D")
np.timedelta64("3")
np.timedelta64(b"5")
np.timedelta64(np.timedelta64(2))
np.timedelta64(dt.timedelta(2))
np.timedelta64(None)
np.timedelta64(None, "D")
np.void(1)
np.void(np.int64(1))
np.void(True)
np.void(np.bool(True))
np.void(b"test")
np.void(np.bytes_("test"))
np.void(object(), [("a", "O"), ("b", "O")])
np.void(object(), dtype=[("a", "O"), ("b", "O")])
# Protocols
i8 = np.int64()
u8 = np.uint64()
f8 = np.float64()
c16 = np.complex128()
b = np.bool()
td = np.timedelta64()
U = np.str_("1")
S = np.bytes_("1")
AR = np.array(1, dtype=np.float64)
int(i8)
int(u8)
int(f8)
int(b)
int(td)
int(U)
int(S)
int(AR)
with pytest.warns(np.exceptions.ComplexWarning):
int(c16)
float(i8)
float(u8)
float(f8)
float(b_)
float(td)
float(U)
float(S)
float(AR)
with pytest.warns(np.exceptions.ComplexWarning):
float(c16)
complex(i8)
complex(u8)
complex(f8)
complex(c16)
complex(b_)
complex(td)
complex(U)
complex(AR)
# Misc
c16.dtype
c16.real
c16.imag
c16.real.real
c16.real.imag
c16.ndim
c16.size
c16.itemsize
c16.shape
c16.strides
c16.squeeze()
c16.byteswap()
c16.transpose()
# Aliases
np.byte()
np.short()
np.intc()
np.intp()
np.int_()
np.longlong()
np.ubyte()
np.ushort()
np.uintc()
np.uintp()
np.uint()
np.ulonglong()
np.half()
np.single()
np.double()
np.longdouble()
np.csingle()
np.cdouble()
np.clongdouble()
b.item()
i8.item()
u8.item()
f8.item()
c16.item()
U.item()
S.item()
b.tolist()
i8.tolist()
u8.tolist()
f8.tolist()
c16.tolist()
U.tolist()
S.tolist()
b.ravel()
i8.ravel()
u8.ravel()
f8.ravel()
c16.ravel()
U.ravel()
S.ravel()
b.flatten()
i8.flatten()
u8.flatten()
f8.flatten()
c16.flatten()
U.flatten()
S.flatten()
b.reshape(1)
i8.reshape(1)
u8.reshape(1)
f8.reshape(1)
c16.reshape(1)
U.reshape(1)
S.reshape(1)
# Indexing scalars with any of {None, ..., tuple[()], tuple[None], tuple[...],
# tuple[None, ...]} should be valid
b[None]
i8[None]
u8[None]
f8[None]
c16[None]
c16[...]
c16[()]
c16[(None,)]
c16[(...,)]
c16[None, None]
| import datetime as dt
import pytest
import numpy as np
b = np.bool()
b_ = np.bool_()
u8 = np.uint64()
i8 = np.int64()
f8 = np.float64()
c16 = np.complex128()
U = np.str_()
S = np.bytes_()
# Construction
class D:
def __index__(self) -> int:
return 0
class C:
def __complex__(self) -> complex:
return 3j
class B:
def __int__(self) -> int:
return 4
class A:
def __float__(self) -> float:
return 4.0
np.complex64(3j)
np.complex64(A())
np.complex64(C())
np.complex128(3j)
np.complex128(C())
np.complex128(None)
np.complex64("1.2")
np.complex128(b"2j")
np.int8(4)
np.int16(3.4)
np.int32(4)
np.int64(-1)
np.uint8(B())
np.uint32()
np.int32("1")
np.int64(b"2")
np.float16(A())
np.float32(16)
np.float64(3.0)
np.float64(None)
np.float32("1")
np.float16(b"2.5")
np.uint64(D())
np.float32(D())
np.complex64(D())
np.bytes_(b"hello")
np.bytes_("hello", 'utf-8')
np.bytes_("hello", encoding='utf-8')
np.str_("hello")
np.str_(b"hello", 'utf-8')
np.str_(b"hello", encoding='utf-8')
# Array-ish semantics
np. | [] | numpy/numpy | numpy/typing/tests/data/pass/scalars.py |
"""These tests are based on the doctests from `numpy/lib/recfunctions.py`."""
from typing import Any, assert_type
import numpy as np
import numpy.typing as npt
from numpy.lib import recfunctions as rfn
def test_recursive_fill_fields() -> None:
a: npt.NDArray[np.void] = np.array(
[(1, 10.0), (2, 20.0)],
dtype=[("A", np.int64), ("B", np.float64)],
)
b = np.zeros((3,), dtype=a.dtype)
out = rfn.recursive_fill_fields(a, b)
assert_type(out, np.ndarray[tuple[int], np.dtype[np.void]])
def test_get_names() -> None:
names: tuple[str | Any, ...]
names = rfn.get_names(np.empty((1,), dtype=[("A", int)]).dtype)
names = rfn.get_names(np.empty((1,), dtype=[("A", int), ("B", float)]).dtype)
adtype = np.dtype([("a", int), ("b", [("b_a", int), ("b_b", int)])])
names = rfn.get_names(adtype)
def test_get_names_flat() -> None:
names: tuple[str, ...]
names = rfn.get_names_flat(np.empty((1,), dtype=[("A", int)]).dtype)
names = rfn.get_names_flat(np.empty((1,), dtype=[("A", int), ("B", float)]).dtype)
adtype = np.dtype([("a", int), ("b", [("b_a", int), ("b_b", int)])])
names = rfn.get_names_flat(adtype)
def test_flatten_descr() -> None:
ndtype = np.dtype([("a", "<i4"), ("b", [("b_a", "<f8"), ("b_b", "<i4")])])
assert_type(rfn.flatten_descr(ndtype), tuple[tuple[str, np.dtype]])
def test_get_fieldstructure() -> None:
ndtype = np.dtype([
("A", int),
("B", [("B_A", int), ("B_B", [("B_B_A", int), ("B_B_B", int)])]),
])
assert_type(rfn.get_fieldstructure(ndtype), dict[str, list[str]])
def test_merge_arrays() -> None:
assert_type(
rfn.merge_arrays((
np.ones((2,), np.int_),
np.ones((3,), np.float64),
)),
np.recarray[tuple[int], np.dtype[np.void]],
)
def test_drop_fields() -> None:
ndtype = [("a", np.int64), ("b", [("b_a", np.double), ("b_b", np.int64)])]
a = np.ones((3,), dtype=ndtype)
assert_type(
rfn.drop_fields(a, "a"),
np.ndarray[tuple[int], np.dtype[np.void]],
)
assert_type(
rfn.drop_fields(a, "a", asrecarray=True),
np.rec.recarray[tuple[int], np.dtype[np.void]],
)
assert_type(
rfn.rec_drop_fields(a, "a"),
np.rec.recarray[tuple[int], np.dtype[np.void]],
)
def test_rename_fields() -> None:
ndtype = [("a", np.int64), ("b", [("b_a", np.double), ("b_b", np.int64)])]
a = np.ones((3,), dtype=ndtype)
assert_type(
rfn.rename_fields(a, {"a": "A", "b_b": "B_B"}),
np.ndarray[tuple[int], np.dtype[np.void]],
)
def test_repack_fields() -> None:
dt: np.dtype[np.void] = np.dtype("u1, <i8, <f8", align=True)
assert_type(rfn.repack_fields(dt), np.dtype[np.void])
assert_type(rfn.repack_fields(dt.type(0)), np.void)
assert_type(
rfn.repack_fields(np.ones((3,), dtype=dt)),
np.ndarray[tuple[int], np.dtype[np.void]],
)
def test_structured_to_unstructured() -> None:
a = np.zeros(4, dtype=[("a", "i4"), ("b", "f4,u2"), ("c", "f4", 2)])
assert_type(rfn.structured_to_unstructured(a), npt.NDArray[Any])
def unstructured_to_structured() -> None:
dt: np.dtype[np.void] = np.dtype([("a", "i4"), ("b", "f4,u2"), ("c", "f4", 2)])
a = np.arange(20, dtype=np.int32).reshape((4, 5))
assert_type(rfn.unstructured_to_structured(a, dt), npt.NDArray[np.void])
def test_apply_along_fields() -> None:
b = np.ones(4, dtype=[("x", "i4"), ("y", "f4"), ("z", "f8")])
assert_type(
rfn.apply_along_fields(np.mean, b),
np.ndarray[tuple[int], np.dtype[np.void]],
)
def test_assign_fields_by_name() -> None:
b = np.ones(4, dtype=[("x", "i4"), ("y", "f4"), ("z", "f8")])
assert_type(
rfn.apply_along_fields(np.mean, b),
np.ndarray[tuple[int], np.dtype[np.void]],
)
def test_require_fields() -> None:
a = np.ones(4, dtype=[("a", "i4"), ("b", "f8"), ("c", "u1")])
assert_type(
rfn.require_fields(a, [("b", "f4"), ("c", "u1")]),
np.ndarray[tuple[int], np.dtype[np.void]],
)
def test_stack_arrays() -> None:
x = np.zeros((2,), np.int32)
assert_type(
rfn.stack_arrays(x),
np.ndarray[tuple[int], np.dtype[np.int32]],
)
z = np.ones((2,), [("A", "|S3"), ("B", float)])
zz = np.ones((2,), [("A", "|S3"), ("B", np.float64), ("C", np.float64)])
assert_type(
rfn.stack_arrays((z, zz)),
np.ma.MaskedArray[tuple[Any, ...], np.dtype[np.void]],
)
def test_find_duplicates() -> None:
ndtype = np.dtype([("a", int)])
a = np.ma.ones(7).view(ndtype)
assert_type(
rfn.find_duplicates(a),
np.ma.MaskedArray[tuple[int], np.dtype[np.void]],
)
assert_type(
rfn.find_duplicates(a, ignoremask=True, return_index=True),
tuple[
np.ma.MaskedArray[tuple[int], np.dtype[np.void]],
np.ndarray[tuple[int], np.dtype[np.int_]],
],
)
| """These tests are based on the doctests from `numpy/lib/recfunctions.py`."""
from typing import Any, assert_type
import numpy as np
import numpy.typing as npt
from numpy.lib import recfunctions as rfn
def test_recursive_fill_fields() -> None:
a: npt.NDArray[np.void] = np.array(
[(1, 10.0), (2, 20.0)],
dtype=[("A", np.int64), ("B", np.float64)],
)
b = np.zeros((3,), dtype=a.dtype)
out = rfn.recursive_fill_fields(a, b)
assert_type(out, np.ndarray[tuple[int], np.dtype[np.void]])
def test_get_names() -> None:
names: tuple[str | Any, ...]
names = rfn.get_names(np.empty((1,), dtype=[("A", int)]).dtype)
names = rfn.get_names(np.empty((1,), dtype=[("A", int), ("B", float)]).dtype)
adtype = np.dtype([("a", int), ("b", [("b_a", int), ("b_b", int)])])
names = rfn.get_names(adtype)
def test_get_names_flat() -> None:
names: tuple[str, ...]
names = rfn.get_names_flat(np.empty((1,), dtype=[("A", int)]).dtype)
names = rfn.get_names_flat(np.empty((1,), dtype=[("A", int), ("B", float)]).dtype)
adtype = np.dtype([("a", int), ("b", [("b_a", int), ("b_b", int)])]) | [] | numpy/numpy | numpy/typing/tests/data/pass/recfunctions.py |
from __future__ import annotations
from typing import Any
import numpy as np
SEED_NONE = None
SEED_INT = 4579435749574957634658964293569
SEED_ARR: np.ndarray[Any, np.dtype[np.int64]] = np.array([1, 2, 3, 4], dtype=np.int64)
SEED_ARRLIKE: list[int] = [1, 2, 3, 4]
SEED_SEED_SEQ: np.random.SeedSequence = np.random.SeedSequence(0)
SEED_MT19937: np.random.MT19937 = np.random.MT19937(0)
SEED_PCG64: np.random.PCG64 = np.random.PCG64(0)
SEED_PHILOX: np.random.Philox = np.random.Philox(0)
SEED_SFC64: np.random.SFC64 = np.random.SFC64(0)
# default rng
np.random.default_rng()
np.random.default_rng(SEED_NONE)
np.random.default_rng(SEED_INT)
np.random.default_rng(SEED_ARR)
np.random.default_rng(SEED_ARRLIKE)
np.random.default_rng(SEED_SEED_SEQ)
np.random.default_rng(SEED_MT19937)
np.random.default_rng(SEED_PCG64)
np.random.default_rng(SEED_PHILOX)
np.random.default_rng(SEED_SFC64)
# Seed Sequence
np.random.SeedSequence(SEED_NONE)
np.random.SeedSequence(SEED_INT)
np.random.SeedSequence(SEED_ARR)
np.random.SeedSequence(SEED_ARRLIKE)
# Bit Generators
np.random.MT19937(SEED_NONE)
np.random.MT19937(SEED_INT)
np.random.MT19937(SEED_ARR)
np.random.MT19937(SEED_ARRLIKE)
np.random.MT19937(SEED_SEED_SEQ)
np.random.PCG64(SEED_NONE)
np.random.PCG64(SEED_INT)
np.random.PCG64(SEED_ARR)
np.random.PCG64(SEED_ARRLIKE)
np.random.PCG64(SEED_SEED_SEQ)
np.random.Philox(SEED_NONE)
np.random.Philox(SEED_INT)
np.random.Philox(SEED_ARR)
np.random.Philox(SEED_ARRLIKE)
np.random.Philox(SEED_SEED_SEQ)
np.random.SFC64(SEED_NONE)
np.random.SFC64(SEED_INT)
np.random.SFC64(SEED_ARR)
np.random.SFC64(SEED_ARRLIKE)
np.random.SFC64(SEED_SEED_SEQ)
seed_seq: np.random.bit_generator.SeedSequence = np.random.SeedSequence(SEED_NONE)
seed_seq.spawn(10)
seed_seq.generate_state(3)
seed_seq.generate_state(3, "u4")
seed_seq.generate_state(3, "uint32")
seed_seq.generate_state(3, "u8")
seed_seq.generate_state(3, "uint64")
seed_seq.generate_state(3, np.uint32)
seed_seq.generate_state(3, np.uint64)
def_gen: np.random.Generator = np.random.default_rng()
D_arr_0p1: np.ndarray[Any, np.dtype[np.float64]] = np.array([0.1])
D_arr_0p5: np.ndarray[Any, np.dtype[np.float64]] = np.array([0.5])
D_arr_0p9: np.ndarray[Any, np.dtype[np.float64]] = np.array([0.9])
D_arr_1p5: np.ndarray[Any, np.dtype[np.float64]] = np.array([1.5])
I_arr_10: np.ndarray[Any, np.dtype[np.int_]] = np.array([10], dtype=np.int_)
I_arr_20: np.ndarray[Any, np.dtype[np.int_]] = np.array([20], dtype=np.int_)
D_arr_like_0p1: list[float] = [0.1]
D_arr_like_0p5: list[float] = [0.5]
D_arr_like_0p9: list[float] = [0.9]
D_arr_like_1p5: list[float] = [1.5]
I_arr_like_10: list[int] = [10]
I_arr_like_20: list[int] = [20]
D_2D_like: list[list[float]] = [[1, 2], [2, 3], [3, 4], [4, 5.1]]
D_2D: np.ndarray[Any, np.dtype[np.float64]] = np.array(D_2D_like)
S_out: np.ndarray[Any, np.dtype[np.float32]] = np.empty(1, dtype=np.float32)
D_out: np.ndarray[Any, np.dtype[np.float64]] = np.empty(1)
def_gen.standard_normal()
def_gen.standard_normal(dtype=np.float32)
def_gen.standard_normal(dtype="float32")
def_gen.standard_normal(dtype="double")
def_gen.standard_normal(dtype=np.float64)
def_gen.standard_normal(size=None)
def_gen.standard_normal(size=1)
def_gen.standard_normal(size=1, dtype=np.float32)
def_gen.standard_normal(size=1, dtype="f4")
def_gen.standard_normal(size=1, dtype="float32", out=S_out)
def_gen.standard_normal(dtype=np.float32, out=S_out)
def_gen.standard_normal(size=1, dtype=np.float64)
def_gen.standard_normal(size=1, dtype="float64")
def_gen.standard_normal(size=1, dtype="f8")
def_gen.standard_normal(out=D_out)
def_gen.standard_normal(size=1, dtype="float64")
def_gen.standard_normal(size=1, dtype="float64", out=D_out)
def_gen.random()
def_gen.random(dtype=np.float32)
def_gen.random(dtype="float32")
def_gen.random(dtype="double")
def_gen.random(dtype=np.float64)
def_gen.random(size=None)
def_gen.random(size=1)
def_gen.random(size=1, dtype=np.float32)
def_gen.random(size=1, dtype="f4")
def_gen.random(size=1, dtype="float32", out=S_out)
def_gen.random(dtype=np.float32, out=S_out)
def_gen.random(size=1, dtype=np.float64)
def_gen.random(size=1, dtype="float64")
def_gen.random(size=1, dtype="f8")
def_gen.random(out=D_out)
def_gen.random(size=1, dtype="float64")
def_gen.random(size=1, dtype="float64", out=D_out)
def_gen.standard_cauchy()
def_gen.standard_cauchy(size=None)
def_gen.standard_cauchy(size=1)
def_gen.standard_exponential()
def_gen.standard_exponential(method="inv")
def_gen.standard_exponential(dtype=np.float32)
def_gen.standard_exponential(dtype="float32")
def_gen.standard_exponential(dtype="double")
def_gen.standard_exponential(dtype=np.float64)
def_gen.standard_exponential(size=None)
def_gen.standard_exponential(size=None, method="inv")
def_gen.standard_exponential(size=1, method="inv")
def_gen.standard_exponential(size=1, dtype=np.float32)
def_gen.standard_exponential(size=1, dtype="f4", method="inv")
def_gen.standard_exponential(size=1, dtype="float32", out=S_out)
def_gen.standard_exponential(dtype=np.float32, out=S_out)
def_gen.standard_exponential(size=1, dtype=np.float64, method="inv")
def_gen.standard_exponential(size=1, dtype="float64")
def_gen.standard_exponential(size=1, dtype="f8")
def_gen.standard_exponential(out=D_out)
def_gen.standard_exponential(size=1, dtype="float64")
def_gen.standard_exponential(size=1, dtype="float64", out=D_out)
def_gen.zipf(1.5)
def_gen.zipf(1.5, size=None)
def_gen.zipf(1.5, size=1)
def_gen.zipf(D_arr_1p5)
def_gen.zipf(D_arr_1p5, size=1)
def_gen.zipf(D_arr_like_1p5)
def_gen.zipf(D_arr_like_1p5, size=1)
def_gen.weibull(0.5)
def_gen.weibull(0.5, size=None)
def_gen.weibull(0.5, size=1)
def_gen.weibull(D_arr_0p5)
def_gen.weibull(D_arr_0p5, size=1)
def_gen.weibull(D_arr_like_0p5)
def_gen.weibull(D_arr_like_0p5, size=1)
def_gen.standard_t(0.5)
def_gen.standard_t(0.5, size=None)
def_gen.standard_t(0.5, size=1)
def_gen.standard_t(D_arr_0p5)
def_gen.standard_t(D_arr_0p5, size=1)
def_gen.standard_t(D_arr_like_0p5)
def_gen.standard_t(D_arr_like_0p5, size=1)
def_gen.poisson(0.5)
def_gen.poisson(0.5, size=None)
def_gen.poisson(0.5, size=1)
def_gen.poisson(D_arr_0p5)
def_gen.poisson(D_arr_0p5, size=1)
def_gen.poisson(D_arr_like_0p5)
def_gen.poisson(D_arr_like_0p5, size=1)
def_gen.power(0.5)
def_gen.power(0.5, size=None)
def_gen.power(0.5, size=1)
def_gen.power(D_arr_0p5)
def_gen.power(D_arr_0p5, size=1)
def_gen.power(D_arr_like_0p5)
def_gen.power(D_arr_like_0p5, size=1)
def_gen.pareto(0.5)
def_gen.pareto(0.5, size=None)
def_gen.pareto(0.5, size=1)
def_gen.pareto(D_arr_0p5)
def_gen.pareto(D_arr_0p5, size=1)
def_gen.pareto(D_arr_like_0p5)
def_gen.pareto(D_arr_like_0p5, size=1)
def_gen.chisquare(0.5)
def_gen.chisquare(0.5, size=None)
def_gen.chisquare(0.5, size=1)
def_gen.chisquare(D_arr_0p5)
def_gen.chisquare(D_arr_0p5, size=1)
def_gen.chisquare(D_arr_like_0p5)
def_gen.chisquare(D_arr_like_0p5, size=1)
def_gen.exponential(0.5)
def_gen.exponential(0.5, size=None)
def_gen.exponential(0.5, size=1)
def_gen.exponential(D_arr_0p5)
def_gen.exponential(D_arr_0p5, size=1)
def_gen.exponential(D_arr_like_0p5)
def_gen.exponential(D_arr_like_0p5, size=1)
def_gen.geometric(0.5)
def_gen.geometric(0.5, size=None)
def_gen.geometric(0.5, size=1)
def_gen.geometric(D_arr_0p5)
def_gen.geometric(D_arr_0p5, size=1)
def_gen.geometric(D_arr_like_0p5)
def_gen.geometric(D_arr_like_0p5, size=1)
def_gen.logseries(0.5)
def_gen.logseries(0.5, size=None)
def_gen.logseries(0.5, size=1)
def_gen.logseries(D_arr_0p5)
def_gen.logseries(D_arr_0p5, size=1)
def_gen.logseries(D_arr_like_0p5)
def_gen.logseries(D_arr_like_0p5, size=1)
def_gen.rayleigh(0.5)
def_gen.rayleigh(0.5, size=None)
def_gen.rayleigh(0.5, size=1)
def_gen.rayleigh(D_arr_0p5)
def_gen.rayleigh(D_arr_0p5, size=1)
def_gen.rayleigh(D_arr_like_0p5)
def_gen.rayleigh(D_arr_like_0p5, size=1)
def_gen.standard_gamma(0.5)
def_gen.standard_gamma(0.5, size=None)
def_gen.standard_gamma(0.5, dtype="float32")
def_gen.standard_gamma(0.5, size=None, dtype="float32")
def_gen.standard_gamma(0.5, size=1)
def_gen.standard_gamma(D_arr_0p5)
def_gen.standard_gamma(D_arr_0p5, dtype="f4")
def_gen.standard_gamma(0.5, size=1, dtype="float32", out=S_out)
def_gen.standard_gamma(D_arr_0p5, dtype=np.float32, out=S_out)
def_gen.standard_gamma(D_arr_0p5, size=1)
def_gen.standard_gamma(D_arr_like_0p5)
def_gen.standard_gamma(D_arr_like_0p5, size=1)
def_gen.standard_gamma(0.5, out=D_out)
def_gen.standard_gamma(D_arr_like_0p5, out=D_out)
def_gen.standard_gamma(D_arr_like_0p5, size=1)
def_gen.standard_gamma(D_arr_like_0p5, size=1, out=D_out, dtype=np.float64)
def_gen.vonmises(0.5, 0.5)
def_gen.vonmises(0.5, 0.5, size=None)
def_gen.vonmises(0.5, 0.5, size=1)
def_gen.vonmises(D_arr_0p5, 0.5)
def_gen.vonmises(0.5, D_arr_0p5)
def_gen.vonmises(D_arr_0p5, 0.5, size=1)
def_gen.vonmises(0.5, D_arr_0p5, size=1)
def_gen.vonmises(D_arr_like_0p5, 0.5)
def_gen.vonmises(0.5, D_arr_like_0p5)
def_gen.vonmises(D_arr_0p5, D_arr_0p5)
def_gen.vonmises(D_arr_like_0p5, D_arr_like_0p5)
def_gen.vonmises(D_arr_0p5, D_arr_0p5, size=1)
def_gen.vonmises(D_arr_like_0p5, D_arr_like_0p5, size=1)
def_gen.wald(0.5, 0.5)
def_gen.wald(0.5, 0.5, size=None)
def_gen.wald(0.5, 0.5, size=1)
def_gen.wald(D_arr_0p5, 0.5)
def_gen.wald(0.5, D_arr_0p5)
def_gen.wald(D_arr_0p5, 0.5, size=1)
def_gen.wald(0.5, D_arr_0p5, size=1)
def_gen.wald(D_arr_like_0p5, 0.5)
def_gen.wald(0.5, D_arr_like_0p5)
def_gen.wald(D_arr_0p5, D_arr_0p5)
def_gen.wald(D_arr_like_0p5, D_arr_like_0p5)
def_gen.wald(D_arr_0p5, D_arr_0p5, size=1)
def_gen.wald(D_arr_like_0p5, D_arr_like_0p5, size=1)
def_gen.uniform(0.5, 0.5)
def_gen.uniform(0.5, 0.5, size=None)
def_gen.uniform(0.5, 0.5, size=1)
def_gen.uniform(D_arr_0p5, 0.5)
def_gen.uniform(0.5, D_arr_0p5)
def_gen.uniform(D_arr_0p5, 0.5, size=1)
def_gen.uniform(0.5, D_arr_0p5, size=1)
def_gen.uniform(D_arr_like_0p5, 0.5)
def_gen.uniform(0.5, D_arr_like_0p5)
def_gen.uniform(D_arr_0p5, D_arr_0p5)
def_gen.uniform(D_arr_like_0p5, D_arr_like_0p5)
def_gen.uniform(D_arr_0p5, D_arr_0p5, size=1)
def_gen.uniform(D_arr_like_0p5, D_arr_like_0p5, size=1)
def_gen.beta(0.5, 0.5)
def_gen.beta(0.5, 0.5, size=None)
def_gen.beta(0.5, 0.5, size=1)
def_gen.beta(D_arr_0p5, 0.5)
def_gen.beta(0.5, D_arr_0p5)
def_gen.beta(D_arr_0p5, 0.5, size=1)
def_gen.beta(0.5, D_arr_0p5, size=1)
def_gen.beta(D_arr_like_0p5, 0.5)
def_gen.beta(0.5, D_arr_like_0p5)
def_gen.beta(D_arr_0p5, D_arr_0p5)
def_gen.beta(D_arr_like_0p5, D_arr_like_0p5)
def_gen.beta(D_arr_0p5, D_arr_0p5, size=1)
def_gen.beta(D_arr_like_0p5, D_arr_like_0p5, size=1)
def_gen.f(0.5, 0.5)
def_gen.f(0.5, 0.5, size=None)
def_gen.f(0.5, 0.5, size=1)
def_gen.f(D_arr_0p5, 0.5)
def_gen.f(0.5, D_arr_0p5)
def_gen.f(D_arr_0p5, 0.5, size=1)
def_gen.f(0.5, D_arr_0p5, size=1)
def_gen.f(D_arr_like_0p5, 0.5)
def_gen.f(0.5, D_arr_like_0p5)
def_gen.f(D_arr_0p5, D_arr_0p5)
def_gen.f(D_arr_like_0p5, D_arr_like_0p5)
def_gen.f(D_arr_0p5, D_arr_0p5, size=1)
def_gen.f(D_arr_like_0p5, D_arr_like_0p5, size=1)
def_gen.gamma(0.5, 0.5)
def_gen.gamma(0.5, 0.5, size=None)
def_gen.gamma(0.5, 0.5, size=1)
def_gen.gamma(D_arr_0p5, 0.5)
def_gen.gamma(0.5, D_arr_0p5)
def_gen.gamma(D_arr_0p5, 0.5, size=1)
def_gen.gamma(0.5, D_arr_0p5, size=1)
def_gen.gamma(D_arr_like_0p5, 0.5)
def_gen.gamma(0.5, D_arr_like_0p5)
def_gen.gamma(D_arr_0p5, D_arr_0p5)
def_gen.gamma(D_arr_like_0p5, D_arr_like_0p5)
def_gen.gamma(D_arr_0p5, D_arr_0p5, size=1)
def_gen.gamma(D_arr_like_0p5, D_arr_like_0p5, size=1)
def_gen.gumbel(0.5, 0.5)
def_gen.gumbel(0.5, 0.5, size=None)
def_gen.gumbel(0.5, 0.5, size=1)
def_gen.gumbel(D_arr_0p5, 0.5)
def_gen.gumbel(0.5, D_arr_0p5)
def_gen.gumbel(D_arr_0p5, 0.5, size=1)
def_gen.gumbel(0.5, D_arr_0p5, size=1)
def_gen.gumbel(D_arr_like_0p5, 0.5)
def_gen.gumbel(0.5, D_arr_like_0p5)
def_gen.gumbel(D_arr_0p5, D_arr_0p5)
def_gen.gumbel(D_arr_like_0p5, D_arr_like_0p5)
def_gen.gumbel(D_arr_0p5, D_arr_0p5, size=1)
def_gen.gumbel(D_arr_like_0p5, D_arr_like_0p5, size=1)
def_gen.laplace(0.5, 0.5)
def_gen.laplace(0.5, 0.5, size=None)
def_gen.laplace(0.5, 0.5, size=1)
def_gen.laplace(D_arr_0p5, 0.5)
def_gen.laplace(0.5, D_arr_0p5)
def_gen.laplace(D_arr_0p5, 0.5, size=1)
def_gen.laplace(0.5, D_arr_0p5, size=1)
def_gen.laplace(D_arr_like_0p5, 0.5)
def_gen.laplace(0.5, D_arr_like_0p5)
def_gen.laplace(D_arr_0p5, D_arr_0p5)
def_gen.laplace(D_arr_like_0p5, D_arr_like_0p5)
def_gen.laplace(D_arr_0p5, D_arr_0p5, size=1)
def_gen.laplace(D_arr_like_0p5, D_arr_like_0p5, size=1)
def_gen.logistic(0.5, 0.5)
def_gen.logistic(0.5, 0.5, size=None)
def_gen.logistic(0.5, 0.5, size=1)
def_gen.logistic(D_arr_0p5, 0.5)
def_gen.logistic(0.5, D_arr_0p5)
def_gen.logistic(D_arr_0p5, 0.5, size=1)
def_gen.logistic(0.5, D_arr_0p5, size=1)
def_gen.logistic(D_arr_like_0p5, 0.5)
def_gen.logistic(0.5, D_arr_like_0p5)
def_gen.logistic(D_arr_0p5, D_arr_0p5)
def_gen.logistic(D_arr_like_0p5, D_arr_like_0p5)
def_gen.logistic(D_arr_0p5, D_arr_0p5, size=1)
def_gen.logistic(D_arr_like_0p5, D_arr_like_0p5, size=1)
def_gen.lognormal(0.5, 0.5)
def_gen.lognormal(0.5, 0.5, size=None)
def_gen.lognormal(0.5, 0.5, size=1)
def_gen.lognormal(D_arr_0p5, 0.5)
def_gen.lognormal(0.5, D_arr_0p5)
def_gen.lognormal(D_arr_0p5, 0.5, size=1)
def_gen.lognormal(0.5, D_arr_0p5, size=1)
def_gen.lognormal(D_arr_like_0p5, 0.5)
def_gen.lognormal(0.5, D_arr_like_0p5)
def_gen.lognormal(D_arr_0p5, D_arr_0p5)
def_gen.lognormal(D_arr_like_0p5, D_arr_like_0p5)
def_gen.lognormal(D_arr_0p5, D_arr_0p5, size=1)
def_gen.lognormal(D_arr_like_0p5, D_arr_like_0p5, size=1)
def_gen.noncentral_chisquare(0.5, 0.5)
def_gen.noncentral_chisquare(0.5, 0.5, size=None)
def_gen.noncentral_chisquare(0.5, 0.5, size=1)
def_gen.noncentral_chisquare(D_arr_0p5, 0.5)
def_gen.noncentral_chisquare(0.5, D_arr_0p5)
def_gen.noncentral_chisquare(D_arr_0p5, 0.5, size=1)
def_gen.noncentral_chisquare(0.5, D_arr_0p5, size=1)
def_gen.noncentral_chisquare(D_arr_like_0p5, 0.5)
def_gen.noncentral_chisquare(0.5, D_arr_like_0p5)
def_gen.noncentral_chisquare(D_arr_0p5, D_arr_0p5)
def_gen.noncentral_chisquare(D_arr_like_0p5, D_arr_like_0p5)
def_gen.noncentral_chisquare(D_arr_0p5, D_arr_0p5, size=1)
def_gen.noncentral_chisquare(D_arr_like_0p5, D_arr_like_0p5, size=1)
def_gen.normal(0.5, 0.5)
def_gen.normal(0.5, 0.5, size=None)
def_gen.normal(0.5, 0.5, size=1)
def_gen.normal(D_arr_0p5, 0.5)
def_gen.normal(0.5, D_arr_0p5)
def_gen.normal(D_arr_0p5, 0.5, size=1)
def_gen.normal(0.5, D_arr_0p5, size=1)
def_gen.normal(D_arr_like_0p5, 0.5)
def_gen.normal(0.5, D_arr_like_0p5)
def_gen.normal(D_arr_0p5, D_arr_0p5)
def_gen.normal(D_arr_like_0p5, D_arr_like_0p5)
def_gen.normal(D_arr_0p5, D_arr_0p5, size=1)
def_gen.normal(D_arr_like_0p5, D_arr_like_0p5, size=1)
def_gen.triangular(0.1, 0.5, 0.9)
def_gen.triangular(0.1, 0.5, 0.9, size=None)
def_gen.triangular(0.1, 0.5, 0.9, size=1)
def_gen.triangular(D_arr_0p1, 0.5, 0.9)
def_gen.triangular(0.1, D_arr_0p5, 0.9)
def_gen.triangular(D_arr_0p1, 0.5, D_arr_like_0p9, size=1)
def_gen.triangular(0.1, D_arr_0p5, 0.9, size=1)
def_gen.triangular(D_arr_like_0p1, 0.5, D_arr_0p9)
def_gen.triangular(0.5, D_arr_like_0p5, 0.9)
def_gen.triangular(D_arr_0p1, D_arr_0p5, 0.9)
def_gen.triangular(D_arr_like_0p1, D_arr_like_0p5, 0.9)
def_gen.triangular(D_arr_0p1, D_arr_0p5, D_arr_0p9, size=1)
def_gen.triangular(D_arr_like_0p1, D_arr_like_0p5, D_arr_like_0p9, size=1)
def_gen.noncentral_f(0.1, 0.5, 0.9)
def_gen.noncentral_f(0.1, 0.5, 0.9, size=None)
def_gen.noncentral_f(0.1, 0.5, 0.9, size=1)
def_gen.noncentral_f(D_arr_0p1, 0.5, 0.9)
def_gen.noncentral_f(0.1, D_arr_0p5, 0.9)
def_gen.noncentral_f(D_arr_0p1, 0.5, D_arr_like_0p9, size=1)
def_gen.noncentral_f(0.1, D_arr_0p5, 0.9, size=1)
def_gen.noncentral_f(D_arr_like_0p1, 0.5, D_arr_0p9)
def_gen.noncentral_f(0.5, D_arr_like_0p5, 0.9)
def_gen.noncentral_f(D_arr_0p1, D_arr_0p5, 0.9)
def_gen.noncentral_f(D_arr_like_0p1, D_arr_like_0p5, 0.9)
def_gen.noncentral_f(D_arr_0p1, D_arr_0p5, D_arr_0p9, size=1)
def_gen.noncentral_f(D_arr_like_0p1, D_arr_like_0p5, D_arr_like_0p9, size=1)
def_gen.binomial(10, 0.5)
def_gen.binomial(10, 0.5, size=None)
def_gen.binomial(10, 0.5, size=1)
def_gen.binomial(I_arr_10, 0.5)
def_gen.binomial(10, D_arr_0p5)
def_gen.binomial(I_arr_10, 0.5, size=1)
def_gen.binomial(10, D_arr_0p5, size=1)
def_gen.binomial(I_arr_like_10, 0.5)
def_gen.binomial(10, D_arr_like_0p5)
def_gen.binomial(I_arr_10, D_arr_0p5)
def_gen.binomial(I_arr_like_10, D_arr_like_0p5)
def_gen.binomial(I_arr_10, D_arr_0p5, size=1)
def_gen.binomial(I_arr_like_10, D_arr_like_0p5, size=1)
def_gen.negative_binomial(10, 0.5)
def_gen.negative_binomial(10, 0.5, size=None)
def_gen.negative_binomial(10, 0.5, size=1)
def_gen.negative_binomial(I_arr_10, 0.5)
def_gen.negative_binomial(10, D_arr_0p5)
def_gen.negative_binomial(I_arr_10, 0.5, size=1)
def_gen.negative_binomial(10, D_arr_0p5, size=1)
def_gen.negative_binomial(I_arr_like_10, 0.5)
def_gen.negative_binomial(10, D_arr_like_0p5)
def_gen.negative_binomial(I_arr_10, D_arr_0p5)
def_gen.negative_binomial(I_arr_like_10, D_arr_like_0p5)
def_gen.negative_binomial(I_arr_10, D_arr_0p5, size=1)
def_gen.negative_binomial(I_arr_like_10, D_arr_like_0p5, size=1)
def_gen.hypergeometric(20, 20, 10)
def_gen.hypergeometric(20, 20, 10, size=None)
def_gen.hypergeometric(20, 20, 10, size=1)
def_gen.hypergeometric(I_arr_20, 20, 10)
def_gen.hypergeometric(20, I_arr_20, 10)
def_gen.hypergeometric(I_arr_20, 20, I_arr_like_10, size=1)
def_gen.hypergeometric(20, I_arr_20, 10, size=1)
def_gen.hypergeometric(I_arr_like_20, 20, I_arr_10)
def_gen.hypergeometric(20, I_arr_like_20, 10)
def_gen.hypergeometric(I_arr_20, I_arr_20, 10)
def_gen.hypergeometric(I_arr_like_20, I_arr_like_20, 10)
def_gen.hypergeometric(I_arr_20, I_arr_20, I_arr_10, size=1)
def_gen.hypergeometric(I_arr_like_20, I_arr_like_20, I_arr_like_10, size=1)
I_int64_100: np.ndarray[Any, np.dtype[np.int64]] = np.array([100], dtype=np.int64)
def_gen.integers(0, 100)
def_gen.integers(100)
def_gen.integers([100])
def_gen.integers(0, [100])
I_bool_low: np.ndarray[Any, np.dtype[np.bool]] = np.array([0], dtype=np.bool)
I_bool_low_like: list[int] = [0]
I_bool_high_open: np.ndarray[Any, np.dtype[np.bool]] = np.array([1], dtype=np.bool)
I_bool_high_closed: np.ndarray[Any, np.dtype[np.bool]] = np.array([1], dtype=np.bool)
def_gen.integers(2, dtype=bool)
def_gen.integers(0, 2, dtype=bool)
def_gen.integers(1, dtype=bool, endpoint=True)
def_gen.integers(0, 1, dtype=bool, endpoint=True)
def_gen.integers(I_bool_low_like, 1, dtype=bool, endpoint=True)
def_gen.integers(I_bool_high_open, dtype=bool)
def_gen.integers(I_bool_low, I_bool_high_open, dtype=bool)
def_gen.integers(0, I_bool_high_open, dtype=bool)
def_gen.integers(I_bool_high_closed, dtype=bool, endpoint=True)
def_gen.integers(I_bool_low, I_bool_high_closed, dtype=bool, endpoint=True)
def_gen.integers(0, I_bool_high_closed, dtype=bool, endpoint=True)
def_gen.integers(2, dtype=np.bool)
def_gen.integers(0, 2, dtype=np.bool)
def_gen.integers(1, dtype=np.bool, endpoint=True)
def_gen.integers(0, 1, dtype=np.bool, endpoint=True)
def_gen.integers(I_bool_low_like, 1, dtype=np.bool, endpoint=True)
def_gen.integers(I_bool_high_open, dtype=np.bool)
def_gen.integers(I_bool_low, I_bool_high_open, dtype=np.bool)
def_gen.integers(0, I_bool_high_open, dtype=np.bool)
def_gen.integers(I_bool_high_closed, dtype=np.bool, endpoint=True)
def_gen.integers(I_bool_low, I_bool_high_closed, dtype=np.bool, endpoint=True)
def_gen.integers(0, I_bool_high_closed, dtype=np.bool, endpoint=True)
I_u1_low: np.ndarray[Any, np.dtype[np.uint8]] = np.array([0], dtype=np.uint8)
I_u1_low_like: list[int] = [0]
I_u1_high_open: np.ndarray[Any, np.dtype[np.uint8]] = np.array([255], dtype=np.uint8)
I_u1_high_closed: np.ndarray[Any, np.dtype[np.uint8]] = np.array([255], dtype=np.uint8)
def_gen.integers(256, dtype="u1")
def_gen.integers(0, 256, dtype="u1")
def_gen.integers(255, dtype="u1", endpoint=True)
def_gen.integers(0, 255, dtype="u1", endpoint=True)
def_gen.integers(I_u1_low_like, 255, dtype="u1", endpoint=True)
def_gen.integers(I_u1_high_open, dtype="u1")
def_gen.integers(I_u1_low, I_u1_high_open, dtype="u1")
def_gen.integers(0, I_u1_high_open, dtype="u1")
def_gen.integers(I_u1_high_closed, dtype="u1", endpoint=True)
def_gen.integers(I_u1_low, I_u1_high_closed, dtype="u1", endpoint=True)
def_gen.integers(0, I_u1_high_closed, dtype="u1", endpoint=True)
def_gen.integers(256, dtype="uint8")
def_gen.integers(0, 256, dtype="uint8")
def_gen.integers(255, dtype="uint8", endpoint=True)
def_gen.integers(0, 255, dtype="uint8", endpoint=True)
def_gen.integers(I_u1_low_like, 255, dtype="uint8", endpoint=True)
def_gen.integers(I_u1_high_open, dtype="uint8")
def_gen.integers(I_u1_low, I_u1_high_open, dtype="uint8")
def_gen.integers(0, I_u1_high_open, dtype="uint8")
def_gen.integers(I_u1_high_closed, dtype="uint8", endpoint=True)
def_gen.integers(I_u1_low, I_u1_high_closed, dtype="uint8", endpoint=True)
def_gen.integers(0, I_u1_high_closed, dtype="uint8", endpoint=True)
def_gen.integers(256, dtype=np.uint8)
def_gen.integers(0, 256, dtype=np.uint8)
def_gen.integers(255, dtype=np.uint8, endpoint=True)
def_gen.integers(0, 255, dtype=np.uint8, endpoint=True)
def_gen.integers(I_u1_low_like, 255, dtype=np.uint8, endpoint=True)
def_gen.integers(I_u1_high_open, dtype=np.uint8)
def_gen.integers(I_u1_low, I_u1_high_open, dtype=np.uint8)
def_gen.integers(0, I_u1_high_open, dtype=np.uint8)
def_gen.integers(I_u1_high_closed, dtype=np.uint8, endpoint=True)
def_gen.integers(I_u1_low, I_u1_high_closed, dtype=np.uint8, endpoint=True)
def_gen.integers(0, I_u1_high_closed, dtype=np.uint8, endpoint=True)
I_u2_low: np.ndarray[Any, np.dtype[np.uint16]] = np.array([0], dtype=np.uint16)
I_u2_low_like: list[int] = [0]
I_u2_high_open: np.ndarray[Any, np.dtype[np.uint16]] = np.array([65535], dtype=np.uint16)
I_u2_high_closed: np.ndarray[Any, np.dtype[np.uint16]] = np.array([65535], dtype=np.uint16)
def_gen.integers(65536, dtype="u2")
def_gen.integers(0, 65536, dtype="u2")
def_gen.integers(65535, dtype="u2", endpoint=True)
def_gen.integers(0, 65535, dtype="u2", endpoint=True)
def_gen.integers(I_u2_low_like, 65535, dtype="u2", endpoint=True)
def_gen.integers(I_u2_high_open, dtype="u2")
def_gen.integers(I_u2_low, I_u2_high_open, dtype="u2")
def_gen.integers(0, I_u2_high_open, dtype="u2")
def_gen.integers(I_u2_high_closed, dtype="u2", endpoint=True)
def_gen.integers(I_u2_low, I_u2_high_closed, dtype="u2", endpoint=True)
def_gen.integers(0, I_u2_high_closed, dtype="u2", endpoint=True)
def_gen.integers(65536, dtype="uint16")
def_gen.integers(0, 65536, dtype="uint16")
def_gen.integers(65535, dtype="uint16", endpoint=True)
def_gen.integers(0, 65535, dtype="uint16", endpoint=True)
def_gen.integers(I_u2_low_like, 65535, dtype="uint16", endpoint=True)
def_gen.integers(I_u2_high_open, dtype="uint16")
def_gen.integers(I_u2_low, I_u2_high_open, dtype="uint16")
def_gen.integers(0, I_u2_high_open, dtype="uint16")
def_gen.integers(I_u2_high_closed, dtype="uint16", endpoint=True)
def_gen.integers(I_u2_low, I_u2_high_closed, dtype="uint16", endpoint=True)
def_gen.integers(0, I_u2_high_closed, dtype="uint16", endpoint=True)
def_gen.integers(65536, dtype=np.uint16)
def_gen.integers(0, 65536, dtype=np.uint16)
def_gen.integers(65535, dtype=np.uint16, endpoint=True)
def_gen.integers(0, 65535, dtype=np.uint16, endpoint=True)
def_gen.integers(I_u2_low_like, 65535, dtype=np.uint16, endpoint=True)
def_gen.integers(I_u2_high_open, dtype=np.uint16)
def_gen.integers(I_u2_low, I_u2_high_open, dtype=np.uint16)
def_gen.integers(0, I_u2_high_open, dtype=np.uint16)
def_gen.integers(I_u2_high_closed, dtype=np.uint16, endpoint=True)
def_gen.integers(I_u2_low, I_u2_high_closed, dtype=np.uint16, endpoint=True)
def_gen.integers(0, I_u2_high_closed, dtype=np.uint16, endpoint=True)
I_u4_low: np.ndarray[Any, np.dtype[np.uint32]] = np.array([0], dtype=np.uint32)
I_u4_low_like: list[int] = [0]
I_u4_high_open: np.ndarray[Any, np.dtype[np.uint32]] = np.array([4294967295], dtype=np.uint32)
I_u4_high_closed: np.ndarray[Any, np.dtype[np.uint32]] = np.array([4294967295], dtype=np.uint32)
def_gen.integers(4294967296, dtype="u4")
def_gen.integers(0, 4294967296, dtype="u4")
def_gen.integers(4294967295, dtype="u4", endpoint=True)
def_gen.integers(0, 4294967295, dtype="u4", endpoint=True)
def_gen.integers(I_u4_low_like, 4294967295, dtype="u4", endpoint=True)
def_gen.integers(I_u4_high_open, dtype="u4")
def_gen.integers(I_u4_low, I_u4_high_open, dtype="u4")
def_gen.integers(0, I_u4_high_open, dtype="u4")
def_gen.integers(I_u4_high_closed, dtype="u4", endpoint=True)
def_gen.integers(I_u4_low, I_u4_high_closed, dtype="u4", endpoint=True)
def_gen.integers(0, I_u4_high_closed, dtype="u4", endpoint=True)
def_gen.integers(4294967296, dtype="uint32")
def_gen.integers(0, 4294967296, dtype="uint32")
def_gen.integers(4294967295, dtype="uint32", endpoint=True)
def_gen.integers(0, 4294967295, dtype="uint32", endpoint=True)
def_gen.integers(I_u4_low_like, 4294967295, dtype="uint32", endpoint=True)
def_gen.integers(I_u4_high_open, dtype="uint32")
def_gen.integers(I_u4_low, I_u4_high_open, dtype="uint32")
def_gen.integers(0, I_u4_high_open, dtype="uint32")
def_gen.integers(I_u4_high_closed, dtype="uint32", endpoint=True)
def_gen.integers(I_u4_low, I_u4_high_closed, dtype="uint32", endpoint=True)
def_gen.integers(0, I_u4_high_closed, dtype="uint32", endpoint=True)
def_gen.integers(4294967296, dtype=np.uint32)
def_gen.integers(0, 4294967296, dtype=np.uint32)
def_gen.integers(4294967295, dtype=np.uint32, endpoint=True)
def_gen.integers(0, 4294967295, dtype=np.uint32, endpoint=True)
def_gen.integers(I_u4_low_like, 4294967295, dtype=np.uint32, endpoint=True)
def_gen.integers(I_u4_high_open, dtype=np.uint32)
def_gen.integers(I_u4_low, I_u4_high_open, dtype=np.uint32)
def_gen.integers(0, I_u4_high_open, dtype=np.uint32)
def_gen.integers(I_u4_high_closed, dtype=np.uint32, endpoint=True)
def_gen.integers(I_u4_low, I_u4_high_closed, dtype=np.uint32, endpoint=True)
def_gen.integers(0, I_u4_high_closed, dtype=np.uint32, endpoint=True)
I_u8_low: np.ndarray[Any, np.dtype[np.uint64]] = np.array([0], dtype=np.uint64)
I_u8_low_like: list[int] = [0]
I_u8_high_open: np.ndarray[Any, np.dtype[np.uint64]] = np.array([18446744073709551615], dtype=np.uint64)
I_u8_high_closed: np.ndarray[Any, np.dtype[np.uint64]] = np.array([18446744073709551615], dtype=np.uint64)
def_gen.integers(18446744073709551616, dtype="u8")
def_gen.integers(0, 18446744073709551616, dtype="u8")
def_gen.integers(18446744073709551615, dtype="u8", endpoint=True)
def_gen.integers(0, 18446744073709551615, dtype="u8", endpoint=True)
def_gen.integers(I_u8_low_like, 18446744073709551615, dtype="u8", endpoint=True)
def_gen.integers(I_u8_high_open, dtype="u8")
def_gen.integers(I_u8_low, I_u8_high_open, dtype="u8")
def_gen.integers(0, I_u8_high_open, dtype="u8")
def_gen.integers(I_u8_high_closed, dtype="u8", endpoint=True)
def_gen.integers(I_u8_low, I_u8_high_closed, dtype="u8", endpoint=True)
def_gen.integers(0, I_u8_high_closed, dtype="u8", endpoint=True)
def_gen.integers(18446744073709551616, dtype="uint64")
def_gen.integers(0, 18446744073709551616, dtype="uint64")
def_gen.integers(18446744073709551615, dtype="uint64", endpoint=True)
def_gen.integers(0, 18446744073709551615, dtype="uint64", endpoint=True)
def_gen.integers(I_u8_low_like, 18446744073709551615, dtype="uint64", endpoint=True)
def_gen.integers(I_u8_high_open, dtype="uint64")
def_gen.integers(I_u8_low, I_u8_high_open, dtype="uint64")
def_gen.integers(0, I_u8_high_open, dtype="uint64")
def_gen.integers(I_u8_high_closed, dtype="uint64", endpoint=True)
def_gen.integers(I_u8_low, I_u8_high_closed, dtype="uint64", endpoint=True)
def_gen.integers(0, I_u8_high_closed, dtype="uint64", endpoint=True)
def_gen.integers(18446744073709551616, dtype=np.uint64)
def_gen.integers(0, 18446744073709551616, dtype=np.uint64)
def_gen.integers(18446744073709551615, dtype=np.uint64, endpoint=True)
def_gen.integers(0, 18446744073709551615, dtype=np.uint64, endpoint=True)
def_gen.integers(I_u8_low_like, 18446744073709551615, dtype=np.uint64, endpoint=True)
def_gen.integers(I_u8_high_open, dtype=np.uint64)
def_gen.integers(I_u8_low, I_u8_high_open, dtype=np.uint64)
def_gen.integers(0, I_u8_high_open, dtype=np.uint64)
def_gen.integers(I_u8_high_closed, dtype=np.uint64, endpoint=True)
def_gen.integers(I_u8_low, I_u8_high_closed, dtype=np.uint64, endpoint=True)
def_gen.integers(0, I_u8_high_closed, dtype=np.uint64, endpoint=True)
I_i1_low: np.ndarray[Any, np.dtype[np.int8]] = np.array([-128], dtype=np.int8)
I_i1_low_like: list[int] = [-128]
I_i1_high_open: np.ndarray[Any, np.dtype[np.int8]] = np.array([127], dtype=np.int8)
I_i1_high_closed: np.ndarray[Any, np.dtype[np.int8]] = np.array([127], dtype=np.int8)
def_gen.integers(128, dtype="i1")
def_gen.integers(-128, 128, dtype="i1")
def_gen.integers(127, dtype="i1", endpoint=True)
def_gen.integers(-128, 127, dtype="i1", endpoint=True)
def_gen.integers(I_i1_low_like, 127, dtype="i1", endpoint=True)
def_gen.integers(I_i1_high_open, dtype="i1")
def_gen.integers(I_i1_low, I_i1_high_open, dtype="i1")
def_gen.integers(-128, I_i1_high_open, dtype="i1")
def_gen.integers(I_i1_high_closed, dtype="i1", endpoint=True)
def_gen.integers(I_i1_low, I_i1_high_closed, dtype="i1", endpoint=True)
def_gen.integers(-128, I_i1_high_closed, dtype="i1", endpoint=True)
def_gen.integers(128, dtype="int8")
def_gen.integers(-128, 128, dtype="int8")
def_gen.integers(127, dtype="int8", endpoint=True)
def_gen.integers(-128, 127, dtype="int8", endpoint=True)
def_gen.integers(I_i1_low_like, 127, dtype="int8", endpoint=True)
def_gen.integers(I_i1_high_open, dtype="int8")
def_gen.integers(I_i1_low, I_i1_high_open, dtype="int8")
def_gen.integers(-128, I_i1_high_open, dtype="int8")
def_gen.integers(I_i1_high_closed, dtype="int8", endpoint=True)
def_gen.integers(I_i1_low, I_i1_high_closed, dtype="int8", endpoint=True)
def_gen.integers(-128, I_i1_high_closed, dtype="int8", endpoint=True)
def_gen.integers(128, dtype=np.int8)
def_gen.integers(-128, 128, dtype=np.int8)
def_gen.integers(127, dtype=np.int8, endpoint=True)
def_gen.integers(-128, 127, dtype=np.int8, endpoint=True)
def_gen.integers(I_i1_low_like, 127, dtype=np.int8, endpoint=True)
def_gen.integers(I_i1_high_open, dtype=np.int8)
def_gen.integers(I_i1_low, I_i1_high_open, dtype=np.int8)
def_gen.integers(-128, I_i1_high_open, dtype=np.int8)
def_gen.integers(I_i1_high_closed, dtype=np.int8, endpoint=True)
def_gen.integers(I_i1_low, I_i1_high_closed, dtype=np.int8, endpoint=True)
def_gen.integers(-128, I_i1_high_closed, dtype=np.int8, endpoint=True)
I_i2_low: np.ndarray[Any, np.dtype[np.int16]] = np.array([-32768], dtype=np.int16)
I_i2_low_like: list[int] = [-32768]
I_i2_high_open: np.ndarray[Any, np.dtype[np.int16]] = np.array([32767], dtype=np.int16)
I_i2_high_closed: np.ndarray[Any, np.dtype[np.int16]] = np.array([32767], dtype=np.int16)
def_gen.integers(32768, dtype="i2")
def_gen.integers(-32768, 32768, dtype="i2")
def_gen.integers(32767, dtype="i2", endpoint=True)
def_gen.integers(-32768, 32767, dtype="i2", endpoint=True)
def_gen.integers(I_i2_low_like, 32767, dtype="i2", endpoint=True)
def_gen.integers(I_i2_high_open, dtype="i2")
def_gen.integers(I_i2_low, I_i2_high_open, dtype="i2")
def_gen.integers(-32768, I_i2_high_open, dtype="i2")
def_gen.integers(I_i2_high_closed, dtype="i2", endpoint=True)
def_gen.integers(I_i2_low, I_i2_high_closed, dtype="i2", endpoint=True)
def_gen.integers(-32768, I_i2_high_closed, dtype="i2", endpoint=True)
def_gen.integers(32768, dtype="int16")
def_gen.integers(-32768, 32768, dtype="int16")
def_gen.integers(32767, dtype="int16", endpoint=True)
def_gen.integers(-32768, 32767, dtype="int16", endpoint=True)
def_gen.integers(I_i2_low_like, 32767, dtype="int16", endpoint=True)
def_gen.integers(I_i2_high_open, dtype="int16")
def_gen.integers(I_i2_low, I_i2_high_open, dtype="int16")
def_gen.integers(-32768, I_i2_high_open, dtype="int16")
def_gen.integers(I_i2_high_closed, dtype="int16", endpoint=True)
def_gen.integers(I_i2_low, I_i2_high_closed, dtype="int16", endpoint=True)
def_gen.integers(-32768, I_i2_high_closed, dtype="int16", endpoint=True)
def_gen.integers(32768, dtype=np.int16)
def_gen.integers(-32768, 32768, dtype=np.int16)
def_gen.integers(32767, dtype=np.int16, endpoint=True)
def_gen.integers(-32768, 32767, dtype=np.int16, endpoint=True)
def_gen.integers(I_i2_low_like, 32767, dtype=np.int16, endpoint=True)
def_gen.integers(I_i2_high_open, dtype=np.int16)
def_gen.integers(I_i2_low, I_i2_high_open, dtype=np.int16)
def_gen.integers(-32768, I_i2_high_open, dtype=np.int16)
def_gen.integers(I_i2_high_closed, dtype=np.int16, endpoint=True)
def_gen.integers(I_i2_low, I_i2_high_closed, dtype=np.int16, endpoint=True)
def_gen.integers(-32768, I_i2_high_closed, dtype=np.int16, endpoint=True)
I_i4_low: np.ndarray[Any, np.dtype[np.int32]] = np.array([-2147483648], dtype=np.int32)
I_i4_low_like: list[int] = [-2147483648]
I_i4_high_open: np.ndarray[Any, np.dtype[np.int32]] = np.array([2147483647], dtype=np.int32)
I_i4_high_closed: np.ndarray[Any, np.dtype[np.int32]] = np.array([2147483647], dtype=np.int32)
def_gen.integers(2147483648, dtype="i4")
def_gen.integers(-2147483648, 2147483648, dtype="i4")
def_gen.integers(2147483647, dtype="i4", endpoint=True)
def_gen.integers(-2147483648, 2147483647, dtype="i4", endpoint=True)
def_gen.integers(I_i4_low_like, 2147483647, dtype="i4", endpoint=True)
def_gen.integers(I_i4_high_open, dtype="i4")
def_gen.integers(I_i4_low, I_i4_high_open, dtype="i4")
def_gen.integers(-2147483648, I_i4_high_open, dtype="i4")
def_gen.integers(I_i4_high_closed, dtype="i4", endpoint=True)
def_gen.integers(I_i4_low, I_i4_high_closed, dtype="i4", endpoint=True)
def_gen.integers(-2147483648, I_i4_high_closed, dtype="i4", endpoint=True)
def_gen.integers(2147483648, dtype="int32")
def_gen.integers(-2147483648, 2147483648, dtype="int32")
def_gen.integers(2147483647, dtype="int32", endpoint=True)
def_gen.integers(-2147483648, 2147483647, dtype="int32", endpoint=True)
def_gen.integers(I_i4_low_like, 2147483647, dtype="int32", endpoint=True)
def_gen.integers(I_i4_high_open, dtype="int32")
def_gen.integers(I_i4_low, I_i4_high_open, dtype="int32")
def_gen.integers(-2147483648, I_i4_high_open, dtype="int32")
def_gen.integers(I_i4_high_closed, dtype="int32", endpoint=True)
def_gen.integers(I_i4_low, I_i4_high_closed, dtype="int32", endpoint=True)
def_gen.integers(-2147483648, I_i4_high_closed, dtype="int32", endpoint=True)
def_gen.integers(2147483648, dtype=np.int32)
def_gen.integers(-2147483648, 2147483648, dtype=np.int32)
def_gen.integers(2147483647, dtype=np.int32, endpoint=True)
def_gen.integers(-2147483648, 2147483647, dtype=np.int32, endpoint=True)
def_gen.integers(I_i4_low_like, 2147483647, dtype=np.int32, endpoint=True)
def_gen.integers(I_i4_high_open, dtype=np.int32)
def_gen.integers(I_i4_low, I_i4_high_open, dtype=np.int32)
def_gen.integers(-2147483648, I_i4_high_open, dtype=np.int32)
def_gen.integers(I_i4_high_closed, dtype=np.int32, endpoint=True)
def_gen.integers(I_i4_low, I_i4_high_closed, dtype=np.int32, endpoint=True)
def_gen.integers(-2147483648, I_i4_high_closed, dtype=np.int32, endpoint=True)
I_i8_low: np.ndarray[Any, np.dtype[np.int64]] = np.array([-9223372036854775808], dtype=np.int64)
I_i8_low_like: list[int] = [-9223372036854775808]
I_i8_high_open: np.ndarray[Any, np.dtype[np.int64]] = np.array([9223372036854775807], dtype=np.int64)
I_i8_high_closed: np.ndarray[Any, np.dtype[np.int64]] = np.array([9223372036854775807], dtype=np.int64)
def_gen.integers(9223372036854775808, dtype="i8")
def_gen.integers(-9223372036854775808, 9223372036854775808, dtype="i8")
def_gen.integers(9223372036854775807, dtype="i8", endpoint=True)
def_gen.integers(-9223372036854775808, 9223372036854775807, dtype="i8", endpoint=True)
def_gen.integers(I_i8_low_like, 9223372036854775807, dtype="i8", endpoint=True)
def_gen.integers(I_i8_high_open, dtype="i8")
def_gen.integers(I_i8_low, I_i8_high_open, dtype="i8")
def_gen.integers(-9223372036854775808, I_i8_high_open, dtype="i8")
def_gen.integers(I_i8_high_closed, dtype="i8", endpoint=True)
def_gen.integers(I_i8_low, I_i8_high_closed, dtype="i8", endpoint=True)
def_gen.integers(-9223372036854775808, I_i8_high_closed, dtype="i8", endpoint=True)
def_gen.integers(9223372036854775808, dtype="int64")
def_gen.integers(-9223372036854775808, 9223372036854775808, dtype="int64")
def_gen.integers(9223372036854775807, dtype="int64", endpoint=True)
def_gen.integers(-9223372036854775808, 9223372036854775807, dtype="int64", endpoint=True)
def_gen.integers(I_i8_low_like, 9223372036854775807, dtype="int64", endpoint=True)
def_gen.integers(I_i8_high_open, dtype="int64")
def_gen.integers(I_i8_low, I_i8_high_open, dtype="int64")
def_gen.integers(-9223372036854775808, I_i8_high_open, dtype="int64")
def_gen.integers(I_i8_high_closed, dtype="int64", endpoint=True)
def_gen.integers(I_i8_low, I_i8_high_closed, dtype="int64", endpoint=True)
def_gen.integers(-9223372036854775808, I_i8_high_closed, dtype="int64", endpoint=True)
def_gen.integers(9223372036854775808, dtype=np.int64)
def_gen.integers(-9223372036854775808, 9223372036854775808, dtype=np.int64)
def_gen.integers(9223372036854775807, dtype=np.int64, endpoint=True)
def_gen.integers(-9223372036854775808, 9223372036854775807, dtype=np.int64, endpoint=True)
def_gen.integers(I_i8_low_like, 9223372036854775807, dtype=np.int64, endpoint=True)
def_gen.integers(I_i8_high_open, dtype=np.int64)
def_gen.integers(I_i8_low, I_i8_high_open, dtype=np.int64)
def_gen.integers(-9223372036854775808, I_i8_high_open, dtype=np.int64)
def_gen.integers(I_i8_high_closed, dtype=np.int64, endpoint=True)
def_gen.integers(I_i8_low, I_i8_high_closed, dtype=np.int64, endpoint=True)
def_gen.integers(-9223372036854775808, I_i8_high_closed, dtype=np.int64, endpoint=True)
def_gen.bit_generator
def_gen.bytes(2)
def_gen.choice(5)
def_gen.choice(5, 3)
def_gen.choice(5, 3, replace=True)
def_gen.choice(5, 3, p=[1 / 5] * 5)
def_gen.choice(5, 3, p=[1 / 5] * 5, replace=False)
def_gen.choice(["pooh", "rabbit", "piglet", "Christopher"])
def_gen.choice(["pooh", "rabbit", "piglet", "Christopher"], 3)
def_gen.choice(["pooh", "rabbit", "piglet", "Christopher"], 3, p=[1 / 4] * 4)
def_gen.choice(["pooh", "rabbit", "piglet", "Christopher"], 3, replace=True)
def_gen.choice(["pooh", "rabbit", "piglet", "Christopher"], 3, replace=False, p=np.array([1 / 8, 1 / 8, 1 / 2, 1 / 4]))
def_gen.dirichlet([0.5, 0.5])
def_gen.dirichlet(np.array([0.5, 0.5]))
def_gen.dirichlet(np.array([0.5, 0.5]), size=3)
def_gen.multinomial(20, [1 / 6.0] * 6)
def_gen.multinomial(20, np.array([0.5, 0.5]))
def_gen.multinomial(20, [1 / 6.0] * 6, size=2)
def_gen.multinomial([[10], [20]], [1 / 6.0] * 6, size=(2, 2))
def_gen.multinomial(np.array([[10], [20]]), np.array([0.5, 0.5]), size=(2, 2))
def_gen.multivariate_hypergeometric([3, 5, 7], 2)
def_gen.multivariate_hypergeometric(np.array([3, 5, 7]), 2)
def_gen.multivariate_hypergeometric(np.array([3, 5, 7]), 2, size=4)
def_gen.multivariate_hypergeometric(np.array([3, 5, 7]), 2, size=(4, 7))
def_gen.multivariate_hypergeometric([3, 5, 7], 2, method="count")
def_gen.multivariate_hypergeometric(np.array([3, 5, 7]), 2, method="marginals")
def_gen.multivariate_normal([0.0], [[1.0]])
def_gen.multivariate_normal([0.0], np.array([[1.0]]))
def_gen.multivariate_normal(np.array([0.0]), [[1.0]])
def_gen.multivariate_normal([0.0], np.array([[1.0]]))
def_gen.permutation(10)
def_gen.permutation([1, 2, 3, 4])
def_gen.permutation(np.array([1, 2, 3, 4]))
def_gen.permutation(D_2D, axis=1)
def_gen.permuted(D_2D)
def_gen.permuted(D_2D_like)
def_gen.permuted(D_2D, axis=1)
def_gen.permuted(D_2D, out=D_2D)
def_gen.permuted(D_2D_like, out=D_2D)
def_gen.permuted(D_2D_like, out=D_2D)
def_gen.permuted(D_2D, axis=1, out=D_2D)
def_gen.shuffle(np.arange(10))
def_gen.shuffle([1, 2, 3, 4, 5])
def_gen.shuffle(D_2D, axis=1)
def_gen.__str__()
def_gen.__repr__()
def_gen.__setstate__(dict(def_gen.bit_generator.state))
# RandomState
random_st: np.random.RandomState = np.random.RandomState()
random_st.standard_normal()
random_st.standard_normal(size=None)
random_st.standard_normal(size=1)
random_st.random()
random_st.random(size=None)
random_st.random(size=1)
random_st.standard_cauchy()
random_st.standard_cauchy(size=None)
random_st.standard_cauchy(size=1)
random_st.standard_exponential()
random_st.standard_exponential(size=None)
random_st.standard_exponential(size=1)
random_st.zipf(1.5)
random_st.zipf(1.5, size=None)
random_st.zipf(1.5, size=1)
random_st.zipf(D_arr_1p5)
random_st.zipf(D_arr_1p5, size=1)
random_st.zipf(D_arr_like_1p5)
random_st.zipf(D_arr_like_1p5, size=1)
random_st.weibull(0.5)
random_st.weibull(0.5, size=None)
random_st.weibull(0.5, size=1)
random_st.weibull(D_arr_0p5)
random_st.weibull(D_arr_0p5, size=1)
random_st.weibull(D_arr_like_0p5)
random_st.weibull(D_arr_like_0p5, size=1)
random_st.standard_t(0.5)
random_st.standard_t(0.5, size=None)
random_st.standard_t(0.5, size=1)
random_st.standard_t(D_arr_0p5)
random_st.standard_t(D_arr_0p5, size=1)
random_st.standard_t(D_arr_like_0p5)
random_st.standard_t(D_arr_like_0p5, size=1)
random_st.poisson(0.5)
random_st.poisson(0.5, size=None)
random_st.poisson(0.5, size=1)
random_st.poisson(D_arr_0p5)
random_st.poisson(D_arr_0p5, size=1)
random_st.poisson(D_arr_like_0p5)
random_st.poisson(D_arr_like_0p5, size=1)
random_st.power(0.5)
random_st.power(0.5, size=None)
random_st.power(0.5, size=1)
random_st.power(D_arr_0p5)
random_st.power(D_arr_0p5, size=1)
random_st.power(D_arr_like_0p5)
random_st.power(D_arr_like_0p5, size=1)
random_st.pareto(0.5)
random_st.pareto(0.5, size=None)
random_st.pareto(0.5, size=1)
random_st.pareto(D_arr_0p5)
random_st.pareto(D_arr_0p5, size=1)
random_st.pareto(D_arr_like_0p5)
random_st.pareto(D_arr_like_0p5, size=1)
random_st.chisquare(0.5)
random_st.chisquare(0.5, size=None)
random_st.chisquare(0.5, size=1)
random_st.chisquare(D_arr_0p5)
random_st.chisquare(D_arr_0p5, size=1)
random_st.chisquare(D_arr_like_0p5)
random_st.chisquare(D_arr_like_0p5, size=1)
random_st.exponential(0.5)
random_st.exponential(0.5, size=None)
random_st.exponential(0.5, size=1)
random_st.exponential(D_arr_0p5)
random_st.exponential(D_arr_0p5, size=1)
random_st.exponential(D_arr_like_0p5)
random_st.exponential(D_arr_like_0p5, size=1)
random_st.geometric(0.5)
random_st.geometric(0.5, size=None)
random_st.geometric(0.5, size=1)
random_st.geometric(D_arr_0p5)
random_st.geometric(D_arr_0p5, size=1)
random_st.geometric(D_arr_like_0p5)
random_st.geometric(D_arr_like_0p5, size=1)
random_st.logseries(0.5)
random_st.logseries(0.5, size=None)
random_st.logseries(0.5, size=1)
random_st.logseries(D_arr_0p5)
random_st.logseries(D_arr_0p5, size=1)
random_st.logseries(D_arr_like_0p5)
random_st.logseries(D_arr_like_0p5, size=1)
random_st.rayleigh(0.5)
random_st.rayleigh(0.5, size=None)
random_st.rayleigh(0.5, size=1)
random_st.rayleigh(D_arr_0p5)
random_st.rayleigh(D_arr_0p5, size=1)
random_st.rayleigh(D_arr_like_0p5)
random_st.rayleigh(D_arr_like_0p5, size=1)
random_st.standard_gamma(0.5)
random_st.standard_gamma(0.5, size=None)
random_st.standard_gamma(0.5, size=1)
random_st.standard_gamma(D_arr_0p5)
random_st.standard_gamma(D_arr_0p5, size=1)
random_st.standard_gamma(D_arr_like_0p5)
random_st.standard_gamma(D_arr_like_0p5, size=1)
random_st.standard_gamma(D_arr_like_0p5, size=1)
random_st.vonmises(0.5, 0.5)
random_st.vonmises(0.5, 0.5, size=None)
random_st.vonmises(0.5, 0.5, size=1)
random_st.vonmises(D_arr_0p5, 0.5)
random_st.vonmises(0.5, D_arr_0p5)
random_st.vonmises(D_arr_0p5, 0.5, size=1)
random_st.vonmises(0.5, D_arr_0p5, size=1)
random_st.vonmises(D_arr_like_0p5, 0.5)
random_st.vonmises(0.5, D_arr_like_0p5)
random_st.vonmises(D_arr_0p5, D_arr_0p5)
random_st.vonmises(D_arr_like_0p5, D_arr_like_0p5)
random_st.vonmises(D_arr_0p5, D_arr_0p5, size=1)
random_st.vonmises(D_arr_like_0p5, D_arr_like_0p5, size=1)
random_st.wald(0.5, 0.5)
random_st.wald(0.5, 0.5, size=None)
random_st.wald(0.5, 0.5, size=1)
random_st.wald(D_arr_0p5, 0.5)
random_st.wald(0.5, D_arr_0p5)
random_st.wald(D_arr_0p5, 0.5, size=1)
random_st.wald(0.5, D_arr_0p5, size=1)
random_st.wald(D_arr_like_0p5, 0.5)
random_st.wald(0.5, D_arr_like_0p5)
random_st.wald(D_arr_0p5, D_arr_0p5)
random_st.wald(D_arr_like_0p5, D_arr_like_0p5)
random_st.wald(D_arr_0p5, D_arr_0p5, size=1)
random_st.wald(D_arr_like_0p5, D_arr_like_0p5, size=1)
random_st.uniform(0.5, 0.5)
random_st.uniform(0.5, 0.5, size=None)
random_st.uniform(0.5, 0.5, size=1)
random_st.uniform(D_arr_0p5, 0.5)
random_st.uniform(0.5, D_arr_0p5)
random_st.uniform(D_arr_0p5, 0.5, size=1)
random_st.uniform(0.5, D_arr_0p5, size=1)
random_st.uniform(D_arr_like_0p5, 0.5)
random_st.uniform(0.5, D_arr_like_0p5)
random_st.uniform(D_arr_0p5, D_arr_0p5)
random_st.uniform(D_arr_like_0p5, D_arr_like_0p5)
random_st.uniform(D_arr_0p5, D_arr_0p5, size=1)
random_st.uniform(D_arr_like_0p5, D_arr_like_0p5, size=1)
random_st.beta(0.5, 0.5)
random_st.beta(0.5, 0.5, size=None)
random_st.beta(0.5, 0.5, size=1)
random_st.beta(D_arr_0p5, 0.5)
random_st.beta(0.5, D_arr_0p5)
random_st.beta(D_arr_0p5, 0.5, size=1)
random_st.beta(0.5, D_arr_0p5, size=1)
random_st.beta(D_arr_like_0p5, 0.5)
random_st.beta(0.5, D_arr_like_0p5)
random_st.beta(D_arr_0p5, D_arr_0p5)
random_st.beta(D_arr_like_0p5, D_arr_like_0p5)
random_st.beta(D_arr_0p5, D_arr_0p5, size=1)
random_st.beta(D_arr_like_0p5, D_arr_like_0p5, size=1)
random_st.f(0.5, 0.5)
random_st.f(0.5, 0.5, size=None)
random_st.f(0.5, 0.5, size=1)
random_st.f(D_arr_0p5, 0.5)
random_st.f(0.5, D_arr_0p5)
random_st.f(D_arr_0p5, 0.5, size=1)
random_st.f(0.5, D_arr_0p5, size=1)
random_st.f(D_arr_like_0p5, 0.5)
random_st.f(0.5, D_arr_like_0p5)
random_st.f(D_arr_0p5, D_arr_0p5)
random_st.f(D_arr_like_0p5, D_arr_like_0p5)
random_st.f(D_arr_0p5, D_arr_0p5, size=1)
random_st.f(D_arr_like_0p5, D_arr_like_0p5, size=1)
random_st.gamma(0.5, 0.5)
random_st.gamma(0.5, 0.5, size=None)
random_st.gamma(0.5, 0.5, size=1)
random_st.gamma(D_arr_0p5, 0.5)
random_st.gamma(0.5, D_arr_0p5)
random_st.gamma(D_arr_0p5, 0.5, size=1)
random_st.gamma(0.5, D_arr_0p5, size=1)
random_st.gamma(D_arr_like_0p5, 0.5)
random_st.gamma(0.5, D_arr_like_0p5)
random_st.gamma(D_arr_0p5, D_arr_0p5)
random_st.gamma(D_arr_like_0p5, D_arr_like_0p5)
random_st.gamma(D_arr_0p5, D_arr_0p5, size=1)
random_st.gamma(D_arr_like_0p5, D_arr_like_0p5, size=1)
random_st.gumbel(0.5, 0.5)
random_st.gumbel(0.5, 0.5, size=None)
random_st.gumbel(0.5, 0.5, size=1)
random_st.gumbel(D_arr_0p5, 0.5)
random_st.gumbel(0.5, D_arr_0p5)
random_st.gumbel(D_arr_0p5, 0.5, size=1)
random_st.gumbel(0.5, D_arr_0p5, size=1)
random_st.gumbel(D_arr_like_0p5, 0.5)
random_st.gumbel(0.5, D_arr_like_0p5)
random_st.gumbel(D_arr_0p5, D_arr_0p5)
random_st.gumbel(D_arr_like_0p5, D_arr_like_0p5)
random_st.gumbel(D_arr_0p5, D_arr_0p5, size=1)
random_st.gumbel(D_arr_like_0p5, D_arr_like_0p5, size=1)
random_st.laplace(0.5, 0.5)
random_st.laplace(0.5, 0.5, size=None)
random_st.laplace(0.5, 0.5, size=1)
random_st.laplace(D_arr_0p5, 0.5)
random_st.laplace(0.5, D_arr_0p5)
random_st.laplace(D_arr_0p5, 0.5, size=1)
random_st.laplace(0.5, D_arr_0p5, size=1)
random_st.laplace(D_arr_like_0p5, 0.5)
random_st.laplace(0.5, D_arr_like_0p5)
random_st.laplace(D_arr_0p5, D_arr_0p5)
random_st.laplace(D_arr_like_0p5, D_arr_like_0p5)
random_st.laplace(D_arr_0p5, D_arr_0p5, size=1)
random_st.laplace(D_arr_like_0p5, D_arr_like_0p5, size=1)
random_st.logistic(0.5, 0.5)
random_st.logistic(0.5, 0.5, size=None)
random_st.logistic(0.5, 0.5, size=1)
random_st.logistic(D_arr_0p5, 0.5)
random_st.logistic(0.5, D_arr_0p5)
random_st.logistic(D_arr_0p5, 0.5, size=1)
random_st.logistic(0.5, D_arr_0p5, size=1)
random_st.logistic(D_arr_like_0p5, 0.5)
random_st.logistic(0.5, D_arr_like_0p5)
random_st.logistic(D_arr_0p5, D_arr_0p5)
random_st.logistic(D_arr_like_0p5, D_arr_like_0p5)
random_st.logistic(D_arr_0p5, D_arr_0p5, size=1)
random_st.logistic(D_arr_like_0p5, D_arr_like_0p5, size=1)
random_st.lognormal(0.5, 0.5)
random_st.lognormal(0.5, 0.5, size=None)
random_st.lognormal(0.5, 0.5, size=1)
random_st.lognormal(D_arr_0p5, 0.5)
random_st.lognormal(0.5, D_arr_0p5)
random_st.lognormal(D_arr_0p5, 0.5, size=1)
random_st.lognormal(0.5, D_arr_0p5, size=1)
random_st.lognormal(D_arr_like_0p5, 0.5)
random_st.lognormal(0.5, D_arr_like_0p5)
random_st.lognormal(D_arr_0p5, D_arr_0p5)
random_st.lognormal(D_arr_like_0p5, D_arr_like_0p5)
random_st.lognormal(D_arr_0p5, D_arr_0p5, size=1)
random_st.lognormal(D_arr_like_0p5, D_arr_like_0p5, size=1)
random_st.noncentral_chisquare(0.5, 0.5)
random_st.noncentral_chisquare(0.5, 0.5, size=None)
random_st.noncentral_chisquare(0.5, 0.5, size=1)
random_st.noncentral_chisquare(D_arr_0p5, 0.5)
random_st.noncentral_chisquare(0.5, D_arr_0p5)
random_st.noncentral_chisquare(D_arr_0p5, 0.5, size=1)
random_st.noncentral_chisquare(0.5, D_arr_0p5, size=1)
random_st.noncentral_chisquare(D_arr_like_0p5, 0.5)
random_st.noncentral_chisquare(0.5, D_arr_like_0p5)
random_st.noncentral_chisquare(D_arr_0p5, D_arr_0p5)
random_st.noncentral_chisquare(D_arr_like_0p5, D_arr_like_0p5)
random_st.noncentral_chisquare(D_arr_0p5, D_arr_0p5, size=1)
random_st.noncentral_chisquare(D_arr_like_0p5, D_arr_like_0p5, size=1)
random_st.normal(0.5, 0.5)
random_st.normal(0.5, 0.5, size=None)
random_st.normal(0.5, 0.5, size=1)
random_st.normal(D_arr_0p5, 0.5)
random_st.normal(0.5, D_arr_0p5)
random_st.normal(D_arr_0p5, 0.5, size=1)
random_st.normal(0.5, D_arr_0p5, size=1)
random_st.normal(D_arr_like_0p5, 0.5)
random_st.normal(0.5, D_arr_like_0p5)
random_st.normal(D_arr_0p5, D_arr_0p5)
random_st.normal(D_arr_like_0p5, D_arr_like_0p5)
random_st.normal(D_arr_0p5, D_arr_0p5, size=1)
random_st.normal(D_arr_like_0p5, D_arr_like_0p5, size=1)
random_st.triangular(0.1, 0.5, 0.9)
random_st.triangular(0.1, 0.5, 0.9, size=None)
random_st.triangular(0.1, 0.5, 0.9, size=1)
random_st.triangular(D_arr_0p1, 0.5, 0.9)
random_st.triangular(0.1, D_arr_0p5, 0.9)
random_st.triangular(D_arr_0p1, 0.5, D_arr_like_0p9, size=1)
random_st.triangular(0.1, D_arr_0p5, 0.9, size=1)
random_st.triangular(D_arr_like_0p1, 0.5, D_arr_0p9)
random_st.triangular(0.5, D_arr_like_0p5, 0.9)
random_st.triangular(D_arr_0p1, D_arr_0p5, 0.9)
random_st.triangular(D_arr_like_0p1, D_arr_like_0p5, 0.9)
random_st.triangular(D_arr_0p1, D_arr_0p5, D_arr_0p9, size=1)
random_st.triangular(D_arr_like_0p1, D_arr_like_0p5, D_arr_like_0p9, size=1)
random_st.noncentral_f(0.1, 0.5, 0.9)
random_st.noncentral_f(0.1, 0.5, 0.9, size=None)
random_st.noncentral_f(0.1, 0.5, 0.9, size=1)
random_st.noncentral_f(D_arr_0p1, 0.5, 0.9)
random_st.noncentral_f(0.1, D_arr_0p5, 0.9)
random_st.noncentral_f(D_arr_0p1, 0.5, D_arr_like_0p9, size=1)
random_st.noncentral_f(0.1, D_arr_0p5, 0.9, size=1)
random_st.noncentral_f(D_arr_like_0p1, 0.5, D_arr_0p9)
random_st.noncentral_f(0.5, D_arr_like_0p5, 0.9)
random_st.noncentral_f(D_arr_0p1, D_arr_0p5, 0.9)
random_st.noncentral_f(D_arr_like_0p1, D_arr_like_0p5, 0.9)
random_st.noncentral_f(D_arr_0p1, D_arr_0p5, D_arr_0p9, size=1)
random_st.noncentral_f(D_arr_like_0p1, D_arr_like_0p5, D_arr_like_0p9, size=1)
random_st.binomial(10, 0.5)
random_st.binomial(10, 0.5, size=None)
random_st.binomial(10, 0.5, size=1)
random_st.binomial(I_arr_10, 0.5)
random_st.binomial(10, D_arr_0p5)
random_st.binomial(I_arr_10, 0.5, size=1)
random_st.binomial(10, D_arr_0p5, size=1)
random_st.binomial(I_arr_like_10, 0.5)
random_st.binomial(10, D_arr_like_0p5)
random_st.binomial(I_arr_10, D_arr_0p5)
random_st.binomial(I_arr_like_10, D_arr_like_0p5)
random_st.binomial(I_arr_10, D_arr_0p5, size=1)
random_st.binomial(I_arr_like_10, D_arr_like_0p5, size=1)
random_st.negative_binomial(10, 0.5)
random_st.negative_binomial(10, 0.5, size=None)
random_st.negative_binomial(10, 0.5, size=1)
random_st.negative_binomial(I_arr_10, 0.5)
random_st.negative_binomial(10, D_arr_0p5)
random_st.negative_binomial(I_arr_10, 0.5, size=1)
random_st.negative_binomial(10, D_arr_0p5, size=1)
random_st.negative_binomial(I_arr_like_10, 0.5)
random_st.negative_binomial(10, D_arr_like_0p5)
random_st.negative_binomial(I_arr_10, D_arr_0p5)
random_st.negative_binomial(I_arr_like_10, D_arr_like_0p5)
random_st.negative_binomial(I_arr_10, D_arr_0p5, size=1)
random_st.negative_binomial(I_arr_like_10, D_arr_like_0p5, size=1)
random_st.hypergeometric(20, 20, 10)
random_st.hypergeometric(20, 20, 10, size=None)
random_st.hypergeometric(20, 20, 10, size=1)
random_st.hypergeometric(I_arr_20, 20, 10)
random_st.hypergeometric(20, I_arr_20, 10)
random_st.hypergeometric(I_arr_20, 20, I_arr_like_10, size=1)
random_st.hypergeometric(20, I_arr_20, 10, size=1)
random_st.hypergeometric(I_arr_like_20, 20, I_arr_10)
random_st.hypergeometric(20, I_arr_like_20, 10)
random_st.hypergeometric(I_arr_20, I_arr_20, 10)
random_st.hypergeometric(I_arr_like_20, I_arr_like_20, 10)
random_st.hypergeometric(I_arr_20, I_arr_20, I_arr_10, size=1)
random_st.hypergeometric(I_arr_like_20, I_arr_like_20, I_arr_like_10, size=1)
random_st.randint(0, 100)
random_st.randint(100)
random_st.randint([100])
random_st.randint(0, [100])
random_st.randint(2, dtype=bool)
random_st.randint(0, 2, dtype=bool)
random_st.randint(I_bool_high_open, dtype=bool)
random_st.randint(I_bool_low, I_bool_high_open, dtype=bool)
random_st.randint(0, I_bool_high_open, dtype=bool)
random_st.randint(2, dtype=np.bool)
random_st.randint(0, 2, dtype=np.bool)
random_st.randint(I_bool_high_open, dtype=np.bool)
random_st.randint(I_bool_low, I_bool_high_open, dtype=np.bool)
random_st.randint(0, I_bool_high_open, dtype=np.bool)
random_st.randint(256, dtype="u1")
random_st.randint(0, 256, dtype="u1")
random_st.randint(I_u1_high_open, dtype="u1")
random_st.randint(I_u1_low, I_u1_high_open, dtype="u1")
random_st.randint(0, I_u1_high_open, dtype="u1")
random_st.randint(256, dtype="uint8")
random_st.randint(0, 256, dtype="uint8")
random_st.randint(I_u1_high_open, dtype="uint8")
random_st.randint(I_u1_low, I_u1_high_open, dtype="uint8")
random_st.randint(0, I_u1_high_open, dtype="uint8")
random_st.randint(256, dtype=np.uint8)
random_st.randint(0, 256, dtype=np.uint8)
random_st.randint(I_u1_high_open, dtype=np.uint8)
random_st.randint(I_u1_low, I_u1_high_open, dtype=np.uint8)
random_st.randint(0, I_u1_high_open, dtype=np.uint8)
random_st.randint(65536, dtype="u2")
random_st.randint(0, 65536, dtype="u2")
random_st.randint(I_u2_high_open, dtype="u2")
random_st.randint(I_u2_low, I_u2_high_open, dtype="u2")
random_st.randint(0, I_u2_high_open, dtype="u2")
random_st.randint(65536, dtype="uint16")
random_st.randint(0, 65536, dtype="uint16")
random_st.randint(I_u2_high_open, dtype="uint16")
random_st.randint(I_u2_low, I_u2_high_open, dtype="uint16")
random_st.randint(0, I_u2_high_open, dtype="uint16")
random_st.randint(65536, dtype=np.uint16)
random_st.randint(0, 65536, dtype=np.uint16)
random_st.randint(I_u2_high_open, dtype=np.uint16)
random_st.randint(I_u2_low, I_u2_high_open, dtype=np.uint16)
random_st.randint(0, I_u2_high_open, dtype=np.uint16)
random_st.randint(4294967296, dtype="u4")
random_st.randint(0, 4294967296, dtype="u4")
random_st.randint(I_u4_high_open, dtype="u4")
random_st.randint(I_u4_low, I_u4_high_open, dtype="u4")
random_st.randint(0, I_u4_high_open, dtype="u4")
random_st.randint(4294967296, dtype="uint32")
random_st.randint(0, 4294967296, dtype="uint32")
random_st.randint(I_u4_high_open, dtype="uint32")
random_st.randint(I_u4_low, I_u4_high_open, dtype="uint32")
random_st.randint(0, I_u4_high_open, dtype="uint32")
random_st.randint(4294967296, dtype=np.uint32)
random_st.randint(0, 4294967296, dtype=np.uint32)
random_st.randint(I_u4_high_open, dtype=np.uint32)
random_st.randint(I_u4_low, I_u4_high_open, dtype=np.uint32)
random_st.randint(0, I_u4_high_open, dtype=np.uint32)
random_st.randint(18446744073709551616, dtype="u8")
random_st.randint(0, 18446744073709551616, dtype="u8")
random_st.randint(I_u8_high_open, dtype="u8")
random_st.randint(I_u8_low, I_u8_high_open, dtype="u8")
random_st.randint(0, I_u8_high_open, dtype="u8")
random_st.randint(18446744073709551616, dtype="uint64")
random_st.randint(0, 18446744073709551616, dtype="uint64")
random_st.randint(I_u8_high_open, dtype="uint64")
random_st.randint(I_u8_low, I_u8_high_open, dtype="uint64")
random_st.randint(0, I_u8_high_open, dtype="uint64")
random_st.randint(18446744073709551616, dtype=np.uint64)
random_st.randint(0, 18446744073709551616, dtype=np.uint64)
random_st.randint(I_u8_high_open, dtype=np.uint64)
random_st.randint(I_u8_low, I_u8_high_open, dtype=np.uint64)
random_st.randint(0, I_u8_high_open, dtype=np.uint64)
random_st.randint(128, dtype="i1")
random_st.randint(-128, 128, dtype="i1")
random_st.randint(I_i1_high_open, dtype="i1")
random_st.randint(I_i1_low, I_i1_high_open, dtype="i1")
random_st.randint(-128, I_i1_high_open, dtype="i1")
random_st.randint(128, dtype="int8")
random_st.randint(-128, 128, dtype="int8")
random_st.randint(I_i1_high_open, dtype="int8")
random_st.randint(I_i1_low, I_i1_high_open, dtype="int8")
random_st.randint(-128, I_i1_high_open, dtype="int8")
random_st.randint(128, dtype=np.int8)
random_st.randint(-128, 128, dtype=np.int8)
random_st.randint(I_i1_high_open, dtype=np.int8)
random_st.randint(I_i1_low, I_i1_high_open, dtype=np.int8)
random_st.randint(-128, I_i1_high_open, dtype=np.int8)
random_st.randint(32768, dtype="i2")
random_st.randint(-32768, 32768, dtype="i2")
random_st.randint(I_i2_high_open, dtype="i2")
random_st.randint(I_i2_low, I_i2_high_open, dtype="i2")
random_st.randint(-32768, I_i2_high_open, dtype="i2")
random_st.randint(32768, dtype="int16")
random_st.randint(-32768, 32768, dtype="int16")
random_st.randint(I_i2_high_open, dtype="int16")
random_st.randint(I_i2_low, I_i2_high_open, dtype="int16")
random_st.randint(-32768, I_i2_high_open, dtype="int16")
random_st.randint(32768, dtype=np.int16)
random_st.randint(-32768, 32768, dtype=np.int16)
random_st.randint(I_i2_high_open, dtype=np.int16)
random_st.randint(I_i2_low, I_i2_high_open, dtype=np.int16)
random_st.randint(-32768, I_i2_high_open, dtype=np.int16)
random_st.randint(2147483648, dtype="i4")
random_st.randint(-2147483648, 2147483648, dtype="i4")
random_st.randint(I_i4_high_open, dtype="i4")
random_st.randint(I_i4_low, I_i4_high_open, dtype="i4")
random_st.randint(-2147483648, I_i4_high_open, dtype="i4")
random_st.randint(2147483648, dtype="int32")
random_st.randint(-2147483648, 2147483648, dtype="int32")
random_st.randint(I_i4_high_open, dtype="int32")
random_st.randint(I_i4_low, I_i4_high_open, dtype="int32")
random_st.randint(-2147483648, I_i4_high_open, dtype="int32")
random_st.randint(2147483648, dtype=np.int32)
random_st.randint(-2147483648, 2147483648, dtype=np.int32)
random_st.randint(I_i4_high_open, dtype=np.int32)
random_st.randint(I_i4_low, I_i4_high_open, dtype=np.int32)
random_st.randint(-2147483648, I_i4_high_open, dtype=np.int32)
random_st.randint(9223372036854775808, dtype="i8")
random_st.randint(-9223372036854775808, 9223372036854775808, dtype="i8")
random_st.randint(I_i8_high_open, dtype="i8")
random_st.randint(I_i8_low, I_i8_high_open, dtype="i8")
random_st.randint(-9223372036854775808, I_i8_high_open, dtype="i8")
random_st.randint(9223372036854775808, dtype="int64")
random_st.randint(-9223372036854775808, 9223372036854775808, dtype="int64")
random_st.randint(I_i8_high_open, dtype="int64")
random_st.randint(I_i8_low, I_i8_high_open, dtype="int64")
random_st.randint(-9223372036854775808, I_i8_high_open, dtype="int64")
random_st.randint(9223372036854775808, dtype=np.int64)
random_st.randint(-9223372036854775808, 9223372036854775808, dtype=np.int64)
random_st.randint(I_i8_high_open, dtype=np.int64)
random_st.randint(I_i8_low, I_i8_high_open, dtype=np.int64)
random_st.randint(-9223372036854775808, I_i8_high_open, dtype=np.int64)
bg: np.random.BitGenerator = random_st._bit_generator
random_st.bytes(2)
random_st.choice(5)
random_st.choice(5, 3)
random_st.choice(5, 3, replace=True)
random_st.choice(5, 3, p=[1 / 5] * 5)
random_st.choice(5, 3, p=[1 / 5] * 5, replace=False)
random_st.choice(["pooh", "rabbit", "piglet", "Christopher"])
random_st.choice(["pooh", "rabbit", "piglet", "Christopher"], 3)
random_st.choice(["pooh", "rabbit", "piglet", "Christopher"], 3, p=[1 / 4] * 4)
random_st.choice(["pooh", "rabbit", "piglet", "Christopher"], 3, replace=True)
random_st.choice(["pooh", "rabbit", "piglet", "Christopher"], 3, replace=False, p=np.array([1 / 8, 1 / 8, 1 / 2, 1 / 4]))
random_st.dirichlet([0.5, 0.5])
random_st.dirichlet(np.array([0.5, 0.5]))
random_st.dirichlet(np.array([0.5, 0.5]), size=3)
random_st.multinomial(20, [1 / 6.0] * 6)
random_st.multinomial(20, np.array([0.5, 0.5]))
random_st.multinomial(20, [1 / 6.0] * 6, size=2)
random_st.multivariate_normal([0.0], [[1.0]])
random_st.multivariate_normal([0.0], np.array([[1.0]]))
random_st.multivariate_normal(np.array([0.0]), [[1.0]])
random_st.multivariate_normal([0.0], np.array([[1.0]]))
random_st.permutation(10)
random_st.permutation([1, 2, 3, 4])
random_st.permutation(np.array([1, 2, 3, 4]))
random_st.permutation(D_2D)
random_st.shuffle(np.arange(10))
random_st.shuffle([1, 2, 3, 4, 5])
random_st.shuffle(D_2D)
np.random.RandomState(SEED_PCG64)
np.random.RandomState(0)
np.random.RandomState([0, 1, 2])
random_st.__str__()
random_st.__repr__()
random_st_state = random_st.__getstate__()
random_st.__setstate__(random_st_state)
random_st.seed()
random_st.seed(1)
random_st.seed([0, 1])
random_st_get_state = random_st.get_state()
random_st_get_state_legacy = random_st.get_state(legacy=True)
random_st.set_state(random_st_get_state)
random_st.rand()
random_st.rand(1)
random_st.rand(1, 2)
random_st.randn()
random_st.randn(1)
random_st.randn(1, 2)
random_st.random_sample()
random_st.random_sample(1)
random_st.random_sample(size=(1, 2))
random_st.tomaxint()
random_st.tomaxint(1)
random_st.tomaxint((1,))
np.random.mtrand.set_bit_generator(SEED_PCG64)
np.random.mtrand.get_bit_generator()
| from __future__ import annotations
from typing import Any
import numpy as np
SEED_NONE = None
SEED_INT = 4579435749574957634658964293569
SEED_ARR: np.ndarray[Any, np.dtype[np.int64]] = np.array([1, 2, 3, 4], dtype=np.int64)
SEED_ARRLIKE: list[int] = [1, 2, 3, 4]
SEED_SEED_SEQ: np.random.SeedSequence = np.random.SeedSequence(0)
SEED_MT19937: np.random.MT19937 = np.random.MT19937(0)
SEED_PCG64: np.random.PCG64 = np.random.PCG64(0)
SEED_PHILOX: np.random.Philox = np.random.Philox(0)
SEED_SFC64: np.random.SFC64 = np.random.SFC64(0)
# default rng
np.random.default_rng()
np.random.default_rng(SEED_NONE)
np.random.default_rng(SEED_INT)
np.random.default_rng(SEED_ARR)
np.random.default_rng(SEED_ARRLIKE)
np.random.default_rng(SEED_SEED_SEQ)
np.random.default_rng(SEED_MT19937)
np.random.default_rng(SEED_PCG64)
np.random.default_rng(SEED_PHILOX)
np.random.default_rng(SEED_SFC64)
# Seed Sequence
np.random.SeedSequence(SEED_NONE)
np.random.SeedSequence(SEED_INT)
np.random.SeedSequence(SEED_ARR)
np.random.SeedSequence(SEED_ARRLIKE)
# Bit Generators
np.random.MT19937(SEED_NONE)
np.random.MT19937 | [] | numpy/numpy | numpy/typing/tests/data/pass/random.py |
import numpy as np
np.isdtype(np.float64, (np.int64, np.float64))
np.isdtype(np.int64, "signed integer")
np.issubdtype("S1", np.bytes_)
np.issubdtype(np.float64, np.float32)
np.ScalarType
np.ScalarType[0]
np.ScalarType[3]
np.ScalarType[8]
np.ScalarType[10]
np.typecodes["Character"]
np.typecodes["Complex"]
np.typecodes["All"]
| import numpy as np
np.isdtype(np.float64, (np.int64, np.float64))
np.isdtype(np.int64, "signed integer")
np.issubdtype("S1", np.bytes_)
np.issubdtype(np.float64, np.float32)
np.ScalarType
np.ScalarType[0]
np.ScalarType[3]
np.ScalarType[8]
np.ScalarType[10]
np.typecodes["Character"]
np.typecodes["Complex"]
np.typecodes["All"]
| [] | numpy/numpy | numpy/typing/tests/data/pass/numerictypes.py |
"""
Tests for :mod:`numpy._core.numeric`.
Does not include tests which fall under ``array_constructors``.
"""
from typing import Any
import numpy as np
class SubClass(np.ndarray[tuple[Any, ...], np.dtype[np.float64]]): ...
i8 = np.int64(1)
A = np.arange(27).reshape(3, 3, 3)
B = A.tolist()
C = np.empty((27, 27)).view(SubClass)
np.count_nonzero(i8)
np.count_nonzero(A)
np.count_nonzero(B)
np.count_nonzero(A, keepdims=True)
np.count_nonzero(A, axis=0)
np.isfortran(i8)
np.isfortran(A)
np.argwhere(i8)
np.argwhere(A)
np.flatnonzero(i8)
np.flatnonzero(A)
np.correlate(B[0][0], A.ravel(), mode="valid")
np.correlate(A.ravel(), A.ravel(), mode="same")
np.convolve(B[0][0], A.ravel(), mode="valid")
np.convolve(A.ravel(), A.ravel(), mode="same")
np.outer(i8, A)
np.outer(B, A)
np.outer(A, A)
np.outer(A, A, out=C)
np.tensordot(B, A)
np.tensordot(A, A)
np.tensordot(A, A, axes=0)
np.tensordot(A, A, axes=(0, 1))
np.isscalar(i8)
np.isscalar(A)
np.isscalar(B)
np.roll(A, 1)
np.roll(A, (1, 2))
np.roll(B, 1)
np.rollaxis(A, 0, 1)
np.moveaxis(A, 0, 1)
np.moveaxis(A, (0, 1), (1, 2))
np.cross(B, A)
np.cross(A, A)
np.indices([0, 1, 2])
np.indices([0, 1, 2], sparse=False)
np.indices([0, 1, 2], sparse=True)
np.binary_repr(1)
np.base_repr(1)
np.allclose(i8, A)
np.allclose(B, A)
np.allclose(A, A)
np.isclose(i8, A)
np.isclose(B, A)
np.isclose(A, A)
np.array_equal(i8, A)
np.array_equal(B, A)
np.array_equal(A, A)
np.array_equiv(i8, A)
np.array_equiv(B, A)
np.array_equiv(A, A)
| """
Tests for :mod:`numpy._core.numeric`.
Does not include tests which fall under ``array_constructors``.
"""
from typing import Any
import numpy as np
class SubClass(np.ndarray[tuple[Any, ...], np.dtype[np.float64]]): ...
i8 = np.int64(1)
A = np.arange(27).reshape(3, 3, 3)
B = A.tolist()
C = np.empty((27, 27)).view(SubClass)
np.count_nonzero(i8)
np.count_nonzero(A)
np.count_nonzero(B)
np.count_nonzero(A, keepdims=True)
np.count_nonzero(A, axis=0)
np.isfortran(i8)
np.isfortran(A)
np.argwhere(i8)
np.argwhere(A)
np.flatnonzero(i8)
np.flatnonzero(A)
np.correlate(B[0][0], A.ravel(), mode="valid")
np.correlate(A.ravel(), A.ravel(), mode="same")
np.convolve(B[0][0], A.ravel(), mode="valid")
np.convolve(A.ravel(), A.ravel(), mode="same")
np.outer(i8, A)
np.outer(B, A)
np.outer(A, A)
np.outer(A, A, out=C)
np.tensordot(B, A)
np.tensordot(A, A)
np.tensordot(A, A, axes=0)
np.tensordot(A, A, axes=(0, 1))
np.isscalar(i8)
np.isscalar(A)
np.isscalar(B)
np.roll(A, 1)
np.roll(A, (1, 2))
np.roll(B, 1)
np.rollaxis(A, 0, 1)
np | [] | numpy/numpy | numpy/typing/tests/data/pass/numeric.py |
import numpy as np
arr = np.array([1])
np.nditer([arr, None])
| import numpy as np
arr = np.array([1])
np.nditer([arr, None])
| [] | numpy/numpy | numpy/typing/tests/data/pass/nditer.py |
import numpy as np
nd1 = np.array([[1, 2], [3, 4]])
# reshape
nd1.reshape(4)
nd1.reshape(2, 2)
nd1.reshape((2, 2))
nd1.reshape((2, 2), order="C")
nd1.reshape(4, order="C")
# resize
nd1.resize() # type: ignore[deprecated]
nd1.resize(4) # type: ignore[deprecated]
nd1.resize(2, 2) # type: ignore[deprecated]
nd1.resize((2, 2)) # type: ignore[deprecated]
nd1.resize((2, 2), refcheck=True) # type: ignore[deprecated]
nd1.resize(4, refcheck=True) # type: ignore[deprecated]
nd2 = np.array([[1, 2], [3, 4]])
# transpose
nd2.transpose()
nd2.transpose(1, 0)
nd2.transpose((1, 0))
# swapaxes
nd2.swapaxes(0, 1)
# flatten
nd2.flatten()
nd2.flatten("C")
# ravel
nd2.ravel()
nd2.ravel("C")
# squeeze
nd2.squeeze()
nd3 = np.array([[1, 2]])
nd3.squeeze(0)
nd4 = np.array([[[1, 2]]])
nd4.squeeze((0, 1))
| import numpy as np
nd1 = np.array([[1, 2], [3, 4]])
# reshape
nd1.reshape(4)
nd1.reshape(2, 2)
nd1.reshape((2, 2))
nd1.reshape((2, 2), order="C")
nd1.reshape(4, order="C")
# resize
nd1.resize() # type: ignore[deprecated]
nd1.resize(4) # type: ignore[deprecated]
nd1.resize(2, 2) # type: ignore[deprecated]
nd1.resize((2, 2)) # type: ignore[deprecated]
nd1.resize((2, 2), refcheck=True) # type: ignore[deprecated]
nd1.resize(4, refcheck=True) # type: ignore[deprecated]
nd2 = np.array([[1, 2], [3, 4]])
# transpose
nd2.transpose()
nd2.transpose(1, 0)
nd2.transpose((1, 0))
# swapaxes
nd2.swapaxes(0, 1)
# flatten
nd2.flatten()
nd2.flatten("C")
# ravel
nd2.ravel()
nd2.ravel("C")
# squeeze
nd2.squeeze()
nd3 = np.array([[1, 2]])
nd3.squeeze(0)
nd4 = np.array([[[1, 2]]])
nd4.squeeze((0, 1))
| [] | numpy/numpy | numpy/typing/tests/data/pass/ndarray_shape_manipulation.py |
"""
Tests for miscellaneous (non-magic) ``np.ndarray``/``np.generic`` methods.
More extensive tests are performed for the methods'
function-based counterpart in `../from_numeric.py`.
"""
from __future__ import annotations
import operator
from collections.abc import Hashable
from typing import Any, cast
import numpy as np
import numpy.typing as npt
class SubClass(np.ndarray[tuple[Any, ...], np.dtype[np.float64]]): ...
class IntSubClass(np.ndarray[tuple[Any, ...], np.dtype[np.intp]]): ...
i4 = np.int32(1)
A: np.ndarray[Any, np.dtype[np.int32]] = np.array([[1]], dtype=np.int32)
B0 = np.empty((), dtype=np.int32).view(SubClass)
B1 = np.empty((1,), dtype=np.int32).view(SubClass)
B2 = np.empty((1, 1), dtype=np.int32).view(SubClass)
B_int0: IntSubClass = np.empty((), dtype=np.intp).view(IntSubClass)
C: np.ndarray[Any, np.dtype[np.int32]] = np.array([0, 1, 2], dtype=np.int32)
D = np.ones(3).view(SubClass)
ctypes_obj = A.ctypes
i4.all()
A.all()
A.all(axis=0)
A.all(keepdims=True)
A.all(out=B0)
i4.any()
A.any()
A.any(axis=0)
A.any(keepdims=True)
A.any(out=B0)
i4.argmax()
A.argmax()
A.argmax(axis=0)
A.argmax(out=B_int0)
i4.argmin()
A.argmin()
A.argmin(axis=0)
A.argmin(out=B_int0)
i4.argsort()
i4.argsort(stable=True)
A.argsort()
A.argsort(stable=True)
A.sort()
A.sort(stable=True)
i4.choose([()])
_choices = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype=np.int32)
C.choose(_choices)
C.choose(_choices, out=D)
i4.clip(1)
A.clip(1)
A.clip(None, 1)
A.clip(1, out=B2)
A.clip(None, 1, out=B2)
i4.compress([1])
A.compress([1])
A.compress([1], out=B1)
i4.conj()
A.conj()
B0.conj()
i4.conjugate()
A.conjugate()
B0.conjugate()
i4.cumprod()
A.cumprod()
A.cumprod(out=B1)
i4.cumsum()
A.cumsum()
A.cumsum(out=B1)
i4.max()
A.max()
A.max(axis=0)
A.max(keepdims=True)
A.max(out=B0)
i4.mean()
A.mean()
A.mean(axis=0)
A.mean(keepdims=True)
A.mean(out=B0)
i4.min()
A.min()
A.min(axis=0)
A.min(keepdims=True)
A.min(out=B0)
i4.prod()
A.prod()
A.prod(axis=0)
A.prod(keepdims=True)
A.prod(out=B0)
i4.round()
A.round()
A.round(out=B2)
i4.repeat(1)
A.repeat(1)
B0.repeat(1)
i4.std()
A.std()
A.std(axis=0)
A.std(keepdims=True, mean=0.)
A.std(out=B0.astype(np.float64))
i4.sum()
A.sum()
A.sum(axis=0)
A.sum(keepdims=True)
A.sum(out=B0)
i4.take(0)
A.take(0)
A.take([0])
A.take(0, out=B0)
A.take([0], out=B1)
i4.var()
A.var()
A.var(axis=0)
A.var(keepdims=True, mean=0.)
A.var(out=B0)
A.argpartition([0])
A.diagonal()
A.dot(1)
A.dot(1, out=B2)
A.nonzero()
C.searchsorted(1)
A.trace()
A.trace(out=B0)
void = cast(np.void, np.array(1, dtype=[("f", np.float64)]).take(0))
void.setfield(10, np.float64)
A.item(0)
C.item(0)
A.ravel()
C.ravel()
A.flatten()
C.flatten()
A.reshape(1)
C.reshape(3)
int(np.array(1.0, dtype=np.float64))
int(np.array("1", dtype=np.str_))
float(np.array(1.0, dtype=np.float64))
float(np.array("1", dtype=np.str_))
complex(np.array(1.0, dtype=np.float64))
operator.index(np.array(1, dtype=np.int64))
# this fails on numpy 2.2.1
# https://github.com/scipy/scipy/blob/a755ee77ec47a64849abe42c349936475a6c2f24/scipy/io/arff/tests/test_arffread.py#L41-L44
A_float = np.array([[1, 5], [2, 4], [np.nan, np.nan]])
A_void: npt.NDArray[np.void] = np.empty(3, [("yop", float), ("yap", float)])
A_void["yop"] = A_float[:, 0]
A_void["yap"] = A_float[:, 1]
# regression test for https://github.com/numpy/numpy/issues/30445
def f(x: np.generic) -> Hashable:
return x
| """
Tests for miscellaneous (non-magic) ``np.ndarray``/``np.generic`` methods.
More extensive tests are performed for the methods'
function-based counterpart in `../from_numeric.py`.
"""
from __future__ import annotations
import operator
from collections.abc import Hashable
from typing import Any, cast
import numpy as np
import numpy.typing as npt
class SubClass(np.ndarray[tuple[Any, ...], np.dtype[np.float64]]): ...
class IntSubClass(np.ndarray[tuple[Any, ...], np.dtype[np.intp]]): ...
i4 = np.int32(1)
A: np.ndarray[Any, np.dtype[np.int32]] = np.array([[1]], dtype=np.int32)
B0 = np.empty((), dtype=np.int32).view(SubClass)
B1 = np.empty((1,), dtype=np.int32).view(SubClass)
B2 = np.empty((1, 1), dtype=np.int32).view(SubClass)
B_int0: IntSubClass = np.empty((), dtype=np.intp).view(IntSubClass)
C: np.ndarray[Any, np.dtype[np.int32]] = np.array([0, 1, 2], dtype=np.int32)
D = np.ones(3).view(SubClass)
ctypes_obj = A.ctypes
i4.all()
A.all()
A.all(axis=0)
A.all(keepdims=True)
A.all(out=B0)
i4.any()
A.any()
A.any(axis=0)
A.any(keepdims=True)
A.any(out=B0)
i4.argmax()
A.argmax()
A.argmax(axis=0)
A.argmax(out=B_int0)
i4.argmin()
A.argmin()
A.argmin | [] | numpy/numpy | numpy/typing/tests/data/pass/ndarray_misc.py |
import os
import tempfile
import numpy as np
nd = np.array([[1, 2], [3, 4]])
scalar_array = np.array(1)
# item
scalar_array.item()
nd.item(1)
nd.item(0, 1)
nd.item((0, 1))
# tobytes
nd.tobytes()
nd.tobytes("C")
nd.tobytes(None)
# tofile
if os.name != "nt":
with tempfile.NamedTemporaryFile(suffix=".txt") as tmp:
nd.tofile(tmp.name)
nd.tofile(tmp.name, "")
nd.tofile(tmp.name, sep="")
nd.tofile(tmp.name, "", "%s")
nd.tofile(tmp.name, format="%s")
nd.tofile(tmp)
# dump is pretty simple
# dumps is pretty simple
# astype
nd.astype("float")
nd.astype(float)
nd.astype(float, "K")
nd.astype(float, order="K")
nd.astype(float, "K", "unsafe")
nd.astype(float, casting="unsafe")
nd.astype(float, "K", "unsafe", True)
nd.astype(float, subok=True)
nd.astype(float, "K", "unsafe", True, True)
nd.astype(float, copy=True)
# byteswap
nd.byteswap()
nd.byteswap(True)
# copy
nd.copy()
nd.copy("C")
# view
nd.view()
nd.view(np.int64)
nd.view(dtype=np.int64)
nd.view(np.int64, np.matrix)
nd.view(type=np.matrix)
# getfield
complex_array = np.array([[1 + 1j, 0], [0, 1 - 1j]], dtype=np.complex128)
complex_array.getfield("float")
complex_array.getfield(float)
complex_array.getfield("float", 8)
complex_array.getfield(float, offset=8)
# setflags
nd.setflags()
nd.setflags(write=True)
nd.setflags(write=True, align=True)
nd.setflags(write=True, align=True, uic=False)
# fill is pretty simple
| import os
import tempfile
import numpy as np
nd = np.array([[1, 2], [3, 4]])
scalar_array = np.array(1)
# item
scalar_array.item()
nd.item(1)
nd.item(0, 1)
nd.item((0, 1))
# tobytes
nd.tobytes()
nd.tobytes("C")
nd.tobytes(None)
# tofile
if os.name != "nt":
with tempfile.NamedTemporaryFile(suffix=".txt") as tmp:
nd.tofile(tmp.name)
nd.tofile(tmp.name, "")
nd.tofile(tmp.name, sep="")
nd.tofile(tmp.name, "", "%s")
nd.tofile(tmp.name, format="%s")
nd.tofile(tmp)
# dump is pretty simple
# dumps is pretty simple
# astype
nd.astype("float")
nd.astype(float)
nd.astype(float, "K")
nd.astype(float, order="K")
nd.astype(float, "K", "unsafe")
nd.astype(float, casting="unsafe")
nd.astype(float, "K", "unsafe", True)
nd.astype(float, subok=True)
nd.astype(float, "K", "unsafe", True, True)
nd.astype(float, copy=True)
# byteswap
nd.byteswap()
nd.byteswap(True)
# copy
nd.copy()
nd.copy("C")
# view
nd.view()
nd.view(np.int64)
nd.view(dtype=np.int64)
nd.view(np.int64, np.matrix)
nd.view(type | [] | numpy/numpy | numpy/typing/tests/data/pass/ndarray_conversion.py |
import numpy as np
import numpy.typing as npt
AR_f8: npt.NDArray[np.float64] = np.array([1.0])
AR_i4 = np.array([1], dtype=np.int32)
AR_u1 = np.array([1], dtype=np.uint8)
AR_LIKE_f = [1.5]
AR_LIKE_i = [1]
b_f8 = np.broadcast(AR_f8)
b_i4_f8_f8 = np.broadcast(AR_i4, AR_f8, AR_f8)
next(b_f8)
b_f8.reset()
b_f8.index
b_f8.iters
b_f8.nd
b_f8.ndim
b_f8.numiter
b_f8.shape
b_f8.size
next(b_i4_f8_f8)
b_i4_f8_f8.reset()
b_i4_f8_f8.ndim
b_i4_f8_f8.index
b_i4_f8_f8.iters
b_i4_f8_f8.nd
b_i4_f8_f8.numiter
b_i4_f8_f8.shape
b_i4_f8_f8.size
np.inner(AR_f8, AR_i4)
np.where([True, True, False])
np.where([True, True, False], 1, 0)
np.lexsort([0, 1, 2])
np.can_cast(np.dtype("i8"), int)
np.can_cast(AR_f8, "f8")
np.can_cast(AR_f8, np.complex128, casting="unsafe")
np.min_scalar_type([1])
np.min_scalar_type(AR_f8)
np.result_type(int, AR_i4)
np.result_type(AR_f8, AR_u1)
np.result_type(AR_f8, np.complex128)
np.dot(AR_LIKE_f, AR_i4)
np.dot(AR_u1, 1)
np.dot(1.5j, 1)
np.dot(AR_u1, 1, out=AR_f8)
np.vdot(AR_LIKE_f, AR_i4)
np.vdot(AR_u1, 1)
np.vdot(1.5j, 1)
np.bincount(AR_i4)
np.copyto(AR_f8, [1.6])
np.putmask(AR_f8, [True], 1.5)
np.packbits(AR_i4)
np.packbits(AR_u1)
np.unpackbits(AR_u1)
np.shares_memory(1, 2)
np.shares_memory(AR_f8, AR_f8, max_work=-1)
np.may_share_memory(1, 2)
np.may_share_memory(AR_f8, AR_f8, max_work=0)
np.may_share_memory(AR_f8, AR_f8, max_work=-1)
| import numpy as np
import numpy.typing as npt
AR_f8: npt.NDArray[np.float64] = np.array([1.0])
AR_i4 = np.array([1], dtype=np.int32)
AR_u1 = np.array([1], dtype=np.uint8)
AR_LIKE_f = [1.5]
AR_LIKE_i = [1]
b_f8 = np.broadcast(AR_f8)
b_i4_f8_f8 = np.broadcast(AR_i4, AR_f8, AR_f8)
next(b_f8)
b_f8.reset()
b_f8.index
b_f8.iters
b_f8.nd
b_f8.ndim
b_f8.numiter
b_f8.shape
b_f8.size
next(b_i4_f8_f8)
b_i4_f8_f8.reset()
b_i4_f8_f8.ndim
b_i4_f8_f8.index
b_i4_f8_f8.iters
b_i4_f8_f8.nd
b_i4_f8_f8.numiter
b_i4_f8_f8.shape
b_i4_f8_f8.size
np.inner(AR_f8, AR_i4)
np.where([True, True, False])
np.where([True, True, False], 1, 0)
np.lexsort([0, 1, 2])
np.can_cast(np.dtype("i8"), int)
np.can_cast(AR_f8, "f8")
np.can_cast(AR_f8, np.complex128, casting="unsafe")
np.min_scalar_type([1])
np.min_scalar_type(AR_f8)
np.result_type(int, AR_i4)
np.result_type( | [] | numpy/numpy | numpy/typing/tests/data/pass/multiarray.py |
import numpy as np
from numpy import f2py
np.char
np.ctypeslib
np.emath
np.fft
np.lib
np.linalg
np.ma
np.matrixlib
np.polynomial
np.random
np.rec
np.strings
np.testing
np.version
np.lib.format
np.lib.mixins
np.lib.scimath
np.lib.stride_tricks
np.lib.array_utils
np.ma.extras
np.polynomial.chebyshev
np.polynomial.hermite
np.polynomial.hermite_e
np.polynomial.laguerre
np.polynomial.legendre
np.polynomial.polynomial
np.__path__
np.__version__
np.__all__
np.char.__all__
np.ctypeslib.__all__
np.emath.__all__
np.lib.__all__
np.ma.__all__
np.random.__all__
np.rec.__all__
np.strings.__all__
np.testing.__all__
f2py.__all__
| import numpy as np
from numpy import f2py
np.char
np.ctypeslib
np.emath
np.fft
np.lib
np.linalg
np.ma
np.matrixlib
np.polynomial
np.random
np.rec
np.strings
np.testing
np.version
np.lib.format
np.lib.mixins
np.lib.scimath
np.lib.stride_tricks
np.lib.array_utils
np.ma.extras
np.polynomial.chebyshev
np.polynomial.hermite
np.polynomial.hermite_e
np.polynomial.laguerre
np.polynomial.legendre
np.polynomial.polynomial
np.__path__
np.__version__
np.__all__
np.char.__all__
np.ctypeslib.__all__
np.emath.__all__
np.lib.__all__
np.ma.__all__
np.random.__all__
np.rec.__all__
np.strings.__all__
np.testing.__all__
f2py.__all__
| [] | numpy/numpy | numpy/typing/tests/data/pass/modules.py |
import numpy as np
f8 = np.float64(1)
i8 = np.int64(1)
u8 = np.uint64(1)
f4 = np.float32(1)
i4 = np.int32(1)
u4 = np.uint32(1)
td = np.timedelta64(1, "D")
b_ = np.bool(1)
b = bool(1)
f = float(1)
i = 1
AR = np.array([1], dtype=np.bool)
AR.setflags(write=False)
AR2 = np.array([1], dtype=np.timedelta64)
AR2.setflags(write=False)
# Time structures
td % td
td % AR2
AR2 % td
divmod(td, td)
divmod(td, AR2)
divmod(AR2, td)
# Bool
b_ % b
b_ % i
b_ % f
b_ % b_
b_ % i8
b_ % u8
b_ % f8
b_ % AR
divmod(b_, b)
divmod(b_, i)
divmod(b_, f)
divmod(b_, b_)
divmod(b_, i8)
divmod(b_, u8)
divmod(b_, f8)
divmod(b_, AR)
b % b_
i % b_
f % b_
b_ % b_
i8 % b_
u8 % b_
f8 % b_
AR % b_
divmod(b, b_)
divmod(i, b_)
divmod(f, b_)
divmod(b_, b_)
divmod(i8, b_)
divmod(u8, b_)
divmod(f8, b_)
divmod(AR, b_)
# int
i8 % b
i8 % i
i8 % f
i8 % i8
i8 % f8
i4 % i8
i4 % f8
i4 % i4
i4 % f4
i8 % AR
divmod(i8, b)
divmod(i8, i)
divmod(i8, f)
divmod(i8, i8)
divmod(i8, f8)
divmod(i8, i4)
divmod(i8, f4)
divmod(i4, i4)
divmod(i4, f4)
divmod(i8, AR)
b % i8
i % i8
f % i8
i8 % i8
f8 % i8
i8 % i4
f8 % i4
i4 % i4
f4 % i4
AR % i8
divmod(b, i8)
divmod(i, i8)
divmod(f, i8)
divmod(i8, i8)
divmod(f8, i8)
divmod(i4, i8)
divmod(f4, i8)
divmod(i4, i4)
divmod(f4, i4)
divmod(AR, i8)
# float
f8 % b
f8 % i
f8 % f
i8 % f4
f4 % f4
f8 % AR
divmod(f8, b)
divmod(f8, i)
divmod(f8, f)
divmod(f8, f8)
divmod(f8, f4)
divmod(f4, f4)
divmod(f8, AR)
b % f8
i % f8
f % f8
f8 % f8
f8 % f8
f4 % f4
AR % f8
divmod(b, f8)
divmod(i, f8)
divmod(f, f8)
divmod(f8, f8)
divmod(f4, f8)
divmod(f4, f4)
divmod(AR, f8)
| import numpy as np
f8 = np.float64(1)
i8 = np.int64(1)
u8 = np.uint64(1)
f4 = np.float32(1)
i4 = np.int32(1)
u4 = np.uint32(1)
td = np.timedelta64(1, "D")
b_ = np.bool(1)
b = bool(1)
f = float(1)
i = 1
AR = np.array([1], dtype=np.bool)
AR.setflags(write=False)
AR2 = np.array([1], dtype=np.timedelta64)
AR2.setflags(write=False)
# Time structures
td % td
td % AR2
AR2 % td
divmod(td, td)
divmod(td, AR2)
divmod(AR2, td)
# Bool
b_ % b
b_ % i
b_ % f
b_ % b_
b_ % i8
b_ % u8
b_ % f8
b_ % AR
divmod(b_, b)
divmod(b_, i)
divmod(b_, f)
divmod(b_, b_)
divmod(b_, i8)
divmod(b_, u8)
divmod(b_, f8)
divmod(b_, AR)
b % b_
i % b_
f % b_
b_ % b_
i8 % b_
u8 % b_
f8 % b_
AR % b_
divmod(b, b_)
divmod(i, b_)
divmod(f, b_)
divmod(b_, b_)
divmod(i8, b_)
divmod(u8, b_)
divmod(f8, b_)
divmod(AR, b_)
# int
i8 % b
i8 % i
i8 % f
i8 % i8
i8 % f8
i4 % i8
| [] | numpy/numpy | numpy/typing/tests/data/pass/mod.py |
import datetime as dt
from typing import Any, cast
import numpy as np
import numpy.typing as npt
from numpy._typing import _Shape
type MaskedArray[ScalarT: np.generic] = np.ma.MaskedArray[_Shape, np.dtype[ScalarT]]
# mypy: disable-error-code=no-untyped-call
MAR_b: MaskedArray[np.bool] = np.ma.MaskedArray([True])
MAR_u: MaskedArray[np.uint32] = np.ma.MaskedArray([1], dtype=np.uint32)
MAR_i: MaskedArray[np.int64] = np.ma.MaskedArray([1])
MAR_f: MaskedArray[np.float64] = np.ma.MaskedArray([1.0])
MAR_c: MaskedArray[np.complex128] = np.ma.MaskedArray([1j])
MAR_td64: MaskedArray[np.timedelta64] = np.ma.MaskedArray([np.timedelta64(1, "D")])
MAR_dt64: MaskedArray[np.datetime64] = np.ma.MaskedArray([np.datetime64(1, "D")])
MAR_S: MaskedArray[np.bytes_] = np.ma.MaskedArray([b'foo'], dtype=np.bytes_)
MAR_U: MaskedArray[np.str_] = np.ma.MaskedArray(['foo'], dtype=np.str_)
MAR_T = cast(np.ma.MaskedArray[Any, np.dtypes.StringDType],
np.ma.MaskedArray(["a"], dtype="T"))
MAR_V: MaskedArray[np.void] = np.ma.MaskedArray(
[(1, 1)],
mask=[(False, False)],
dtype=[('a', int), ('b', int)]
)
AR_b: npt.NDArray[np.bool] = np.array([True, False, True])
AR_LIKE_b = [True]
AR_LIKE_u = [np.uint32(1)]
AR_LIKE_i = [1]
AR_LIKE_f = [1.0]
AR_LIKE_c = [1j]
AR_LIKE_m = [np.timedelta64(1, "D")]
AR_LIKE_M = [np.datetime64(1, "D")]
MAR_f.mask = AR_b
MAR_f.mask = np.False_
MAR_i.fill_value = 0
MAR_b.flat[MAR_i > 0] = False
MAR_i.flat[:] = 1
MAR_f.flat[[0]] = AR_LIKE_f
MAR_c.flat[[0, 0]] = [3, 4 + 3j]
MAR_td64.flat[0] = dt.timedelta(1)
MAR_dt64.flat[0] = dt.datetime(2020, 1, 1)
MAR_b[MAR_i > 0] = False
MAR_i[:] = 1
MAR_f[[0]] = AR_LIKE_f
MAR_c[[0, 0]] = [3, 4 + 3j]
MAR_td64[0] = dt.timedelta(1)
MAR_dt64[0] = dt.datetime(2020, 1, 1)
MAR_V['a'] = [2]
# Inplace addition
MAR_b += AR_LIKE_b
MAR_u += AR_LIKE_b
MAR_u += AR_LIKE_u
MAR_i += AR_LIKE_b
MAR_i += 2
MAR_i += AR_LIKE_i
MAR_f += AR_LIKE_b
MAR_f += 2
MAR_f += AR_LIKE_u
MAR_f += AR_LIKE_i
MAR_f += AR_LIKE_f
MAR_c += AR_LIKE_b
MAR_c += AR_LIKE_u
MAR_c += AR_LIKE_i
MAR_c += AR_LIKE_f
MAR_c += AR_LIKE_c
MAR_td64 += AR_LIKE_b
MAR_td64 += AR_LIKE_u
MAR_td64 += AR_LIKE_i
MAR_td64 += AR_LIKE_m
MAR_dt64 += AR_LIKE_b
MAR_dt64 += AR_LIKE_u
MAR_dt64 += AR_LIKE_i
MAR_dt64 += AR_LIKE_m
MAR_S += b'snakes'
MAR_U += 'snakes'
MAR_T += 'snakes'
# Inplace subtraction
MAR_u -= AR_LIKE_b
MAR_u -= AR_LIKE_u
MAR_i -= AR_LIKE_b
MAR_i -= AR_LIKE_i
MAR_f -= AR_LIKE_b
MAR_f -= AR_LIKE_u
MAR_f -= AR_LIKE_i
MAR_f -= AR_LIKE_f
MAR_c -= AR_LIKE_b
MAR_c -= AR_LIKE_u
MAR_c -= AR_LIKE_i
MAR_c -= AR_LIKE_f
MAR_c -= AR_LIKE_c
MAR_td64 -= AR_LIKE_b
MAR_td64 -= AR_LIKE_u
MAR_td64 -= AR_LIKE_i
MAR_td64 -= AR_LIKE_m
MAR_dt64 -= AR_LIKE_b
MAR_dt64 -= AR_LIKE_u
MAR_dt64 -= AR_LIKE_i
MAR_dt64 -= AR_LIKE_m
# Inplace floor division
MAR_f //= AR_LIKE_b
MAR_f //= 2
MAR_f //= AR_LIKE_u
MAR_f //= AR_LIKE_i
MAR_f //= AR_LIKE_f
MAR_td64 //= AR_LIKE_i
# Inplace true division
MAR_f /= AR_LIKE_b
MAR_f /= 2
MAR_f /= AR_LIKE_u
MAR_f /= AR_LIKE_i
MAR_f /= AR_LIKE_f
MAR_c /= AR_LIKE_b
MAR_c /= AR_LIKE_u
MAR_c /= AR_LIKE_i
MAR_c /= AR_LIKE_f
MAR_c /= AR_LIKE_c
MAR_td64 /= AR_LIKE_i
# Inplace multiplication
MAR_b *= AR_LIKE_b
MAR_u *= AR_LIKE_b
MAR_u *= AR_LIKE_u
MAR_i *= AR_LIKE_b
MAR_i *= 2
MAR_i *= AR_LIKE_i
MAR_f *= AR_LIKE_b
MAR_f *= 2
MAR_f *= AR_LIKE_u
MAR_f *= AR_LIKE_i
MAR_f *= AR_LIKE_f
MAR_c *= AR_LIKE_b
MAR_c *= AR_LIKE_u
MAR_c *= AR_LIKE_i
MAR_c *= AR_LIKE_f
MAR_c *= AR_LIKE_c
MAR_td64 *= AR_LIKE_b
MAR_td64 *= AR_LIKE_u
MAR_td64 *= AR_LIKE_i
MAR_td64 *= AR_LIKE_f
MAR_S *= 2
MAR_U *= 2
MAR_T *= 2
# Inplace power
MAR_u **= AR_LIKE_b
MAR_u **= AR_LIKE_u
MAR_i **= AR_LIKE_b
MAR_i **= AR_LIKE_i
MAR_f **= AR_LIKE_b
MAR_f **= AR_LIKE_u
MAR_f **= AR_LIKE_i
MAR_f **= AR_LIKE_f
MAR_c **= AR_LIKE_b
MAR_c **= AR_LIKE_u
MAR_c **= AR_LIKE_i
MAR_c **= AR_LIKE_f
MAR_c **= AR_LIKE_c
| import datetime as dt
from typing import Any, cast
import numpy as np
import numpy.typing as npt
from numpy._typing import _Shape
type MaskedArray[ScalarT: np.generic] = np.ma.MaskedArray[_Shape, np.dtype[ScalarT]]
# mypy: disable-error-code=no-untyped-call
MAR_b: MaskedArray[np.bool] = np.ma.MaskedArray([True])
MAR_u: MaskedArray[np.uint32] = np.ma.MaskedArray([1], dtype=np.uint32)
MAR_i: MaskedArray[np.int64] = np.ma.MaskedArray([1])
MAR_f: MaskedArray[np.float64] = np.ma.MaskedArray([1.0])
MAR_c: MaskedArray[np.complex128] = np.ma.MaskedArray([1j])
MAR_td64: MaskedArray[np.timedelta64] = np.ma.MaskedArray([np.timedelta64(1, "D")])
MAR_dt64: MaskedArray[np.datetime64] = np.ma.MaskedArray([np.datetime64(1, "D")])
MAR_S: MaskedArray[np.bytes_] = np.ma.MaskedArray([b'foo'], dtype=np.bytes_)
MAR_U: MaskedArray[np.str_] = np.ma.MaskedArray(['foo'], dtype=np.str_)
MAR_T = cast(np.ma.MaskedArray[Any, np.dtypes.StringDType],
np.ma.MaskedArray(["a"], dtype="T"))
MAR_V: MaskedArray[np.void] = np.ma.MaskedArray(
[(1, 1)],
mask=[(False, False)],
dtype=[('a', int), ('b', int)]
)
AR_b: npt.NDArray[np.bool | [] | numpy/numpy | numpy/typing/tests/data/pass/ma.py |
from __future__ import annotations
from functools import partial
from typing import TYPE_CHECKING, Any
import pytest
import numpy as np
if TYPE_CHECKING:
from collections.abc import Callable
AR = np.array(0)
AR.setflags(write=False)
KACF = frozenset({None, "K", "A", "C", "F"})
ACF = frozenset({None, "A", "C", "F"})
CF = frozenset({None, "C", "F"})
order_list: list[tuple[frozenset[str | None], Callable[..., Any]]] = [
(KACF, AR.tobytes),
(KACF, partial(AR.astype, int)),
(KACF, AR.copy),
(ACF, partial(AR.reshape, 1)),
(KACF, AR.flatten),
(KACF, AR.ravel),
(KACF, partial(np.array, 1)),
# NOTE: __call__ is needed due to python/mypy#17620
(KACF, partial(np.ndarray.__call__, 1)),
(CF, partial(np.zeros, 1)),
(CF, partial(np.ones, 1)),
(CF, partial(np.empty, 1)),
(CF, partial(np.full, 1, 1)),
(KACF, partial(np.zeros_like, AR)),
(KACF, partial(np.ones_like, AR)),
(KACF, partial(np.empty_like, AR)),
(KACF, partial(np.full_like, AR, 1)),
(KACF, partial(np.add.__call__, 1, 1)), # i.e. np.ufunc.__call__
(ACF, partial(np.reshape, AR, 1)),
(KACF, partial(np.ravel, AR)),
(KACF, partial(np.asarray, 1)),
(KACF, partial(np.asanyarray, 1)),
]
for order_set, func in order_list:
for order in order_set:
func(order=order)
invalid_orders = KACF - order_set
for order in invalid_orders:
with pytest.raises(ValueError):
func(order=order)
| from __future__ import annotations
from functools import partial
from typing import TYPE_CHECKING, Any
import pytest
import numpy as np
if TYPE_CHECKING:
from collections.abc import Callable
AR = np.array(0)
AR.setflags(write=False)
KACF = frozenset({None, "K", "A", "C", "F"})
ACF = frozenset({None, "A", "C", "F"})
CF = frozenset({None, "C", "F"})
order_list: list[tuple[frozenset[str | None], Callable[..., Any]]] = [
(KACF, AR.tobytes),
(KACF, partial(AR.astype, int)),
(KACF, AR.copy),
(ACF, partial(AR.reshape, 1)),
(KACF, AR.flatten),
(KACF, AR.ravel),
(KACF, partial(np.array, 1)),
# NOTE: __call__ is needed due to python/mypy#17620
(KACF, partial(np.ndarray.__call__, 1)),
(CF, partial(np.zeros, 1)),
(CF, partial(np.ones, 1)),
(CF, partial(np.empty, 1)),
(CF, partial(np.full, 1, 1)),
(KACF, partial(np.zeros_like, AR)),
(KACF, partial(np.ones_like, AR)),
(KACF, partial(np.empty_like, AR)),
(KACF, partial(np.full_like, AR, 1)),
(KACF, partial(np.add.__call__, 1, 1)), # i.e. np.ufunc.__call__
(ACF, partial(np.reshape, AR, | [] | numpy/numpy | numpy/typing/tests/data/pass/literal.py |
from numpy.lib import NumpyVersion
version = NumpyVersion("1.8.0")
version.vstring
version.version
version.major
version.minor
version.bugfix
version.pre_release
version.is_devversion
version == version
version != version
version < "1.8.0"
version <= version
version > version
version >= "1.8.0"
| from numpy.lib import NumpyVersion
version = NumpyVersion("1.8.0")
version.vstring
version.version
version.major
version.minor
version.bugfix
version.pre_release
version.is_devversion
version == version
version != version
version < "1.8.0"
version <= version
version > version
version >= "1.8.0"
| [
"# numpy/numpy:numpy/lib/_version.py\nNumpyVersion"
] | numpy/numpy | numpy/typing/tests/data/pass/lib_version.py |
from __future__ import annotations
from io import StringIO
import numpy as np
import numpy.lib.array_utils as array_utils
FILE = StringIO()
AR = np.arange(10, dtype=np.float64)
def func(a: int) -> bool:
return True
array_utils.byte_bounds(AR)
array_utils.byte_bounds(np.float64())
np.info(1, output=FILE)
| from __future__ import annotations
from io import StringIO
import numpy as np
import numpy.lib.array_utils as array_utils
FILE = StringIO()
AR = np.arange(10, dtype=np.float64)
def func(a: int) -> bool:
return True
array_utils.byte_bounds(AR)
array_utils.byte_bounds(np.float64())
np.info(1, output=FILE)
| [] | numpy/numpy | numpy/typing/tests/data/pass/lib_utils.py |
"""Based on the `if __name__ == "__main__"` test code in `lib/_user_array_impl.py`."""
from __future__ import annotations
import numpy as np
from numpy.lib.user_array import container # type: ignore[deprecated]
N = 10_000
W = H = int(N**0.5)
a: np.ndarray[tuple[int, int], np.dtype[np.int32]]
ua: container[tuple[int, int], np.dtype[np.int32]]
a = np.arange(N, dtype=np.int32).reshape(W, H)
ua = container(a)
ua_small: container[tuple[int, int], np.dtype[np.int32]] = ua[:3, :5]
ua_small[0, 0] = 10
ua_bool: container[tuple[int, int], np.dtype[np.bool]] = ua_small > 1
# shape: tuple[int, int] = np.shape(ua)
| """Based on the `if __name__ == "__main__"` test code in `lib/_user_array_impl.py`."""
from __future__ import annotations
import numpy as np
from numpy.lib.user_array import container # type: ignore[deprecated]
N = 10_000
W = H = int(N**0.5)
a: np.ndarray[tuple[int, int], np.dtype[np.int32]]
ua: container[tuple[int, int], np.dtype[np.int32]]
a = np.arange(N, dtype=np.int32).reshape(W, H)
ua = container(a)
ua_small: container[tuple[int, int], np.dtype[np.int32]] = ua[:3, :5]
ua_small[0, 0] = 10
ua_bool: container[tuple[int, int], np.dtype[np.bool]] = ua_small > 1
# shape: tuple[int, int] = np.shape(ua)
| [
"# numpy/numpy:numpy/lib/_user_array_impl.py\ncontainer"
] | numpy/numpy | numpy/typing/tests/data/pass/lib_user_array.py |
from __future__ import annotations
from typing import Any
import numpy as np
AR_LIKE_b = [[True, True], [True, True]]
AR_LIKE_i = [[1, 2], [3, 4]]
AR_LIKE_f = [[1.0, 2.0], [3.0, 4.0]]
AR_LIKE_U = [["1", "2"], ["3", "4"]]
AR_i8: np.ndarray[Any, np.dtype[np.int64]] = np.array(AR_LIKE_i, dtype=np.int64)
np.ndenumerate(AR_i8)
np.ndenumerate(AR_LIKE_f)
np.ndenumerate(AR_LIKE_U)
next(np.ndenumerate(AR_i8))
next(np.ndenumerate(AR_LIKE_f))
next(np.ndenumerate(AR_LIKE_U))
iter(np.ndenumerate(AR_i8))
iter(np.ndenumerate(AR_LIKE_f))
iter(np.ndenumerate(AR_LIKE_U))
iter(np.ndindex(1, 2, 3))
next(np.ndindex(1, 2, 3))
np.unravel_index([22, 41, 37], (7, 6))
np.unravel_index([31, 41, 13], (7, 6), order='F')
np.unravel_index(1621, (6, 7, 8, 9))
np.ravel_multi_index(AR_LIKE_i, (7, 6))
np.ravel_multi_index(AR_LIKE_i, (7, 6), order='F')
np.ravel_multi_index(AR_LIKE_i, (4, 6), mode='clip')
np.ravel_multi_index(AR_LIKE_i, (4, 4), mode=('clip', 'wrap'))
np.ravel_multi_index((3, 1, 4, 1), (6, 7, 8, 9))
np.mgrid[1:1:2]
np.mgrid[1:1:2, None:10]
np.ogrid[1:1:2]
np.ogrid[1:1:2, None:10]
np.index_exp[0:1]
np.index_exp[0:1, None:3]
np.index_exp[0, 0:1, ..., [0, 1, 3]]
np.s_[0:1]
np.s_[0:1, None:3]
np.s_[0, 0:1, ..., [0, 1, 3]]
np.ix_(AR_LIKE_b[0])
np.ix_(AR_LIKE_i[0], AR_LIKE_f[0])
np.ix_(AR_i8[0])
np.fill_diagonal(AR_i8, 5)
np.diag_indices(4)
np.diag_indices(2, 3)
np.diag_indices_from(AR_i8)
| from __future__ import annotations
from typing import Any
import numpy as np
AR_LIKE_b = [[True, True], [True, True]]
AR_LIKE_i = [[1, 2], [3, 4]]
AR_LIKE_f = [[1.0, 2.0], [3.0, 4.0]]
AR_LIKE_U = [["1", "2"], ["3", "4"]]
AR_i8: np.ndarray[Any, np.dtype[np.int64]] = np.array(AR_LIKE_i, dtype=np.int64)
np.ndenumerate(AR_i8)
np.ndenumerate(AR_LIKE_f)
np.ndenumerate(AR_LIKE_U)
next(np.ndenumerate(AR_i8))
next(np.ndenumerate(AR_LIKE_f))
next(np.ndenumerate(AR_LIKE_U))
iter(np.ndenumerate(AR_i8))
iter(np.ndenumerate(AR_LIKE_f))
iter(np.ndenumerate(AR_LIKE_U))
iter(np.ndindex(1, 2, 3))
next(np.ndindex(1, 2, 3))
np.unravel_index([22, 41, 37], (7, 6))
np.unravel_index([31, 41, 13], (7, 6), order='F')
np.unravel_index(1621, (6, 7, 8, 9))
np.ravel_multi_index(AR_LIKE_i, (7, 6))
np.ravel_multi_index(AR_LIKE_i, (7, 6), order='F')
np.ravel_multi_index(AR_LIKE_i, (4, 6), mode='clip')
np.ravel_multi_index(AR_LIKE_i, (4, 4), mode=('clip', 'wrap'))
np.ravel_multi_index((3, 1, 4, 1), (6, 7, 8, 9)) | [] | numpy/numpy | numpy/typing/tests/data/pass/index_tricks.py |
"""Tests for :mod:`numpy._core.fromnumeric`."""
import numpy as np
A = np.array(True, ndmin=2, dtype=bool)
B = np.array(1.0, ndmin=2, dtype=np.float32)
A.setflags(write=False)
B.setflags(write=False)
a = np.bool(True)
b = np.float32(1.0)
c = 1.0
d = np.array(1.0, dtype=np.float32) # writeable
np.take(a, 0)
np.take(b, 0)
np.take(c, 0)
np.take(A, 0)
np.take(B, 0)
np.take(A, [0])
np.take(B, [0])
np.reshape(a, 1)
np.reshape(b, 1)
np.reshape(c, 1)
np.reshape(A, 1)
np.reshape(B, 1)
np.choose(a, [True, True])
np.choose(A, [1.0, 1.0])
np.repeat(a, 1)
np.repeat(b, 1)
np.repeat(c, 1)
np.repeat(A, 1)
np.repeat(B, 1)
np.swapaxes(A, 0, 0)
np.swapaxes(B, 0, 0)
np.transpose(a)
np.transpose(b)
np.transpose(c)
np.transpose(A)
np.transpose(B)
np.partition(a, 0, axis=None)
np.partition(b, 0, axis=None)
np.partition(c, 0, axis=None)
np.partition(A, 0)
np.partition(B, 0)
np.argpartition(a, 0)
np.argpartition(b, 0)
np.argpartition(c, 0)
np.argpartition(A, 0)
np.argpartition(B, 0)
np.sort(A, 0)
np.sort(B, 0)
np.argsort(A, 0)
np.argsort(B, 0)
np.argmax(A)
np.argmax(B)
np.argmax(A, axis=0)
np.argmax(B, axis=0)
np.argmin(A)
np.argmin(B)
np.argmin(A, axis=0)
np.argmin(B, axis=0)
np.searchsorted(A[0], 0)
np.searchsorted(B[0], 0)
np.searchsorted(A[0], [0])
np.searchsorted(B[0], [0])
np.resize(a, (5, 5))
np.resize(b, (5, 5))
np.resize(c, (5, 5))
np.resize(A, (5, 5))
np.resize(B, (5, 5))
np.squeeze(a)
np.squeeze(b)
np.squeeze(c)
np.squeeze(A)
np.squeeze(B)
np.diagonal(A)
np.diagonal(B)
np.trace(A)
np.trace(B)
np.ravel(a)
np.ravel(b)
np.ravel(c)
np.ravel(A)
np.ravel(B)
np.nonzero(A)
np.nonzero(B)
np.shape(a)
np.shape(b)
np.shape(c)
np.shape(A)
np.shape(B)
np.compress([True], a)
np.compress([True], b)
np.compress([True], c)
np.compress([True], A)
np.compress([True], B)
np.clip(a, 0, 1.0)
np.clip(b, -1, 1)
np.clip(a, 0, None)
np.clip(b, None, 1)
np.clip(c, 0, 1)
np.clip(A, 0, 1)
np.clip(B, 0, 1)
np.clip(B, [0, 1], [1, 2])
np.sum(a)
np.sum(b)
np.sum(c)
np.sum(A)
np.sum(B)
np.sum(A, axis=0)
np.sum(B, axis=0)
np.all(a)
np.all(b)
np.all(c)
np.all(A)
np.all(B)
np.all(A, axis=0)
np.all(B, axis=0)
np.all(A, keepdims=True)
np.all(B, keepdims=True)
np.any(a)
np.any(b)
np.any(c)
np.any(A)
np.any(B)
np.any(A, axis=0)
np.any(B, axis=0)
np.any(A, keepdims=True)
np.any(B, keepdims=True)
np.cumsum(a)
np.cumsum(b)
np.cumsum(c)
np.cumsum(A)
np.cumsum(B)
np.cumulative_sum(a)
np.cumulative_sum(b)
np.cumulative_sum(c)
np.cumulative_sum(A, axis=0)
np.cumulative_sum(B, axis=0)
np.ptp(b)
np.ptp(c)
np.ptp(B)
np.ptp(B, axis=0)
np.ptp(B, keepdims=True)
np.amax(a)
np.amax(b)
np.amax(c)
np.amax(A)
np.amax(B)
np.amax(A, axis=0)
np.amax(B, axis=0)
np.amax(A, keepdims=True)
np.amax(B, keepdims=True)
np.amin(a)
np.amin(b)
np.amin(c)
np.amin(A)
np.amin(B)
np.amin(A, axis=0)
np.amin(B, axis=0)
np.amin(A, keepdims=True)
np.amin(B, keepdims=True)
np.prod(a)
np.prod(b)
np.prod(c)
np.prod(A)
np.prod(B)
np.prod(a, dtype=None)
np.prod(A, dtype=None)
np.prod(A, axis=0)
np.prod(B, axis=0)
np.prod(A, keepdims=True)
np.prod(B, keepdims=True)
np.prod(b, out=d)
np.prod(B, out=d)
np.cumprod(a)
np.cumprod(b)
np.cumprod(c)
np.cumprod(A)
np.cumprod(B)
np.cumulative_prod(a)
np.cumulative_prod(b)
np.cumulative_prod(c)
np.cumulative_prod(A, axis=0)
np.cumulative_prod(B, axis=0)
np.ndim(a)
np.ndim(b)
np.ndim(c)
np.ndim(A)
np.ndim(B)
np.size(a)
np.size(b)
np.size(c)
np.size(A)
np.size(B)
np.around(a)
np.around(b)
np.around(c)
np.around(A)
np.around(B)
np.mean(a)
np.mean(b)
np.mean(c)
np.mean(A)
np.mean(B)
np.mean(A, axis=0)
np.mean(B, axis=0)
np.mean(A, keepdims=True)
np.mean(B, keepdims=True)
np.mean(b, out=d)
np.mean(B, out=d)
np.std(a)
np.std(b)
np.std(c)
np.std(A)
np.std(B)
np.std(A, axis=0)
np.std(B, axis=0)
np.std(A, keepdims=True)
np.std(B, keepdims=True)
np.std(b, out=d)
np.std(B, out=d)
np.var(a)
np.var(b)
np.var(c)
np.var(A)
np.var(B)
np.var(A, axis=0)
np.var(B, axis=0)
np.var(A, keepdims=True)
np.var(B, keepdims=True)
np.var(b, out=d)
np.var(B, out=d)
| """Tests for :mod:`numpy._core.fromnumeric`."""
import numpy as np
A = np.array(True, ndmin=2, dtype=bool)
B = np.array(1.0, ndmin=2, dtype=np.float32)
A.setflags(write=False)
B.setflags(write=False)
a = np.bool(True)
b = np.float32(1.0)
c = 1.0
d = np.array(1.0, dtype=np.float32) # writeable
np.take(a, 0)
np.take(b, 0)
np.take(c, 0)
np.take(A, 0)
np.take(B, 0)
np.take(A, [0])
np.take(B, [0])
np.reshape(a, 1)
np.reshape(b, 1)
np.reshape(c, 1)
np.reshape(A, 1)
np.reshape(B, 1)
np.choose(a, [True, True])
np.choose(A, [1.0, 1.0])
np.repeat(a, 1)
np.repeat(b, 1)
np.repeat(c, 1)
np.repeat(A, 1)
np.repeat(B, 1)
np.swapaxes(A, 0, 0)
np.swapaxes(B, 0, 0)
np.transpose(a)
np.transpose(b)
np.transpose(c)
np.transpose(A)
np.transpose(B)
np.partition(a, 0, axis=None)
np.partition(b, 0, axis=None)
np.partition(c, 0, axis=None)
np.partition(A, 0)
np.partition(B, 0)
np.argpartition(a, 0)
np.argpartition(b, 0)
np.argpartition(c, 0)
np.argpartition(A | [] | numpy/numpy | numpy/typing/tests/data/pass/fromnumeric.py |
import numpy as np
a = np.empty((2, 2)).flat
a.base
a.copy()
a.coords
a.index
iter(a)
next(a)
a[0]
a[...]
a[:]
a.__array__()
b = np.array([1]).flat
a[b]
a[0] = "1"
a[:] = "2"
a[...] = "3"
a[[]] = "4"
a[[0]] = "5"
a[[[0]]] = "6"
a[[[[[0]]]]] = "7"
a[b] = "8"
| import numpy as np
a = np.empty((2, 2)).flat
a.base
a.copy()
a.coords
a.index
iter(a)
next(a)
a[0]
a[...]
a[:]
a.__array__()
b = np.array([1]).flat
a[b]
a[0] = "1"
a[:] = "2"
a[...] = "3"
a[[]] = "4"
a[[0]] = "5"
a[[[0]]] = "6"
a[[[[[0]]]]] = "7"
a[b] = "8"
| [] | numpy/numpy | numpy/typing/tests/data/pass/flatiter.py |
from __future__ import annotations
from typing import Any
import numpy as np
AR_LIKE_b = [True, True, True]
AR_LIKE_u = [np.uint32(1), np.uint32(2), np.uint32(3)]
AR_LIKE_i = [1, 2, 3]
AR_LIKE_f = [1.0, 2.0, 3.0]
AR_LIKE_c = [1j, 2j, 3j]
AR_LIKE_U = ["1", "2", "3"]
OUT_f: np.ndarray[Any, np.dtype[np.float64]] = np.empty(3, dtype=np.float64)
OUT_c: np.ndarray[Any, np.dtype[np.complex128]] = np.empty(3, dtype=np.complex128)
np.einsum("i,i->i", AR_LIKE_b, AR_LIKE_b)
np.einsum("i,i->i", AR_LIKE_u, AR_LIKE_u)
np.einsum("i,i->i", AR_LIKE_i, AR_LIKE_i)
np.einsum("i,i->i", AR_LIKE_f, AR_LIKE_f)
np.einsum("i,i->i", AR_LIKE_c, AR_LIKE_c)
np.einsum("i,i->i", AR_LIKE_b, AR_LIKE_i)
np.einsum("i,i,i,i->i", AR_LIKE_b, AR_LIKE_u, AR_LIKE_i, AR_LIKE_c)
np.einsum("i,i->i", AR_LIKE_f, AR_LIKE_f, dtype="c16")
np.einsum("i,i->i", AR_LIKE_U, AR_LIKE_U, dtype=bool, casting="unsafe")
np.einsum("i,i->i", AR_LIKE_f, AR_LIKE_f, out=OUT_c)
np.einsum("i,i->i", AR_LIKE_U, AR_LIKE_U, dtype=int, casting="unsafe", out=OUT_f)
np.einsum_path("i,i->i", AR_LIKE_b, AR_LIKE_b)
np.einsum_path("i,i->i", AR_LIKE_u, AR_LIKE_u)
np.einsum_path("i,i->i", AR_LIKE_i, AR_LIKE_i)
np.einsum_path("i,i->i", AR_LIKE_f, AR_LIKE_f)
np.einsum_path("i,i->i", AR_LIKE_c, AR_LIKE_c)
np.einsum_path("i,i->i", AR_LIKE_b, AR_LIKE_i)
np.einsum_path("i,i,i,i->i", AR_LIKE_b, AR_LIKE_u, AR_LIKE_i, AR_LIKE_c)
| from __future__ import annotations
from typing import Any
import numpy as np
AR_LIKE_b = [True, True, True]
AR_LIKE_u = [np.uint32(1), np.uint32(2), np.uint32(3)]
AR_LIKE_i = [1, 2, 3]
AR_LIKE_f = [1.0, 2.0, 3.0]
AR_LIKE_c = [1j, 2j, 3j]
AR_LIKE_U = ["1", "2", "3"]
OUT_f: np.ndarray[Any, np.dtype[np.float64]] = np.empty(3, dtype=np.float64)
OUT_c: np.ndarray[Any, np.dtype[np.complex128]] = np.empty(3, dtype=np.complex128)
np.einsum("i,i->i", AR_LIKE_b, AR_LIKE_b)
np.einsum("i,i->i", AR_LIKE_u, AR_LIKE_u)
np.einsum("i,i->i", AR_LIKE_i, AR_LIKE_i)
np.einsum("i,i->i", AR_LIKE_f, AR_LIKE_f)
np.einsum("i,i->i", AR_LIKE_c, AR_LIKE_c)
np.einsum("i,i->i", AR_LIKE_b, AR_LIKE_i)
np.einsum("i,i,i,i->i", AR_LIKE_b, AR_LIKE_u, AR_LIKE_i, AR_LIKE_c)
np.einsum("i,i->i", AR_LIKE_f, AR_LIKE_f, dtype="c16")
np.einsum("i,i->i", AR_LIKE_U, AR_LIKE_U, dtype=bool, casting="unsafe")
np.einsum("i,i->i", AR_LIKE_f, AR_ | [] | numpy/numpy | numpy/typing/tests/data/pass/einsumfunc.py |
import numpy as np
dtype_obj = np.dtype(np.str_)
void_dtype_obj = np.dtype([("f0", np.float64), ("f1", np.float32)])
np.dtype(dtype=np.int64)
np.dtype(int)
np.dtype("int")
np.dtype(None)
np.dtype((int, 2))
np.dtype((int, (1,)))
np.dtype({"names": ["a", "b"], "formats": [int, float]})
np.dtype({"names": ["a"], "formats": [int], "titles": [object]})
np.dtype({"names": ["a"], "formats": [int], "titles": [object()]})
np.dtype([("name", np.str_, 16), ("grades", np.float64, (2,)), ("age", "int32")])
np.dtype(
{
"names": ["a", "b"],
"formats": [int, float],
"itemsize": 9,
"aligned": False,
"titles": ["x", "y"],
"offsets": [0, 1],
}
)
np.dtype((np.float64, float))
class Test:
dtype = np.dtype(float)
np.dtype(Test())
# Methods and attributes
dtype_obj.base
dtype_obj.subdtype
dtype_obj.newbyteorder()
dtype_obj.type
dtype_obj.name
dtype_obj.names
dtype_obj * 0
dtype_obj * 2
0 * dtype_obj
2 * dtype_obj
void_dtype_obj["f0"]
void_dtype_obj[0]
void_dtype_obj[["f0", "f1"]]
void_dtype_obj[["f0"]]
| import numpy as np
dtype_obj = np.dtype(np.str_)
void_dtype_obj = np.dtype([("f0", np.float64), ("f1", np.float32)])
np.dtype(dtype=np.int64)
np.dtype(int)
np.dtype("int")
np.dtype(None)
np.dtype((int, 2))
np.dtype((int, (1,)))
np.dtype({"names": ["a", "b"], "formats": [int, float]})
np.dtype({"names": ["a"], "formats": [int], "titles": [object]})
np.dtype({"names": ["a"], "formats": [int], "titles": [object()]})
np.dtype([("name", np.str_, 16), ("grades", np.float64, (2,)), ("age", "int32")])
np.dtype(
{
"names": ["a", "b"],
"formats": [int, float],
"itemsize": 9,
"aligned": False,
"titles": ["x", "y"],
"offsets": [0, 1],
}
)
np.dtype((np.float64, float))
class Test:
dtype = np.dtype(float)
np.dtype(Test())
# Methods and attributes
dtype_obj.base
dtype_obj.subdtype
dtype_obj.newbyteorder()
dtype_obj.type
dtype_obj.name
dtype_obj.names
dtype_obj * 0
dtype_obj * 2
0 * dtype_obj
2 * dtype_obj
void_dtype_obj["f0"]
void_dtype_obj[0]
void_dtype_obj[["f0", "f1"] | [] | numpy/numpy | numpy/typing/tests/data/pass/dtype.py |
from __future__ import annotations
from typing import Any, cast
import numpy as np
c16 = np.complex128()
f8 = np.float64()
i8 = np.int64()
u8 = np.uint64()
c8 = np.complex64()
f4 = np.float32()
i4 = np.int32()
u4 = np.uint32()
dt = np.datetime64(0, "D")
td = np.timedelta64(0, "D")
b_ = np.bool()
b = False
c = complex()
f = 0.0
i = 0
SEQ = (0, 1, 2, 3, 4)
AR_b: np.ndarray[Any, np.dtype[np.bool]] = np.array([True])
AR_u: np.ndarray[Any, np.dtype[np.uint32]] = np.array([1], dtype=np.uint32)
AR_i: np.ndarray[Any, np.dtype[np.int_]] = np.array([1])
AR_f: np.ndarray[Any, np.dtype[np.float64]] = np.array([1.0])
AR_c: np.ndarray[Any, np.dtype[np.complex128]] = np.array([1.0j])
AR_S: np.ndarray[Any, np.dtype[np.bytes_]] = np.array([b"a"], "S")
AR_T = cast(np.ndarray[Any, np.dtypes.StringDType], np.array(["a"], "T"))
AR_U: np.ndarray[Any, np.dtype[np.str_]] = np.array(["a"], "U")
AR_m: np.ndarray[Any, np.dtype[np.timedelta64]] = np.array([np.timedelta64("1")])
AR_M: np.ndarray[Any, np.dtype[np.datetime64]] = np.array([np.datetime64("1")])
AR_O: np.ndarray[Any, np.dtype[np.object_]] = np.array([1], dtype=object)
# Arrays
AR_b > AR_b
AR_b > AR_u
AR_b > AR_i
AR_b > AR_f
AR_b > AR_c
AR_u > AR_b
AR_u > AR_u
AR_u > AR_i
AR_u > AR_f
AR_u > AR_c
AR_i > AR_b
AR_i > AR_u
AR_i > AR_i
AR_i > AR_f
AR_i > AR_c
AR_f > AR_b
AR_f > AR_u
AR_f > AR_i
AR_f > AR_f
AR_f > AR_c
AR_c > AR_b
AR_c > AR_u
AR_c > AR_i
AR_c > AR_f
AR_c > AR_c
AR_S > AR_S
AR_S > b""
AR_T > AR_T
AR_T > AR_U
AR_T > ""
AR_U > AR_U
AR_U > AR_T
AR_U > ""
AR_m > AR_b
AR_m > AR_u
AR_m > AR_i
AR_b > AR_m
AR_u > AR_m
AR_i > AR_m
AR_M > AR_M
AR_O > AR_O
1 > AR_O
AR_O > 1
# Time structures
dt > dt
td > td
td > i
td > i4
td > i8
td > AR_i
td > SEQ
# boolean
b_ > b
b_ > b_
b_ > i
b_ > i8
b_ > i4
b_ > u8
b_ > u4
b_ > f
b_ > f8
b_ > f4
b_ > c
b_ > c16
b_ > c8
b_ > AR_i
b_ > SEQ
# Complex
c16 > c16
c16 > f8
c16 > i8
c16 > c8
c16 > f4
c16 > i4
c16 > b_
c16 > b
c16 > c
c16 > f
c16 > i
c16 > AR_i
c16 > SEQ
c16 > c16
f8 > c16
i8 > c16
c8 > c16
f4 > c16
i4 > c16
b_ > c16
b > c16
c > c16
f > c16
i > c16
AR_i > c16
SEQ > c16
c8 > c16
c8 > f8
c8 > i8
c8 > c8
c8 > f4
c8 > i4
c8 > b_
c8 > b
c8 > c
c8 > f
c8 > i
c8 > AR_i
c8 > SEQ
c16 > c8
f8 > c8
i8 > c8
c8 > c8
f4 > c8
i4 > c8
b_ > c8
b > c8
c > c8
f > c8
i > c8
AR_i > c8
SEQ > c8
# Float
f8 > f8
f8 > i8
f8 > f4
f8 > i4
f8 > b_
f8 > b
f8 > c
f8 > f
f8 > i
f8 > AR_i
f8 > SEQ
f8 > f8
i8 > f8
f4 > f8
i4 > f8
b_ > f8
b > f8
c > f8
f > f8
i > f8
AR_i > f8
SEQ > f8
f4 > f8
f4 > i8
f4 > f4
f4 > i4
f4 > b_
f4 > b
f4 > c
f4 > f
f4 > i
f4 > AR_i
f4 > SEQ
f8 > f4
i8 > f4
f4 > f4
i4 > f4
b_ > f4
b > f4
c > f4
f > f4
i > f4
AR_i > f4
SEQ > f4
# Int
i8 > i8
i8 > u8
i8 > i4
i8 > u4
i8 > b_
i8 > b
i8 > c
i8 > f
i8 > i
i8 > AR_i
i8 > SEQ
u8 > u8
u8 > i4
u8 > u4
u8 > b_
u8 > b
u8 > c
u8 > f
u8 > i
u8 > AR_i
u8 > SEQ
i8 > i8
u8 > i8
i4 > i8
u4 > i8
b_ > i8
b > i8
c > i8
f > i8
i > i8
AR_i > i8
SEQ > i8
u8 > u8
i4 > u8
u4 > u8
b_ > u8
b > u8
c > u8
f > u8
i > u8
AR_i > u8
SEQ > u8
i4 > i8
i4 > i4
i4 > i
i4 > b_
i4 > b
i4 > AR_i
i4 > SEQ
u4 > i8
u4 > i4
u4 > u8
u4 > u4
u4 > i
u4 > b_
u4 > b
u4 > AR_i
u4 > SEQ
i8 > i4
i4 > i4
i > i4
b_ > i4
b > i4
AR_i > i4
SEQ > i4
i8 > u4
i4 > u4
u8 > u4
u4 > u4
b_ > u4
b > u4
i > u4
AR_i > u4
SEQ > u4
| from __future__ import annotations
from typing import Any, cast
import numpy as np
c16 = np.complex128()
f8 = np.float64()
i8 = np.int64()
u8 = np.uint64()
c8 = np.complex64()
f4 = np.float32()
i4 = np.int32()
u4 = np.uint32()
dt = np.datetime64(0, "D")
td = np.timedelta64(0, "D")
b_ = np.bool()
b = False
c = complex()
f = 0.0
i = 0
SEQ = (0, 1, 2, 3, 4)
AR_b: np.ndarray[Any, np.dtype[np.bool]] = np.array([True])
AR_u: np.ndarray[Any, np.dtype[np.uint32]] = np.array([1], dtype=np.uint32)
AR_i: np.ndarray[Any, np.dtype[np.int_]] = np.array([1])
AR_f: np.ndarray[Any, np.dtype[np.float64]] = np.array([1.0])
AR_c: np.ndarray[Any, np.dtype[np.complex128]] = np.array([1.0j])
AR_S: np.ndarray[Any, np.dtype[np.bytes_]] = np.array([b"a"], "S")
AR_T = cast(np.ndarray[Any, np.dtypes.StringDType], np.array(["a"], "T"))
AR_U: np.ndarray[Any, np.dtype[np.str_]] = np.array(["a"], "U")
AR_m: np.ndarray[Any, np.dtype[np.timedelta64]] = np.array([np.timedelta64("1")])
AR_M: np.ndarray[Any, np.dtype[np.datetime64]] = np.array([np.datetime64("1")])
AR_O: np.nd | [] | numpy/numpy | numpy/typing/tests/data/pass/comparisons.py |
import numpy as np
i8 = np.int64(1)
u8 = np.uint64(1)
i4 = np.int32(1)
u4 = np.uint32(1)
b_ = np.bool(1)
b = bool(1)
i = 1
AR = np.array([0, 1, 2], dtype=np.int32)
AR.setflags(write=False)
i8 << i8
i8 >> i8
i8 | i8
i8 ^ i8
i8 & i8
i << AR
i >> AR
i | AR
i ^ AR
i & AR
i8 << AR
i8 >> AR
i8 | AR
i8 ^ AR
i8 & AR
i4 << i4
i4 >> i4
i4 | i4
i4 ^ i4
i4 & i4
i8 << i4
i8 >> i4
i8 | i4
i8 ^ i4
i8 & i4
i8 << i
i8 >> i
i8 | i
i8 ^ i
i8 & i
i8 << b_
i8 >> b_
i8 | b_
i8 ^ b_
i8 & b_
i8 << b
i8 >> b
i8 | b
i8 ^ b
i8 & b
u8 << u8
u8 >> u8
u8 | u8
u8 ^ u8
u8 & u8
u4 << u4
u4 >> u4
u4 | u4
u4 ^ u4
u4 & u4
u4 << i4
u4 >> i4
u4 | i4
u4 ^ i4
u4 & i4
u4 << i
u4 >> i
u4 | i
u4 ^ i
u4 & i
u8 << b_
u8 >> b_
u8 | b_
u8 ^ b_
u8 & b_
u8 << b
u8 >> b
u8 | b
u8 ^ b
u8 & b
b_ << b_
b_ >> b_
b_ | b_
b_ ^ b_
b_ & b_
b_ << AR
b_ >> AR
b_ | AR
b_ ^ AR
b_ & AR
b_ << b
b_ >> b
b_ | b
b_ ^ b
b_ & b
b_ << i
b_ >> i
b_ | i
b_ ^ i
b_ & i
~i8
~i4
~u8
~u4
~b_
~AR
| import numpy as np
i8 = np.int64(1)
u8 = np.uint64(1)
i4 = np.int32(1)
u4 = np.uint32(1)
b_ = np.bool(1)
b = bool(1)
i = 1
AR = np.array([0, 1, 2], dtype=np.int32)
AR.setflags(write=False)
i8 << i8
i8 >> i8
i8 | i8
i8 ^ i8
i8 & i8
i << AR
i >> AR
i | AR
i ^ AR
i & AR
i8 << AR
i8 >> AR
i8 | AR
i8 ^ AR
i8 & AR
i4 << i4
i4 >> i4
i4 | i4
i4 ^ i4
i4 & i4
i8 << i4
i8 >> i4
i8 | i4
i8 ^ i4
i8 & i4
i8 << i
i8 >> i
i8 | i
i8 ^ i
i8 & i
i8 << b_
i8 >> b_
i8 | b_
i8 ^ b_
i8 & b_
i8 << b
i8 >> b
i8 | b
i8 ^ b
i8 & b
u8 << u8
u8 >> u8
u8 | u8
u8 ^ u8
u8 & u8
u4 << u4
u4 >> u4
u4 | u4
u4 ^ u4
u4 & u4
u4 << i4
u4 >> i4
u4 | i4
u4 ^ i4
u4 & i4
u4 << i
u4 >> i
u4 | i
u4 ^ i
u4 & i
u8 << b_
u8 >> b_
u8 | b_
u8 ^ b_
u8 & b_
u8 << b
u8 >> b
u8 | b
u8 ^ b
u8 & b
b_ << b_ | [] | numpy/numpy | numpy/typing/tests/data/pass/bitwise_ops.py |
from __future__ import annotations
from typing import Any
import numpy as np
AR_i8: np.ndarray[Any, np.dtype[np.int_]] = np.arange(10)
ar_iter = np.lib.Arrayterator(AR_i8)
ar_iter.var
ar_iter.buf_size
ar_iter.start
ar_iter.stop
ar_iter.step
ar_iter.shape
ar_iter.flat
ar_iter.__array__()
for i in ar_iter:
pass
ar_iter[0]
ar_iter[...]
ar_iter[:]
ar_iter[0, 0, 0]
ar_iter[..., 0, :]
|
from __future__ import annotations
from typing import Any
import numpy as np
AR_i8: np.ndarray[Any, np.dtype[np.int_]] = np.arange(10)
ar_iter = np.lib.Arrayterator(AR_i8)
ar_iter.var
ar_iter.buf_size
ar_iter.start
ar_iter.stop
ar_iter.step
ar_iter.shape
ar_iter.flat
ar_iter.__array__()
for i in ar_iter:
pass
ar_iter[0]
ar_iter[...]
ar_iter[:]
ar_iter[0, 0, 0]
ar_iter[..., 0, :]
| [] | numpy/numpy | numpy/typing/tests/data/pass/arrayterator.py |
import numpy as np
AR = np.arange(10)
AR.setflags(write=False)
with np.printoptions():
np.set_printoptions(
precision=1,
threshold=2,
edgeitems=3,
linewidth=4,
suppress=False,
nanstr="Bob",
infstr="Bill",
formatter={},
sign="+",
floatmode="unique",
)
np.get_printoptions()
str(AR)
np.array2string(
AR,
max_line_width=5,
precision=2,
suppress_small=True,
separator=";",
prefix="test",
threshold=5,
floatmode="fixed",
suffix="?",
legacy="1.13",
)
np.format_float_scientific(1, precision=5)
np.format_float_positional(1, trim="k")
np.array_repr(AR)
np.array_str(AR)
| import numpy as np
AR = np.arange(10)
AR.setflags(write=False)
with np.printoptions():
np.set_printoptions(
precision=1,
threshold=2,
edgeitems=3,
linewidth=4,
suppress=False,
nanstr="Bob",
infstr="Bill",
formatter={},
sign="+",
floatmode="unique",
)
np.get_printoptions()
str(AR)
np.array2string(
AR,
max_line_width=5,
precision=2,
suppress_small=True,
separator=";",
prefix="test",
threshold=5,
floatmode="fixed",
suffix="?",
legacy="1.13",
)
np.format_float_scientific(1, precision=5)
np.format_float_positional(1, trim="k")
np.array_repr(AR)
np.array_str(AR)
| [] | numpy/numpy | numpy/typing/tests/data/pass/arrayprint.py |
import numpy as np
from numpy._typing import ArrayLike, NDArray, _SupportsArray
x1: ArrayLike = True
x2: ArrayLike = 5
x3: ArrayLike = 1.0
x4: ArrayLike = 1 + 1j
x5: ArrayLike = np.int8(1)
x6: ArrayLike = np.float64(1)
x7: ArrayLike = np.complex128(1)
x8: ArrayLike = np.array([1, 2, 3])
x9: ArrayLike = [1, 2, 3]
x10: ArrayLike = (1, 2, 3)
x11: ArrayLike = "foo"
x12: ArrayLike = memoryview(b'foo')
class A:
def __array__(self, dtype: np.dtype | None = None) -> NDArray[np.float64]:
return np.array([1.0, 2.0, 3.0])
x13: ArrayLike = A()
scalar: _SupportsArray[np.dtype[np.int64]] = np.int64(1)
scalar.__array__()
array: _SupportsArray[np.dtype[np.int_]] = np.array(1)
array.__array__()
a: _SupportsArray[np.dtype[np.float64]] = A()
a.__array__()
a.__array__()
# Escape hatch for when you mean to make something like an object
# array.
object_array_scalar: object = (i for i in range(10))
np.array(object_array_scalar)
| import numpy as np
from numpy._typing import ArrayLike, NDArray, _SupportsArray
x1: ArrayLike = True
x2: ArrayLike = 5
x3: ArrayLike = 1.0
x4: ArrayLike = 1 + 1j
x5: ArrayLike = np.int8(1)
x6: ArrayLike = np.float64(1)
x7: ArrayLike = np.complex128(1)
x8: ArrayLike = np.array([1, 2, 3])
x9: ArrayLike = [1, 2, 3]
x10: ArrayLike = (1, 2, 3)
x11: ArrayLike = "foo"
x12: ArrayLike = memoryview(b'foo')
class A:
def __array__(self, dtype: np.dtype | None = None) -> NDArray[np.float64]:
return np.array([1.0, 2.0, 3.0])
x13: ArrayLike = A()
scalar: _SupportsArray[np.dtype[np.int64]] = np.int64(1)
scalar.__array__()
array: _SupportsArray[np.dtype[np.int_]] = np.array(1)
array.__array__()
a: _SupportsArray[np.dtype[np.float64]] = A()
a.__array__()
a.__array__()
# Escape hatch for when you mean to make something like an object
# array.
object_array_scalar: object = (i for i in range(10))
np.array(object_array_scalar)
| [
"# numpy/numpy:numpy/lib/tests/test_mixins.py\nArrayLike",
"# numpy/numpy:numpy/_typing/_array_like.py\n_SupportsArray"
] | numpy/numpy | numpy/typing/tests/data/pass/array_like.py |
from typing import Any
import numpy as np
class Index:
def __index__(self) -> int:
return 0
class SubClass(np.ndarray[tuple[Any, ...], np.dtype[np.float64]]):
pass
def func(i: int, j: int, **kwargs: Any) -> SubClass:
return B
i8 = np.int64(1)
A = np.array([1])
B = A.view(SubClass).copy()
B_stack = np.array([[1], [1]]).view(SubClass)
C = [1]
np.ndarray(Index())
np.ndarray([Index()])
np.array(1, dtype=float)
np.array(1, copy=None)
np.array(1, order='F')
np.array(1, order=None)
np.array(1, subok=True)
np.array(1, ndmin=3)
np.array(1, str, copy=True, order='C', subok=False, ndmin=2)
np.asarray(A)
np.asarray(B)
np.asarray(C)
np.asanyarray(A)
np.asanyarray(B)
np.asanyarray(B, dtype=int)
np.asanyarray(C)
np.ascontiguousarray(A)
np.ascontiguousarray(B)
np.ascontiguousarray(C)
np.asfortranarray(A)
np.asfortranarray(B)
np.asfortranarray(C)
np.require(A)
np.require(B)
np.require(B, dtype=int)
np.require(B, requirements=None)
np.require(B, requirements="E")
np.require(B, requirements=["ENSUREARRAY"])
np.require(B, requirements={"F", "E"})
np.require(B, requirements=["C", "OWNDATA"])
np.require(B, requirements="W")
np.require(B, requirements="A")
np.require(C)
np.linspace(0, 2)
np.linspace(0.5, [0, 1, 2])
np.linspace([0, 1, 2], 3)
np.linspace(0j, 2)
np.linspace(0, 2, num=10)
np.linspace(0, 2, endpoint=True)
np.linspace(0, 2, retstep=True)
np.linspace(0j, 2j, retstep=True)
np.linspace(0, 2, dtype=bool)
np.linspace([0, 1], [2, 3], axis=Index())
np.logspace(0, 2, base=2)
np.logspace(0, 2, base=2)
np.logspace(0, 2, base=[1j, 2j], num=2)
np.geomspace(1, 2)
np.zeros_like(A)
np.zeros_like(C)
np.zeros_like(B)
np.zeros_like(B, dtype=np.int64)
np.ones_like(A)
np.ones_like(C)
np.ones_like(B)
np.ones_like(B, dtype=np.int64)
np.empty_like(A)
np.empty_like(C)
np.empty_like(B)
np.empty_like(B, dtype=np.int64)
np.full_like(A, i8)
np.full_like(C, i8)
np.full_like(B, i8)
np.full_like(B, i8, dtype=np.int64)
np.ones(1)
np.ones([1, 1, 1])
np.full(1, i8)
np.full([1, 1, 1], i8)
np.indices([1, 2, 3])
np.indices([1, 2, 3], sparse=True)
np.fromfunction(func, (3, 5))
np.identity(10)
np.atleast_1d(C)
np.atleast_1d(A)
np.atleast_1d(C, C)
np.atleast_1d(C, A)
np.atleast_1d(A, A)
np.atleast_2d(C)
np.atleast_3d(C)
np.vstack([C, C])
np.vstack([C, A])
np.vstack([A, A])
np.hstack([C, C])
np.stack([C, C])
np.stack([C, C], axis=0)
np.stack([C, C], out=B_stack)
np.block([[C, C], [C, C]])
np.block(A)
| from typing import Any
import numpy as np
class Index:
def __index__(self) -> int:
return 0
class SubClass(np.ndarray[tuple[Any, ...], np.dtype[np.float64]]):
pass
def func(i: int, j: int, **kwargs: Any) -> SubClass:
return B
i8 = np.int64(1)
A = np.array([1])
B = A.view(SubClass).copy()
B_stack = np.array([[1], [1]]).view(SubClass)
C = [1]
np.ndarray(Index())
np.ndarray([Index()])
np.array(1, dtype=float)
np.array(1, copy=None)
np.array(1, order='F')
np.array(1, order=None)
np.array(1, subok=True)
np.array(1, ndmin=3)
np.array(1, str, copy=True, order='C', subok=False, ndmin=2)
np.asarray(A)
np.asarray(B)
np.asarray(C)
np.asanyarray(A)
np.asanyarray(B)
np.asanyarray(B, dtype=int)
np.asanyarray(C)
np.ascontiguousarray(A)
np.ascontiguousarray(B)
np.ascontiguousarray(C)
np.asfortranarray(A)
np.asfortranarray(B)
np.asfortranarray(C)
np.require(A)
np.require(B)
np.require(B, dtype=int)
np.require(B, requirements=None)
np.require(B, requirements="E")
np.require(B, requirements=["ENSUREARRAY"])
np.require(B, requirements={"F", "E"})
np.require(B, requirements=["C", "OWNDATA"])
np. | [] | numpy/numpy | numpy/typing/tests/data/pass/array_constructors.py |
from __future__ import annotations
from typing import Any, cast
import pytest
import numpy as np
import numpy.typing as npt
c16 = np.complex128(1)
f8 = np.float64(1)
i8 = np.int64(1)
u8 = np.uint64(1)
c8 = np.complex64(1)
f4 = np.float32(1)
i4 = np.int32(1)
u4 = np.uint32(1)
dt = np.datetime64(1, "D")
td = np.timedelta64(1, "D")
b_ = np.bool(1)
b = bool(1)
c = complex(1)
f = float(1)
i = 1
class Object:
def __array__(self, dtype: np.typing.DTypeLike | None = None,
copy: bool | None = None) -> np.ndarray[Any, np.dtype[np.object_]]:
ret = np.empty((), dtype=object)
ret[()] = self
return ret
def __sub__(self, value: Any) -> Object:
return self
def __rsub__(self, value: Any) -> Object:
return self
def __floordiv__(self, value: Any) -> Object:
return self
def __rfloordiv__(self, value: Any) -> Object:
return self
def __mul__(self, value: Any) -> Object:
return self
def __rmul__(self, value: Any) -> Object:
return self
def __pow__(self, value: Any) -> Object:
return self
def __rpow__(self, value: Any) -> Object:
return self
AR_b: npt.NDArray[np.bool] = np.array([True])
AR_u: npt.NDArray[np.uint32] = np.array([1], dtype=np.uint32)
AR_i: npt.NDArray[np.int64] = np.array([1])
AR_integer: npt.NDArray[np.integer] = cast(npt.NDArray[np.integer], AR_i)
AR_f: npt.NDArray[np.float64] = np.array([1.0])
AR_c: npt.NDArray[np.complex128] = np.array([1j])
AR_m: npt.NDArray[np.timedelta64] = np.array([np.timedelta64(1, "D")])
AR_M: npt.NDArray[np.datetime64] = np.array([np.datetime64(1, "D")])
AR_O: npt.NDArray[np.object_] = np.array([Object()])
AR_LIKE_b = [True]
AR_LIKE_u = [np.uint32(1)]
AR_LIKE_i = [1]
AR_LIKE_f = [1.0]
AR_LIKE_c = [1j]
AR_LIKE_m = [np.timedelta64(1, "D")]
AR_LIKE_M = [np.datetime64(1, "D")]
AR_LIKE_O = [Object()]
# Array subtractions
AR_b - AR_LIKE_u
AR_b - AR_LIKE_i
AR_b - AR_LIKE_f
AR_b - AR_LIKE_c
AR_b - AR_LIKE_m
AR_b - AR_LIKE_O
AR_LIKE_u - AR_b
AR_LIKE_i - AR_b
AR_LIKE_f - AR_b
AR_LIKE_c - AR_b
AR_LIKE_m - AR_b
AR_LIKE_M - AR_b
AR_LIKE_O - AR_b
AR_u - AR_LIKE_b
AR_u - AR_LIKE_u
AR_u - AR_LIKE_i
AR_u - AR_LIKE_f
AR_u - AR_LIKE_c
AR_u - AR_LIKE_m
AR_u - AR_LIKE_O
AR_LIKE_b - AR_u
AR_LIKE_u - AR_u
AR_LIKE_i - AR_u
AR_LIKE_f - AR_u
AR_LIKE_c - AR_u
AR_LIKE_m - AR_u
AR_LIKE_M - AR_u
AR_LIKE_O - AR_u
AR_i - AR_LIKE_b
AR_i - AR_LIKE_u
AR_i - AR_LIKE_i
AR_i - AR_LIKE_f
AR_i - AR_LIKE_c
AR_i - AR_LIKE_m
AR_i - AR_LIKE_O
AR_LIKE_b - AR_i
AR_LIKE_u - AR_i
AR_LIKE_i - AR_i
AR_LIKE_f - AR_i
AR_LIKE_c - AR_i
AR_LIKE_m - AR_i
AR_LIKE_M - AR_i
AR_LIKE_O - AR_i
AR_f - AR_LIKE_b
AR_f - AR_LIKE_u
AR_f - AR_LIKE_i
AR_f - AR_LIKE_f
AR_f - AR_LIKE_c
AR_f - AR_LIKE_O
AR_LIKE_b - AR_f
AR_LIKE_u - AR_f
AR_LIKE_i - AR_f
AR_LIKE_f - AR_f
AR_LIKE_c - AR_f
AR_LIKE_O - AR_f
AR_c - AR_LIKE_b
AR_c - AR_LIKE_u
AR_c - AR_LIKE_i
AR_c - AR_LIKE_f
AR_c - AR_LIKE_c
AR_c - AR_LIKE_O
AR_LIKE_b - AR_c
AR_LIKE_u - AR_c
AR_LIKE_i - AR_c
AR_LIKE_f - AR_c
AR_LIKE_c - AR_c
AR_LIKE_O - AR_c
AR_m - AR_LIKE_b
AR_m - AR_LIKE_u
AR_m - AR_LIKE_i
AR_m - AR_LIKE_m
AR_LIKE_b - AR_m
AR_LIKE_u - AR_m
AR_LIKE_i - AR_m
AR_LIKE_m - AR_m
AR_LIKE_M - AR_m
AR_M - AR_LIKE_b
AR_M - AR_LIKE_u
AR_M - AR_LIKE_i
AR_M - AR_LIKE_m
AR_M - AR_LIKE_M
AR_LIKE_M - AR_M
AR_O - AR_LIKE_b
AR_O - AR_LIKE_u
AR_O - AR_LIKE_i
AR_O - AR_LIKE_f
AR_O - AR_LIKE_c
AR_O - AR_LIKE_O
AR_LIKE_b - AR_O
AR_LIKE_u - AR_O
AR_LIKE_i - AR_O
AR_LIKE_f - AR_O
AR_LIKE_c - AR_O
AR_LIKE_O - AR_O
AR_u += AR_b
AR_u += AR_u
AR_u += 1 # Allowed during runtime as long as the object is 0D and >=0
# Array floor division
AR_b // AR_LIKE_b
AR_b // AR_LIKE_u
AR_b // AR_LIKE_i
AR_b // AR_LIKE_f
AR_b // AR_LIKE_O
AR_LIKE_b // AR_b
AR_LIKE_u // AR_b
AR_LIKE_i // AR_b
AR_LIKE_f // AR_b
AR_LIKE_O // AR_b
AR_u // AR_LIKE_b
AR_u // AR_LIKE_u
AR_u // AR_LIKE_i
AR_u // AR_LIKE_f
AR_u // AR_LIKE_O
AR_LIKE_b // AR_u
AR_LIKE_u // AR_u
AR_LIKE_i // AR_u
AR_LIKE_f // AR_u
AR_LIKE_m // AR_u
AR_LIKE_O // AR_u
AR_i // AR_LIKE_b
AR_i // AR_LIKE_u
AR_i // AR_LIKE_i
AR_i // AR_LIKE_f
AR_i // AR_LIKE_O
AR_LIKE_b // AR_i
AR_LIKE_u // AR_i
AR_LIKE_i // AR_i
AR_LIKE_f // AR_i
AR_LIKE_m // AR_i
AR_LIKE_O // AR_i
AR_f // AR_LIKE_b
AR_f // AR_LIKE_u
AR_f // AR_LIKE_i
AR_f // AR_LIKE_f
AR_f // AR_LIKE_O
AR_LIKE_b // AR_f
AR_LIKE_u // AR_f
AR_LIKE_i // AR_f
AR_LIKE_f // AR_f
AR_LIKE_m // AR_f
AR_LIKE_O // AR_f
AR_m // AR_LIKE_u
AR_m // AR_LIKE_i
AR_m // AR_LIKE_f
AR_m // AR_LIKE_m
AR_LIKE_m // AR_m
AR_m /= f
AR_m //= f
AR_m /= AR_f
AR_m /= AR_LIKE_f
AR_m //= AR_f
AR_m //= AR_LIKE_f
AR_O // AR_LIKE_b
AR_O // AR_LIKE_u
AR_O // AR_LIKE_i
AR_O // AR_LIKE_f
AR_O // AR_LIKE_O
AR_LIKE_b // AR_O
AR_LIKE_u // AR_O
AR_LIKE_i // AR_O
AR_LIKE_f // AR_O
AR_LIKE_O // AR_O
# Inplace multiplication
AR_b *= AR_LIKE_b
AR_u *= AR_LIKE_b
AR_u *= AR_LIKE_u
AR_i *= AR_LIKE_b
AR_i *= AR_LIKE_u
AR_i *= AR_LIKE_i
AR_integer *= AR_LIKE_b
AR_integer *= AR_LIKE_u
AR_integer *= AR_LIKE_i
AR_f *= AR_LIKE_b
AR_f *= AR_LIKE_u
AR_f *= AR_LIKE_i
AR_f *= AR_LIKE_f
AR_c *= AR_LIKE_b
AR_c *= AR_LIKE_u
AR_c *= AR_LIKE_i
AR_c *= AR_LIKE_f
AR_c *= AR_LIKE_c
AR_m *= AR_LIKE_b
AR_m *= AR_LIKE_u
AR_m *= AR_LIKE_i
AR_m *= AR_LIKE_f
AR_O *= AR_LIKE_b
AR_O *= AR_LIKE_u
AR_O *= AR_LIKE_i
AR_O *= AR_LIKE_f
AR_O *= AR_LIKE_c
AR_O *= AR_LIKE_O
# Inplace power
AR_u **= AR_LIKE_b
AR_u **= AR_LIKE_u
AR_i **= AR_LIKE_b
AR_i **= AR_LIKE_u
AR_i **= AR_LIKE_i
AR_integer **= AR_LIKE_b
AR_integer **= AR_LIKE_u
AR_integer **= AR_LIKE_i
AR_f **= AR_LIKE_b
AR_f **= AR_LIKE_u
AR_f **= AR_LIKE_i
AR_f **= AR_LIKE_f
AR_c **= AR_LIKE_b
AR_c **= AR_LIKE_u
AR_c **= AR_LIKE_i
AR_c **= AR_LIKE_f
AR_c **= AR_LIKE_c
AR_O **= AR_LIKE_b
AR_O **= AR_LIKE_u
AR_O **= AR_LIKE_i
AR_O **= AR_LIKE_f
AR_O **= AR_LIKE_c
AR_O **= AR_LIKE_O
# unary ops
-c16
-c8
-f8
-f4
-i8
-i4
with pytest.warns(RuntimeWarning):
-u8
-u4
-td
-AR_f
+c16
+c8
+f8
+f4
+i8
+i4
+u8
+u4
+td
+AR_f
abs(c16)
abs(c8)
abs(f8)
abs(f4)
abs(i8)
abs(i4)
abs(u8)
abs(u4)
abs(td)
abs(b_)
abs(AR_f)
# Time structures
dt + td
dt + i
dt + i4
dt + i8
dt - dt
dt - i
dt - i4
dt - i8
td + td
td + i
td + i4
td + i8
td - td
td - i
td - i4
td - i8
td / f
td / f4
td / f8
td / td
td // td
td % td
# boolean
b_ / b
b_ / b_
b_ / i
b_ / i8
b_ / i4
b_ / u8
b_ / u4
b_ / f
b_ / f8
b_ / f4
b_ / c
b_ / c16
b_ / c8
b / b_
b_ / b_
i / b_
i8 / b_
i4 / b_
u8 / b_
u4 / b_
f / b_
f8 / b_
f4 / b_
c / b_
c16 / b_
c8 / b_
# Complex
c16 + c16
c16 + f8
c16 + i8
c16 + c8
c16 + f4
c16 + i4
c16 + b_
c16 + b
c16 + c
c16 + f
c16 + i
c16 + AR_f
c16 + c16
f8 + c16
i8 + c16
c8 + c16
f4 + c16
i4 + c16
b_ + c16
b + c16
c + c16
f + c16
i + c16
AR_f + c16
c8 + c16
c8 + f8
c8 + i8
c8 + c8
c8 + f4
c8 + i4
c8 + b_
c8 + b
c8 + c
c8 + f
c8 + i
c8 + AR_f
c16 + c8
f8 + c8
i8 + c8
c8 + c8
f4 + c8
i4 + c8
b_ + c8
b + c8
c + c8
f + c8
i + c8
AR_f + c8
# Float
f8 + f8
f8 + i8
f8 + f4
f8 + i4
f8 + b_
f8 + b
f8 + c
f8 + f
f8 + i
f8 + AR_f
f8 + f8
i8 + f8
f4 + f8
i4 + f8
b_ + f8
b + f8
c + f8
f + f8
i + f8
AR_f + f8
f4 + f8
f4 + i8
f4 + f4
f4 + i4
f4 + b_
f4 + b
f4 + c
f4 + f
f4 + i
f4 + AR_f
f8 + f4
i8 + f4
f4 + f4
i4 + f4
b_ + f4
b + f4
c + f4
f + f4
i + f4
AR_f + f4
# Int
i8 + i8
i8 + u8
i8 + i4
i8 + u4
i8 + b_
i8 + b
i8 + c
i8 + f
i8 + i
i8 + AR_f
u8 + u8
u8 + i4
u8 + u4
u8 + b_
u8 + b
u8 + c
u8 + f
u8 + i
u8 + AR_f
i8 + i8
u8 + i8
i4 + i8
u4 + i8
b_ + i8
b + i8
c + i8
f + i8
i + i8
AR_f + i8
u8 + u8
i4 + u8
u4 + u8
b_ + u8
b + u8
c + u8
f + u8
i + u8
AR_f + u8
i4 + i8
i4 + i4
i4 + i
i4 + b_
i4 + b
i4 + AR_f
u4 + i8
u4 + i4
u4 + u8
u4 + u4
u4 + i
u4 + b_
u4 + b
u4 + AR_f
i8 + i4
i4 + i4
i + i4
b_ + i4
b + i4
AR_f + i4
i8 + u4
i4 + u4
u8 + u4
u4 + u4
b_ + u4
b + u4
i + u4
AR_f + u4
| from __future__ import annotations
from typing import Any, cast
import pytest
import numpy as np
import numpy.typing as npt
c16 = np.complex128(1)
f8 = np.float64(1)
i8 = np.int64(1)
u8 = np.uint64(1)
c8 = np.complex64(1)
f4 = np.float32(1)
i4 = np.int32(1)
u4 = np.uint32(1)
dt = np.datetime64(1, "D")
td = np.timedelta64(1, "D")
b_ = np.bool(1)
b = bool(1)
c = complex(1)
f = float(1)
i = 1
class Object:
def __array__(self, dtype: np.typing.DTypeLike | None = None,
copy: bool | None = None) -> np.ndarray[Any, np.dtype[np.object_]]:
ret = np.empty((), dtype=object)
ret[()] = self
return ret
def __sub__(self, value: Any) -> Object:
return self
def __rsub__(self, value: Any) -> Object:
return self
def __floordiv__(self, value: Any) -> Object:
return self
def __rfloordiv__(self, value: Any) -> Object:
return self
def __mul__(self, value: Any) -> Object:
return self
def __rmul__(self, value: Any) -> Object:
return self
def __pow__(self, value: Any) -> Object:
| [] | numpy/numpy | numpy/typing/tests/data/pass/arithmetic.py |
"""A mypy_ plugin for managing a number of platform-specific annotations.
Its functionality can be split into three distinct parts:
* Assigning the (platform-dependent) precisions of certain `~numpy.number`
subclasses, including the likes of `~numpy.int_`, `~numpy.intp` and
`~numpy.longlong`. See the documentation on
:ref:`scalar types <arrays.scalars.built-in>` for a comprehensive overview
of the affected classes. Without the plugin the precision of all relevant
classes will be inferred as `~typing.Any`.
* Removing all extended-precision `~numpy.number` subclasses that are
unavailable for the platform in question. Most notably this includes the
likes of `~numpy.float128` and `~numpy.complex256`. Without the plugin *all*
extended-precision types will, as far as mypy is concerned, be available
to all platforms.
* Assigning the (platform-dependent) precision of `~numpy.ctypeslib.c_intp`.
Without the plugin the type will default to `ctypes.c_int64`.
.. versionadded:: 1.22
.. deprecated:: 2.3
The :mod:`numpy.typing.mypy_plugin` entry-point is deprecated in favor of
platform-agnostic static type inference. Remove
``numpy.typing.mypy_plugin`` from the ``plugins`` section of your mypy
configuration; if that surfaces new errors, please open an issue with a
minimal reproducer.
Examples
--------
To enable the plugin, one must add it to their mypy `configuration file`_:
.. code-block:: ini
[mypy]
plugins = numpy.typing.mypy_plugin
.. _mypy: https://mypy-lang.org/
.. _configuration file: https://mypy.readthedocs.io/en/stable/config_file.html
"""
from collections.abc import Callable, Iterable
from typing import TYPE_CHECKING, Final, cast
import numpy as np
__all__: list[str] = []
def _get_precision_dict() -> dict[str, str]:
names = [
("_NBitByte", np.byte),
("_NBitShort", np.short),
("_NBitIntC", np.intc),
("_NBitIntP", np.intp),
("_NBitInt", np.int_),
("_NBitLong", np.long),
("_NBitLongLong", np.longlong),
("_NBitHalf", np.half),
("_NBitSingle", np.single),
("_NBitDouble", np.double),
("_NBitLongDouble", np.longdouble),
]
ret: dict[str, str] = {}
for name, typ in names:
n = 8 * np.dtype(typ).itemsize
ret[f"{_MODULE}._nbit.{name}"] = f"{_MODULE}._nbit_base._{n}Bit"
return ret
def _get_extended_precision_list() -> list[str]:
extended_names = [
"float96",
"float128",
"complex192",
"complex256",
]
return [i for i in extended_names if hasattr(np, i)]
def _get_c_intp_name() -> str:
# Adapted from `np.core._internal._getintp_ctype`
return {
"i": "c_int",
"l": "c_long",
"q": "c_longlong",
}.get(np.dtype("n").char, "c_long")
_MODULE: Final = "numpy._typing"
#: A dictionary mapping type-aliases in `numpy._typing._nbit` to
#: concrete `numpy.typing.NBitBase` subclasses.
_PRECISION_DICT: Final = _get_precision_dict()
#: A list with the names of all extended precision `np.number` subclasses.
_EXTENDED_PRECISION_LIST: Final = _get_extended_precision_list()
#: The name of the ctypes equivalent of `np.intp`
_C_INTP: Final = _get_c_intp_name()
try:
if TYPE_CHECKING:
from mypy.typeanal import TypeAnalyser
import mypy.types
from mypy.build import PRI_MED
from mypy.nodes import ImportFrom, MypyFile, Statement
from mypy.plugin import AnalyzeTypeContext, Plugin
except ModuleNotFoundError as _exc:
def plugin(version: str) -> type:
raise _exc
else:
type _HookFunc = Callable[[AnalyzeTypeContext], mypy.types.Type]
def _hook(ctx: AnalyzeTypeContext) -> mypy.types.Type:
"""Replace a type-alias with a concrete ``NBitBase`` subclass."""
typ, _, api = ctx
name = typ.name.split(".")[-1]
name_new = _PRECISION_DICT[f"{_MODULE}._nbit.{name}"]
return cast("TypeAnalyser", api).named_type(name_new)
def _index(iterable: Iterable[Statement], id: str) -> int:
"""Identify the first ``ImportFrom`` instance the specified `id`."""
for i, value in enumerate(iterable):
if getattr(value, "id", None) == id:
return i
raise ValueError("Failed to identify a `ImportFrom` instance "
f"with the following id: {id!r}")
def _override_imports(
file: MypyFile,
module: str,
imports: list[tuple[str, str | None]],
) -> None:
"""Override the first `module`-based import with new `imports`."""
# Construct a new `from module import y` statement
import_obj = ImportFrom(module, 0, names=imports)
import_obj.is_top_level = True
# Replace the first `module`-based import statement with `import_obj`
for lst in [file.defs, cast("list[Statement]", file.imports)]:
i = _index(lst, module)
lst[i] = import_obj
class _NumpyPlugin(Plugin):
"""A mypy plugin for handling versus numpy-specific typing tasks."""
def get_type_analyze_hook(self, fullname: str) -> _HookFunc | None:
"""Set the precision of platform-specific `numpy.number`
subclasses.
For example: `numpy.int_`, `numpy.longlong` and `numpy.longdouble`.
"""
if fullname in _PRECISION_DICT:
return _hook
return None
def get_additional_deps(
self, file: MypyFile
) -> list[tuple[int, str, int]]:
"""Handle all import-based overrides.
* Import platform-specific extended-precision `numpy.number`
subclasses (*e.g.* `numpy.float96` and `numpy.float128`).
* Import the appropriate `ctypes` equivalent to `numpy.intp`.
"""
fullname = file.fullname
if fullname == "numpy":
_override_imports(
file,
f"{_MODULE}._extended_precision",
imports=[(v, v) for v in _EXTENDED_PRECISION_LIST],
)
elif fullname == "numpy.ctypeslib":
_override_imports(
file,
"ctypes",
imports=[(_C_INTP, "_c_intp")],
)
return [(PRI_MED, fullname, -1)]
def plugin(version: str) -> type:
import warnings
plugin = "numpy.typing.mypy_plugin"
# Deprecated 2025-01-10, NumPy 2.3
warn_msg = (
f"`{plugin}` is deprecated, and will be removed in a future "
f"release. Please remove `plugins = {plugin}` in your mypy config."
f"(deprecated in NumPy 2.3)"
)
warnings.warn(warn_msg, DeprecationWarning, stacklevel=3)
return _NumpyPlugin
| """A mypy_ plugin for managing a number of platform-specific annotations.
Its functionality can be split into three distinct parts:
* Assigning the (platform-dependent) precisions of certain `~numpy.number`
subclasses, including the likes of `~numpy.int_`, `~numpy.intp` and
`~numpy.longlong`. See the documentation on
:ref:`scalar types <arrays.scalars.built-in>` for a comprehensive overview
of the affected classes. Without the plugin the precision of all relevant
classes will be inferred as `~typing.Any`.
* Removing all extended-precision `~numpy.number` subclasses that are
unavailable for the platform in question. Most notably this includes the
likes of `~numpy.float128` and `~numpy.complex256`. Without the plugin *all*
extended-precision types will, as far as mypy is concerned, be available
to all platforms.
* Assigning the (platform-dependent) precision of `~numpy.ctypeslib.c_intp`.
Without the plugin the type will default to `ctypes.c_int64`.
.. versionadded:: 1.22
.. deprecated:: 2.3
The :mod:`numpy.typing.mypy_plugin` entry-point is deprecated in favor of
platform-agnostic static type inference. Remove
``numpy.typing.mypy_plugin`` from the ``plugins`` section of your mypy
configuration; if that surfaces new errors, please open an issue with a
minimal reproducer.
Examples
--------
To enable the plugin, one must add it to their mypy `configuration file`_:
.. code-block:: ini
[mypy]
plugins = numpy.typing.mypy_plugin
.. _mypy: https://mypy-lang.org/
.. _configuration file: https://mypy.readthedocs.io/en/stable/config_file.html
"""
from collections.abc import Callable, Iterable
from typing import TYPE_CHECK | [] | numpy/numpy | numpy/typing/mypy_plugin.py |
"""
============================
Typing (:mod:`numpy.typing`)
============================
.. versionadded:: 1.20
Large parts of the NumPy API have :pep:`484`-style type annotations. In
addition a number of type aliases are available to users, most prominently
the two below:
- `ArrayLike`: objects that can be converted to arrays
- `DTypeLike`: objects that can be converted to dtypes
.. _typing-extensions: https://pypi.org/project/typing-extensions/
Mypy plugin
-----------
.. versionadded:: 1.21
.. automodule:: numpy.typing.mypy_plugin
.. currentmodule:: numpy.typing
Differences from the runtime NumPy API
--------------------------------------
NumPy is very flexible. Trying to describe the full range of
possibilities statically would result in types that are not very
helpful. For that reason, the typed NumPy API is often stricter than
the runtime NumPy API. This section describes some notable
differences.
ArrayLike
~~~~~~~~~
The `ArrayLike` type tries to avoid creating object arrays. For
example,
.. code-block:: python
>>> np.array(x**2 for x in range(10))
array(<generator object <genexpr> at ...>, dtype=object)
is valid NumPy code which will create a 0-dimensional object
array. Type checkers will complain about the above example when using
the NumPy types however. If you really intended to do the above, then
you can either use a ``# type: ignore`` comment:
.. code-block:: python
>>> np.array(x**2 for x in range(10)) # type: ignore
or explicitly type the array like object as `~typing.Any`:
.. code-block:: python
>>> from typing import Any
>>> array_like: Any = (x**2 for x in range(10))
>>> np.array(array_like)
array(<generator object <genexpr> at ...>, dtype=object)
ndarray
~~~~~~~
It's possible to mutate the dtype of an array at runtime. For example,
the following code is valid:
.. code-block:: python
>>> x = np.array([1, 2])
>>> x.dtype = np.bool
This sort of mutation is not allowed by the types. Users who want to
write statically typed code should instead use the `numpy.ndarray.view`
method to create a view of the array with a different dtype.
DTypeLike
~~~~~~~~~
The `DTypeLike` type tries to avoid creation of dtype objects using
dictionary of fields like below:
.. code-block:: python
>>> x = np.dtype({"field1": (float, 1), "field2": (int, 3)})
Although this is valid NumPy code, the type checker will complain about it,
since its usage is discouraged.
Please see : :ref:`Data type objects <arrays.dtypes>`
Number precision
~~~~~~~~~~~~~~~~
The precision of `numpy.number` subclasses is treated as an invariant generic
parameter (see :class:`~NBitBase`), simplifying the annotating of processes
involving precision-based casting.
.. code-block:: python
>>> from typing import TypeVar
>>> import numpy as np
>>> import numpy.typing as npt
>>> T = TypeVar("T", bound=npt.NBitBase)
>>> def func(a: np.floating[T], b: np.floating[T]) -> np.floating[T]:
... ...
Consequently, the likes of `~numpy.float16`, `~numpy.float32` and
`~numpy.float64` are still sub-types of `~numpy.floating`, but, contrary to
runtime, they're not necessarily considered as sub-classes.
.. deprecated:: 2.3
The :class:`~numpy.typing.NBitBase` helper is deprecated and will be
removed in a future release. Prefer expressing precision relationships via
``typing.overload`` or ``TypeVar`` definitions bounded by concrete scalar
classes. For example:
.. code-block:: python
from typing import TypeVar
import numpy as np
S = TypeVar("S", bound=np.floating)
def func(a: S, b: S) -> S:
...
or in the case of different input types mapping to different output types:
.. code-block:: python
from typing import overload
import numpy as np
@overload
def phase(x: np.complex64) -> np.float32: ...
@overload
def phase(x: np.complex128) -> np.float64: ...
@overload
def phase(x: np.clongdouble) -> np.longdouble: ...
def phase(x: np.complexfloating) -> np.floating:
...
Timedelta64
~~~~~~~~~~~
The `~numpy.timedelta64` class is not considered a subclass of
`~numpy.signedinteger`, the former only inheriting from `~numpy.generic`
while static type checking.
0D arrays
~~~~~~~~~
During runtime numpy aggressively casts any passed 0D arrays into their
corresponding `~numpy.generic` instance. Until the introduction of shape
typing (see :pep:`646`) it is unfortunately not possible to make the
necessary distinction between 0D and >0D arrays. While thus not strictly
correct, all operations that can potentially perform a 0D-array -> scalar
cast are currently annotated as exclusively returning an `~numpy.ndarray`.
If it is known in advance that an operation *will* perform a
0D-array -> scalar cast, then one can consider manually remedying the
situation with either `typing.cast` or a ``# type: ignore`` comment.
Record array dtypes
~~~~~~~~~~~~~~~~~~~
The dtype of `numpy.recarray`, and the :ref:`routines.array-creation.rec`
functions in general, can be specified in one of two ways:
* Directly via the ``dtype`` argument.
* With up to five helper arguments that operate via `numpy.rec.format_parser`:
``formats``, ``names``, ``titles``, ``aligned`` and ``byteorder``.
These two approaches are currently typed as being mutually exclusive,
*i.e.* if ``dtype`` is specified than one may not specify ``formats``.
While this mutual exclusivity is not (strictly) enforced during runtime,
combining both dtype specifiers can lead to unexpected or even downright
buggy behavior.
API
---
"""
# NOTE: The API section will be appended with additional entries
# further down in this file
# pyright: reportDeprecated=false
from numpy._typing import ArrayLike, DTypeLike, NBitBase, NDArray
__all__ = ["ArrayLike", "DTypeLike", "NBitBase", "NDArray"]
__DIR = __all__ + [k for k in globals() if k.startswith("__") and k.endswith("__")]
__DIR_SET = frozenset(__DIR)
def __dir__() -> list[str]:
return __DIR
def __getattr__(name: str) -> object:
if name == "NBitBase":
import warnings
# Deprecated in NumPy 2.3, 2025-05-01
warnings.warn(
"`NBitBase` is deprecated and will be removed from numpy.typing in the "
"future. Use `@typing.overload` or a `TypeVar` with a scalar-type as upper "
"bound, instead. (deprecated in NumPy 2.3)",
DeprecationWarning,
stacklevel=2,
)
return NBitBase
if name in __DIR_SET:
return globals()[name]
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
if __doc__ is not None:
from numpy._typing._add_docstring import _docstrings
__doc__ += _docstrings
__doc__ += '\n.. autoclass:: numpy.typing.NBitBase\n'
del _docstrings
from numpy._pytesttester import PytestTester
test = PytestTester(__name__)
del PytestTester
| """
============================
Typing (:mod:`numpy.typing`)
============================
.. versionadded:: 1.20
Large parts of the NumPy API have :pep:`484`-style type annotations. In
addition a number of type aliases are available to users, most prominently
the two below:
- `ArrayLike`: objects that can be converted to arrays
- `DTypeLike`: objects that can be converted to dtypes
.. _typing-extensions: https://pypi.org/project/typing-extensions/
Mypy plugin
-----------
.. versionadded:: 1.21
.. automodule:: numpy.typing.mypy_plugin
.. currentmodule:: numpy.typing
Differences from the runtime NumPy API
--------------------------------------
NumPy is very flexible. Trying to describe the full range of
possibilities statically would result in types that are not very
helpful. For that reason, the typed NumPy API is often stricter than
the runtime NumPy API. This section describes some notable
differences.
ArrayLike
~~~~~~~~~
The `ArrayLike` type tries to avoid creating object arrays. For
example,
.. code-block:: python
>>> np.array(x**2 for x in range(10))
array(<generator object <genexpr> at ...>, dtype=object)
is valid NumPy code which will create a 0-dimensional object
array. Type checkers will complain about the above example when using
the NumPy types however. If you really intended to do the above, then
you can either use a ``# type: ignore`` comment:
.. code-block:: python
>>> np.array(x**2 for x in range(10)) # type: ignore
or explicitly type the array like object as `~typing.Any`:
.. code-block:: python
>>> from typing import Any
>>> array_like: Any = (x**2 for x in range(10))
>>> np.array(array_like)
array(<generator object <genexpr> at ...>, dtype=object)
ndarray | [
"# numpy/numpy:numpy/lib/tests/test_mixins.py\nArrayLike",
"# numpy/numpy:numpy/_pytesttester.py\nPytestTester",
"# numpy/numpy:numpy/_typing/_nbit_base.py\nNBitBase"
] | numpy/numpy | numpy/typing/__init__.py |
"""
Tests which scan for certain occurrences in the code, they may not find
all of these occurrences but should catch almost all.
"""
import ast
import tokenize
from pathlib import Path
import pytest
import numpy
class ParseCall(ast.NodeVisitor):
def __init__(self):
self.ls = []
def visit_Attribute(self, node):
ast.NodeVisitor.generic_visit(self, node)
self.ls.append(node.attr)
def visit_Name(self, node):
self.ls.append(node.id)
class FindFuncs(ast.NodeVisitor):
def __init__(self, filename):
super().__init__()
self.__filename = filename
def visit_Call(self, node):
p = ParseCall()
p.visit(node.func)
ast.NodeVisitor.generic_visit(self, node)
if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings':
if getattr(node.args[0], "value", None) == "ignore":
if not self.__filename.name.startswith("test_"):
raise AssertionError(
"ignore filters should only be used in tests; "
f"found in {self.__filename} on line {node.lineno}")
if p.ls[-1] == 'warn' and (
len(p.ls) == 1 or p.ls[-2] == 'warnings'):
if "testing/tests/test_warnings.py" == self.__filename:
# This file
return
# See if stacklevel or skip_file_prefixes exists:
if len(node.args) == 3:
return
args = {kw.arg for kw in node.keywords}
if "stacklevel" in args:
return
if "skip_file_prefixes" in args:
return
raise AssertionError(
"warnings should have an appropriate stacklevel or skip_file_prefixes; "
f"found in {self.__filename} on line {node.lineno}")
@pytest.mark.slow
def test_warning_calls():
# combined "ignore" and stacklevel error
base = Path(numpy.__file__).parent
for path in base.rglob("*.py"):
if base / "testing" in path.parents:
continue
if path == base / "__init__.py":
continue
if path == base / "random" / "__init__.py":
continue
if path == base / "conftest.py":
continue
# use tokenize to auto-detect encoding on systems where no
# default encoding is defined (e.g. LANG='C')
with tokenize.open(str(path)) as file:
tree = ast.parse(file.read())
FindFuncs(path).visit(tree)
| """
Tests which scan for certain occurrences in the code, they may not find
all of these occurrences but should catch almost all.
"""
import ast
import tokenize
from pathlib import Path
import pytest
import numpy
class ParseCall(ast.NodeVisitor):
def __init__(self):
self.ls = []
def visit_Attribute(self, node):
ast.NodeVisitor.generic_visit(self, node)
self.ls.append(node.attr)
def visit_Name(self, node):
self.ls.append(node.id)
class FindFuncs(ast.NodeVisitor):
def __init__(self, filename):
super().__init__()
self.__filename = filename
def visit_Call(self, node):
p = ParseCall()
p.visit(node.func)
ast.NodeVisitor.generic_visit(self, node)
if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings':
if getattr(node.args[0], "value", None) == "ignore":
if not self.__filename.name.startswith("test_"):
raise AssertionError(
"ignore filters should only be used in tests; "
f"found in {self.__filename} on line {node.lineno}")
if p.ls[ | [] | numpy/numpy | numpy/tests/test_warnings.py |
""" Test scripts
Test that we can run executable scripts that have been installed with numpy.
"""
import os
import subprocess
import sys
from os.path import dirname
import pytest
import numpy as np
from numpy.testing import IS_WASM, assert_equal
def find_f2py_commands():
if sys.platform == 'win32':
exe_dir = dirname(sys.executable)
if exe_dir.endswith('Scripts'): # virtualenv
return [os.path.join(exe_dir, 'f2py')]
else:
return [os.path.join(exe_dir, "Scripts", 'f2py')]
else:
# Three scripts are installed in Unix-like systems:
# 'f2py', 'f2py{major}', and 'f2py{major.minor}'. For example,
# if installed with python3.9 the scripts would be named
# 'f2py', 'f2py3', and 'f2py3.9'.
version = sys.version_info
major = str(version.major)
minor = str(version.minor)
return ['f2py', 'f2py' + major, 'f2py' + major + '.' + minor]
@pytest.mark.xfail(reason="Test is unreliable")
@pytest.mark.parametrize('f2py_cmd', find_f2py_commands())
def test_f2py(f2py_cmd):
# test that we can run f2py script
stdout = subprocess.check_output([f2py_cmd, '-v'])
assert_equal(stdout.strip(), np.__version__.encode('ascii'))
@pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess")
def test_pep338():
stdout = subprocess.check_output([sys.executable, '-mnumpy.f2py', '-v'])
assert_equal(stdout.strip(), np.__version__.encode('ascii'))
| """ Test scripts
Test that we can run executable scripts that have been installed with numpy.
"""
import os
import subprocess
import sys
from os.path import dirname
import pytest
import numpy as np
from numpy.testing import IS_WASM, assert_equal
def find_f2py_commands():
if sys.platform == 'win32':
exe_dir = dirname(sys.executable)
if exe_dir.endswith('Scripts'): # virtualenv
return [os.path.join(exe_dir, 'f2py')]
else:
return [os.path.join(exe_dir, "Scripts", 'f2py')]
else:
# Three scripts are installed in Unix-like systems:
# 'f2py', 'f2py{major}', and 'f2py{major.minor}'. For example,
# if installed with python3.9 the scripts would be named
# 'f2py', 'f2py3', and 'f2py3.9'.
version = sys.version_info
major = str(version.major)
minor = str(version.minor)
return ['f2py', 'f2py' + major, 'f2py' + major + '.' + minor]
@pytest.mark.xfail(reason="Test is unreliable")
@pytest.mark.parametrize('f2py_cmd', find_f2py_commands())
def test_f2py(f2py_cmd):
# test that we can run f2py script
stdout = subprocess.check_output([f2py_cmd, '-v'])
assert_ | [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_equal"
] | numpy/numpy | numpy/tests/test_scripts.py |
import pickle
import subprocess
import sys
import textwrap
from importlib import reload
import pytest
import numpy.exceptions as ex
from numpy.testing import IS_WASM, assert_, assert_equal, assert_raises
@pytest.mark.thread_unsafe(reason="reloads global module")
def test_numpy_reloading():
# gh-7844. Also check that relevant globals retain their identity.
import numpy as np
import numpy._globals
_NoValue = np._NoValue
VisibleDeprecationWarning = ex.VisibleDeprecationWarning
ModuleDeprecationWarning = ex.ModuleDeprecationWarning
with pytest.warns(UserWarning):
reload(np)
assert_(_NoValue is np._NoValue)
assert_(ModuleDeprecationWarning is ex.ModuleDeprecationWarning)
assert_(VisibleDeprecationWarning is ex.VisibleDeprecationWarning)
assert_raises(RuntimeError, reload, numpy._globals)
with pytest.warns(UserWarning):
reload(np)
assert_(_NoValue is np._NoValue)
assert_(ModuleDeprecationWarning is ex.ModuleDeprecationWarning)
assert_(VisibleDeprecationWarning is ex.VisibleDeprecationWarning)
def test_novalue():
import numpy as np
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
assert_equal(repr(np._NoValue), '<no value>')
assert_(pickle.loads(pickle.dumps(np._NoValue,
protocol=proto)) is np._NoValue)
@pytest.mark.skipif(IS_WASM, reason="can't start subprocess")
def test_full_reimport():
# Reimporting numpy like this is not safe due to use of global C state,
# and has unexpected side effects. Test that an ImportError is raised.
# When all extension modules are isolated, this should test that clearing
# sys.modules and reimporting numpy works without error.
# Test within a new process, to ensure that we do not mess with the
# global state during the test run (could lead to cryptic test failures).
# This is generally unsafe, especially, since we also reload the C-modules.
code = textwrap.dedent(r"""
import sys
import numpy as np
for k in [k for k in sys.modules if k.startswith('numpy')]:
del sys.modules[k]
try:
import numpy as np
except ImportError as err:
if str(err) != "cannot load module more than once per process":
raise SystemExit(f"Unexpected ImportError: {err}")
else:
raise SystemExit("DID NOT RAISE ImportError")
""")
p = subprocess.run(
(sys.executable, '-c', code),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='utf-8',
check=False,
)
assert p.returncode == 0, p.stdout
| import pickle
import subprocess
import sys
import textwrap
from importlib import reload
import pytest
import numpy.exceptions as ex
from numpy.testing import IS_WASM, assert_, assert_equal, assert_raises
@pytest.mark.thread_unsafe(reason="reloads global module")
def test_numpy_reloading():
# gh-7844. Also check that relevant globals retain their identity.
import numpy as np
import numpy._globals
_NoValue = np._NoValue
VisibleDeprecationWarning = ex.VisibleDeprecationWarning
ModuleDeprecationWarning = ex.ModuleDeprecationWarning
with pytest.warns(UserWarning):
reload(np)
assert_(_NoValue is np._NoValue)
assert_(ModuleDeprecationWarning is ex.ModuleDeprecationWarning)
assert_(VisibleDeprecationWarning is ex.VisibleDeprecationWarning)
assert_raises(RuntimeError, reload, numpy._globals)
with pytest.warns(UserWarning):
reload(np)
assert_(_NoValue is np._NoValue)
assert_(ModuleDeprecationWarning is ex.ModuleDeprecationWarning)
assert_(VisibleDeprecationWarning is ex.VisibleDeprecationWarning)
def test_novalue():
import numpy as np
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
assert_equal(repr(np._NoValue), '<no value>')
assert_(pickle.loads(pickle.dumps(np._NoValue,
protocol=proto)) is np._NoValue) | [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_"
] | numpy/numpy | numpy/tests/test_reloading.py |
import functools
import importlib
import inspect
import pkgutil
import subprocess
import sys
import sysconfig
import types
import warnings
import pytest
import numpy
import numpy as np
from numpy.testing import IS_WASM
try:
import ctypes
except ImportError:
ctypes = None
def check_dir(module, module_name=None):
"""Returns a mapping of all objects with the wrong __module__ attribute."""
if module_name is None:
module_name = module.__name__
results = {}
for name in dir(module):
if name == "core":
continue
item = getattr(module, name)
if (hasattr(item, '__module__') and hasattr(item, '__name__')
and item.__module__ != module_name):
results[name] = item.__module__ + '.' + item.__name__
return results
def test_numpy_namespace():
# We override dir to not show these members
allowlist = {
'recarray': 'numpy.rec.recarray',
}
bad_results = check_dir(np)
# pytest gives better error messages with the builtin assert than with
# assert_equal
assert bad_results == allowlist
@pytest.mark.skipif(IS_WASM, reason="can't start subprocess")
@pytest.mark.parametrize('name', ['testing'])
def test_import_lazy_import(name):
"""Make sure we can actually use the modules we lazy load.
While not exported as part of the public API, it was accessible. With the
use of __getattr__ and __dir__, this isn't always true It can happen that
an infinite recursion may happen.
This is the only way I found that would force the failure to appear on the
badly implemented code.
We also test for the presence of the lazily imported modules in dir
"""
exe = (sys.executable, '-c', "import numpy; numpy." + name)
result = subprocess.check_output(exe)
assert not result
# Make sure they are still in the __dir__
assert name in dir(np)
def test_dir_testing():
"""Assert that output of dir has only one "testing/tester"
attribute without duplicate"""
assert len(dir(np)) == len(set(dir(np)))
def test_numpy_linalg():
bad_results = check_dir(np.linalg)
assert bad_results == {}
def test_numpy_fft():
bad_results = check_dir(np.fft)
assert bad_results == {}
@pytest.mark.skipif(ctypes is None,
reason="ctypes not available in this python")
def test_NPY_NO_EXPORT():
cdll = ctypes.CDLL(np._core._multiarray_tests.__file__)
# Make sure an arbitrary NPY_NO_EXPORT function is actually hidden
f = getattr(cdll, 'test_not_exported', None)
assert f is None, ("'test_not_exported' is mistakenly exported, "
"NPY_NO_EXPORT does not work")
# Historically NumPy has not used leading underscores for private submodules
# much. This has resulted in lots of things that look like public modules
# (i.e. things that can be imported as `import numpy.somesubmodule.somefile`),
# but were never intended to be public. The PUBLIC_MODULES list contains
# modules that are either public because they were meant to be, or because they
# contain public functions/objects that aren't present in any other namespace
# for whatever reason and therefore should be treated as public.
#
# The PRIVATE_BUT_PRESENT_MODULES list contains modules that look public (lack
# of underscores) but should not be used. For many of those modules the
# current status is fine. For others it may make sense to work on making them
# private, to clean up our public API and avoid confusion.
PUBLIC_MODULES = ['numpy.' + s for s in [
"ctypeslib",
"dtypes",
"exceptions",
"f2py",
"fft",
"lib",
"lib.array_utils",
"lib.format",
"lib.introspect",
"lib.mixins",
"lib.npyio",
"lib.recfunctions", # note: still needs cleaning, was forgotten for 2.0
"lib.scimath",
"lib.stride_tricks",
"linalg",
"ma",
"ma.extras",
"ma.mrecords",
"polynomial",
"polynomial.chebyshev",
"polynomial.hermite",
"polynomial.hermite_e",
"polynomial.laguerre",
"polynomial.legendre",
"polynomial.polynomial",
"random",
"strings",
"testing",
"testing.overrides",
"typing",
"typing.mypy_plugin",
"version",
]]
PUBLIC_ALIASED_MODULES = [
"numpy.char",
"numpy.emath",
"numpy.rec",
]
PRIVATE_BUT_PRESENT_MODULES = ['numpy.' + s for s in [
"conftest",
"core",
"core.multiarray",
"core.numeric",
"core.umath",
"core.arrayprint",
"core.defchararray",
"core.einsumfunc",
"core.fromnumeric",
"core.function_base",
"core.getlimits",
"core.numerictypes",
"core.overrides",
"core.records",
"core.shape_base",
"f2py.auxfuncs",
"f2py.capi_maps",
"f2py.cb_rules",
"f2py.cfuncs",
"f2py.common_rules",
"f2py.crackfortran",
"f2py.diagnose",
"f2py.f2py2e",
"f2py.f90mod_rules",
"f2py.func2subr",
"f2py.rules",
"f2py.symbolic",
"f2py.use_rules",
"lib.user_array", # note: not in np.lib, but probably should just be deleted
"linalg.lapack_lite",
"ma.core",
"ma.testutils",
"matlib",
"matrixlib",
"matrixlib.defmatrix",
"polynomial.polyutils",
"random.mtrand",
"random.bit_generator",
"testing.print_coercion_tables",
]]
def is_unexpected(name):
"""Check if this needs to be considered."""
return (
'._' not in name and '.tests' not in name and '.setup' not in name
and name not in PUBLIC_MODULES
and name not in PUBLIC_ALIASED_MODULES
and name not in PRIVATE_BUT_PRESENT_MODULES
)
def test_all_modules_are_expected():
"""
Test that we don't add anything that looks like a new public module by
accident. Check is based on filenames.
"""
modnames = []
for _, modname, ispkg in pkgutil.walk_packages(path=np.__path__,
prefix=np.__name__ + '.',
onerror=None):
if is_unexpected(modname):
# We have a name that is new. If that's on purpose, add it to
# PUBLIC_MODULES. We don't expect to have to add anything to
# PRIVATE_BUT_PRESENT_MODULES. Use an underscore in the name!
modnames.append(modname)
if modnames:
raise AssertionError(f'Found unexpected modules: {modnames}')
# Stuff that clearly shouldn't be in the API and is detected by the next test
# below
SKIP_LIST_2 = [
'numpy.matlib.char',
'numpy.matlib.rec',
'numpy.matlib.emath',
'numpy.matlib.exceptions',
'numpy.matlib.math',
'numpy.matlib.linalg',
'numpy.matlib.fft',
'numpy.matlib.random',
'numpy.matlib.ctypeslib',
'numpy.matlib.ma',
]
def test_all_modules_are_expected_2():
"""
Method checking all objects. The pkgutil-based method in
`test_all_modules_are_expected` does not catch imports into a namespace,
only filenames. So this test is more thorough, and checks this like:
import .lib.scimath as emath
To check if something in a module is (effectively) public, one can check if
there's anything in that namespace that's a public function/object but is
not exposed in a higher-level namespace. For example for a `numpy.lib`
submodule::
mod = np.lib.mixins
for obj in mod.__all__:
if obj in np.__all__:
continue
elif obj in np.lib.__all__:
continue
else:
print(obj)
"""
def find_unexpected_members(mod_name):
members = []
module = importlib.import_module(mod_name)
if hasattr(module, '__all__'):
objnames = module.__all__
else:
objnames = dir(module)
for objname in objnames:
if not objname.startswith('_'):
fullobjname = mod_name + '.' + objname
if isinstance(getattr(module, objname), types.ModuleType):
if is_unexpected(fullobjname):
if fullobjname not in SKIP_LIST_2:
members.append(fullobjname)
return members
unexpected_members = find_unexpected_members("numpy")
for modname in PUBLIC_MODULES:
unexpected_members.extend(find_unexpected_members(modname))
if unexpected_members:
raise AssertionError("Found unexpected object(s) that look like "
f"modules: {unexpected_members}")
def test_api_importable():
"""
Check that all submodules listed higher up in this file can be imported
Note that if a PRIVATE_BUT_PRESENT_MODULES entry goes missing, it may
simply need to be removed from the list (deprecation may or may not be
needed - apply common sense).
"""
def check_importable(module_name):
try:
importlib.import_module(module_name)
except (ImportError, AttributeError):
return False
return True
module_names = []
for module_name in PUBLIC_MODULES:
if not check_importable(module_name):
module_names.append(module_name)
if module_names:
raise AssertionError("Modules in the public API that cannot be "
f"imported: {module_names}")
for module_name in PUBLIC_ALIASED_MODULES:
try:
eval(module_name)
except AttributeError:
module_names.append(module_name)
if module_names:
raise AssertionError("Modules in the public API that were not "
f"found: {module_names}")
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', category=DeprecationWarning)
warnings.filterwarnings('always', category=ImportWarning)
for module_name in PRIVATE_BUT_PRESENT_MODULES:
if not check_importable(module_name):
module_names.append(module_name)
if module_names:
raise AssertionError("Modules that are not really public but looked "
"public and can not be imported: "
f"{module_names}")
@pytest.mark.xfail(
sysconfig.get_config_var("Py_DEBUG") not in (None, 0, "0"),
reason=(
"NumPy possibly built with `USE_DEBUG=True ./tools/travis-test.sh`, "
"which does not expose the `array_api` entry point. "
"See https://github.com/numpy/numpy/pull/19800"
),
)
def test_array_api_entry_point():
"""
Entry point for Array API implementation can be found with importlib and
returns the main numpy namespace.
"""
# For a development install that did not go through meson-python,
# the entrypoint will not have been installed. So ensure this test fails
# only if numpy is inside site-packages.
numpy_in_sitepackages = sysconfig.get_path('platlib') in np.__file__
eps = importlib.metadata.entry_points()
xp_eps = eps.select(group="array_api")
if len(xp_eps) == 0:
if numpy_in_sitepackages:
msg = "No entry points for 'array_api' found"
raise AssertionError(msg) from None
return
try:
ep = next(ep for ep in xp_eps if ep.name == "numpy")
except StopIteration:
if numpy_in_sitepackages:
msg = "'numpy' not in array_api entry points"
raise AssertionError(msg) from None
return
if ep.value == 'numpy.array_api':
# Looks like the entrypoint for the current numpy build isn't
# installed, but an older numpy is also installed and hence the
# entrypoint is pointing to the old (no longer existing) location.
# This isn't a problem except for when running tests with `spin` or an
# in-place build.
return
xp = ep.load()
msg = (
f"numpy entry point value '{ep.value}' "
"does not point to our Array API implementation"
)
assert xp is numpy, msg
def test_main_namespace_all_dir_coherence():
"""
Checks if `dir(np)` and `np.__all__` are consistent and return
the same content, excluding exceptions and private members.
"""
def _remove_private_members(member_set):
return {m for m in member_set if not m.startswith('_')}
def _remove_exceptions(member_set):
return member_set.difference({
"bool" # included only in __dir__
})
all_members = _remove_private_members(np.__all__)
all_members = _remove_exceptions(all_members)
dir_members = _remove_private_members(np.__dir__())
dir_members = _remove_exceptions(dir_members)
assert all_members == dir_members, (
"Members that break symmetry: "
f"{all_members.symmetric_difference(dir_members)}"
)
@pytest.mark.filterwarnings(
r"ignore:numpy.core(\.\w+)? is deprecated:DeprecationWarning"
)
def test_core_shims_coherence():
"""
Check that all "semi-public" members of `numpy._core` are also accessible
from `numpy.core` shims.
"""
import numpy.core as core
for member_name in dir(np._core):
# Skip private and test members. Also if a module is aliased,
# no need to add it to np.core
if (
member_name.startswith("_")
or member_name in ["tests", "strings"]
or f"numpy.{member_name}" in PUBLIC_ALIASED_MODULES
):
continue
member = getattr(np._core, member_name)
# np.core is a shim and all submodules of np.core are shims
# but we should be able to import everything in those shims
# that are available in the "real" modules in np._core, with
# the exception of the namespace packages (__spec__.origin is None),
# like numpy._core.include, or numpy._core.lib.pkgconfig.
if (
inspect.ismodule(member)
and member.__spec__ and member.__spec__.origin is not None
):
submodule = member
submodule_name = member_name
for submodule_member_name in dir(submodule):
# ignore dunder names
if submodule_member_name.startswith("__"):
continue
submodule_member = getattr(submodule, submodule_member_name)
core_submodule = __import__(
f"numpy.core.{submodule_name}",
fromlist=[submodule_member_name]
)
assert submodule_member is getattr(
core_submodule, submodule_member_name
)
else:
assert member is getattr(core, member_name)
@pytest.mark.filterwarnings(r"ignore:\w+ chararray \w+:DeprecationWarning")
def test_functions_single_location():
"""
Check that each public function is available from one location only.
Test performs BFS search traversing NumPy's public API. It flags
any function-like object that is accessible from more that one place.
"""
from collections.abc import Callable
from typing import Any
from numpy._core._multiarray_umath import (
_ArrayFunctionDispatcher as dispatched_function,
)
visited_modules: set[types.ModuleType] = {np}
visited_functions: set[Callable[..., Any]] = set()
# Functions often have `__name__` overridden, therefore we need
# to keep track of locations where functions have been found.
functions_original_paths: dict[Callable[..., Any], str] = {}
# Here we aggregate functions with more than one location.
# It must be empty for the test to pass.
duplicated_functions: list[tuple] = []
modules_queue = [np]
while len(modules_queue) > 0:
module = modules_queue.pop()
for member_name in dir(module):
member = getattr(module, member_name)
# first check if we got a module
if (
inspect.ismodule(member) and # it's a module
"numpy" in member.__name__ and # inside NumPy
not member_name.startswith("_") and # not private
"numpy._core" not in member.__name__ and # outside _core
# not a legacy or testing module
member_name not in ["f2py", "ma", "testing", "tests"] and
member not in visited_modules # not visited yet
):
modules_queue.append(member)
visited_modules.add(member)
# else check if we got a function-like object
elif (
inspect.isfunction(member) or
isinstance(member, (dispatched_function, np.ufunc))
):
if member in visited_functions:
# skip main namespace functions with aliases
if (
member.__name__ in [
"absolute", # np.abs
"arccos", # np.acos
"arccosh", # np.acosh
"arcsin", # np.asin
"arcsinh", # np.asinh
"arctan", # np.atan
"arctan2", # np.atan2
"arctanh", # np.atanh
"left_shift", # np.bitwise_left_shift
"right_shift", # np.bitwise_right_shift
"conjugate", # np.conj
"invert", # np.bitwise_not & np.bitwise_invert
"remainder", # np.mod
"divide", # np.true_divide
"concatenate", # np.concat
"power", # np.pow
"transpose", # np.permute_dims
] and
module.__name__ == "numpy"
):
continue
# skip trimcoef from numpy.polynomial as it is
# duplicated by design.
if (
member.__name__ == "trimcoef" and
module.__name__.startswith("numpy.polynomial")
):
continue
# skip ufuncs that are exported in np.strings as well
if member.__name__ in (
"add",
"equal",
"not_equal",
"greater",
"greater_equal",
"less",
"less_equal",
) and module.__name__ == "numpy.strings":
continue
# numpy.char reexports all numpy.strings functions for
# backwards-compatibility
if module.__name__ == "numpy.char":
continue
# function is present in more than one location!
duplicated_functions.append(
(member.__name__,
module.__name__,
functions_original_paths[member])
)
else:
visited_functions.add(member)
functions_original_paths[member] = module.__name__
del visited_functions, visited_modules, functions_original_paths
assert len(duplicated_functions) == 0, duplicated_functions
def test___module___attribute():
modules_queue = [np]
visited_modules = {np}
visited_functions = set()
incorrect_entries = []
while len(modules_queue) > 0:
module = modules_queue.pop()
for member_name in dir(module):
member = getattr(module, member_name)
# first check if we got a module
if (
inspect.ismodule(member) and # it's a module
"numpy" in member.__name__ and # inside NumPy
not member_name.startswith("_") and # not private
"numpy._core" not in member.__name__ and # outside _core
# not in a skip module list
member_name not in [
"char", "core", "f2py", "ma", "lapack_lite", "mrecords",
"testing", "tests", "polynomial", "typing", "mtrand",
"bit_generator",
] and
member not in visited_modules # not visited yet
):
modules_queue.append(member)
visited_modules.add(member)
elif (
not inspect.ismodule(member) and
hasattr(member, "__name__") and
not member.__name__.startswith("_") and
member.__module__ != module.__name__ and
member not in visited_functions
):
# skip ufuncs that are exported in np.strings as well
if member.__name__ in (
"add", "equal", "not_equal", "greater", "greater_equal",
"less", "less_equal",
) and module.__name__ == "numpy.strings":
continue
# recarray and record are exported in np and np.rec
if (
(member.__name__ == "recarray" and module.__name__ == "numpy") or
(member.__name__ == "record" and module.__name__ == "numpy.rec")
):
continue
# ctypeslib exports ctypes c_long/c_longlong
if (
member.__name__ in ("c_long", "c_longlong") and
module.__name__ == "numpy.ctypeslib"
):
continue
# skip cdef classes
if member.__name__ in (
"BitGenerator", "Generator", "MT19937", "PCG64", "PCG64DXSM",
"Philox", "RandomState", "SFC64", "SeedSequence",
):
continue
incorrect_entries.append(
{
"Func": member.__name__,
"actual": member.__module__,
"expected": module.__name__,
}
)
visited_functions.add(member)
if incorrect_entries:
assert len(incorrect_entries) == 0, incorrect_entries
def _check_correct_qualname_and_module(obj) -> bool:
qualname = obj.__qualname__
name = obj.__name__
module_name = obj.__module__
assert name == qualname.split(".")[-1]
module = sys.modules[module_name]
actual_obj = functools.reduce(getattr, qualname.split("."), module)
return (
actual_obj is obj or
# `obj` may be a bound method/property of `actual_obj`:
(
hasattr(actual_obj, "__get__") and hasattr(obj, "__self__") and
actual_obj.__module__ == obj.__module__ and
actual_obj.__qualname__ == qualname
)
)
@pytest.mark.filterwarnings(r"ignore:\w+ chararray \w+:DeprecationWarning")
def test___qualname___and___module___attribute():
# NumPy messes with module and name/qualname attributes, but any object
# should be discoverable based on its module and qualname, so test that.
# We do this for anything with a name (ensuring qualname is also set).
modules_queue = [np]
visited_modules = {np}
visited_functions = set()
incorrect_entries = []
while len(modules_queue) > 0:
module = modules_queue.pop()
for member_name in dir(module):
member = getattr(module, member_name)
# first check if we got a module
if (
inspect.ismodule(member) and # it's a module
"numpy" in member.__name__ and # inside NumPy
not member_name.startswith("_") and # not private
member_name not in {"tests", "typing"} and # type names don't match
"numpy._core" not in member.__name__ and # outside _core
member not in visited_modules # not visited yet
):
modules_queue.append(member)
visited_modules.add(member)
elif (
not inspect.ismodule(member) and
hasattr(member, "__name__") and
not member.__name__.startswith("_") and
not member_name.startswith("_") and
not _check_correct_qualname_and_module(member) and
member not in visited_functions
):
incorrect_entries.append(
{
"found_at": f"{module.__name__}:{member_name}",
"advertises": f"{member.__module__}:{member.__qualname__}",
}
)
visited_functions.add(member)
if incorrect_entries:
assert len(incorrect_entries) == 0, incorrect_entries
| import functools
import importlib
import inspect
import pkgutil
import subprocess
import sys
import sysconfig
import types
import warnings
import pytest
import numpy
import numpy as np
from numpy.testing import IS_WASM
try:
import ctypes
except ImportError:
ctypes = None
def check_dir(module, module_name=None):
"""Returns a mapping of all objects with the wrong __module__ attribute."""
if module_name is None:
module_name = module.__name__
results = {}
for name in dir(module):
if name == "core":
continue
item = getattr(module, name)
if (hasattr(item, '__module__') and hasattr(item, '__name__')
and item.__module__ != module_name):
results[name] = item.__module__ + '.' + item.__name__
return results
def test_numpy_namespace():
# We override dir to not show these members
allowlist = {
'recarray': 'numpy.rec.recarray',
}
bad_results = check_dir(np)
# pytest gives better error messages with the builtin assert than with
# assert_equal
assert bad_results == allowlist
@pytest.mark.skipif(IS_WASM, reason="can't start subprocess")
@pytest.mark.parametrize('name', ['testing'])
def test_import_lazy_import(name):
"""Make sure we can actually use the modules we lazy load.
While not exported as part of the public API, it was accessible. With the
| [] | numpy/numpy | numpy/tests/test_public_api.py |
"""
Check the numpy version is valid.
Note that a development version is marked by the presence of 'dev0' or '+'
in the version string, all else is treated as a release. The version string
itself is set from the output of ``git describe`` which relies on tags.
Examples
--------
Valid Development: 1.22.0.dev0 1.22.0.dev0+5-g7999db4df2 1.22.0+5-g7999db4df2
Valid Release: 1.21.0.rc1, 1.21.0.b1, 1.21.0
Invalid: 1.22.0.dev, 1.22.0.dev0-5-g7999db4dfB, 1.21.0.d1, 1.21.a
Note that a release is determined by the version string, which in turn
is controlled by the result of the ``git describe`` command.
"""
import re
import numpy as np
from numpy.testing import assert_
def test_valid_numpy_version():
# Verify that the numpy version is a valid one (no .post suffix or other
# nonsense). See gh-6431 for an issue caused by an invalid version.
version_pattern = r"^[0-9]+\.[0-9]+\.[0-9]+(a[0-9]|b[0-9]|rc[0-9])?"
dev_suffix = r"(\.dev[0-9]+(\+git[0-9]+\.[0-9a-f]+)?)?"
res = re.match(version_pattern + dev_suffix + '$', np.__version__)
assert_(res is not None, np.__version__)
def test_short_version():
# Check numpy.short_version actually exists
if np.version.release:
assert_(np.__version__ == np.version.short_version,
"short_version mismatch in release version")
else:
assert_(np.__version__.split("+")[0] == np.version.short_version,
"short_version mismatch in development version")
def test_version_module():
contents = {s for s in dir(np.version) if not s.startswith('_')}
expected = {
'full_version',
'git_revision',
'release',
'short_version',
'version',
}
assert contents == expected
| """
Check the numpy version is valid.
Note that a development version is marked by the presence of 'dev0' or '+'
in the version string, all else is treated as a release. The version string
itself is set from the output of ``git describe`` which relies on tags.
Examples
--------
Valid Development: 1.22.0.dev0 1.22.0.dev0+5-g7999db4df2 1.22.0+5-g7999db4df2
Valid Release: 1.21.0.rc1, 1.21.0.b1, 1.21.0
Invalid: 1.22.0.dev, 1.22.0.dev0-5-g7999db4dfB, 1.21.0.d1, 1.21.a
Note that a release is determined by the version string, which in turn
is controlled by the result of the ``git describe`` command.
"""
import re
import numpy as np
from numpy.testing import assert_
def test_valid_numpy_version():
# Verify that the numpy version is a valid one (no .post suffix or other
# nonsense). See gh-6431 for an issue caused by an invalid version.
version_pattern = r"^[0-9]+\.[0-9]+\.[0-9]+(a[0-9]|b[0-9]|rc[0-9])?"
dev_suffix = r"(\.dev[0-9]+(\+git[0-9]+\.[0-9a-f]+)?)?"
res = re.match(version_pattern + dev_suffix + '$', np.__version__)
assert_(res is not None, np.__version__)
def test_short_version():
# Check numpy.short_version actually exists
if np.version.release:
assert_(np.__version__ == np.version.short_version,
"short_version mismatch in release version") | [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_"
] | numpy/numpy | numpy/tests/test_numpy_version.py |
"""
Check the numpy config is valid.
"""
from unittest.mock import patch
import pytest
import numpy as np
pytestmark = pytest.mark.skipif(
not hasattr(np.__config__, "_built_with_meson"),
reason="Requires Meson builds",
)
class TestNumPyConfigs:
REQUIRED_CONFIG_KEYS = [
"Compilers",
"Machine Information",
"Python Information",
]
@patch("numpy.__config__._check_pyyaml")
@pytest.mark.thread_unsafe(reason="unittest.mock.patch updates global state")
def test_pyyaml_not_found(self, mock_yaml_importer):
mock_yaml_importer.side_effect = ModuleNotFoundError()
with pytest.warns(UserWarning):
np.show_config()
def test_dict_mode(self):
config = np.show_config(mode="dicts")
assert isinstance(config, dict)
assert all(key in config for key in self.REQUIRED_CONFIG_KEYS), (
"Required key missing,"
" see index of `False` with `REQUIRED_CONFIG_KEYS`"
)
def test_invalid_mode(self):
with pytest.raises(AttributeError):
np.show_config(mode="foo")
def test_warn_to_add_tests(self):
assert len(np.__config__.DisplayModes) == 2, (
"New mode detected,"
" please add UT if applicable and increment this count"
)
| """
Check the numpy config is valid.
"""
from unittest.mock import patch
import pytest
import numpy as np
pytestmark = pytest.mark.skipif(
not hasattr(np.__config__, "_built_with_meson"),
reason="Requires Meson builds",
)
class TestNumPyConfigs:
REQUIRED_CONFIG_KEYS = [
"Compilers",
"Machine Information",
"Python Information",
]
@patch("numpy.__config__._check_pyyaml")
@pytest.mark.thread_unsafe(reason="unittest.mock.patch updates global state")
def test_pyyaml_not_found(self, mock_yaml_importer):
mock_yaml_importer.side_effect = ModuleNotFoundError()
with pytest.warns(UserWarning):
np.show_config()
def test_dict_mode(self):
config = np.show_config(mode="dicts")
assert isinstance(config, dict)
assert all(key in config for key in self.REQUIRED_CONFIG_KEYS), (
"Required key missing,"
" see index of `False` with `REQUIRED_CONFIG_KEYS`"
)
def test_invalid_mode(self):
with pytest.raises(AttributeError):
np.show_config(mode="foo")
def test_warn_to_add_tests(self):
assert len(np.__config__.DisplayModes | [] | numpy/numpy | numpy/tests/test_numpy_config.py |
import numpy as np
import numpy.matlib
from numpy.testing import assert_, assert_array_equal
def test_empty():
x = numpy.matlib.empty((2,))
assert_(isinstance(x, np.matrix))
assert_(x.shape, (1, 2))
def test_ones():
assert_array_equal(numpy.matlib.ones((2, 3)),
np.matrix([[ 1., 1., 1.],
[ 1., 1., 1.]]))
assert_array_equal(numpy.matlib.ones(2), np.matrix([[ 1., 1.]]))
def test_zeros():
assert_array_equal(numpy.matlib.zeros((2, 3)),
np.matrix([[ 0., 0., 0.],
[ 0., 0., 0.]]))
assert_array_equal(numpy.matlib.zeros(2), np.matrix([[0., 0.]]))
def test_identity():
x = numpy.matlib.identity(2, dtype=int)
assert_array_equal(x, np.matrix([[1, 0], [0, 1]]))
def test_eye():
xc = numpy.matlib.eye(3, k=1, dtype=int)
assert_array_equal(xc, np.matrix([[ 0, 1, 0],
[ 0, 0, 1],
[ 0, 0, 0]]))
assert xc.flags.c_contiguous
assert not xc.flags.f_contiguous
xf = numpy.matlib.eye(3, 4, dtype=int, order='F')
assert_array_equal(xf, np.matrix([[ 1, 0, 0, 0],
[ 0, 1, 0, 0],
[ 0, 0, 1, 0]]))
assert not xf.flags.c_contiguous
assert xf.flags.f_contiguous
def test_rand():
x = numpy.matlib.rand(3)
# check matrix type, array would have shape (3,)
assert_(x.ndim == 2)
def test_randn():
x = np.matlib.randn(3)
# check matrix type, array would have shape (3,)
assert_(x.ndim == 2)
def test_repmat():
a1 = np.arange(4)
x = numpy.matlib.repmat(a1, 2, 2)
y = np.array([[0, 1, 2, 3, 0, 1, 2, 3],
[0, 1, 2, 3, 0, 1, 2, 3]])
assert_array_equal(x, y)
| import numpy as np
import numpy.matlib
from numpy.testing import assert_, assert_array_equal
def test_empty():
x = numpy.matlib.empty((2,))
assert_(isinstance(x, np.matrix))
assert_(x.shape, (1, 2))
def test_ones():
assert_array_equal(numpy.matlib.ones((2, 3)),
np.matrix([[ 1., 1., 1.],
[ 1., 1., 1.]]))
assert_array_equal(numpy.matlib.ones(2), np.matrix([[ 1., 1.]]))
def test_zeros():
assert_array_equal(numpy.matlib.zeros((2, 3)),
np.matrix([[ 0., 0., 0.],
[ 0., 0., 0.]]))
assert_array_equal(numpy.matlib.zeros(2), np.matrix([[0., 0.]]))
def test_identity():
x = numpy.matlib.identity(2, dtype=int)
assert_array_equal(x, np.matrix([[1, 0], [0, 1]]))
def test_eye():
xc = numpy.matlib.eye(3, k=1, dtype=int)
assert_array_equal(xc, np.matrix([[ 0, 1, 0],
| [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_"
] | numpy/numpy | numpy/tests/test_matlib.py |
import subprocess
import sys
import textwrap
import pytest
from numpy.testing import IS_WASM
@pytest.mark.skipif(IS_WASM, reason="can't start subprocess")
def test_lazy_load():
# gh-22045. lazyload doesn't import submodule names into the namespace
# Test within a new process, to ensure that we do not mess with the
# global state during the test run (could lead to cryptic test failures).
# This is generally unsafe, especially, since we also reload the C-modules.
code = textwrap.dedent(r"""
import sys
from importlib.util import LazyLoader, find_spec, module_from_spec
# create lazy load of numpy as np
spec = find_spec("numpy")
module = module_from_spec(spec)
sys.modules["numpy"] = module
loader = LazyLoader(spec.loader)
loader.exec_module(module)
np = module
# test a subpackage import
from numpy.lib import recfunctions # noqa: F401
# test triggering the import of the package
np.ndarray
""")
p = subprocess.run(
(sys.executable, '-c', code),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='utf-8',
check=False,
)
assert p.returncode == 0, p.stdout
| import subprocess
import sys
import textwrap
import pytest
from numpy.testing import IS_WASM
@pytest.mark.skipif(IS_WASM, reason="can't start subprocess")
def test_lazy_load():
# gh-22045. lazyload doesn't import submodule names into the namespace
# Test within a new process, to ensure that we do not mess with the
# global state during the test run (could lead to cryptic test failures).
# This is generally unsafe, especially, since we also reload the C-modules.
code = textwrap.dedent(r"""
import sys
from importlib.util import LazyLoader, find_spec, module_from_spec
# create lazy load of numpy as np
spec = find_spec("numpy")
module = module_from_spec(spec)
sys.modules["numpy"] = module
loader = LazyLoader(spec.loader)
loader.exec_module(module)
np = module
# test a subpackage import
from numpy.lib import recfunctions # noqa: F401
# test triggering the import of the package
np.ndarray
""")
p = subprocess.run(
(sys.executable, '-c', code),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='utf-8',
check=False,
)
assert p.returncode == 0, p.stdout
| [] | numpy/numpy | numpy/tests/test_lazyloading.py |
import sys
import sysconfig
import weakref
from pathlib import Path
import pytest
import numpy as np
from numpy.ctypeslib import as_array, load_library, ndpointer
from numpy.testing import assert_, assert_array_equal, assert_equal, assert_raises
try:
import ctypes
except ImportError:
ctypes = None
else:
cdll = None
test_cdll = None
if hasattr(sys, 'gettotalrefcount'):
try:
cdll = load_library(
'_multiarray_umath_d', np._core._multiarray_umath.__file__
)
except OSError:
pass
try:
test_cdll = load_library(
'_multiarray_tests', np._core._multiarray_tests.__file__
)
except OSError:
pass
if cdll is None:
cdll = load_library(
'_multiarray_umath', np._core._multiarray_umath.__file__)
if test_cdll is None:
test_cdll = load_library(
'_multiarray_tests', np._core._multiarray_tests.__file__
)
c_forward_pointer = test_cdll.forward_pointer
@pytest.mark.skipif(ctypes is None,
reason="ctypes not available in this python")
@pytest.mark.skipif(sys.platform == 'cygwin',
reason="Known to fail on cygwin")
class TestLoadLibrary:
def test_basic(self):
loader_path = np._core._multiarray_umath.__file__
out1 = load_library('_multiarray_umath', loader_path)
out2 = load_library(Path('_multiarray_umath'), loader_path)
out3 = load_library('_multiarray_umath', Path(loader_path))
out4 = load_library(b'_multiarray_umath', loader_path)
assert isinstance(out1, ctypes.CDLL)
assert out1 is out2 is out3 is out4
def test_basic2(self):
# Regression for #801: load_library with a full library name
# (including extension) does not work.
try:
so_ext = sysconfig.get_config_var('EXT_SUFFIX')
load_library(f'_multiarray_umath{so_ext}',
np._core._multiarray_umath.__file__)
except ImportError as e:
msg = ("ctypes is not available on this python: skipping the test"
" (import error was: %s)" % str(e))
print(msg)
class TestNdpointer:
def test_dtype(self):
dt = np.intc
p = ndpointer(dtype=dt)
assert_(p.from_param(np.array([1], dt)))
dt = '<i4'
p = ndpointer(dtype=dt)
assert_(p.from_param(np.array([1], dt)))
dt = np.dtype('>i4')
p = ndpointer(dtype=dt)
p.from_param(np.array([1], dt))
assert_raises(TypeError, p.from_param,
np.array([1], dt.newbyteorder('swap')))
dtnames = ['x', 'y']
dtformats = [np.intc, np.float64]
dtdescr = {'names': dtnames, 'formats': dtformats}
dt = np.dtype(dtdescr)
p = ndpointer(dtype=dt)
assert_(p.from_param(np.zeros((10,), dt)))
samedt = np.dtype(dtdescr)
p = ndpointer(dtype=samedt)
assert_(p.from_param(np.zeros((10,), dt)))
dt2 = np.dtype(dtdescr, align=True)
if dt.itemsize != dt2.itemsize:
assert_raises(TypeError, p.from_param, np.zeros((10,), dt2))
else:
assert_(p.from_param(np.zeros((10,), dt2)))
def test_ndim(self):
p = ndpointer(ndim=0)
assert_(p.from_param(np.array(1)))
assert_raises(TypeError, p.from_param, np.array([1]))
p = ndpointer(ndim=1)
assert_raises(TypeError, p.from_param, np.array(1))
assert_(p.from_param(np.array([1])))
p = ndpointer(ndim=2)
assert_(p.from_param(np.array([[1]])))
def test_shape(self):
p = ndpointer(shape=(1, 2))
assert_(p.from_param(np.array([[1, 2]])))
assert_raises(TypeError, p.from_param, np.array([[1], [2]]))
p = ndpointer(shape=())
assert_(p.from_param(np.array(1)))
def test_flags(self):
x = np.array([[1, 2], [3, 4]], order='F')
p = ndpointer(flags='FORTRAN')
assert_(p.from_param(x))
p = ndpointer(flags='CONTIGUOUS')
assert_raises(TypeError, p.from_param, x)
p = ndpointer(flags=x.flags.num)
assert_(p.from_param(x))
assert_raises(TypeError, p.from_param, np.array([[1, 2], [3, 4]]))
@pytest.mark.thread_unsafe(reason="checks that global ndpointer cache is updating")
def test_cache(self):
assert_(ndpointer(dtype=np.float64) is ndpointer(dtype=np.float64))
# shapes are normalized
assert_(ndpointer(shape=2) is ndpointer(shape=(2,)))
# 1.12 <= v < 1.16 had a bug that made these fail
assert_(ndpointer(shape=2) is not ndpointer(ndim=2))
assert_(ndpointer(ndim=2) is not ndpointer(shape=2))
@pytest.mark.skipif(ctypes is None,
reason="ctypes not available on this python installation")
class TestNdpointerCFunc:
def test_arguments(self):
""" Test that arguments are coerced from arrays """
c_forward_pointer.restype = ctypes.c_void_p
c_forward_pointer.argtypes = (ndpointer(ndim=2),)
c_forward_pointer(np.zeros((2, 3)))
# too many dimensions
assert_raises(
ctypes.ArgumentError, c_forward_pointer, np.zeros((2, 3, 4)))
@pytest.mark.parametrize(
'dt', [
float,
np.dtype({
'formats': ['<i4', '<i4'],
'names': ['a', 'b'],
'offsets': [0, 2],
'itemsize': 6
})
], ids=[
'float',
'overlapping-fields'
]
)
def test_return(self, dt):
""" Test that return values are coerced to arrays """
arr = np.zeros((2, 3), dt)
ptr_type = ndpointer(shape=arr.shape, dtype=arr.dtype)
c_forward_pointer.restype = ptr_type
c_forward_pointer.argtypes = (ptr_type,)
# check that the arrays are equivalent views on the same data
arr2 = c_forward_pointer(arr)
assert_equal(arr2.dtype, arr.dtype)
assert_equal(arr2.shape, arr.shape)
assert_equal(
arr2.__array_interface__['data'],
arr.__array_interface__['data']
)
@pytest.mark.thread_unsafe(reason="mutates global test vars")
def test_vague_return_value(self):
""" Test that vague ndpointer return values do not promote to arrays """
arr = np.zeros((2, 3))
ptr_type = ndpointer(dtype=arr.dtype)
c_forward_pointer.restype = ptr_type
c_forward_pointer.argtypes = (ptr_type,)
ret = c_forward_pointer(arr)
assert_(isinstance(ret, ptr_type))
@pytest.mark.skipif(ctypes is None,
reason="ctypes not available on this python installation")
class TestAsArray:
def test_array(self):
from ctypes import c_int
pair_t = c_int * 2
a = as_array(pair_t(1, 2))
assert_equal(a.shape, (2,))
assert_array_equal(a, np.array([1, 2]))
a = as_array((pair_t * 3)(pair_t(1, 2), pair_t(3, 4), pair_t(5, 6)))
assert_equal(a.shape, (3, 2))
assert_array_equal(a, np.array([[1, 2], [3, 4], [5, 6]]))
def test_pointer(self):
from ctypes import POINTER, c_int, cast
p = cast((c_int * 10)(*range(10)), POINTER(c_int))
a = as_array(p, shape=(10,))
assert_equal(a.shape, (10,))
assert_array_equal(a, np.arange(10))
a = as_array(p, shape=(2, 5))
assert_equal(a.shape, (2, 5))
assert_array_equal(a, np.arange(10).reshape((2, 5)))
# shape argument is required
assert_raises(TypeError, as_array, p)
@pytest.mark.skipif(
sys.version_info[:2] == (3, 12),
reason="Broken in 3.12.0rc1, see gh-24399",
)
def test_struct_array_pointer(self):
from ctypes import Structure, c_int16, pointer
class Struct(Structure):
_fields_ = [('a', c_int16)]
Struct3 = 3 * Struct
c_array = (2 * Struct3)(
Struct3(Struct(a=1), Struct(a=2), Struct(a=3)),
Struct3(Struct(a=4), Struct(a=5), Struct(a=6))
)
expected = np.array([
[(1,), (2,), (3,)],
[(4,), (5,), (6,)],
], dtype=[('a', np.int16)])
def check(x):
assert_equal(x.dtype, expected.dtype)
assert_equal(x, expected)
# all of these should be equivalent
check(as_array(c_array))
check(as_array(pointer(c_array), shape=()))
check(as_array(pointer(c_array[0]), shape=(2,)))
check(as_array(pointer(c_array[0][0]), shape=(2, 3)))
@pytest.mark.thread_unsafe(reason="garbage collector is global state")
def test_reference_cycles(self):
# related to gh-6511
import ctypes
# create array to work with
# don't use int/long to avoid running into bpo-10746
N = 100
a = np.arange(N, dtype=np.short)
# get pointer to array
pnt = np.ctypeslib.as_ctypes(a)
with np.testing.assert_no_gc_cycles():
# decay the array above to a pointer to its first element
newpnt = ctypes.cast(pnt, ctypes.POINTER(ctypes.c_short))
# and construct an array using this data
b = np.ctypeslib.as_array(newpnt, (N,))
# now delete both, which should cleanup both objects
del newpnt, b
def test_segmentation_fault(self):
arr = np.zeros((224, 224, 3))
c_arr = np.ctypeslib.as_ctypes(arr)
arr_ref = weakref.ref(arr)
del arr
# check the reference wasn't cleaned up
assert_(arr_ref() is not None)
# check we avoid the segfault
c_arr[0][0][0]
@pytest.mark.skipif(ctypes is None,
reason="ctypes not available on this python installation")
class TestAsCtypesType:
""" Test conversion from dtypes to ctypes types """
def test_scalar(self):
dt = np.dtype('<u2')
ct = np.ctypeslib.as_ctypes_type(dt)
assert_equal(ct, ctypes.c_uint16.__ctype_le__)
dt = np.dtype('>u2')
ct = np.ctypeslib.as_ctypes_type(dt)
assert_equal(ct, ctypes.c_uint16.__ctype_be__)
dt = np.dtype('u2')
ct = np.ctypeslib.as_ctypes_type(dt)
assert_equal(ct, ctypes.c_uint16)
@pytest.mark.thread_unsafe(reason="some sort of data race? (gh-29943)")
def test_subarray(self):
dt = np.dtype((np.int32, (2, 3)))
ct = np.ctypeslib.as_ctypes_type(dt)
assert_equal(ct, 2 * (3 * ctypes.c_int32))
def test_structure(self):
dt = np.dtype([
('a', np.uint16),
('b', np.uint32),
])
ct = np.ctypeslib.as_ctypes_type(dt)
assert_(issubclass(ct, ctypes.Structure))
assert_equal(ctypes.sizeof(ct), dt.itemsize)
assert_equal(ct._fields_, [
('a', ctypes.c_uint16),
('b', ctypes.c_uint32),
])
@pytest.mark.thread_unsafe(reason="some sort of data race? (gh-29943)")
def test_structure_aligned(self):
dt = np.dtype([
('a', np.uint16),
('b', np.uint32),
], align=True)
ct = np.ctypeslib.as_ctypes_type(dt)
assert_(issubclass(ct, ctypes.Structure))
assert_equal(ctypes.sizeof(ct), dt.itemsize)
assert_equal(ct._fields_, [
('a', ctypes.c_uint16),
('', ctypes.c_char * 2), # padding
('b', ctypes.c_uint32),
])
def test_union(self):
dt = np.dtype({
'names': ['a', 'b'],
'offsets': [0, 0],
'formats': [np.uint16, np.uint32]
})
ct = np.ctypeslib.as_ctypes_type(dt)
assert_(issubclass(ct, ctypes.Union))
assert_equal(ctypes.sizeof(ct), dt.itemsize)
assert_equal(ct._fields_, [
('a', ctypes.c_uint16),
('b', ctypes.c_uint32),
])
@pytest.mark.thread_unsafe(reason="some sort of data race? (gh-29943)")
def test_padded_union(self):
dt = np.dtype({
'names': ['a', 'b'],
'offsets': [0, 0],
'formats': [np.uint16, np.uint32],
'itemsize': 5,
})
ct = np.ctypeslib.as_ctypes_type(dt)
assert_(issubclass(ct, ctypes.Union))
assert_equal(ctypes.sizeof(ct), dt.itemsize)
assert_equal(ct._fields_, [
('a', ctypes.c_uint16),
('b', ctypes.c_uint32),
('', ctypes.c_char * 5), # padding
])
def test_overlapping(self):
dt = np.dtype({
'names': ['a', 'b'],
'offsets': [0, 2],
'formats': [np.uint32, np.uint32]
})
assert_raises(NotImplementedError, np.ctypeslib.as_ctypes_type, dt)
def test_cannot_convert_to_ctypes(self):
_type_to_value = {
np.str_: ("aa",),
np.bool: (True,),
np.datetime64: ("2026-01-01",),
np.timedelta64: (1, "s")
}
for _scalar_type in np.sctypeDict.values():
if _scalar_type == np.object_:
continue
if _scalar_type in _type_to_value:
numpy_scalar = _scalar_type(*_type_to_value[_scalar_type])
else:
numpy_scalar = _scalar_type(1)
with pytest.raises(
TypeError, match="readonly arrays unsupported"
):
np.ctypeslib.as_ctypes(numpy_scalar)
| import sys
import sysconfig
import weakref
from pathlib import Path
import pytest
import numpy as np
from numpy.ctypeslib import as_array, load_library, ndpointer
from numpy.testing import assert_, assert_array_equal, assert_equal, assert_raises
try:
import ctypes
except ImportError:
ctypes = None
else:
cdll = None
test_cdll = None
if hasattr(sys, 'gettotalrefcount'):
try:
cdll = load_library(
'_multiarray_umath_d', np._core._multiarray_umath.__file__
)
except OSError:
pass
try:
test_cdll = load_library(
'_multiarray_tests', np._core._multiarray_tests.__file__
)
except OSError:
pass
if cdll is None:
cdll = load_library(
'_multiarray_umath', np._core._multiarray_umath.__file__)
if test_cdll is None:
test_cdll = load_library(
'_multiarray_tests', np._core._multiarray_tests.__file__
)
c_forward_pointer = test_cdll.forward_pointer
@pytest.mark.skipif | [
"# numpy/numpy:numpy/f2py/symbolic.py\nas_array",
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_",
"# numpy/numpy:numpy/ctypeslib/_ctypeslib.py\nndpointer"
] | numpy/numpy | numpy/tests/test_ctypeslib.py |
import importlib.metadata
import os
import pathlib
import subprocess
import pytest
import numpy as np
import numpy._core.include
import numpy._core.lib.pkgconfig
from numpy.testing import IS_EDITABLE, IS_INSTALLED, IS_WASM, NUMPY_ROOT
INCLUDE_DIR = NUMPY_ROOT / '_core' / 'include'
PKG_CONFIG_DIR = NUMPY_ROOT / '_core' / 'lib' / 'pkgconfig'
@pytest.mark.skipif(not IS_INSTALLED,
reason="`numpy-config` not expected to be installed")
@pytest.mark.skipif(IS_WASM,
reason="wasm interpreter cannot start subprocess")
class TestNumpyConfig:
def check_numpyconfig(self, arg):
p = subprocess.run(['numpy-config', arg], capture_output=True, text=True)
p.check_returncode()
return p.stdout.strip()
def test_configtool_version(self):
stdout = self.check_numpyconfig('--version')
assert stdout == np.__version__
def test_configtool_cflags(self):
stdout = self.check_numpyconfig('--cflags')
assert f'-I{os.fspath(INCLUDE_DIR)}' in stdout
def test_configtool_pkgconfigdir(self):
stdout = self.check_numpyconfig('--pkgconfigdir')
assert pathlib.Path(stdout) == PKG_CONFIG_DIR.resolve()
@pytest.mark.skipif(not IS_INSTALLED,
reason="numpy must be installed to check its entrypoints")
def test_pkg_config_entrypoint():
(entrypoint,) = importlib.metadata.entry_points(group='pkg_config', name='numpy')
assert entrypoint.value == numpy._core.lib.pkgconfig.__name__
@pytest.mark.skipif(not IS_INSTALLED,
reason="numpy.pc is only available when numpy is installed")
@pytest.mark.skipif(IS_EDITABLE, reason="editable installs don't have a numpy.pc")
def test_pkg_config_config_exists():
assert PKG_CONFIG_DIR.joinpath('numpy.pc').is_file()
| import importlib.metadata
import os
import pathlib
import subprocess
import pytest
import numpy as np
import numpy._core.include
import numpy._core.lib.pkgconfig
from numpy.testing import IS_EDITABLE, IS_INSTALLED, IS_WASM, NUMPY_ROOT
INCLUDE_DIR = NUMPY_ROOT / '_core' / 'include'
PKG_CONFIG_DIR = NUMPY_ROOT / '_core' / 'lib' / 'pkgconfig'
@pytest.mark.skipif(not IS_INSTALLED,
reason="`numpy-config` not expected to be installed")
@pytest.mark.skipif(IS_WASM,
reason="wasm interpreter cannot start subprocess")
class TestNumpyConfig:
def check_numpyconfig(self, arg):
p = subprocess.run(['numpy-config', arg], capture_output=True, text=True)
p.check_returncode()
return p.stdout.strip()
def test_configtool_version(self):
stdout = self.check_numpyconfig('--version')
assert stdout == np.__version__
def test_configtool_cflags(self):
stdout = self.check_numpyconfig('--cflags')
assert f'-I{os.fspath(INCLUDE_DIR)}' in stdout
def test_configtool_pkgconfigdir(self):
stdout = self.check_numpyconfig('--pkgconfigdir')
assert pathlib.Path(stdout) == PKG_CONFIG_DIR.resolve()
@pytest.mark. | [] | numpy/numpy | numpy/tests/test_configtool.py |
import collections
import numpy as np
def test_no_duplicates_in_np__all__():
# Regression test for gh-10198.
dups = {k: v for k, v in collections.Counter(np.__all__).items() if v > 1}
assert len(dups) == 0
|
import collections
import numpy as np
def test_no_duplicates_in_np__all__():
# Regression test for gh-10198.
dups = {k: v for k, v in collections.Counter(np.__all__).items() if v > 1}
assert len(dups) == 0
| [] | numpy/numpy | numpy/tests/test__all__.py |
import itertools
import os
import re
import sys
import warnings
import weakref
import pytest
import numpy as np
import numpy._core._multiarray_umath as ncu
from numpy.testing import (
HAS_REFCOUNT,
assert_,
assert_allclose,
assert_almost_equal,
assert_approx_equal,
assert_array_almost_equal,
assert_array_almost_equal_nulp,
assert_array_equal,
assert_array_less,
assert_array_max_ulp,
assert_equal,
assert_no_gc_cycles,
assert_no_warnings,
assert_raises,
assert_string_equal,
assert_warns,
build_err_msg,
clear_and_catch_warnings,
suppress_warnings,
tempdir,
temppath,
)
class _GenericTest:
def _assert_func(self, *args, **kwargs):
pass
def _test_equal(self, a, b):
self._assert_func(a, b)
def _test_not_equal(self, a, b):
with assert_raises(AssertionError):
self._assert_func(a, b)
def test_array_rank1_eq(self):
"""Test two equal array of rank 1 are found equal."""
a = np.array([1, 2])
b = np.array([1, 2])
self._test_equal(a, b)
def test_array_rank1_noteq(self):
"""Test two different array of rank 1 are found not equal."""
a = np.array([1, 2])
b = np.array([2, 2])
self._test_not_equal(a, b)
def test_array_rank2_eq(self):
"""Test two equal array of rank 2 are found equal."""
a = np.array([[1, 2], [3, 4]])
b = np.array([[1, 2], [3, 4]])
self._test_equal(a, b)
def test_array_diffshape(self):
"""Test two arrays with different shapes are found not equal."""
a = np.array([1, 2])
b = np.array([[1, 2], [1, 2]])
self._test_not_equal(a, b)
def test_objarray(self):
"""Test object arrays."""
a = np.array([1, 1], dtype=object)
self._test_equal(a, 1)
def test_array_likes(self):
self._test_equal([1, 2, 3], (1, 2, 3))
class TestArrayEqual(_GenericTest):
def _assert_func(self, *args, **kwargs):
assert_array_equal(*args, **kwargs)
def test_generic_rank1(self):
"""Test rank 1 array for all dtypes."""
def foo(t):
a = np.empty(2, t)
a.fill(1)
b = a.copy()
c = a.copy()
c.fill(0)
self._test_equal(a, b)
self._test_not_equal(c, b)
# Test numeric types and object
for t in '?bhilqpBHILQPfdgFDG':
foo(t)
# Test strings
for t in ['S1', 'U1']:
foo(t)
def test_0_ndim_array(self):
x = np.array(473963742225900817127911193656584771)
y = np.array(18535119325151578301457182298393896)
with pytest.raises(AssertionError) as exc_info:
self._assert_func(x, y)
msg = str(exc_info.value)
assert_('Mismatched elements: 1 / 1 (100%)\n'
in msg)
y = x
self._assert_func(x, y)
x = np.array(4395065348745.5643764887869876)
y = np.array(0)
expected_msg = ('Mismatched elements: 1 / 1 (100%)\n'
'Max absolute difference among violations: '
'4.39506535e+12\n'
'Max relative difference among violations: inf\n')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(x, y)
x = y
self._assert_func(x, y)
def test_generic_rank3(self):
"""Test rank 3 array for all dtypes."""
def foo(t):
a = np.empty((4, 2, 3), t)
a.fill(1)
b = a.copy()
c = a.copy()
c.fill(0)
self._test_equal(a, b)
self._test_not_equal(c, b)
# Test numeric types and object
for t in '?bhilqpBHILQPfdgFDG':
foo(t)
# Test strings
for t in ['S1', 'U1']:
foo(t)
def test_nan_array(self):
"""Test arrays with nan values in them."""
a = np.array([1, 2, np.nan])
b = np.array([1, 2, np.nan])
self._test_equal(a, b)
c = np.array([1, 2, 3])
self._test_not_equal(c, b)
def test_string_arrays(self):
"""Test two arrays with different shapes are found not equal."""
a = np.array(['floupi', 'floupa'])
b = np.array(['floupi', 'floupa'])
self._test_equal(a, b)
c = np.array(['floupipi', 'floupa'])
self._test_not_equal(c, b)
def test_recarrays(self):
"""Test record arrays."""
a = np.empty(2, [('floupi', float), ('floupa', float)])
a['floupi'] = [1, 2]
a['floupa'] = [1, 2]
b = a.copy()
self._test_equal(a, b)
c = np.empty(2, [('floupipi', float),
('floupi', float), ('floupa', float)])
c['floupipi'] = a['floupi'].copy()
c['floupa'] = a['floupa'].copy()
with pytest.raises(TypeError):
self._test_not_equal(c, b)
def test_masked_nan_inf(self):
# Regression test for gh-11121
a = np.ma.MaskedArray([3., 4., 6.5], mask=[False, True, False])
b = np.array([3., np.nan, 6.5])
self._test_equal(a, b)
self._test_equal(b, a)
a = np.ma.MaskedArray([3., 4., 6.5], mask=[True, False, False])
b = np.array([np.inf, 4., 6.5])
self._test_equal(a, b)
self._test_equal(b, a)
# Also provides test cases for gh-11121
def test_masked_scalar(self):
# Test masked scalar vs. plain/masked scalar
for a_val, b_val, b_masked in itertools.product(
[3., np.nan, np.inf],
[3., 4., np.nan, np.inf, -np.inf],
[False, True],
):
a = np.ma.MaskedArray(a_val, mask=True)
b = np.ma.MaskedArray(b_val, mask=True) if b_masked else np.array(b_val)
self._test_equal(a, b)
self._test_equal(b, a)
# Test masked scalar vs. plain array
for a_val, b_val in itertools.product(
[3., np.nan, -np.inf],
itertools.product([3., 4., np.nan, np.inf, -np.inf], repeat=2),
):
a = np.ma.MaskedArray(a_val, mask=True)
b = np.array(b_val)
self._test_equal(a, b)
self._test_equal(b, a)
# Test masked scalar vs. masked array
for a_val, b_val, b_mask in itertools.product(
[3., np.nan, np.inf],
itertools.product([3., 4., np.nan, np.inf, -np.inf], repeat=2),
itertools.product([False, True], repeat=2),
):
a = np.ma.MaskedArray(a_val, mask=True)
b = np.ma.MaskedArray(b_val, mask=b_mask)
self._test_equal(a, b)
self._test_equal(b, a)
def test_subclass_that_overrides_eq(self):
# While we cannot guarantee testing functions will always work for
# subclasses, the tests should ideally rely only on subclasses having
# comparison operators, not on them being able to store booleans
# (which, e.g., astropy Quantity cannot usefully do). See gh-8452.
class MyArray(np.ndarray):
def __eq__(self, other):
return bool(np.equal(self, other).all())
def __ne__(self, other):
return not self == other
a = np.array([1., 2.]).view(MyArray)
b = np.array([2., 3.]).view(MyArray)
assert_(type(a == a), bool)
assert_(a == a)
assert_(a != b)
self._test_equal(a, a)
self._test_not_equal(a, b)
self._test_not_equal(b, a)
expected_msg = ('Mismatched elements: 1 / 2 (50%)\n'
'Max absolute difference among violations: 1.\n'
'Max relative difference among violations: 0.5')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._test_equal(a, b)
c = np.array([0., 2.9]).view(MyArray)
expected_msg = ('Mismatched elements: 1 / 2 (50%)\n'
'Max absolute difference among violations: 2.\n'
'Max relative difference among violations: inf')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._test_equal(b, c)
def test_subclass_that_does_not_implement_npall(self):
class MyArray(np.ndarray):
def __array_function__(self, *args, **kwargs):
return NotImplemented
a = np.array([1., 2.]).view(MyArray)
b = np.array([2., 3.]).view(MyArray)
with assert_raises(TypeError):
np.all(a)
self._test_equal(a, a)
self._test_not_equal(a, b)
self._test_not_equal(b, a)
def test_suppress_overflow_warnings(self):
# Based on issue #18992
with pytest.raises(AssertionError):
with np.errstate(all="raise"):
np.testing.assert_array_equal(
np.array([1, 2, 3], np.float32),
np.array([1, 1e-40, 3], np.float32))
def test_array_vs_scalar_is_equal(self):
"""Test comparing an array with a scalar when all values are equal."""
a = np.array([1., 1., 1.])
b = 1.
self._test_equal(a, b)
def test_array_vs_array_not_equal(self):
"""Test comparing an array with a scalar when not all values equal."""
a = np.array([34986, 545676, 439655, 563766])
b = np.array([34986, 545676, 439655, 0])
expected_msg = ('Mismatched elements: 1 / 4 (25%)\n'
'Mismatch at index:\n'
' [3]: 563766 (ACTUAL), 0 (DESIRED)\n'
'Max absolute difference among violations: 563766\n'
'Max relative difference among violations: inf')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(a, b)
a = np.array([34986, 545676, 439655.2, 563766])
expected_msg = ('Mismatched elements: 2 / 4 (50%)\n'
'Mismatch at indices:\n'
' [2]: 439655.2 (ACTUAL), 439655 (DESIRED)\n'
' [3]: 563766.0 (ACTUAL), 0 (DESIRED)\n'
'Max absolute difference among violations: '
'563766.\n'
'Max relative difference among violations: '
'4.54902139e-07')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(a, b)
def test_array_vs_scalar_strict(self):
"""Test comparing an array with a scalar with strict option."""
a = np.array([1., 1., 1.])
b = 1.
with pytest.raises(AssertionError):
self._assert_func(a, b, strict=True)
def test_array_vs_array_strict(self):
"""Test comparing two arrays with strict option."""
a = np.array([1., 1., 1.])
b = np.array([1., 1., 1.])
self._assert_func(a, b, strict=True)
def test_array_vs_float_array_strict(self):
"""Test comparing two arrays with strict option."""
a = np.array([1, 1, 1])
b = np.array([1., 1., 1.])
with pytest.raises(AssertionError):
self._assert_func(a, b, strict=True)
class TestBuildErrorMessage:
def test_build_err_msg_defaults(self):
x = np.array([1.00001, 2.00002, 3.00003])
y = np.array([1.00002, 2.00003, 3.00004])
err_msg = 'There is a mismatch'
a = build_err_msg([x, y], err_msg)
b = ('\nItems are not equal: There is a mismatch\n ACTUAL: array(['
'1.00001, 2.00002, 3.00003])\n DESIRED: array([1.00002, '
'2.00003, 3.00004])')
assert_equal(a, b)
def test_build_err_msg_no_verbose(self):
x = np.array([1.00001, 2.00002, 3.00003])
y = np.array([1.00002, 2.00003, 3.00004])
err_msg = 'There is a mismatch'
a = build_err_msg([x, y], err_msg, verbose=False)
b = '\nItems are not equal: There is a mismatch'
assert_equal(a, b)
def test_build_err_msg_custom_names(self):
x = np.array([1.00001, 2.00002, 3.00003])
y = np.array([1.00002, 2.00003, 3.00004])
err_msg = 'There is a mismatch'
a = build_err_msg([x, y], err_msg, names=('FOO', 'BAR'))
b = ('\nItems are not equal: There is a mismatch\n FOO: array(['
'1.00001, 2.00002, 3.00003])\n BAR: array([1.00002, 2.00003, '
'3.00004])')
assert_equal(a, b)
def test_build_err_msg_custom_precision(self):
x = np.array([1.000000001, 2.00002, 3.00003])
y = np.array([1.000000002, 2.00003, 3.00004])
err_msg = 'There is a mismatch'
a = build_err_msg([x, y], err_msg, precision=10)
b = ('\nItems are not equal: There is a mismatch\n ACTUAL: array(['
'1.000000001, 2.00002 , 3.00003 ])\n DESIRED: array(['
'1.000000002, 2.00003 , 3.00004 ])')
assert_equal(a, b)
class TestEqual(TestArrayEqual):
def _assert_func(self, *args, **kwargs):
assert_equal(*args, **kwargs)
def test_nan_items(self):
self._assert_func(np.nan, np.nan)
self._assert_func([np.nan], [np.nan])
self._test_not_equal(np.nan, [np.nan])
self._test_not_equal(np.nan, 1)
def test_inf_items(self):
self._assert_func(np.inf, np.inf)
self._assert_func([np.inf], [np.inf])
self._test_not_equal(np.inf, [np.inf])
def test_datetime(self):
self._test_equal(
np.datetime64("2017-01-01", "s"),
np.datetime64("2017-01-01", "s")
)
self._test_equal(
np.datetime64("2017-01-01", "s"),
np.datetime64("2017-01-01", "m")
)
# gh-10081
self._test_not_equal(
np.datetime64("2017-01-01", "s"),
np.datetime64("2017-01-02", "s")
)
self._test_not_equal(
np.datetime64("2017-01-01", "s"),
np.datetime64("2017-01-02", "m")
)
def test_nat_items(self):
# not a datetime
nadt_no_unit = np.datetime64("NaT")
nadt_s = np.datetime64("NaT", "s")
nadt_d = np.datetime64("NaT", "ns")
# not a timedelta
with pytest.warns(
DeprecationWarning,
match="Using 'generic' unit for NumPy timedelta is deprecated",
):
natd_no_unit = np.timedelta64("NaT")
natd_s = np.timedelta64("NaT", "s")
natd_d = np.timedelta64("NaT", "ns")
dts = [nadt_no_unit, nadt_s, nadt_d]
tds = [natd_no_unit, natd_s, natd_d]
for a, b in itertools.product(dts, dts):
self._assert_func(a, b)
self._assert_func([a], [b])
self._test_not_equal([a], b)
for a, b in itertools.product(tds, tds):
self._assert_func(a, b)
self._assert_func([a], [b])
self._test_not_equal([a], b)
for a, b in itertools.product(tds, dts):
self._test_not_equal(a, b)
self._test_not_equal(a, [b])
self._test_not_equal([a], [b])
self._test_not_equal([a], np.datetime64("2017-01-01", "s"))
self._test_not_equal([b], np.datetime64("2017-01-01", "s"))
self._test_not_equal([a], np.timedelta64(123, "s"))
self._test_not_equal([b], np.timedelta64(123, "s"))
def test_non_numeric(self):
self._assert_func('ab', 'ab')
self._test_not_equal('ab', 'abb')
def test_complex_item(self):
self._assert_func(complex(1, 2), complex(1, 2))
self._assert_func(complex(1, np.nan), complex(1, np.nan))
self._test_not_equal(complex(1, np.nan), complex(1, 2))
self._test_not_equal(complex(np.nan, 1), complex(1, np.nan))
self._test_not_equal(complex(np.nan, np.inf), complex(np.nan, 2))
def test_negative_zero(self):
self._test_not_equal(ncu.PZERO, ncu.NZERO)
def test_complex(self):
x = np.array([complex(1, 2), complex(1, np.nan)])
y = np.array([complex(1, 2), complex(1, 2)])
self._assert_func(x, x)
self._test_not_equal(x, y)
def test_object(self):
# gh-12942
import datetime
a = np.array([datetime.datetime(2000, 1, 1),
datetime.datetime(2000, 1, 2)])
self._test_not_equal(a, a[::-1])
class TestArrayAlmostEqual(_GenericTest):
def _assert_func(self, *args, **kwargs):
assert_array_almost_equal(*args, **kwargs)
def test_closeness(self):
# Note that in the course of time we ended up with
# `abs(x - y) < 1.5 * 10**(-decimal)`
# instead of the previously documented
# `abs(x - y) < 0.5 * 10**(-decimal)`
# so this check serves to preserve the wrongness.
# test scalars
expected_msg = ('Mismatched elements: 1 / 1 (100%)\n'
'Max absolute difference among violations: 1.5\n'
'Max relative difference among violations: inf')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(1.5, 0.0, decimal=0)
# test arrays
self._assert_func([1.499999], [0.0], decimal=0)
expected_msg = ('Mismatched elements: 1 / 1 (100%)\n'
'Mismatch at index:\n'
' [0]: 1.5 (ACTUAL), 0.0 (DESIRED)\n'
'Max absolute difference among violations: 1.5\n'
'Max relative difference among violations: inf')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func([1.5], [0.0], decimal=0)
a = [1.4999999, 0.00003]
b = [1.49999991, 0]
expected_msg = ('Mismatched elements: 1 / 2 (50%)\n'
'Mismatch at index:\n'
' [1]: 3e-05 (ACTUAL), 0.0 (DESIRED)\n'
'Max absolute difference among violations: 3.e-05\n'
'Max relative difference among violations: inf')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(a, b, decimal=7)
expected_msg = ('Mismatched elements: 1 / 2 (50%)\n'
'Mismatch at index:\n'
' [1]: 0.0 (ACTUAL), 3e-05 (DESIRED)\n'
'Max absolute difference among violations: 3.e-05\n'
'Max relative difference among violations: 1.')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(b, a, decimal=7)
def test_simple(self):
x = np.array([1234.2222])
y = np.array([1234.2223])
self._assert_func(x, y, decimal=3)
self._assert_func(x, y, decimal=4)
expected_msg = ('Mismatched elements: 1 / 1 (100%)\n'
'Mismatch at index:\n'
' [0]: 1234.2222 (ACTUAL), 1234.2223 (DESIRED)\n'
'Max absolute difference among violations: '
'1.e-04\n'
'Max relative difference among violations: '
'8.10226812e-08')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(x, y, decimal=5)
def test_array_vs_scalar(self):
a = [5498.42354, 849.54345, 0.00]
b = 5498.42354
expected_msg = ('Mismatched elements: 2 / 3 (66.7%)\n'
'Mismatch at indices:\n'
' [1]: 849.54345 (ACTUAL), 5498.42354 (DESIRED)\n'
' [2]: 0.0 (ACTUAL), 5498.42354 (DESIRED)\n'
'Max absolute difference among violations: '
'5498.42354\n'
'Max relative difference among violations: 1.')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(a, b, decimal=9)
expected_msg = ('Mismatched elements: 2 / 3 (66.7%)\n'
'Mismatch at indices:\n'
' [1]: 5498.42354 (ACTUAL), 849.54345 (DESIRED)\n'
' [2]: 5498.42354 (ACTUAL), 0.0 (DESIRED)\n'
'Max absolute difference among violations: '
'5498.42354\n'
'Max relative difference among violations: 5.4722099')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(b, a, decimal=9)
a = [5498.42354, 0.00]
expected_msg = ('Mismatched elements: 1 / 2 (50%)\n'
'Mismatch at index:\n'
' [1]: 5498.42354 (ACTUAL), 0.0 (DESIRED)\n'
'Max absolute difference among violations: '
'5498.42354\n'
'Max relative difference among violations: inf')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(b, a, decimal=7)
b = 0
expected_msg = ('Mismatched elements: 1 / 2 (50%)\n'
'Mismatch at index:\n'
' [0]: 5498.42354 (ACTUAL), 0 (DESIRED)\n'
'Max absolute difference among violations: '
'5498.42354\n'
'Max relative difference among violations: inf')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(a, b, decimal=7)
def test_nan(self):
anan = np.array([np.nan])
aone = np.array([1])
ainf = np.array([np.inf])
self._assert_func(anan, anan)
assert_raises(AssertionError,
lambda: self._assert_func(anan, aone))
assert_raises(AssertionError,
lambda: self._assert_func(anan, ainf))
assert_raises(AssertionError,
lambda: self._assert_func(ainf, anan))
def test_inf(self):
a = np.array([[1., 2.], [3., 4.]])
b = a.copy()
a[0, 0] = np.inf
assert_raises(AssertionError,
lambda: self._assert_func(a, b))
b[0, 0] = -np.inf
assert_raises(AssertionError,
lambda: self._assert_func(a, b))
def test_complex_inf(self):
a = np.array([np.inf + 1.j, 2. + 1.j, 3. + 1.j])
b = a.copy()
self._assert_func(a, b)
b[1] = 3. + 1.j
expected_msg = ('Mismatched elements: 1 / 3 (33.3%)\n'
'Mismatch at index:\n'
' [1]: (2+1j) (ACTUAL), (3+1j) (DESIRED)\n'
'Max absolute difference among violations: 1.\n')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(a, b)
def test_subclass(self):
a = np.array([[1., 2.], [3., 4.]])
b = np.ma.masked_array([[1., 2.], [0., 4.]],
[[False, False], [True, False]])
self._assert_func(a, b)
self._assert_func(b, a)
self._assert_func(b, b)
# Test fully masked as well (see gh-11123).
a = np.ma.MaskedArray(3.5, mask=True)
b = np.array([3., 4., 6.5])
self._test_equal(a, b)
self._test_equal(b, a)
a = np.ma.masked
b = np.array([3., 4., 6.5])
self._test_equal(a, b)
self._test_equal(b, a)
a = np.ma.MaskedArray([3., 4., 6.5], mask=[True, True, True])
b = np.array([1., 2., 3.])
self._test_equal(a, b)
self._test_equal(b, a)
a = np.ma.MaskedArray([3., 4., 6.5], mask=[True, True, True])
b = np.array(1.)
self._test_equal(a, b)
self._test_equal(b, a)
def test_subclass_2(self):
# While we cannot guarantee testing functions will always work for
# subclasses, the tests should ideally rely only on subclasses having
# comparison operators, not on them being able to store booleans
# (which, e.g., astropy Quantity cannot usefully do). See gh-8452.
class MyArray(np.ndarray):
def __eq__(self, other):
return super().__eq__(other).view(np.ndarray)
def __lt__(self, other):
return super().__lt__(other).view(np.ndarray)
def all(self, *args, **kwargs):
return all(self)
a = np.array([1., 2.]).view(MyArray)
self._assert_func(a, a)
z = np.array([True, True]).view(MyArray)
all(z)
b = np.array([1., 202]).view(MyArray)
expected_msg = ('Mismatched elements: 1 / 2 (50%)\n'
'Mismatch at index:\n'
' [1]: 2.0 (ACTUAL), 202.0 (DESIRED)\n'
'Max absolute difference among violations: 200.\n'
'Max relative difference among violations: 0.99009')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(a, b)
def test_subclass_that_cannot_be_bool(self):
# While we cannot guarantee testing functions will always work for
# subclasses, the tests should ideally rely only on subclasses having
# comparison operators, not on them being able to store booleans
# (which, e.g., astropy Quantity cannot usefully do). See gh-8452.
class MyArray(np.ndarray):
def __eq__(self, other):
return super().__eq__(other).view(np.ndarray)
def __lt__(self, other):
return super().__lt__(other).view(np.ndarray)
def all(self, *args, **kwargs):
raise NotImplementedError
a = np.array([1., 2.]).view(MyArray)
self._assert_func(a, a)
class TestAlmostEqual(_GenericTest):
def _assert_func(self, *args, **kwargs):
assert_almost_equal(*args, **kwargs)
def test_closeness(self):
# Note that in the course of time we ended up with
# `abs(x - y) < 1.5 * 10**(-decimal)`
# instead of the previously documented
# `abs(x - y) < 0.5 * 10**(-decimal)`
# so this check serves to preserve the wrongness.
# test scalars
self._assert_func(1.499999, 0.0, decimal=0)
assert_raises(AssertionError,
lambda: self._assert_func(1.5, 0.0, decimal=0))
# test arrays
self._assert_func([1.499999], [0.0], decimal=0)
assert_raises(AssertionError,
lambda: self._assert_func([1.5], [0.0], decimal=0))
def test_nan_item(self):
self._assert_func(np.nan, np.nan)
assert_raises(AssertionError,
lambda: self._assert_func(np.nan, 1))
assert_raises(AssertionError,
lambda: self._assert_func(np.nan, np.inf))
assert_raises(AssertionError,
lambda: self._assert_func(np.inf, np.nan))
def test_inf_item(self):
self._assert_func(np.inf, np.inf)
self._assert_func(-np.inf, -np.inf)
assert_raises(AssertionError,
lambda: self._assert_func(np.inf, 1))
assert_raises(AssertionError,
lambda: self._assert_func(-np.inf, np.inf))
def test_simple_item(self):
self._test_not_equal(1, 2)
def test_complex_item(self):
self._assert_func(complex(1, 2), complex(1, 2))
self._assert_func(complex(1, np.nan), complex(1, np.nan))
self._assert_func(complex(np.inf, np.nan), complex(np.inf, np.nan))
self._test_not_equal(complex(1, np.nan), complex(1, 2))
self._test_not_equal(complex(np.nan, 1), complex(1, np.nan))
self._test_not_equal(complex(np.nan, np.inf), complex(np.nan, 2))
def test_complex(self):
x = np.array([complex(1, 2), complex(1, np.nan)])
z = np.array([complex(1, 2), complex(np.nan, 1)])
y = np.array([complex(1, 2), complex(1, 2)])
self._assert_func(x, x)
self._test_not_equal(x, y)
self._test_not_equal(x, z)
def test_error_message(self):
"""Check the message is formatted correctly for the decimal value.
Also check the message when input includes inf or nan (gh12200)"""
x = np.array([1.00000000001, 2.00000000002, 3.00003])
y = np.array([1.00000000002, 2.00000000003, 3.00004])
# Test with a different amount of decimal digits
expected_msg = ('Mismatched elements: 3 / 3 (100%)\n'
'Mismatch at indices:\n'
' [0]: 1.00000000001 (ACTUAL), 1.00000000002 (DESIRED)\n'
' [1]: 2.00000000002 (ACTUAL), 2.00000000003 (DESIRED)\n'
' [2]: 3.00003 (ACTUAL), 3.00004 (DESIRED)\n'
'Max absolute difference among violations: 1.e-05\n'
'Max relative difference among violations: '
'3.33328889e-06\n'
' ACTUAL: array([1.00000000001, '
'2.00000000002, '
'3.00003 ])\n'
' DESIRED: array([1.00000000002, 2.00000000003, '
'3.00004 ])')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(x, y, decimal=12)
# With the default value of decimal digits, only the 3rd element
# differs. Note that we only check for the formatting of the arrays
# themselves.
expected_msg = ('Mismatched elements: 1 / 3 (33.3%)\n'
'Mismatch at index:\n'
' [2]: 3.00003 (ACTUAL), 3.00004 (DESIRED)\n'
'Max absolute difference among violations: 1.e-05\n'
'Max relative difference among violations: '
'3.33328889e-06\n'
' ACTUAL: array([1. , 2. , 3.00003])\n'
' DESIRED: array([1. , 2. , 3.00004])')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(x, y)
# Check the error message when input includes inf
x = np.array([np.inf, 0])
y = np.array([np.inf, 1])
expected_msg = ('Mismatched elements: 1 / 2 (50%)\n'
'Mismatch at index:\n'
' [1]: 0.0 (ACTUAL), 1.0 (DESIRED)\n'
'Max absolute difference among violations: 1.\n'
'Max relative difference among violations: 1.\n'
' ACTUAL: array([inf, 0.])\n'
' DESIRED: array([inf, 1.])')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(x, y)
# Check the error message when dividing by zero
x = np.array([1, 2])
y = np.array([0, 0])
expected_msg = ('Mismatched elements: 2 / 2 (100%)\n'
'Mismatch at indices:\n'
' [0]: 1 (ACTUAL), 0 (DESIRED)\n'
' [1]: 2 (ACTUAL), 0 (DESIRED)\n'
'Max absolute difference among violations: 2\n'
'Max relative difference among violations: inf')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(x, y)
def test_error_message_2(self):
"""Check the message is formatted correctly """
"""when either x or y is a scalar."""
x = 2
y = np.ones(20)
expected_msg = ('Mismatched elements: 20 / 20 (100%)\n'
'First 5 mismatches are at indices:\n'
' [0]: 2 (ACTUAL), 1.0 (DESIRED)\n'
' [1]: 2 (ACTUAL), 1.0 (DESIRED)\n'
' [2]: 2 (ACTUAL), 1.0 (DESIRED)\n'
' [3]: 2 (ACTUAL), 1.0 (DESIRED)\n'
' [4]: 2 (ACTUAL), 1.0 (DESIRED)\n'
'Max absolute difference among violations: 1.\n'
'Max relative difference among violations: 1.')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(x, y)
y = 2
x = np.ones(20)
expected_msg = ('Mismatched elements: 20 / 20 (100%)\n'
'First 5 mismatches are at indices:\n'
' [0]: 1.0 (ACTUAL), 2 (DESIRED)\n'
' [1]: 1.0 (ACTUAL), 2 (DESIRED)\n'
' [2]: 1.0 (ACTUAL), 2 (DESIRED)\n'
' [3]: 1.0 (ACTUAL), 2 (DESIRED)\n'
' [4]: 1.0 (ACTUAL), 2 (DESIRED)\n'
'Max absolute difference among violations: 1.\n'
'Max relative difference among violations: 0.5')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(x, y)
def test_subclass_that_cannot_be_bool(self):
# While we cannot guarantee testing functions will always work for
# subclasses, the tests should ideally rely only on subclasses having
# comparison operators, not on them being able to store booleans
# (which, e.g., astropy Quantity cannot usefully do). See gh-8452.
class MyArray(np.ndarray):
def __eq__(self, other):
return super().__eq__(other).view(np.ndarray)
def __lt__(self, other):
return super().__lt__(other).view(np.ndarray)
def all(self, *args, **kwargs):
raise NotImplementedError
a = np.array([1., 2.]).view(MyArray)
self._assert_func(a, a)
class TestApproxEqual:
def _assert_func(self, *args, **kwargs):
assert_approx_equal(*args, **kwargs)
def test_simple_0d_arrays(self):
x = np.array(1234.22)
y = np.array(1234.23)
self._assert_func(x, y, significant=5)
self._assert_func(x, y, significant=6)
assert_raises(AssertionError,
lambda: self._assert_func(x, y, significant=7))
def test_simple_items(self):
x = 1234.22
y = 1234.23
self._assert_func(x, y, significant=4)
self._assert_func(x, y, significant=5)
self._assert_func(x, y, significant=6)
assert_raises(AssertionError,
lambda: self._assert_func(x, y, significant=7))
def test_nan_array(self):
anan = np.array(np.nan)
aone = np.array(1)
ainf = np.array(np.inf)
self._assert_func(anan, anan)
assert_raises(AssertionError, lambda: self._assert_func(anan, aone))
assert_raises(AssertionError, lambda: self._assert_func(anan, ainf))
assert_raises(AssertionError, lambda: self._assert_func(ainf, anan))
def test_nan_items(self):
anan = np.array(np.nan)
aone = np.array(1)
ainf = np.array(np.inf)
self._assert_func(anan, anan)
assert_raises(AssertionError, lambda: self._assert_func(anan, aone))
assert_raises(AssertionError, lambda: self._assert_func(anan, ainf))
assert_raises(AssertionError, lambda: self._assert_func(ainf, anan))
class TestArrayAssertLess:
def _assert_func(self, *args, **kwargs):
assert_array_less(*args, **kwargs)
def test_simple_arrays(self):
x = np.array([1.1, 2.2])
y = np.array([1.2, 2.3])
self._assert_func(x, y)
assert_raises(AssertionError, lambda: self._assert_func(y, x))
y = np.array([1.0, 2.3])
assert_raises(AssertionError, lambda: self._assert_func(x, y))
assert_raises(AssertionError, lambda: self._assert_func(y, x))
a = np.array([1, 3, 6, 20])
b = np.array([2, 4, 6, 8])
expected_msg = ('Mismatched elements: 2 / 4 (50%)\n'
'Mismatch at indices:\n'
' [2]: 6 (x), 6 (y)\n'
' [3]: 20 (x), 8 (y)\n'
'Max absolute difference among violations: 12\n'
'Max relative difference among violations: 1.5')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(a, b)
def test_rank2(self):
x = np.array([[1.1, 2.2], [3.3, 4.4]])
y = np.array([[1.2, 2.3], [3.4, 4.5]])
self._assert_func(x, y)
expected_msg = ('Mismatched elements: 4 / 4 (100%)\n'
'Mismatch at indices:\n'
' [0, 0]: 1.2 (x), 1.1 (y)\n'
' [0, 1]: 2.3 (x), 2.2 (y)\n'
' [1, 0]: 3.4 (x), 3.3 (y)\n'
' [1, 1]: 4.5 (x), 4.4 (y)\n'
'Max absolute difference among violations: 0.1\n'
'Max relative difference among violations: 0.09090909')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(y, x)
y = np.array([[1.0, 2.3], [3.4, 4.5]])
assert_raises(AssertionError, lambda: self._assert_func(x, y))
assert_raises(AssertionError, lambda: self._assert_func(y, x))
def test_rank3(self):
x = np.ones(shape=(2, 2, 2))
y = np.ones(shape=(2, 2, 2)) + 1
self._assert_func(x, y)
assert_raises(AssertionError, lambda: self._assert_func(y, x))
y[0, 0, 0] = 0
expected_msg = ('Mismatched elements: 1 / 8 (12.5%)\n'
'Mismatch at index:\n'
' [0, 0, 0]: 1.0 (x), 0.0 (y)\n'
'Max absolute difference among violations: 1.\n'
'Max relative difference among violations: inf')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(x, y)
assert_raises(AssertionError, lambda: self._assert_func(y, x))
def test_simple_items(self):
x = 1.1
y = 2.2
self._assert_func(x, y)
expected_msg = ('Mismatched elements: 1 / 1 (100%)\n'
'Max absolute difference among violations: 1.1\n'
'Max relative difference among violations: 1.')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(y, x)
y = np.array([2.2, 3.3])
self._assert_func(x, y)
assert_raises(AssertionError, lambda: self._assert_func(y, x))
y = np.array([1.0, 3.3])
assert_raises(AssertionError, lambda: self._assert_func(x, y))
def test_simple_items_and_array(self):
x = np.array([[621.345454, 390.5436, 43.54657, 626.4535],
[54.54, 627.3399, 13., 405.5435],
[543.545, 8.34, 91.543, 333.3]])
y = 627.34
self._assert_func(x, y)
y = 8.339999
self._assert_func(y, x)
x = np.array([[3.4536, 2390.5436, 435.54657, 324525.4535],
[5449.54, 999090.54, 130303.54, 405.5435],
[543.545, 8.34, 91.543, 999090.53999]])
y = 999090.54
expected_msg = ('Mismatched elements: 1 / 12 (8.33%)\n'
'Mismatch at index:\n'
' [1, 1]: 999090.54 (x), 999090.54 (y)\n'
'Max absolute difference among violations: 0.\n'
'Max relative difference among violations: 0.')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(x, y)
expected_msg = ('Mismatched elements: 12 / 12 (100%)\n'
'First 5 mismatches are at indices:\n'
' [0, 0]: 999090.54 (x), 3.4536 (y)\n'
' [0, 1]: 999090.54 (x), 2390.5436 (y)\n'
' [0, 2]: 999090.54 (x), 435.54657 (y)\n'
' [0, 3]: 999090.54 (x), 324525.4535 (y)\n'
' [1, 0]: 999090.54 (x), 5449.54 (y)\n'
'Max absolute difference among violations: '
'999087.0864\n'
'Max relative difference among violations: '
'289288.5934676')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(y, x)
def test_zeroes(self):
x = np.array([546456., 0, 15.455])
y = np.array(87654.)
expected_msg = ('Mismatched elements: 1 / 3 (33.3%)\n'
'Mismatch at index:\n'
' [0]: 546456.0 (x), 87654.0 (y)\n'
'Max absolute difference among violations: 458802.\n'
'Max relative difference among violations: 5.23423917')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(x, y)
expected_msg = ('Mismatched elements: 2 / 3 (66.7%)\n'
'Mismatch at indices:\n'
' [1]: 87654.0 (x), 0.0 (y)\n'
' [2]: 87654.0 (x), 15.455 (y)\n'
'Max absolute difference among violations: 87654.\n'
'Max relative difference among violations: '
'5670.5626011')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(y, x)
y = 0
expected_msg = ('Mismatched elements: 3 / 3 (100%)\n'
'Mismatch at indices:\n'
' [0]: 546456.0 (x), 0 (y)\n'
' [1]: 0.0 (x), 0 (y)\n'
' [2]: 15.455 (x), 0 (y)\n'
'Max absolute difference among violations: 546456.\n'
'Max relative difference among violations: inf')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(x, y)
expected_msg = ('Mismatched elements: 1 / 3 (33.3%)\n'
'Mismatch at index:\n'
' [1]: 0 (x), 0.0 (y)\n'
'Max absolute difference among violations: 0.\n'
'Max relative difference among violations: inf')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
self._assert_func(y, x)
def test_nan_noncompare(self):
anan = np.array(np.nan)
aone = np.array(1)
ainf = np.array(np.inf)
self._assert_func(anan, anan)
assert_raises(AssertionError, lambda: self._assert_func(aone, anan))
assert_raises(AssertionError, lambda: self._assert_func(anan, aone))
assert_raises(AssertionError, lambda: self._assert_func(anan, ainf))
assert_raises(AssertionError, lambda: self._assert_func(ainf, anan))
def test_nan_noncompare_array(self):
x = np.array([1.1, 2.2, 3.3])
anan = np.array(np.nan)
assert_raises(AssertionError, lambda: self._assert_func(x, anan))
assert_raises(AssertionError, lambda: self._assert_func(anan, x))
x = np.array([1.1, 2.2, np.nan])
assert_raises(AssertionError, lambda: self._assert_func(x, anan))
assert_raises(AssertionError, lambda: self._assert_func(anan, x))
y = np.array([1.0, 2.0, np.nan])
self._assert_func(y, x)
assert_raises(AssertionError, lambda: self._assert_func(x, y))
def test_inf_compare(self):
aone = np.array(1)
ainf = np.array(np.inf)
self._assert_func(aone, ainf)
self._assert_func(-ainf, aone)
self._assert_func(-ainf, ainf)
assert_raises(AssertionError, lambda: self._assert_func(ainf, aone))
assert_raises(AssertionError, lambda: self._assert_func(aone, -ainf))
assert_raises(AssertionError, lambda: self._assert_func(ainf, ainf))
assert_raises(AssertionError, lambda: self._assert_func(ainf, -ainf))
assert_raises(AssertionError, lambda: self._assert_func(-ainf, -ainf))
def test_inf_compare_array(self):
x = np.array([1.1, 2.2, np.inf])
ainf = np.array(np.inf)
assert_raises(AssertionError, lambda: self._assert_func(x, ainf))
assert_raises(AssertionError, lambda: self._assert_func(ainf, x))
assert_raises(AssertionError, lambda: self._assert_func(x, -ainf))
assert_raises(AssertionError, lambda: self._assert_func(-x, -ainf))
assert_raises(AssertionError, lambda: self._assert_func(-ainf, -x))
self._assert_func(-ainf, x)
def test_strict(self):
"""Test the behavior of the `strict` option."""
x = np.zeros(3)
y = np.ones(())
self._assert_func(x, y)
with pytest.raises(AssertionError):
self._assert_func(x, y, strict=True)
y = np.broadcast_to(y, x.shape)
self._assert_func(x, y)
with pytest.raises(AssertionError):
self._assert_func(x, y.astype(np.float32), strict=True)
@pytest.mark.filterwarnings(
"ignore:.*NumPy warning suppression and assertion utilities are deprecated"
".*:DeprecationWarning")
@pytest.mark.thread_unsafe(reason="checks global module & deprecated warnings")
class TestWarns:
def test_warn(self):
def f():
warnings.warn("yo")
return 3
before_filters = sys.modules['warnings'].filters[:]
assert_equal(assert_warns(UserWarning, f), 3)
after_filters = sys.modules['warnings'].filters
assert_raises(AssertionError, assert_no_warnings, f)
assert_equal(assert_no_warnings(lambda x: x, 1), 1)
# Check that the warnings state is unchanged
assert_equal(before_filters, after_filters,
"assert_warns does not preserver warnings state")
def test_context_manager(self):
before_filters = sys.modules['warnings'].filters[:]
with assert_warns(UserWarning):
warnings.warn("yo")
after_filters = sys.modules['warnings'].filters
def no_warnings():
with assert_no_warnings():
warnings.warn("yo")
assert_raises(AssertionError, no_warnings)
assert_equal(before_filters, after_filters,
"assert_warns does not preserver warnings state")
def test_args(self):
def f(a=0, b=1):
warnings.warn("yo")
return a + b
assert assert_warns(UserWarning, f, b=20) == 20
with pytest.raises(RuntimeError) as exc:
# assert_warns cannot do regexp matching, use pytest.warns
with assert_warns(UserWarning, match="A"):
warnings.warn("B", UserWarning)
assert "assert_warns" in str(exc)
assert "pytest.warns" in str(exc)
with pytest.raises(RuntimeError) as exc:
# assert_warns cannot do regexp matching, use pytest.warns
with assert_warns(UserWarning, wrong="A"):
warnings.warn("B", UserWarning)
assert "assert_warns" in str(exc)
assert "pytest.warns" not in str(exc)
def test_warn_wrong_warning(self):
def f():
warnings.warn("yo", DeprecationWarning)
failed = False
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
try:
# Should raise a DeprecationWarning
assert_warns(UserWarning, f)
failed = True
except DeprecationWarning:
pass
if failed:
raise AssertionError("wrong warning caught by assert_warn")
class TestAssertAllclose:
def test_simple(self):
x = 1e-3
y = 1e-9
assert_allclose(x, y, atol=1)
assert_raises(AssertionError, assert_allclose, x, y)
expected_msg = ('Mismatched elements: 1 / 1 (100%)\n'
'Max absolute difference among violations: 0.001\n'
'Max relative difference among violations: 999999.')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
assert_allclose(x, y)
z = 0
expected_msg = ('Mismatched elements: 1 / 1 (100%)\n'
'Max absolute difference among violations: 1.e-09\n'
'Max relative difference among violations: inf')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
assert_allclose(y, z)
expected_msg = ('Mismatched elements: 1 / 1 (100%)\n'
'Max absolute difference among violations: 1.e-09\n'
'Max relative difference among violations: 1.')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
assert_allclose(z, y)
a = np.array([x, y, x, y])
b = np.array([x, y, x, x])
assert_allclose(a, b, atol=1)
assert_raises(AssertionError, assert_allclose, a, b)
b[-1] = y * (1 + 1e-8)
assert_allclose(a, b)
assert_raises(AssertionError, assert_allclose, a, b, rtol=1e-9)
assert_allclose(6, 10, rtol=0.5)
assert_raises(AssertionError, assert_allclose, 10, 6, rtol=0.5)
b = np.array([x, y, x, x])
c = np.array([x, y, x, z])
expected_msg = ('Mismatched elements: 1 / 4 (25%)\n'
'Mismatch at index:\n'
' [3]: 0.001 (ACTUAL), 0.0 (DESIRED)\n'
'Max absolute difference among violations: 0.001\n'
'Max relative difference among violations: inf')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
assert_allclose(b, c)
expected_msg = ('Mismatched elements: 1 / 4 (25%)\n'
'Mismatch at index:\n'
' [3]: 0.0 (ACTUAL), 0.001 (DESIRED)\n'
'Max absolute difference among violations: 0.001\n'
'Max relative difference among violations: 1.')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
assert_allclose(c, b)
def test_min_int(self):
a = np.array([np.iinfo(np.int_).min], dtype=np.int_)
# Should not raise:
assert_allclose(a, a)
def test_report_fail_percentage(self):
a = np.array([1, 1, 1, 1])
b = np.array([1, 1, 1, 2])
expected_msg = ('Mismatched elements: 1 / 4 (25%)\n'
'Mismatch at index:\n'
' [3]: 1 (ACTUAL), 2 (DESIRED)\n'
'Max absolute difference among violations: 1\n'
'Max relative difference among violations: 0.5')
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
assert_allclose(a, b)
def test_equal_nan(self):
a = np.array([np.nan])
b = np.array([np.nan])
# Should not raise:
assert_allclose(a, b, equal_nan=True)
a = np.array([complex(np.nan, np.inf)])
b = np.array([complex(np.nan, np.inf)])
assert_allclose(a, b, equal_nan=True)
b = np.array([complex(np.nan, -np.inf)])
assert_allclose(a, b, equal_nan=True)
def test_not_equal_nan(self):
a = np.array([np.nan])
b = np.array([np.nan])
assert_raises(AssertionError, assert_allclose, a, b, equal_nan=False)
a = np.array([complex(np.nan, np.inf)])
b = np.array([complex(np.nan, np.inf)])
assert_raises(AssertionError, assert_allclose, a, b, equal_nan=False)
def test_equal_nan_default(self):
# Make sure equal_nan default behavior remains unchanged. (All
# of these functions use assert_array_compare under the hood.)
# None of these should raise.
a = np.array([np.nan])
b = np.array([np.nan])
assert_array_equal(a, b)
assert_array_almost_equal(a, b)
assert_array_less(a, b)
assert_allclose(a, b)
def test_report_max_relative_error(self):
a = np.array([0, 1])
b = np.array([0, 2])
expected_msg = 'Max relative difference among violations: 0.5'
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
assert_allclose(a, b)
def test_timedelta(self):
# see gh-18286
with pytest.warns(
DeprecationWarning,
match="Using 'generic' unit for NumPy timedelta is deprecated",
):
a = np.array([[1, 2, 3, "NaT"]], dtype="m8[ns]")
assert_allclose(a, a)
def test_error_message_unsigned(self):
"""Check the message is formatted correctly when overflow can occur
(gh21768)"""
# Ensure to test for potential overflow in the case of:
# x - y
# and
# y - x
x = np.asarray([0, 1, 8], dtype='uint8')
y = np.asarray([4, 4, 4], dtype='uint8')
expected_msg = 'Max absolute difference among violations: 4'
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
assert_allclose(x, y, atol=3)
def test_strict(self):
"""Test the behavior of the `strict` option."""
x = np.ones(3)
y = np.ones(())
assert_allclose(x, y)
with pytest.raises(AssertionError):
assert_allclose(x, y, strict=True)
assert_allclose(x, x)
with pytest.raises(AssertionError):
assert_allclose(x, x.astype(np.float32), strict=True)
def test_infs(self):
a = np.array([np.inf])
b = np.array([np.inf])
assert_allclose(a, b)
b = np.array([3.])
expected_msg = 'inf location mismatch:'
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
assert_allclose(a, b)
b = np.array([-np.inf])
expected_msg = 'inf values mismatch:'
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
assert_allclose(a, b)
b = np.array([complex(np.inf, 1.)])
expected_msg = 'inf values mismatch:'
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
assert_allclose(a, b)
a = np.array([complex(np.inf, 1.)])
b = np.array([complex(np.inf, 1.)])
assert_allclose(a, b)
b = np.array([complex(np.inf, 2.)])
expected_msg = 'inf values mismatch:'
with pytest.raises(AssertionError, match=re.escape(expected_msg)):
assert_allclose(a, b)
class TestArrayAlmostEqualNulp:
def test_float64_pass(self):
# The number of units of least precision
# In this case, use a few places above the lowest level (ie nulp=1)
nulp = 5
x = np.linspace(-20, 20, 50, dtype=np.float64)
x = 10**x
x = np.r_[-x, x]
# Addition
eps = np.finfo(x.dtype).eps
y = x + x * eps * nulp / 2.
assert_array_almost_equal_nulp(x, y, nulp)
# Subtraction
epsneg = np.finfo(x.dtype).epsneg
y = x - x * epsneg * nulp / 2.
assert_array_almost_equal_nulp(x, y, nulp)
def test_float64_fail(self):
nulp = 5
x = np.linspace(-20, 20, 50, dtype=np.float64)
x = 10**x
x = np.r_[-x, x]
eps = np.finfo(x.dtype).eps
y = x + x * eps * nulp * 2.
assert_raises(AssertionError, assert_array_almost_equal_nulp,
x, y, nulp)
epsneg = np.finfo(x.dtype).epsneg
y = x - x * epsneg * nulp * 2.
assert_raises(AssertionError, assert_array_almost_equal_nulp,
x, y, nulp)
def test_float64_ignore_nan(self):
# Ignore ULP differences between various NAN's
# Note that MIPS may reverse quiet and signaling nans
# so we use the builtin version as a base.
offset = np.uint64(0xffffffff)
nan1_i64 = np.array(np.nan, dtype=np.float64).view(np.uint64)
nan2_i64 = nan1_i64 ^ offset # nan payload on MIPS is all ones.
nan1_f64 = nan1_i64.view(np.float64)
nan2_f64 = nan2_i64.view(np.float64)
assert_array_max_ulp(nan1_f64, nan2_f64, 0)
def test_float32_pass(self):
nulp = 5
x = np.linspace(-20, 20, 50, dtype=np.float32)
x = 10**x
x = np.r_[-x, x]
eps = np.finfo(x.dtype).eps
y = x + x * eps * nulp / 2.
assert_array_almost_equal_nulp(x, y, nulp)
epsneg = np.finfo(x.dtype).epsneg
y = x - x * epsneg * nulp / 2.
assert_array_almost_equal_nulp(x, y, nulp)
def test_float32_fail(self):
nulp = 5
x = np.linspace(-20, 20, 50, dtype=np.float32)
x = 10**x
x = np.r_[-x, x]
eps = np.finfo(x.dtype).eps
y = x + x * eps * nulp * 2.
assert_raises(AssertionError, assert_array_almost_equal_nulp,
x, y, nulp)
epsneg = np.finfo(x.dtype).epsneg
y = x - x * epsneg * nulp * 2.
assert_raises(AssertionError, assert_array_almost_equal_nulp,
x, y, nulp)
def test_float32_ignore_nan(self):
# Ignore ULP differences between various NAN's
# Note that MIPS may reverse quiet and signaling nans
# so we use the builtin version as a base.
offset = np.uint32(0xffff)
nan1_i32 = np.array(np.nan, dtype=np.float32).view(np.uint32)
nan2_i32 = nan1_i32 ^ offset # nan payload on MIPS is all ones.
nan1_f32 = nan1_i32.view(np.float32)
nan2_f32 = nan2_i32.view(np.float32)
assert_array_max_ulp(nan1_f32, nan2_f32, 0)
def test_float16_pass(self):
nulp = 5
x = np.linspace(-4, 4, 10, dtype=np.float16)
x = 10**x
x = np.r_[-x, x]
eps = np.finfo(x.dtype).eps
y = x + x * eps * nulp / 2.
assert_array_almost_equal_nulp(x, y, nulp)
epsneg = np.finfo(x.dtype).epsneg
y = x - x * epsneg * nulp / 2.
assert_array_almost_equal_nulp(x, y, nulp)
def test_float16_fail(self):
nulp = 5
x = np.linspace(-4, 4, 10, dtype=np.float16)
x = 10**x
x = np.r_[-x, x]
eps = np.finfo(x.dtype).eps
y = x + x * eps * nulp * 2.
assert_raises(AssertionError, assert_array_almost_equal_nulp,
x, y, nulp)
epsneg = np.finfo(x.dtype).epsneg
y = x - x * epsneg * nulp * 2.
assert_raises(AssertionError, assert_array_almost_equal_nulp,
x, y, nulp)
def test_float16_ignore_nan(self):
# Ignore ULP differences between various NAN's
# Note that MIPS may reverse quiet and signaling nans
# so we use the builtin version as a base.
offset = np.uint16(0xff)
nan1_i16 = np.array(np.nan, dtype=np.float16).view(np.uint16)
nan2_i16 = nan1_i16 ^ offset # nan payload on MIPS is all ones.
nan1_f16 = nan1_i16.view(np.float16)
nan2_f16 = nan2_i16.view(np.float16)
assert_array_max_ulp(nan1_f16, nan2_f16, 0)
def test_complex128_pass(self):
nulp = 5
x = np.linspace(-20, 20, 50, dtype=np.float64)
x = 10**x
x = np.r_[-x, x]
xi = x + x * 1j
eps = np.finfo(x.dtype).eps
y = x + x * eps * nulp / 2.
assert_array_almost_equal_nulp(xi, x + y * 1j, nulp)
assert_array_almost_equal_nulp(xi, y + x * 1j, nulp)
# The test condition needs to be at least a factor of sqrt(2) smaller
# because the real and imaginary parts both change
y = x + x * eps * nulp / 4.
assert_array_almost_equal_nulp(xi, y + y * 1j, nulp)
epsneg = np.finfo(x.dtype).epsneg
y = x - x * epsneg * nulp / 2.
assert_array_almost_equal_nulp(xi, x + y * 1j, nulp)
assert_array_almost_equal_nulp(xi, y + x * 1j, nulp)
y = x - x * epsneg * nulp / 4.
assert_array_almost_equal_nulp(xi, y + y * 1j, nulp)
def test_complex128_fail(self):
nulp = 5
x = np.linspace(-20, 20, 50, dtype=np.float64)
x = 10**x
x = np.r_[-x, x]
xi = x + x * 1j
eps = np.finfo(x.dtype).eps
y = x + x * eps * nulp * 2.
assert_raises(AssertionError, assert_array_almost_equal_nulp,
xi, x + y * 1j, nulp)
assert_raises(AssertionError, assert_array_almost_equal_nulp,
xi, y + x * 1j, nulp)
# The test condition needs to be at least a factor of sqrt(2) smaller
# because the real and imaginary parts both change
y = x + x * eps * nulp
assert_raises(AssertionError, assert_array_almost_equal_nulp,
xi, y + y * 1j, nulp)
epsneg = np.finfo(x.dtype).epsneg
y = x - x * epsneg * nulp * 2.
assert_raises(AssertionError, assert_array_almost_equal_nulp,
xi, x + y * 1j, nulp)
assert_raises(AssertionError, assert_array_almost_equal_nulp,
xi, y + x * 1j, nulp)
y = x - x * epsneg * nulp
assert_raises(AssertionError, assert_array_almost_equal_nulp,
xi, y + y * 1j, nulp)
def test_complex64_pass(self):
nulp = 5
x = np.linspace(-20, 20, 50, dtype=np.float32)
x = 10**x
x = np.r_[-x, x]
xi = x + x * 1j
eps = np.finfo(x.dtype).eps
y = x + x * eps * nulp / 2.
assert_array_almost_equal_nulp(xi, x + y * 1j, nulp)
assert_array_almost_equal_nulp(xi, y + x * 1j, nulp)
y = x + x * eps * nulp / 4.
assert_array_almost_equal_nulp(xi, y + y * 1j, nulp)
epsneg = np.finfo(x.dtype).epsneg
y = x - x * epsneg * nulp / 2.
assert_array_almost_equal_nulp(xi, x + y * 1j, nulp)
assert_array_almost_equal_nulp(xi, y + x * 1j, nulp)
y = x - x * epsneg * nulp / 4.
assert_array_almost_equal_nulp(xi, y + y * 1j, nulp)
def test_complex64_fail(self):
nulp = 5
x = np.linspace(-20, 20, 50, dtype=np.float32)
x = 10**x
x = np.r_[-x, x]
xi = x + x * 1j
eps = np.finfo(x.dtype).eps
y = x + x * eps * nulp * 2.
assert_raises(AssertionError, assert_array_almost_equal_nulp,
xi, x + y * 1j, nulp)
assert_raises(AssertionError, assert_array_almost_equal_nulp,
xi, y + x * 1j, nulp)
y = x + x * eps * nulp
assert_raises(AssertionError, assert_array_almost_equal_nulp,
xi, y + y * 1j, nulp)
epsneg = np.finfo(x.dtype).epsneg
y = x - x * epsneg * nulp * 2.
assert_raises(AssertionError, assert_array_almost_equal_nulp,
xi, x + y * 1j, nulp)
assert_raises(AssertionError, assert_array_almost_equal_nulp,
xi, y + x * 1j, nulp)
y = x - x * epsneg * nulp
assert_raises(AssertionError, assert_array_almost_equal_nulp,
xi, y + y * 1j, nulp)
class TestULP:
def test_equal(self):
x = np.random.randn(10)
assert_array_max_ulp(x, x, maxulp=0)
def test_single(self):
# Generate 1 + small deviation, check that adding eps gives a few UNL
x = np.ones(10).astype(np.float32)
x += 0.01 * np.random.randn(10).astype(np.float32)
eps = np.finfo(np.float32).eps
assert_array_max_ulp(x, x + eps, maxulp=20)
def test_double(self):
# Generate 1 + small deviation, check that adding eps gives a few UNL
x = np.ones(10).astype(np.float64)
x += 0.01 * np.random.randn(10).astype(np.float64)
eps = np.finfo(np.float64).eps
assert_array_max_ulp(x, x + eps, maxulp=200)
def test_inf(self):
for dt in [np.float32, np.float64]:
inf = np.array([np.inf]).astype(dt)
big = np.array([np.finfo(dt).max])
assert_array_max_ulp(inf, big, maxulp=200)
def test_nan(self):
# Test that nan is 'far' from small, tiny, inf, max and min
for dt in [np.float32, np.float64]:
if dt == np.float32:
maxulp = 1e6
else:
maxulp = 1e12
inf = np.array([np.inf]).astype(dt)
nan = np.array([np.nan]).astype(dt)
big = np.array([np.finfo(dt).max])
tiny = np.array([np.finfo(dt).tiny])
zero = np.array([0.0]).astype(dt)
nzero = np.array([-0.0]).astype(dt)
assert_raises(AssertionError,
lambda: assert_array_max_ulp(nan, inf,
maxulp=maxulp))
assert_raises(AssertionError,
lambda: assert_array_max_ulp(nan, big,
maxulp=maxulp))
assert_raises(AssertionError,
lambda: assert_array_max_ulp(nan, tiny,
maxulp=maxulp))
assert_raises(AssertionError,
lambda: assert_array_max_ulp(nan, zero,
maxulp=maxulp))
assert_raises(AssertionError,
lambda: assert_array_max_ulp(nan, nzero,
maxulp=maxulp))
class TestStringEqual:
def test_simple(self):
assert_string_equal("hello", "hello")
assert_string_equal("hello\nmultiline", "hello\nmultiline")
with pytest.raises(AssertionError) as exc_info:
assert_string_equal("foo\nbar", "hello\nbar")
msg = str(exc_info.value)
assert_equal(msg, "Differences in strings:\n- foo\n+ hello")
assert_raises(AssertionError,
lambda: assert_string_equal("foo", "hello"))
def test_regex(self):
assert_string_equal("a+*b", "a+*b")
assert_raises(AssertionError,
lambda: assert_string_equal("aaa", "a+b"))
def assert_warn_len_equal(mod, n_in_context):
try:
mod_warns = mod.__warningregistry__
except AttributeError:
# the lack of a __warningregistry__
# attribute means that no warning has
# occurred; this can be triggered in
# a parallel test scenario, while in
# a serial test scenario an initial
# warning (and therefore the attribute)
# are always created first
mod_warns = {}
num_warns = len(mod_warns)
if 'version' in mod_warns:
# Python adds a 'version' entry to the registry,
# do not count it.
num_warns -= 1
assert_equal(num_warns, n_in_context)
def test_warn_len_equal_call_scenarios():
# assert_warn_len_equal is called under
# varying circumstances depending on serial
# vs. parallel test scenarios; this test
# simply aims to probe both code paths and
# check that no assertion is uncaught
# parallel scenario -- no warning issued yet
class mod:
pass
mod_inst = mod()
assert_warn_len_equal(mod=mod_inst,
n_in_context=0)
# serial test scenario -- the __warningregistry__
# attribute should be present
class mod:
def __init__(self):
self.__warningregistry__ = {'warning1': 1,
'warning2': 2}
mod_inst = mod()
assert_warn_len_equal(mod=mod_inst,
n_in_context=2)
def _get_fresh_mod():
# Get this module, with warning registry empty
my_mod = sys.modules[__name__]
try:
my_mod.__warningregistry__.clear()
except AttributeError:
# will not have a __warningregistry__ unless warning has been
# raised in the module at some point
pass
return my_mod
@pytest.mark.thread_unsafe(reason="checks global module & deprecated warnings")
def test_clear_and_catch_warnings():
# Initial state of module, no warnings
my_mod = _get_fresh_mod()
assert_equal(getattr(my_mod, '__warningregistry__', {}), {})
with clear_and_catch_warnings(modules=[my_mod]):
warnings.simplefilter('ignore')
warnings.warn('Some warning')
assert_equal(my_mod.__warningregistry__, {})
# Without specified modules, don't clear warnings during context.
# catch_warnings doesn't make an entry for 'ignore'.
with clear_and_catch_warnings():
warnings.simplefilter('ignore')
warnings.warn('Some warning')
assert_warn_len_equal(my_mod, 0)
# Manually adding two warnings to the registry:
my_mod.__warningregistry__ = {'warning1': 1,
'warning2': 2}
# Confirm that specifying module keeps old warning, does not add new
with clear_and_catch_warnings(modules=[my_mod]):
warnings.simplefilter('ignore')
warnings.warn('Another warning')
assert_warn_len_equal(my_mod, 2)
# Another warning, no module spec it clears up registry
with clear_and_catch_warnings():
warnings.simplefilter('ignore')
warnings.warn('Another warning')
assert_warn_len_equal(my_mod, 0)
@pytest.mark.filterwarnings(
"ignore:.*NumPy warning suppression and assertion utilities are deprecated"
".*:DeprecationWarning")
@pytest.mark.thread_unsafe(reason="checks global module & deprecated warnings")
def test_suppress_warnings_module():
# Initial state of module, no warnings
my_mod = _get_fresh_mod()
assert_equal(getattr(my_mod, '__warningregistry__', {}), {})
def warn_other_module():
# Apply along axis is implemented in python; stacklevel=2 means
# we end up inside its module, not ours.
def warn(arr):
warnings.warn("Some warning 2", stacklevel=2)
return arr
np.apply_along_axis(warn, 0, [0])
# Test module based warning suppression:
assert_warn_len_equal(my_mod, 0)
with suppress_warnings() as sup:
sup.record(UserWarning)
# suppress warning from other module (may have .pyc ending),
# if apply_along_axis is moved, had to be changed.
sup.filter(module=np.lib._shape_base_impl)
warnings.warn("Some warning")
warn_other_module()
# Check that the suppression did test the file correctly (this module
# got filtered)
assert_equal(len(sup.log), 1)
assert_equal(sup.log[0].message.args[0], "Some warning")
assert_warn_len_equal(my_mod, 0)
sup = suppress_warnings()
# Will have to be changed if apply_along_axis is moved:
sup.filter(module=my_mod)
with sup:
warnings.warn('Some warning')
assert_warn_len_equal(my_mod, 0)
# And test repeat works:
sup.filter(module=my_mod)
with sup:
warnings.warn('Some warning')
assert_warn_len_equal(my_mod, 0)
# Without specified modules
with suppress_warnings():
warnings.simplefilter('ignore')
warnings.warn('Some warning')
assert_warn_len_equal(my_mod, 0)
@pytest.mark.filterwarnings(
"ignore:.*NumPy warning suppression and assertion utilities are deprecated"
".*:DeprecationWarning")
@pytest.mark.thread_unsafe(reason="checks global module & deprecated warnings")
def test_suppress_warnings_type():
# Initial state of module, no warnings
my_mod = _get_fresh_mod()
assert_equal(getattr(my_mod, '__warningregistry__', {}), {})
# Test module based warning suppression:
with suppress_warnings() as sup:
sup.filter(UserWarning)
warnings.warn('Some warning')
assert_warn_len_equal(my_mod, 0)
sup = suppress_warnings()
sup.filter(UserWarning)
with sup:
warnings.warn('Some warning')
assert_warn_len_equal(my_mod, 0)
# And test repeat works:
sup.filter(module=my_mod)
with sup:
warnings.warn('Some warning')
assert_warn_len_equal(my_mod, 0)
# Without specified modules
with suppress_warnings():
warnings.simplefilter('ignore')
warnings.warn('Some warning')
assert_warn_len_equal(my_mod, 0)
@pytest.mark.filterwarnings(
"ignore:.*NumPy warning suppression and assertion utilities are deprecated"
".*:DeprecationWarning")
@pytest.mark.thread_unsafe(
reason="uses deprecated thread-unsafe warnings control utilities"
)
def test_suppress_warnings_decorate_no_record():
sup = suppress_warnings()
sup.filter(UserWarning)
@sup
def warn(category):
warnings.warn('Some warning', category)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
warn(UserWarning) # should be suppressed
warn(RuntimeWarning)
assert_equal(len(w), 1)
@pytest.mark.filterwarnings(
"ignore:.*NumPy warning suppression and assertion utilities are deprecated"
".*:DeprecationWarning")
@pytest.mark.thread_unsafe(
reason="uses deprecated thread-unsafe warnings control utilities"
)
def test_suppress_warnings_record():
sup = suppress_warnings()
log1 = sup.record()
with sup:
log2 = sup.record(message='Some other warning 2')
sup.filter(message='Some warning')
warnings.warn('Some warning')
warnings.warn('Some other warning')
warnings.warn('Some other warning 2')
assert_equal(len(sup.log), 2)
assert_equal(len(log1), 1)
assert_equal(len(log2), 1)
assert_equal(log2[0].message.args[0], 'Some other warning 2')
# Do it again, with the same context to see if some warnings survived:
with sup:
log2 = sup.record(message='Some other warning 2')
sup.filter(message='Some warning')
warnings.warn('Some warning')
warnings.warn('Some other warning')
warnings.warn('Some other warning 2')
assert_equal(len(sup.log), 2)
assert_equal(len(log1), 1)
assert_equal(len(log2), 1)
assert_equal(log2[0].message.args[0], 'Some other warning 2')
# Test nested:
with suppress_warnings() as sup:
sup.record()
with suppress_warnings() as sup2:
sup2.record(message='Some warning')
warnings.warn('Some warning')
warnings.warn('Some other warning')
assert_equal(len(sup2.log), 1)
# includes a DeprecationWarning for suppress_warnings
assert_equal(len(sup.log), 2)
@pytest.mark.filterwarnings(
"ignore:.*NumPy warning suppression and assertion utilities are deprecated"
".*:DeprecationWarning")
@pytest.mark.thread_unsafe(
reason="uses deprecated thread-unsafe warnings control utilities"
)
def test_suppress_warnings_forwarding():
def warn_other_module():
# Apply along axis is implemented in python; stacklevel=2 means
# we end up inside its module, not ours.
def warn(arr):
warnings.warn("Some warning", stacklevel=2)
return arr
np.apply_along_axis(warn, 0, [0])
with suppress_warnings() as sup:
sup.record()
with suppress_warnings("always"):
for i in range(2):
warnings.warn("Some warning")
# includes a DeprecationWarning for suppress_warnings
assert_equal(len(sup.log), 3)
with suppress_warnings() as sup:
sup.record()
with suppress_warnings("location"):
for i in range(2):
warnings.warn("Some warning")
warnings.warn("Some warning")
# includes a DeprecationWarning for suppress_warnings
assert_equal(len(sup.log), 3)
with suppress_warnings() as sup:
sup.record()
with suppress_warnings("module"):
for i in range(2):
warnings.warn("Some warning")
warnings.warn("Some warning")
warn_other_module()
# includes a DeprecationWarning for suppress_warnings
assert_equal(len(sup.log), 3)
with suppress_warnings() as sup:
sup.record()
with suppress_warnings("once"):
for i in range(2):
warnings.warn("Some warning")
warnings.warn("Some other warning")
warn_other_module()
# includes a DeprecationWarning for suppress_warnings
assert_equal(len(sup.log), 3)
def test_tempdir():
with tempdir() as tdir:
fpath = os.path.join(tdir, 'tmp')
with open(fpath, 'w'):
pass
assert_(not os.path.isdir(tdir))
raised = False
try:
with tempdir() as tdir:
raise ValueError
except ValueError:
raised = True
assert_(raised)
assert_(not os.path.isdir(tdir))
def test_temppath():
with temppath() as fpath:
with open(fpath, 'w'):
pass
assert_(not os.path.isfile(fpath))
raised = False
try:
with temppath() as fpath:
raise ValueError
except ValueError:
raised = True
assert_(raised)
assert_(not os.path.isfile(fpath))
class my_cacw(clear_and_catch_warnings):
class_modules = (sys.modules[__name__],)
@pytest.mark.thread_unsafe(reason="checks global module & deprecated warnings")
def test_clear_and_catch_warnings_inherit():
# Test can subclass and add default modules
my_mod = _get_fresh_mod()
with my_cacw():
warnings.simplefilter('ignore')
warnings.warn('Some warning')
assert_equal(my_mod.__warningregistry__, {})
@pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
@pytest.mark.thread_unsafe(reason="garbage collector is global state")
class TestAssertNoGcCycles:
""" Test assert_no_gc_cycles """
def test_passes(self):
def no_cycle():
b = []
b.append([])
return b
with assert_no_gc_cycles():
no_cycle()
assert_no_gc_cycles(no_cycle)
def test_asserts(self):
def make_cycle():
a = []
a.append(a)
a.append(a)
return a
with assert_raises(AssertionError):
with assert_no_gc_cycles():
make_cycle()
with assert_raises(AssertionError):
assert_no_gc_cycles(make_cycle)
@pytest.mark.slow
def test_fails(self):
"""
Test that in cases where the garbage cannot be collected, we raise an
error, instead of hanging forever trying to clear it.
"""
class ReferenceCycleInDel:
"""
An object that not only contains a reference cycle, but creates new
cycles whenever it's garbage-collected and its __del__ runs
"""
make_cycle = True
def __init__(self):
self.cycle = self
def __del__(self):
# break the current cycle so that `self` can be freed
self.cycle = None
if ReferenceCycleInDel.make_cycle:
# but create a new one so that the garbage collector (GC) has more
# work to do.
ReferenceCycleInDel()
try:
w = weakref.ref(ReferenceCycleInDel())
try:
with assert_raises(RuntimeError):
# this will be unable to get a baseline empty garbage
assert_no_gc_cycles(lambda: None)
except AssertionError:
# the above test is only necessary if the GC actually tried to free
# our object anyway.
if w() is not None:
pytest.skip("GC does not call __del__ on cyclic objects")
raise
finally:
# make sure that we stop creating reference cycles
ReferenceCycleInDel.make_cycle = False
| import itertools
import os
import re
import sys
import warnings
import weakref
import pytest
import numpy as np
import numpy._core._multiarray_umath as ncu
from numpy.testing import (
HAS_REFCOUNT,
assert_,
assert_allclose,
assert_almost_equal,
assert_approx_equal,
assert_array_almost_equal,
assert_array_almost_equal_nulp,
assert_array_equal,
assert_array_less,
assert_array_max_ulp,
assert_equal,
assert_no_gc_cycles,
assert_no_warnings,
assert_raises,
assert_string_equal,
assert_warns,
build_err_msg,
clear_and_catch_warnings,
suppress_warnings,
tempdir,
temppath,
)
class _GenericTest:
def _assert_func(self, *args, **kwargs):
pass
def _test_equal(self, a, b):
self._assert_func(a, b)
def _test_not_equal(self, a, b):
with assert_raises(AssertionError):
self._assert_func(a, b)
def test_array_rank1_eq(self):
"""Test two equal array of rank 1 are found equal."""
a = np.array([1, 2])
b = np.array([1, 2])
self._test_equal(a, b)
def test_array_rank1_noteq(self):
| [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_raises",
"# numpy/numpy:numpy/linalg/tests/test_linalg.py\nassert_almost_equal"
] | numpy/numpy | numpy/testing/tests/test_utils.py |
#!/usr/bin/env python3
"""Prints type-coercion tables for the built-in NumPy types
"""
from collections import namedtuple
import numpy as np
from numpy._core.numerictypes import obj2sctype
# Generic object that can be added, but doesn't do anything else
class GenericObject:
def __init__(self, v):
self.v = v
def __add__(self, other):
return self
def __radd__(self, other):
return self
dtype = np.dtype('O')
def print_cancast_table(ntypes):
print('X', end=' ')
for char in ntypes:
print(char, end=' ')
print()
for row in ntypes:
print(row, end=' ')
for col in ntypes:
if np.can_cast(row, col, "equiv"):
cast = "#"
elif np.can_cast(row, col, "safe"):
cast = "="
elif np.can_cast(row, col, "same_kind"):
cast = "~"
elif np.can_cast(row, col, "unsafe"):
cast = "."
else:
cast = " "
print(cast, end=' ')
print()
def print_coercion_table(ntypes, inputfirstvalue, inputsecondvalue, firstarray,
use_promote_types=False):
print('+', end=' ')
for char in ntypes:
print(char, end=' ')
print()
for row in ntypes:
if row == 'O':
rowtype = GenericObject
else:
rowtype = obj2sctype(row)
print(row, end=' ')
for col in ntypes:
if col == 'O':
coltype = GenericObject
else:
coltype = obj2sctype(col)
try:
if firstarray:
rowvalue = np.array([rowtype(inputfirstvalue)], dtype=rowtype)
else:
rowvalue = rowtype(inputfirstvalue)
colvalue = coltype(inputsecondvalue)
if use_promote_types:
char = np.promote_types(rowvalue.dtype, colvalue.dtype).char
else:
value = np.add(rowvalue, colvalue)
if isinstance(value, np.ndarray):
char = value.dtype.char
else:
char = np.dtype(type(value)).char
except ValueError:
char = '!'
except OverflowError:
char = '@'
except TypeError:
char = '#'
print(char, end=' ')
print()
def print_new_cast_table(*, can_cast=True, legacy=False, flags=False):
"""Prints new casts, the values given are default "can-cast" values, not
actual ones.
"""
from numpy._core._multiarray_tests import get_all_cast_information
cast_table = {
-1: " ",
0: "#", # No cast (classify as equivalent here)
1: "#", # equivalent casting
2: "=", # safe casting
3: "~", # same-kind casting
4: ".", # unsafe casting
}
flags_table = {
0: "▗", 7: "█",
1: "▚", 2: "▐", 4: "▄",
3: "▜", 5: "▙",
6: "▟",
}
cast_info = namedtuple("cast_info", ["can_cast", "legacy", "flags"])
no_cast_info = cast_info(" ", " ", " ")
casts = get_all_cast_information()
table = {}
dtypes = set()
for cast in casts:
dtypes.add(cast["from"])
dtypes.add(cast["to"])
if cast["from"] not in table:
table[cast["from"]] = {}
to_dict = table[cast["from"]]
can_cast = cast_table[cast["casting"]]
legacy = "L" if cast["legacy"] else "."
flags = 0
if cast["requires_pyapi"]:
flags |= 1
if cast["supports_unaligned"]:
flags |= 2
if cast["no_floatingpoint_errors"]:
flags |= 4
flags = flags_table[flags]
to_dict[cast["to"]] = cast_info(can_cast=can_cast, legacy=legacy, flags=flags)
# The np.dtype(x.type) is a bit strange, because dtype classes do
# not expose much yet.
types = np.typecodes["All"]
def sorter(x):
# This is a bit weird hack, to get a table as close as possible to
# the one printing all typecodes (but expecting user-dtypes).
dtype = np.dtype(x.type)
try:
indx = types.index(dtype.char)
except ValueError:
indx = np.inf
return (indx, dtype.char)
dtypes = sorted(dtypes, key=sorter)
def print_table(field="can_cast"):
print('X', end=' ')
for dt in dtypes:
print(np.dtype(dt.type).char, end=' ')
print()
for from_dt in dtypes:
print(np.dtype(from_dt.type).char, end=' ')
row = table.get(from_dt, {})
for to_dt in dtypes:
print(getattr(row.get(to_dt, no_cast_info), field), end=' ')
print()
if can_cast:
# Print the actual table:
print()
print("Casting: # is equivalent, = is safe, ~ is same-kind, and . is unsafe")
print()
print_table("can_cast")
if legacy:
print()
print("L denotes a legacy cast . a non-legacy one.")
print()
print_table("legacy")
if flags:
print()
print(f"{flags_table[0]}: no flags, "
f"{flags_table[1]}: PyAPI, "
f"{flags_table[2]}: supports unaligned, "
f"{flags_table[4]}: no-float-errors")
print()
print_table("flags")
if __name__ == '__main__':
print("can cast")
print_cancast_table(np.typecodes['All'])
print()
print("In these tables, ValueError is '!', OverflowError is '@', TypeError is '#'")
print()
print("scalar + scalar")
print_coercion_table(np.typecodes['All'], 0, 0, False)
print()
print("scalar + neg scalar")
print_coercion_table(np.typecodes['All'], 0, -1, False)
print()
print("array + scalar")
print_coercion_table(np.typecodes['All'], 0, 0, True)
print()
print("array + neg scalar")
print_coercion_table(np.typecodes['All'], 0, -1, True)
print()
print("promote_types")
print_coercion_table(np.typecodes['All'], 0, 0, False, True)
print("New casting type promotion:")
print_new_cast_table(can_cast=True, legacy=True, flags=True)
| #!/usr/bin/env python3
"""Prints type-coercion tables for the built-in NumPy types
"""
from collections import namedtuple
import numpy as np
from numpy._core.numerictypes import obj2sctype
# Generic object that can be added, but doesn't do anything else
class GenericObject:
def __init__(self, v):
self.v = v
def __add__(self, other):
return self
def __radd__(self, other):
return self
dtype = np.dtype('O')
def print_cancast_table(ntypes):
print('X', end=' ')
for char in ntypes:
print(char, end=' ')
print()
for row in ntypes:
print(row, end=' ')
for col in ntypes:
if np.can_cast(row, col, "equiv"):
cast = "#"
elif np.can_cast(row, col, "safe"):
cast = "="
elif np.can_cast(row, col, "same_kind"):
cast = "~"
elif np.can_cast(row, col, "unsafe"):
cast = "."
else:
cast = " "
print(cast | [
"# numpy/numpy:numpy/_core/numerictypes.py\nobj2sctype"
] | numpy/numpy | numpy/testing/print_coercion_tables.py |
"""Tools for testing implementations of __array_function__ and ufunc overrides
"""
import numpy._core.umath as _umath
from numpy import ufunc as _ufunc
from numpy._core.overrides import ARRAY_FUNCTIONS as _array_functions
def get_overridable_numpy_ufuncs():
"""List all numpy ufuncs overridable via `__array_ufunc__`
Parameters
----------
None
Returns
-------
set
A set containing all overridable ufuncs in the public numpy API.
"""
ufuncs = {obj for obj in _umath.__dict__.values()
if isinstance(obj, _ufunc)}
return ufuncs
def allows_array_ufunc_override(func):
"""Determine if a function can be overridden via `__array_ufunc__`
Parameters
----------
func : callable
Function that may be overridable via `__array_ufunc__`
Returns
-------
bool
`True` if `func` is overridable via `__array_ufunc__` and
`False` otherwise.
Notes
-----
This function is equivalent to ``isinstance(func, np.ufunc)`` and
will work correctly for ufuncs defined outside of Numpy.
"""
return isinstance(func, _ufunc)
def get_overridable_numpy_array_functions():
"""List all numpy functions overridable via `__array_function__`
Parameters
----------
None
Returns
-------
set
A set containing all functions in the public numpy API that are
overridable via `__array_function__`.
"""
# 'import numpy' doesn't import recfunctions, so make sure it's imported
# so ufuncs defined there show up in the ufunc listing
from numpy.lib import recfunctions # noqa: F401
return _array_functions.copy()
def allows_array_function_override(func):
"""Determine if a Numpy function can be overridden via `__array_function__`
Parameters
----------
func : callable
Function that may be overridable via `__array_function__`
Returns
-------
bool
`True` if `func` is a function in the Numpy API that is
overridable via `__array_function__` and `False` otherwise.
"""
return func in _array_functions
| """Tools for testing implementations of __array_function__ and ufunc overrides
"""
import numpy._core.umath as _umath
from numpy import ufunc as _ufunc
from numpy._core.overrides import ARRAY_FUNCTIONS as _array_functions
def get_overridable_numpy_ufuncs():
"""List all numpy ufuncs overridable via `__array_ufunc__`
Parameters
----------
None
Returns
-------
set
A set containing all overridable ufuncs in the public numpy API.
"""
ufuncs = {obj for obj in _umath.__dict__.values()
if isinstance(obj, _ufunc)}
return ufuncs
def allows_array_ufunc_override(func):
"""Determine if a function can be overridden via `__array_ufunc__`
Parameters
----------
func : callable
Function that may be overridable via `__array_ufunc__`
Returns
-------
bool
`True` if `func` is overridable via `__array_ufunc__` and
`False` otherwise.
Notes
-----
This function is equivalent to ``isinstance(func, np.ufunc)`` and
will work correctly for ufuncs defined outside of Numpy.
"""
return isinstance(func, _ufunc)
def get_overridable_numpy_array_functions():
"""List all numpy functions overridable via `__array_function__`
Parameters
----------
None
Returns
-------
set
A set containing all functions | [] | numpy/numpy | numpy/testing/overrides.py |
"""
Utility function to facilitate testing.
"""
import concurrent.futures
import contextlib
import gc
import importlib.metadata
import importlib.util
import operator
import os
import pathlib
import platform
import pprint
import re
import shutil
import sys
import sysconfig
import threading
import warnings
from functools import partial, wraps
from io import StringIO
from tempfile import mkdtemp, mkstemp
from unittest.case import SkipTest
from warnings import WarningMessage
import numpy as np
import numpy.linalg._umath_linalg
from numpy import isfinite, isnan
from numpy._core import arange, array, array_repr, empty, float32, intp, isnat, ndarray
__all__ = [
'assert_equal', 'assert_almost_equal', 'assert_approx_equal',
'assert_array_equal', 'assert_array_less', 'assert_string_equal',
'assert_array_almost_equal', 'assert_raises', 'build_err_msg',
'decorate_methods', 'jiffies', 'memusage', 'print_assert_equal',
'rundocs', 'runstring', 'verbose', 'measure',
'assert_', 'assert_array_almost_equal_nulp', 'assert_raises_regex',
'assert_array_max_ulp', 'assert_warns', 'assert_no_warnings',
'assert_allclose', 'IgnoreException', 'clear_and_catch_warnings',
'SkipTest', 'KnownFailureException', 'temppath', 'tempdir', 'IS_PYPY',
'HAS_REFCOUNT', "IS_WASM", 'suppress_warnings', 'assert_array_compare',
'assert_no_gc_cycles', 'break_cycles', 'HAS_LAPACK64', 'IS_PYSTON',
'IS_MUSL', 'check_support_sve', 'NOGIL_BUILD',
'IS_EDITABLE', 'IS_INSTALLED', 'NUMPY_ROOT', 'run_threaded', 'IS_64BIT',
'BLAS_SUPPORTS_FPE',
]
class KnownFailureException(Exception):
'''Raise this exception to mark a test as a known failing test.'''
pass
KnownFailureTest = KnownFailureException # backwards compat
verbose = 0
NUMPY_ROOT = pathlib.Path(np.__file__).parent
try:
np_dist = importlib.metadata.distribution('numpy')
except importlib.metadata.PackageNotFoundError:
IS_INSTALLED = IS_EDITABLE = False
else:
IS_INSTALLED = True
try:
if sys.version_info < (3, 13):
# Backport importlib.metadata.Distribution.origin
import json
import types
origin = json.loads(
np_dist.read_text('direct_url.json') or '{}',
object_hook=lambda data: types.SimpleNamespace(**data),
)
IS_EDITABLE = origin.dir_info.editable
else:
IS_EDITABLE = np_dist.origin.dir_info.editable
except AttributeError:
IS_EDITABLE = False
# spin installs numpy directly via meson, instead of using meson-python, and
# runs the module by setting PYTHONPATH. This is problematic because the
# resulting installation lacks the Python metadata (.dist-info), and numpy
# might already be installed on the environment, causing us to find its
# metadata, even though we are not actually loading that package.
# Work around this issue by checking if the numpy root matches.
if not IS_EDITABLE and np_dist.locate_file('numpy') != NUMPY_ROOT:
IS_INSTALLED = False
IS_WASM = platform.machine() in ["wasm32", "wasm64"]
IS_PYPY = sys.implementation.name == 'pypy'
IS_PYSTON = hasattr(sys, "pyston_version_info")
HAS_REFCOUNT = getattr(sys, 'getrefcount', None) is not None and not IS_PYSTON
BLAS_SUPPORTS_FPE = np._core._multiarray_umath._blas_supports_fpe(None)
HAS_LAPACK64 = numpy.linalg._umath_linalg._ilp64
IS_MUSL = False
# alternate way is
# from packaging.tags import sys_tags
# _tags = list(sys_tags())
# if 'musllinux' in _tags[0].platform:
_v = sysconfig.get_config_var('HOST_GNU_TYPE') or ''
if 'musl' in _v:
IS_MUSL = True
NOGIL_BUILD = bool(sysconfig.get_config_var("Py_GIL_DISABLED"))
IS_64BIT = np.dtype(np.intp).itemsize == 8
def assert_(val, msg=''):
"""
Assert that works in release mode.
Accepts callable msg to allow deferring evaluation until failure.
The Python built-in ``assert`` does not work when executing code in
optimized mode (the ``-O`` flag) - no byte-code is generated for it.
For documentation on usage, refer to the Python documentation.
"""
__tracebackhide__ = True # Hide traceback for py.test
if not val:
try:
smsg = msg()
except TypeError:
smsg = msg
raise AssertionError(smsg)
if os.name == 'nt':
# Code "stolen" from enthought/debug/memusage.py
def GetPerformanceAttributes(object, counter, instance=None,
inum=-1, format=None, machine=None):
# NOTE: Many counters require 2 samples to give accurate results,
# including "% Processor Time" (as by definition, at any instant, a
# thread's CPU usage is either 0 or 100). To read counters like this,
# you should copy this function, but keep the counter open, and call
# CollectQueryData() each time you need to know.
# See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp
# (dead link)
# My older explanation for this was that the "AddCounter" process
# forced the CPU to 100%, but the above makes more sense :)
import win32pdh
if format is None:
format = win32pdh.PDH_FMT_LONG
path = win32pdh.MakeCounterPath((machine, object, instance, None,
inum, counter))
hq = win32pdh.OpenQuery()
try:
hc = win32pdh.AddCounter(hq, path)
try:
win32pdh.CollectQueryData(hq)
type, val = win32pdh.GetFormattedCounterValue(hc, format)
return val
finally:
win32pdh.RemoveCounter(hc)
finally:
win32pdh.CloseQuery(hq)
def memusage(processName="python", instance=0):
# from win32pdhutil, part of the win32all package
import win32pdh
return GetPerformanceAttributes("Process", "Virtual Bytes",
processName, instance,
win32pdh.PDH_FMT_LONG, None)
elif sys.platform[:5] == 'linux':
def memusage(_proc_pid_stat=None):
"""
Return virtual memory size in bytes of the running python.
"""
_proc_pid_stat = _proc_pid_stat or f'/proc/{os.getpid()}/stat'
try:
with open(_proc_pid_stat) as f:
l = f.readline().split(' ')
return int(l[22])
except Exception:
return
else:
def memusage():
"""
Return memory usage of running python. [Not implemented]
"""
raise NotImplementedError
if sys.platform[:5] == 'linux':
def jiffies(_proc_pid_stat=None, _load_time=None):
"""
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this
process has been scheduled in user mode. See man 5 proc.
"""
_proc_pid_stat = _proc_pid_stat or f'/proc/{os.getpid()}/stat'
_load_time = _load_time or []
import time
if not _load_time:
_load_time.append(time.time())
try:
with open(_proc_pid_stat) as f:
l = f.readline().split(' ')
return int(l[13])
except Exception:
return int(100 * (time.time() - _load_time[0]))
else:
# os.getpid is not in all platforms available.
# Using time is safe but inaccurate, especially when process
# was suspended or sleeping.
def jiffies(_load_time=[]):
"""
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this
process has been scheduled in user mode. See man 5 proc.
"""
import time
if not _load_time:
_load_time.append(time.time())
return int(100 * (time.time() - _load_time[0]))
def build_err_msg(arrays, err_msg, header='Items are not equal:',
verbose=True, names=('ACTUAL', 'DESIRED'), precision=8):
msg = ['\n' + header]
err_msg = str(err_msg)
if err_msg:
if err_msg.find('\n') == -1 and len(err_msg) < 79 - len(header):
msg = [msg[0] + ' ' + err_msg]
else:
msg.append(err_msg)
if verbose:
for i, a in enumerate(arrays):
if isinstance(a, ndarray):
# precision argument is only needed if the objects are ndarrays
r_func = partial(array_repr, precision=precision)
else:
r_func = repr
try:
r = r_func(a)
except Exception as exc:
r = f'[repr failed for <{type(a).__name__}>: {exc}]'
if r.count('\n') > 3:
r = '\n'.join(r.splitlines()[:3])
r += '...'
msg.append(f' {names[i]}: {r}')
return '\n'.join(msg)
def assert_equal(actual, desired, err_msg='', verbose=True, *, strict=False):
"""
Raises an AssertionError if two objects are not equal.
Given two objects (scalars, lists, tuples, dictionaries or numpy arrays),
check that all elements of these objects are equal. An exception is raised
at the first conflicting values.
This function handles NaN comparisons as if NaN was a "normal" number.
That is, AssertionError is not raised if both objects have NaNs in the same
positions. This is in contrast to the IEEE standard on NaNs, which says
that NaN compared to anything must return False.
Parameters
----------
actual : array_like
The object to check.
desired : array_like
The expected object.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
strict : bool, optional
If True and either of the `actual` and `desired` arguments is an array,
raise an ``AssertionError`` when either the shape or the data type of
the arguments does not match. If neither argument is an array, this
parameter has no effect.
.. versionadded:: 2.0.0
Raises
------
AssertionError
If actual and desired are not equal.
See Also
--------
assert_allclose
assert_array_almost_equal_nulp,
assert_array_max_ulp,
Notes
-----
When one of `actual` and `desired` is a scalar and the other is array_like, the
function checks that each element of the array_like is equal to the scalar.
Note that empty arrays are therefore considered equal to scalars.
This behaviour can be disabled by setting ``strict==True``.
Examples
--------
>>> np.testing.assert_equal([4, 5], [4, 6])
Traceback (most recent call last):
...
AssertionError:
Items are not equal:
item=1
ACTUAL: 5
DESIRED: 6
The following comparison does not raise an exception. There are NaNs
in the inputs, but they are in the same positions.
>>> np.testing.assert_equal(np.array([1.0, 2.0, np.nan]), [1, 2, np.nan])
As mentioned in the Notes section, `assert_equal` has special
handling for scalars when one of the arguments is an array.
Here, the test checks that each value in `x` is 3:
>>> x = np.full((2, 5), fill_value=3)
>>> np.testing.assert_equal(x, 3)
Use `strict` to raise an AssertionError when comparing a scalar with an
array of a different shape:
>>> np.testing.assert_equal(x, 3, strict=True)
Traceback (most recent call last):
...
AssertionError:
Arrays are not equal
<BLANKLINE>
(shapes (2, 5), () mismatch)
ACTUAL: array([[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3]])
DESIRED: array(3)
The `strict` parameter also ensures that the array data types match:
>>> x = np.array([2, 2, 2])
>>> y = np.array([2., 2., 2.], dtype=np.float32)
>>> np.testing.assert_equal(x, y, strict=True)
Traceback (most recent call last):
...
AssertionError:
Arrays are not equal
<BLANKLINE>
(dtypes int64, float32 mismatch)
ACTUAL: array([2, 2, 2])
DESIRED: array([2., 2., 2.], dtype=float32)
"""
__tracebackhide__ = True # Hide traceback for py.test
if isinstance(desired, dict):
if not isinstance(actual, dict):
raise AssertionError(repr(type(actual)))
assert_equal(len(actual), len(desired), err_msg, verbose)
for k in desired:
if k not in actual:
raise AssertionError(repr(k))
assert_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}',
verbose)
return
if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
assert_equal(len(actual), len(desired), err_msg, verbose)
for k in range(len(desired)):
assert_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}',
verbose)
return
from numpy import imag, iscomplexobj, real
from numpy._core import isscalar, ndarray, signbit
if isinstance(actual, ndarray) or isinstance(desired, ndarray):
return assert_array_equal(actual, desired, err_msg, verbose,
strict=strict)
msg = build_err_msg([actual, desired], err_msg, verbose=verbose)
# Handle complex numbers: separate into real/imag to handle
# nan/inf/negative zero correctly
# XXX: catch ValueError for subclasses of ndarray where iscomplex fail
try:
usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
except (ValueError, TypeError):
usecomplex = False
if usecomplex:
if iscomplexobj(actual):
actualr = real(actual)
actuali = imag(actual)
else:
actualr = actual
actuali = 0
if iscomplexobj(desired):
desiredr = real(desired)
desiredi = imag(desired)
else:
desiredr = desired
desiredi = 0
try:
assert_equal(actualr, desiredr)
assert_equal(actuali, desiredi)
except AssertionError:
raise AssertionError(msg)
# isscalar test to check cases such as [np.nan] != np.nan
if isscalar(desired) != isscalar(actual):
raise AssertionError(msg)
try:
isdesnat = isnat(desired)
isactnat = isnat(actual)
dtypes_match = (np.asarray(desired).dtype.type ==
np.asarray(actual).dtype.type)
if isdesnat and isactnat:
# If both are NaT (and have the same dtype -- datetime or
# timedelta) they are considered equal.
if dtypes_match:
return
else:
raise AssertionError(msg)
except (TypeError, ValueError, NotImplementedError):
pass
# Inf/nan/negative zero handling
try:
isdesnan = isnan(desired)
isactnan = isnan(actual)
if isdesnan and isactnan:
return # both nan, so equal
# handle signed zero specially for floats
array_actual = np.asarray(actual)
array_desired = np.asarray(desired)
if (array_actual.dtype.char in 'Mm' or
array_desired.dtype.char in 'Mm'):
# version 1.18
# until this version, isnan failed for datetime64 and timedelta64.
# Now it succeeds but comparison to scalar with a different type
# emits a DeprecationWarning.
# Avoid that by skipping the next check
raise NotImplementedError('cannot compare to a scalar '
'with a different type')
if desired == 0 and actual == 0:
if not signbit(desired) == signbit(actual):
raise AssertionError(msg)
except (TypeError, ValueError, NotImplementedError):
pass
try:
# Explicitly use __eq__ for comparison, gh-2552
if not (desired == actual):
raise AssertionError(msg)
except (DeprecationWarning, FutureWarning) as e:
# this handles the case when the two types are not even comparable
if 'elementwise == comparison' in e.args[0]:
raise AssertionError(msg)
else:
raise
def print_assert_equal(test_string, actual, desired):
"""
Test if two objects are equal, and print an error message if test fails.
The test is performed with ``actual == desired``.
Parameters
----------
test_string : str
The message supplied to AssertionError.
actual : object
The object to test for equality against `desired`.
desired : object
The expected result.
Examples
--------
>>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 1])
>>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 2])
Traceback (most recent call last):
...
AssertionError: Test XYZ of func xyz failed
ACTUAL:
[0, 1]
DESIRED:
[0, 2]
"""
__tracebackhide__ = True # Hide traceback for py.test
import pprint
if not (actual == desired):
msg = StringIO()
msg.write(test_string)
msg.write(' failed\nACTUAL: \n')
pprint.pprint(actual, msg)
msg.write('DESIRED: \n')
pprint.pprint(desired, msg)
raise AssertionError(msg.getvalue())
def assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True):
"""
Raises an AssertionError if two items are not equal up to desired
precision.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
comparisons.
The test verifies that the elements of `actual` and `desired` satisfy::
abs(desired-actual) < float64(1.5 * 10**(-decimal))
That is a looser test than originally documented, but agrees with what the
actual implementation in `assert_array_almost_equal` did up to rounding
vagaries. An exception is raised at conflicting values. For ndarrays this
delegates to assert_array_almost_equal
Parameters
----------
actual : array_like
The object to check.
desired : array_like
The expected object.
decimal : int, optional
Desired precision, default is 7.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
Raises
------
AssertionError
If actual and desired are not equal up to specified precision.
See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
Examples
--------
>>> from numpy.testing import assert_almost_equal
>>> assert_almost_equal(2.3333333333333, 2.33333334)
>>> assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
Traceback (most recent call last):
...
AssertionError:
Arrays are not almost equal to 10 decimals
ACTUAL: 2.3333333333333
DESIRED: 2.33333334
>>> assert_almost_equal(np.array([1.0,2.3333333333333]),
... np.array([1.0,2.33333334]), decimal=9)
Traceback (most recent call last):
...
AssertionError:
Arrays are not almost equal to 9 decimals
<BLANKLINE>
Mismatched elements: 1 / 2 (50%)
Mismatch at index:
[1]: 2.3333333333333 (ACTUAL), 2.33333334 (DESIRED)
Max absolute difference among violations: 6.66669964e-09
Max relative difference among violations: 2.85715698e-09
ACTUAL: array([1. , 2.333333333])
DESIRED: array([1. , 2.33333334])
"""
__tracebackhide__ = True # Hide traceback for py.test
from numpy import imag, iscomplexobj, real
from numpy._core import ndarray
# Handle complex numbers: separate into real/imag to handle
# nan/inf/negative zero correctly
# XXX: catch ValueError for subclasses of ndarray where iscomplex fail
try:
usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
except ValueError:
usecomplex = False
def _build_err_msg():
header = ('Arrays are not almost equal to %d decimals' % decimal)
return build_err_msg([actual, desired], err_msg, verbose=verbose,
header=header)
if usecomplex:
if iscomplexobj(actual):
actualr = real(actual)
actuali = imag(actual)
else:
actualr = actual
actuali = 0
if iscomplexobj(desired):
desiredr = real(desired)
desiredi = imag(desired)
else:
desiredr = desired
desiredi = 0
try:
assert_almost_equal(actualr, desiredr, decimal=decimal)
assert_almost_equal(actuali, desiredi, decimal=decimal)
except AssertionError:
raise AssertionError(_build_err_msg())
if isinstance(actual, (ndarray, tuple, list)) \
or isinstance(desired, (ndarray, tuple, list)):
return assert_array_almost_equal(actual, desired, decimal, err_msg)
try:
# If one of desired/actual is not finite, handle it specially here:
# check that both are nan if any is a nan, and test for equality
# otherwise
if not (isfinite(desired) and isfinite(actual)):
if isnan(desired) or isnan(actual):
if not (isnan(desired) and isnan(actual)):
raise AssertionError(_build_err_msg())
elif not desired == actual:
raise AssertionError(_build_err_msg())
return
except (NotImplementedError, TypeError):
pass
if abs(desired - actual) >= np.float64(1.5 * 10.0**(-decimal)):
raise AssertionError(_build_err_msg())
def assert_approx_equal(actual, desired, significant=7, err_msg='',
verbose=True):
"""
Raises an AssertionError if two items are not equal up to significant
digits.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
comparisons.
Given two numbers, check that they are approximately equal.
Approximately equal is defined as the number of significant digits
that agree.
Parameters
----------
actual : scalar
The object to check.
desired : scalar
The expected object.
significant : int, optional
Desired precision, default is 7.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
Raises
------
AssertionError
If actual and desired are not equal up to specified precision.
See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
Examples
--------
>>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20)
>>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20,
... significant=8)
>>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20,
... significant=8)
Traceback (most recent call last):
...
AssertionError:
Items are not equal to 8 significant digits:
ACTUAL: 1.234567e-21
DESIRED: 1.2345672e-21
the evaluated condition that raises the exception is
>>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1)
True
"""
__tracebackhide__ = True # Hide traceback for py.test
import numpy as np
(actual, desired) = map(float, (actual, desired))
if desired == actual:
return
# Normalized the numbers to be in range (-10.0,10.0)
# scale = float(pow(10,math.floor(math.log10(0.5*(abs(desired)+abs(actual))))))
with np.errstate(invalid='ignore'):
scale = 0.5 * (np.abs(desired) + np.abs(actual))
scale = np.power(10, np.floor(np.log10(scale)))
try:
sc_desired = desired / scale
except ZeroDivisionError:
sc_desired = 0.0
try:
sc_actual = actual / scale
except ZeroDivisionError:
sc_actual = 0.0
msg = build_err_msg(
[actual, desired], err_msg,
header='Items are not equal to %d significant digits:' % significant,
verbose=verbose)
try:
# If one of desired/actual is not finite, handle it specially here:
# check that both are nan if any is a nan, and test for equality
# otherwise
if not (isfinite(desired) and isfinite(actual)):
if isnan(desired) or isnan(actual):
if not (isnan(desired) and isnan(actual)):
raise AssertionError(msg)
elif not desired == actual:
raise AssertionError(msg)
return
except (TypeError, NotImplementedError):
pass
if np.abs(sc_desired - sc_actual) >= np.power(10., -(significant - 1)):
raise AssertionError(msg)
def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='',
precision=6, equal_nan=True, equal_inf=True,
*, strict=False, names=('ACTUAL', 'DESIRED')):
__tracebackhide__ = True # Hide traceback for py.test
from numpy._core import all, array2string, errstate, inf, isnan, max, object_
x = np.asanyarray(x)
y = np.asanyarray(y)
# original array for output formatting
ox, oy = x, y
def isnumber(x):
return type(x.dtype)._is_numeric
def istime(x):
return x.dtype.char in "Mm"
def isvstring(x):
return x.dtype.char == "T"
def robust_any_difference(x, y):
# We include work-arounds here to handle three types of slightly
# pathological ndarray subclasses:
# (1) all() on fully masked arrays returns np.ma.masked, so we use != True
# (np.ma.masked != True evaluates as np.ma.masked, which is falsy).
# (2) __eq__ on some ndarray subclasses returns Python booleans
# instead of element-wise comparisons, so we cast to np.bool() in
# that case (or in case __eq__ returns some other value with no
# all() method).
# (3) subclasses with bare-bones __array_function__ implementations may
# not implement np.all(), so favor using the .all() method
# We are not committed to supporting cases (2) and (3), but it's nice to
# support them if possible.
result = x == y
if not hasattr(result, "all") or not callable(result.all):
result = np.bool(result)
return result.all() != True
def func_assert_same_pos(x, y, func=isnan, hasval='nan'):
"""Handling nan/inf.
Combine results of running func on x and y, checking that they are True
at the same locations.
"""
__tracebackhide__ = True # Hide traceback for py.test
x_id = func(x)
y_id = func(y)
if robust_any_difference(x_id, y_id):
msg = build_err_msg(
[x, y],
err_msg + '\n%s location mismatch:'
% (hasval), verbose=verbose, header=header,
names=names,
precision=precision)
raise AssertionError(msg)
# If there is a scalar, then here we know the array has the same
# flag as it everywhere, so we should return the scalar flag.
# np.ma.masked is also handled and converted to np.False_ (even if the other
# array has nans/infs etc.; that's OK given the handling later of fully-masked
# results).
if isinstance(x_id, bool) or x_id.ndim == 0:
return np.bool(x_id)
elif isinstance(y_id, bool) or y_id.ndim == 0:
return np.bool(y_id)
else:
return y_id
def assert_same_inf_values(x, y, infs_mask):
"""
Verify all inf values match in the two arrays
"""
__tracebackhide__ = True # Hide traceback for py.test
if not infs_mask.any():
return
if x.ndim > 0 and y.ndim > 0:
x = x[infs_mask]
y = y[infs_mask]
else:
assert infs_mask.all()
if robust_any_difference(x, y):
msg = build_err_msg(
[x, y],
err_msg + '\ninf values mismatch:',
verbose=verbose, header=header,
names=names,
precision=precision)
raise AssertionError(msg)
try:
if strict:
cond = x.shape == y.shape and x.dtype == y.dtype
else:
cond = (x.shape == () or y.shape == ()) or x.shape == y.shape
if not cond:
if x.shape != y.shape:
reason = f'\n(shapes {x.shape}, {y.shape} mismatch)'
else:
reason = f'\n(dtypes {x.dtype}, {y.dtype} mismatch)'
msg = build_err_msg([x, y],
err_msg
+ reason,
verbose=verbose, header=header,
names=names,
precision=precision)
raise AssertionError(msg)
flagged = np.bool(False)
if isnumber(x) and isnumber(y):
if equal_nan:
flagged = func_assert_same_pos(x, y, func=isnan, hasval='nan')
if equal_inf:
# If equal_nan=True, skip comparing nans below for equality if they are
# also infs (e.g. inf+nanj) since that would always fail.
isinf_func = lambda xy: np.logical_and(np.isinf(xy), np.invert(flagged))
infs_mask = func_assert_same_pos(
x, y,
func=isinf_func,
hasval='inf')
assert_same_inf_values(x, y, infs_mask)
flagged |= infs_mask
elif istime(x) and istime(y):
# If one is datetime64 and the other timedelta64 there is no point
if equal_nan and x.dtype.type == y.dtype.type:
flagged = func_assert_same_pos(x, y, func=isnat, hasval="NaT")
elif isvstring(x) and isvstring(y):
dt = x.dtype
if equal_nan and dt == y.dtype and hasattr(dt, 'na_object'):
is_nan = (isinstance(dt.na_object, float) and
np.isnan(dt.na_object))
bool_errors = 0
try:
bool(dt.na_object)
except TypeError:
bool_errors = 1
if is_nan or bool_errors:
# nan-like NA object
flagged = func_assert_same_pos(
x, y, func=isnan, hasval=x.dtype.na_object)
if flagged.ndim > 0:
x, y = x[~flagged], y[~flagged]
# Only do the comparison if actual values are left
if x.size == 0:
return
elif flagged:
# no sense doing comparison if everything is flagged.
return
val = comparison(x, y)
invalids = np.logical_not(val)
if isinstance(val, bool):
cond = val
reduced = array([val])
else:
reduced = val.ravel()
cond = reduced.all()
# The below comparison is a hack to ensure that fully masked
# results, for which val.ravel().all() returns np.ma.masked,
# do not trigger a failure (np.ma.masked != True evaluates as
# np.ma.masked, which is falsy).
if cond != True:
n_mismatch = reduced.size - reduced.sum(dtype=intp)
n_elements = flagged.size if flagged.ndim != 0 else reduced.size
percent_mismatch = 100 * n_mismatch / n_elements
remarks = [(f'Mismatched elements: {n_mismatch} / {n_elements} '
f'({percent_mismatch:.3g}%)')]
if invalids.ndim != 0:
if flagged.ndim > 0:
positions = np.argwhere(np.asarray(~flagged))[invalids]
else:
positions = np.argwhere(np.asarray(invalids))
s = "\n".join(
[
f" {p.tolist()}: {ox if ox.ndim == 0 else ox[tuple(p)]} "
f"({names[0]}), {oy if oy.ndim == 0 else oy[tuple(p)]} "
f"({names[1]})"
for p in positions[:5]
]
)
if len(positions) == 1:
remarks.append(
f"Mismatch at index:\n{s}"
)
elif len(positions) <= 5:
remarks.append(
f"Mismatch at indices:\n{s}"
)
else:
remarks.append(
f"First 5 mismatches are at indices:\n{s}"
)
with errstate(all='ignore'):
# ignore errors for non-numeric types
with contextlib.suppress(TypeError):
error = abs(x - y)
if np.issubdtype(x.dtype, np.unsignedinteger):
error2 = abs(y - x)
np.minimum(error, error2, out=error)
reduced_error = error[invalids]
max_abs_error = max(reduced_error)
if getattr(error, 'dtype', object_) == object_:
remarks.append(
'Max absolute difference among violations: '
+ str(max_abs_error))
else:
remarks.append(
'Max absolute difference among violations: '
+ array2string(max_abs_error))
# note: this definition of relative error matches that one
# used by assert_allclose (found in np.isclose)
# Filter values where the divisor would be zero
nonzero = np.bool(y != np.zeros_like(y))
nonzero_and_invalid = np.logical_and(invalids, nonzero)
if all(~nonzero_and_invalid):
max_rel_error = array(inf)
else:
nonzero_invalid_error = error[nonzero_and_invalid]
broadcasted_y = np.broadcast_to(y, error.shape)
nonzero_invalid_y = broadcasted_y[nonzero_and_invalid]
max_rel_error = max(nonzero_invalid_error
/ abs(nonzero_invalid_y))
if getattr(error, 'dtype', object_) == object_:
remarks.append(
'Max relative difference among violations: '
+ str(max_rel_error))
else:
remarks.append(
'Max relative difference among violations: '
+ array2string(max_rel_error))
err_msg = str(err_msg)
err_msg += '\n' + '\n'.join(remarks)
msg = build_err_msg([ox, oy], err_msg,
verbose=verbose, header=header,
names=names,
precision=precision)
raise AssertionError(msg)
except ValueError:
import traceback
efmt = traceback.format_exc()
header = f'error during assertion:\n\n{efmt}\n\n{header}'
msg = build_err_msg([x, y], err_msg, verbose=verbose, header=header,
names=names, precision=precision)
raise ValueError(msg)
def assert_array_equal(actual, desired, err_msg='', verbose=True, *,
strict=False):
"""
Raises an AssertionError if two array_like objects are not equal.
Given two array_like objects, check that the shape is equal and all
elements of these objects are equal (but see the Notes for the special
handling of a scalar). An exception is raised at shape mismatch or
conflicting values. In contrast to the standard usage in numpy, NaNs
are compared like numbers, no assertion is raised if both objects have
NaNs in the same positions.
The usual caution for verifying equality with floating point numbers is
advised.
.. note:: When either `actual` or `desired` is already an instance of
`numpy.ndarray` and `desired` is not a ``dict``, the behavior of
``assert_equal(actual, desired)`` is identical to the behavior of this
function. Otherwise, this function performs `np.asanyarray` on the
inputs before comparison, whereas `assert_equal` defines special
comparison rules for common Python types. For example, only
`assert_equal` can be used to compare nested Python lists. In new code,
consider using only `assert_equal`, explicitly converting either
`actual` or `desired` to arrays if the behavior of `assert_array_equal`
is desired.
Parameters
----------
actual : array_like
The actual object to check.
desired : array_like
The desired, expected object.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
strict : bool, optional
If True, raise an AssertionError when either the shape or the data
type of the array_like objects does not match. The special
handling for scalars mentioned in the Notes section is disabled.
.. versionadded:: 1.24.0
Raises
------
AssertionError
If actual and desired objects are not equal.
See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
Notes
-----
When one of `actual` and `desired` is a scalar and the other is array_like, the
function checks that each element of the array_like is equal to the scalar.
Note that empty arrays are therefore considered equal to scalars.
This behaviour can be disabled by setting ``strict==True``.
Examples
--------
>>> import numpy as np
The first assert does not raise an exception:
>>> np.testing.assert_array_equal([1.0,2.33333,np.nan],
... [np.exp(0),2.33333, np.nan])
Assert fails with numerical imprecision with floats:
>>> np.testing.assert_array_equal([1.0,np.pi,np.nan],
... [1, np.sqrt(np.pi)**2, np.nan])
Traceback (most recent call last):
...
AssertionError:
Arrays are not equal
<BLANKLINE>
Mismatched elements: 1 / 3 (33.3%)
Mismatch at index:
[1]: 3.141592653589793 (ACTUAL), 3.1415926535897927 (DESIRED)
Max absolute difference among violations: 4.4408921e-16
Max relative difference among violations: 1.41357986e-16
ACTUAL: array([1. , 3.141593, nan])
DESIRED: array([1. , 3.141593, nan])
Use `assert_allclose` or one of the nulp (number of floating point values)
functions for these cases instead:
>>> np.testing.assert_allclose([1.0,np.pi,np.nan],
... [1, np.sqrt(np.pi)**2, np.nan],
... rtol=1e-10, atol=0)
As mentioned in the Notes section, `assert_array_equal` has special
handling for scalars. Here the test checks that each value in `x` is 3:
>>> x = np.full((2, 5), fill_value=3)
>>> np.testing.assert_array_equal(x, 3)
Use `strict` to raise an AssertionError when comparing a scalar with an
array:
>>> np.testing.assert_array_equal(x, 3, strict=True)
Traceback (most recent call last):
...
AssertionError:
Arrays are not equal
<BLANKLINE>
(shapes (2, 5), () mismatch)
ACTUAL: array([[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3]])
DESIRED: array(3)
The `strict` parameter also ensures that the array data types match:
>>> x = np.array([2, 2, 2])
>>> y = np.array([2., 2., 2.], dtype=np.float32)
>>> np.testing.assert_array_equal(x, y, strict=True)
Traceback (most recent call last):
...
AssertionError:
Arrays are not equal
<BLANKLINE>
(dtypes int64, float32 mismatch)
ACTUAL: array([2, 2, 2])
DESIRED: array([2., 2., 2.], dtype=float32)
"""
__tracebackhide__ = True # Hide traceback for py.test
assert_array_compare(operator.__eq__, actual, desired, err_msg=err_msg,
verbose=verbose, header='Arrays are not equal',
strict=strict)
def assert_array_almost_equal(actual, desired, decimal=6, err_msg='',
verbose=True):
"""
Raises an AssertionError if two objects are not equal up to desired
precision.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
comparisons.
The test verifies identical shapes and that the elements of ``actual`` and
``desired`` satisfy::
abs(desired-actual) < 1.5 * 10**(-decimal)
That is a looser test than originally documented, but agrees with what the
actual implementation did up to rounding vagaries. An exception is raised
at shape mismatch or conflicting values. In contrast to the standard usage
in numpy, NaNs are compared like numbers, no assertion is raised if both
objects have NaNs in the same positions.
Parameters
----------
actual : array_like
The actual object to check.
desired : array_like
The desired, expected object.
decimal : int, optional
Desired precision, default is 6.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
Raises
------
AssertionError
If actual and desired are not equal up to specified precision.
See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
Examples
--------
the first assert does not raise an exception
>>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan],
... [1.0,2.333,np.nan])
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
... [1.0,2.33339,np.nan], decimal=5)
Traceback (most recent call last):
...
AssertionError:
Arrays are not almost equal to 5 decimals
<BLANKLINE>
Mismatched elements: 1 / 3 (33.3%)
Mismatch at index:
[1]: 2.33333 (ACTUAL), 2.33339 (DESIRED)
Max absolute difference among violations: 6.e-05
Max relative difference among violations: 2.57136612e-05
ACTUAL: array([1. , 2.33333, nan])
DESIRED: array([1. , 2.33339, nan])
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
... [1.0,2.33333, 5], decimal=5)
Traceback (most recent call last):
...
AssertionError:
Arrays are not almost equal to 5 decimals
<BLANKLINE>
nan location mismatch:
ACTUAL: array([1. , 2.33333, nan])
DESIRED: array([1. , 2.33333, 5. ])
"""
__tracebackhide__ = True # Hide traceback for py.test
from numpy._core import number, result_type
from numpy._core.numerictypes import issubdtype
def compare(x, y):
# make sure y is an inexact type to avoid abs(MIN_INT); will cause
# casting of x later.
dtype = result_type(y, 1.)
y = np.asanyarray(y, dtype)
z = abs(x - y)
if not issubdtype(z.dtype, number):
z = z.astype(np.float64) # handle object arrays
return z < 1.5 * 10.0**(-decimal)
assert_array_compare(compare, actual, desired, err_msg=err_msg,
verbose=verbose,
header=('Arrays are not almost equal to %d decimals' % decimal),
precision=decimal)
def assert_array_less(x, y, err_msg='', verbose=True, *, strict=False):
"""
Raises an AssertionError if two array_like objects are not ordered by less
than.
Given two array_like objects `x` and `y`, check that the shape is equal and
all elements of `x` are strictly less than the corresponding elements of
`y` (but see the Notes for the special handling of a scalar). An exception
is raised at shape mismatch or values that are not correctly ordered. In
contrast to the standard usage in NumPy, no assertion is raised if both
objects have NaNs in the same positions.
Parameters
----------
x : array_like
The smaller object to check.
y : array_like
The larger object to compare.
err_msg : string
The error message to be printed in case of failure.
verbose : bool
If True, the conflicting values are appended to the error message.
strict : bool, optional
If True, raise an AssertionError when either the shape or the data
type of the array_like objects does not match. The special
handling for scalars mentioned in the Notes section is disabled.
.. versionadded:: 2.0.0
Raises
------
AssertionError
If x is not strictly smaller than y, element-wise.
See Also
--------
assert_array_equal: tests objects for equality
assert_array_almost_equal: test objects for equality up to precision
Notes
-----
When one of `x` and `y` is a scalar and the other is array_like, the
function performs the comparison as though the scalar were broadcasted
to the shape of the array. This behaviour can be disabled with the `strict`
parameter.
Examples
--------
The following assertion passes because each finite element of `x` is
strictly less than the corresponding element of `y`, and the NaNs are in
corresponding locations.
>>> x = [1.0, 1.0, np.nan]
>>> y = [1.1, 2.0, np.nan]
>>> np.testing.assert_array_less(x, y)
The following assertion fails because the zeroth element of `x` is no
longer strictly less than the zeroth element of `y`.
>>> y[0] = 1
>>> np.testing.assert_array_less(x, y)
Traceback (most recent call last):
...
AssertionError:
Arrays are not strictly ordered `x < y`
<BLANKLINE>
Mismatched elements: 1 / 3 (33.3%)
Mismatch at index:
[0]: 1.0 (x), 1.0 (y)
Max absolute difference among violations: 0.
Max relative difference among violations: 0.
x: array([ 1., 1., nan])
y: array([ 1., 2., nan])
Here, `y` is a scalar, so each element of `x` is compared to `y`, and
the assertion passes.
>>> x = [1.0, 4.0]
>>> y = 5.0
>>> np.testing.assert_array_less(x, y)
However, with ``strict=True``, the assertion will fail because the shapes
do not match.
>>> np.testing.assert_array_less(x, y, strict=True)
Traceback (most recent call last):
...
AssertionError:
Arrays are not strictly ordered `x < y`
<BLANKLINE>
(shapes (2,), () mismatch)
x: array([1., 4.])
y: array(5.)
With ``strict=True``, the assertion also fails if the dtypes of the two
arrays do not match.
>>> y = [5, 5]
>>> np.testing.assert_array_less(x, y, strict=True)
Traceback (most recent call last):
...
AssertionError:
Arrays are not strictly ordered `x < y`
<BLANKLINE>
(dtypes float64, int64 mismatch)
x: array([1., 4.])
y: array([5, 5])
"""
__tracebackhide__ = True # Hide traceback for py.test
assert_array_compare(operator.__lt__, x, y, err_msg=err_msg,
verbose=verbose,
header='Arrays are not strictly ordered `x < y`',
equal_inf=False,
strict=strict,
names=('x', 'y'))
def runstring(astr, dict):
exec(astr, dict)
def assert_string_equal(actual, desired):
"""
Test if two strings are equal.
If the given strings are equal, `assert_string_equal` does nothing.
If they are not equal, an AssertionError is raised, and the diff
between the strings is shown.
Parameters
----------
actual : str
The string to test for equality against the expected string.
desired : str
The expected string.
Examples
--------
>>> np.testing.assert_string_equal('abc', 'abc')
>>> np.testing.assert_string_equal('abc', 'abcd')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...
AssertionError: Differences in strings:
- abc+ abcd? +
"""
# delay import of difflib to reduce startup time
__tracebackhide__ = True # Hide traceback for py.test
import difflib
if not isinstance(actual, str):
raise AssertionError(repr(type(actual)))
if not isinstance(desired, str):
raise AssertionError(repr(type(desired)))
if desired == actual:
return
diff = list(difflib.Differ().compare(actual.splitlines(True),
desired.splitlines(True)))
diff_list = []
while diff:
d1 = diff.pop(0)
if d1.startswith(' '):
continue
if d1.startswith('- '):
l = [d1]
d2 = diff.pop(0)
if d2.startswith('? '):
l.append(d2)
d2 = diff.pop(0)
if not d2.startswith('+ '):
raise AssertionError(repr(d2))
l.append(d2)
if diff:
d3 = diff.pop(0)
if d3.startswith('? '):
l.append(d3)
else:
diff.insert(0, d3)
if d2[2:] == d1[2:]:
continue
diff_list.extend(l)
continue
raise AssertionError(repr(d1))
if not diff_list:
return
msg = f"Differences in strings:\n{''.join(diff_list).rstrip()}"
if actual != desired:
raise AssertionError(msg)
def rundocs(filename=None, raise_on_error=True):
"""
Run doctests found in the given file.
By default `rundocs` raises an AssertionError on failure.
Parameters
----------
filename : str
The path to the file for which the doctests are run.
raise_on_error : bool
Whether to raise an AssertionError when a doctest fails. Default is
True.
Notes
-----
The doctests can be run by the user/developer by adding the ``doctests``
argument to the ``test()`` call. For example, to run all tests (including
doctests) for ``numpy.lib``:
>>> np.lib.test(doctests=True) # doctest: +SKIP
"""
import doctest
if filename is None:
f = sys._getframe(1)
filename = f.f_globals['__file__']
name = os.path.splitext(os.path.basename(filename))[0]
spec = importlib.util.spec_from_file_location(name, filename)
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
tests = doctest.DocTestFinder().find(m)
runner = doctest.DocTestRunner(verbose=False)
msg = []
if raise_on_error:
out = msg.append
else:
out = None
for test in tests:
runner.run(test, out=out)
if runner.failures > 0 and raise_on_error:
raise AssertionError("Some doctests failed:\n%s" % "\n".join(msg))
def check_support_sve(__cache=[]):
"""
gh-22982
"""
if __cache:
return __cache[0]
import subprocess
cmd = 'lscpu'
try:
output = subprocess.run(cmd, capture_output=True, text=True)
result = 'sve' in output.stdout
except (OSError, subprocess.SubprocessError):
result = False
__cache.append(result)
return __cache[0]
#
# assert_raises and assert_raises_regex are taken from unittest.
#
import unittest
class _Dummy(unittest.TestCase):
def nop(self):
pass
_d = _Dummy('nop')
def assert_raises(*args, **kwargs):
"""
assert_raises(exception_class, callable, *args, **kwargs)
assert_raises(exception_class)
Fail unless an exception of class exception_class is thrown
by callable when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
thrown, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
Alternatively, `assert_raises` can be used as a context manager:
>>> from numpy.testing import assert_raises
>>> with assert_raises(ZeroDivisionError):
... 1 / 0
is equivalent to
>>> def div(x, y):
... return x / y
>>> assert_raises(ZeroDivisionError, div, 1, 0)
"""
__tracebackhide__ = True # Hide traceback for py.test
return _d.assertRaises(*args, **kwargs)
def assert_raises_regex(exception_class, expected_regexp, *args, **kwargs):
"""
assert_raises_regex(exception_class, expected_regexp, callable, *args,
**kwargs)
assert_raises_regex(exception_class, expected_regexp)
Fail unless an exception of class exception_class and with message that
matches expected_regexp is thrown by callable when invoked with arguments
args and keyword arguments kwargs.
Alternatively, can be used as a context manager like `assert_raises`.
"""
__tracebackhide__ = True # Hide traceback for py.test
return _d.assertRaisesRegex(exception_class, expected_regexp, *args, **kwargs)
def decorate_methods(cls, decorator, testmatch=None):
"""
Apply a decorator to all methods in a class matching a regular expression.
The given decorator is applied to all public methods of `cls` that are
matched by the regular expression `testmatch`
(``testmatch.search(methodname)``). Methods that are private, i.e. start
with an underscore, are ignored.
Parameters
----------
cls : class
Class whose methods to decorate.
decorator : function
Decorator to apply to methods
testmatch : compiled regexp or str, optional
The regular expression. Default value is None, in which case the
nose default (``re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)``)
is used.
If `testmatch` is a string, it is compiled to a regular expression
first.
"""
if testmatch is None:
testmatch = re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)
else:
testmatch = re.compile(testmatch)
cls_attr = cls.__dict__
# delayed import to reduce startup time
from inspect import isfunction
methods = [_m for _m in cls_attr.values() if isfunction(_m)]
for function in methods:
try:
if hasattr(function, 'compat_func_name'):
funcname = function.compat_func_name
else:
funcname = function.__name__
except AttributeError:
# not a function
continue
if testmatch.search(funcname) and not funcname.startswith('_'):
setattr(cls, funcname, decorator(function))
def measure(code_str, times=1, label=None):
"""
Return elapsed time for executing code in the namespace of the caller.
The supplied code string is compiled with the Python builtin ``compile``.
The precision of the timing is 10 milli-seconds. If the code will execute
fast on this timescale, it can be executed many times to get reasonable
timing accuracy.
Parameters
----------
code_str : str
The code to be timed.
times : int, optional
The number of times the code is executed. Default is 1. The code is
only compiled once.
label : str, optional
A label to identify `code_str` with. This is passed into ``compile``
as the second argument (for run-time error messages).
Returns
-------
elapsed : float
Total elapsed time in seconds for executing `code_str` `times` times.
Examples
--------
>>> times = 10
>>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times)
>>> print("Time for a single execution : ", etime / times, "s") # doctest: +SKIP
Time for a single execution : 0.005 s
"""
frame = sys._getframe(1)
locs, globs = frame.f_locals, frame.f_globals
code = compile(code_str, f'Test name: {label} ', 'exec')
i = 0
elapsed = jiffies()
while i < times:
i += 1
exec(code, globs, locs)
elapsed = jiffies() - elapsed
return 0.01 * elapsed
def _assert_valid_refcount(op):
"""
Check that ufuncs don't mishandle refcount of object `1`.
Used in a few regression tests.
"""
if not HAS_REFCOUNT:
return True
import gc
import numpy as np
b = np.arange(100 * 100).reshape(100, 100)
c = b
i = 1
gc.disable()
try:
rc = sys.getrefcount(i)
for j in range(15):
d = op(b, c)
assert_(sys.getrefcount(i) >= rc)
finally:
gc.enable()
def assert_allclose(actual, desired, rtol=1e-7, atol=0, equal_nan=True,
err_msg='', verbose=True, *, strict=False):
"""
Raises an AssertionError if two objects are not equal up to desired
tolerance.
Given two array_like objects, check that their shapes and all elements
are equal (but see the Notes for the special handling of a scalar). An
exception is raised if the shapes mismatch or any values conflict. In
contrast to the standard usage in numpy, NaNs are compared like numbers,
no assertion is raised if both objects have NaNs in the same positions.
The test is equivalent to ``allclose(actual, desired, rtol, atol)``,
except that it is stricter: it doesn't broadcast its operands, and has
tighter default tolerance values. It compares the difference between
`actual` and `desired` to ``atol + rtol * abs(desired)``.
Parameters
----------
actual : array_like
Array obtained.
desired : array_like
Array desired.
rtol : float, optional
Relative tolerance.
atol : float | np.timedelta64, optional
Absolute tolerance.
equal_nan : bool, optional.
If True, NaNs will compare equal.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
strict : bool, optional
If True, raise an ``AssertionError`` when either the shape or the data
type of the arguments does not match. The special handling of scalars
mentioned in the Notes section is disabled.
.. versionadded:: 2.0.0
Raises
------
AssertionError
If actual and desired are not equal up to specified precision.
See Also
--------
assert_array_almost_equal_nulp, assert_array_max_ulp
Notes
-----
When one of `actual` and `desired` is a scalar and the other is array_like, the
function performs the comparison as if the scalar were broadcasted to the shape
of the array. Note that empty arrays are therefore considered equal to scalars.
This behaviour can be disabled by setting ``strict==True``.
Examples
--------
>>> x = [1e-5, 1e-3, 1e-1]
>>> y = np.arccos(np.cos(x))
>>> np.testing.assert_allclose(x, y, rtol=1e-5, atol=0)
As mentioned in the Notes section, `assert_allclose` has special
handling for scalars. Here, the test checks that the value of `numpy.sin`
is nearly zero at integer multiples of π.
>>> x = np.arange(3) * np.pi
>>> np.testing.assert_allclose(np.sin(x), 0, atol=1e-15)
Use `strict` to raise an ``AssertionError`` when comparing an array
with one or more dimensions against a scalar.
>>> np.testing.assert_allclose(np.sin(x), 0, atol=1e-15, strict=True)
Traceback (most recent call last):
...
AssertionError:
Not equal to tolerance rtol=1e-07, atol=1e-15
<BLANKLINE>
(shapes (3,), () mismatch)
ACTUAL: array([ 0.000000e+00, 1.224647e-16, -2.449294e-16])
DESIRED: array(0)
The `strict` parameter also ensures that the array data types match:
>>> y = np.zeros(3, dtype=np.float32)
>>> np.testing.assert_allclose(np.sin(x), y, atol=1e-15, strict=True)
Traceback (most recent call last):
...
AssertionError:
Not equal to tolerance rtol=1e-07, atol=1e-15
<BLANKLINE>
(dtypes float64, float32 mismatch)
ACTUAL: array([ 0.000000e+00, 1.224647e-16, -2.449294e-16])
DESIRED: array([0., 0., 0.], dtype=float32)
"""
__tracebackhide__ = True # Hide traceback for py.test
import numpy as np
def compare(x, y):
return np._core.numeric.isclose(x, y, rtol=rtol, atol=atol,
equal_nan=equal_nan)
actual, desired = np.asanyarray(actual), np.asanyarray(desired)
if isinstance(atol, np.timedelta64):
atol_str = str(atol)
else:
atol_str = f"{atol:g}"
header = f'Not equal to tolerance rtol={rtol:g}, atol={atol_str}'
assert_array_compare(compare, actual, desired, err_msg=str(err_msg),
verbose=verbose, header=header, equal_nan=equal_nan,
strict=strict)
def assert_array_almost_equal_nulp(x, y, nulp=1):
"""
Compare two arrays relatively to their spacing.
This is a relatively robust method to compare two arrays whose amplitude
is variable.
Parameters
----------
x, y : array_like
Input arrays.
nulp : int, optional
The maximum number of unit in the last place for tolerance (see Notes).
Default is 1.
Returns
-------
None
Raises
------
AssertionError
If the spacing between `x` and `y` for one or more elements is larger
than `nulp`.
See Also
--------
assert_array_max_ulp : Check that all items of arrays differ in at most
N Units in the Last Place.
spacing : Return the distance between x and the nearest adjacent number.
Notes
-----
An assertion is raised if the following condition is not met::
abs(x - y) <= nulp * spacing(maximum(abs(x), abs(y)))
Examples
--------
>>> x = np.array([1., 1e-10, 1e-20])
>>> eps = np.finfo(x.dtype).eps
>>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)
>>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
Traceback (most recent call last):
...
AssertionError: Arrays are not equal to 1 ULP (max is 2)
"""
__tracebackhide__ = True # Hide traceback for py.test
import numpy as np
ax = np.abs(x)
ay = np.abs(y)
ref = nulp * np.spacing(np.where(ax > ay, ax, ay))
if not np.all(np.abs(x - y) <= ref):
if np.iscomplexobj(x) or np.iscomplexobj(y):
msg = f"Arrays are not equal to {nulp} ULP"
else:
max_nulp = np.max(nulp_diff(x, y))
msg = f"Arrays are not equal to {nulp} ULP (max is {max_nulp:g})"
raise AssertionError(msg)
def assert_array_max_ulp(a, b, maxulp=1, dtype=None):
"""
Check that all items of arrays differ in at most N Units in the Last Place.
Parameters
----------
a, b : array_like
Input arrays to be compared.
maxulp : int, optional
The maximum number of units in the last place that elements of `a` and
`b` can differ. Default is 1.
dtype : dtype, optional
Data-type to convert `a` and `b` to if given. Default is None.
Returns
-------
ret : ndarray
Array containing number of representable floating point numbers between
items in `a` and `b`.
Raises
------
AssertionError
If one or more elements differ by more than `maxulp`.
Notes
-----
For computing the ULP difference, this API does not differentiate between
various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000
is zero).
See Also
--------
assert_array_almost_equal_nulp : Compare two arrays relatively to their
spacing.
Examples
--------
>>> a = np.linspace(0., 1., 100)
>>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a)))
"""
__tracebackhide__ = True # Hide traceback for py.test
import numpy as np
ret = nulp_diff(a, b, dtype)
if not np.all(ret <= maxulp):
raise AssertionError("Arrays are not almost equal up to %g "
"ULP (max difference is %g ULP)" %
(maxulp, np.max(ret)))
return ret
def nulp_diff(x, y, dtype=None):
"""For each item in x and y, return the number of representable floating
points between them.
Parameters
----------
x : array_like
first input array
y : array_like
second input array
dtype : dtype, optional
Data-type to convert `x` and `y` to if given. Default is None.
Returns
-------
nulp : array_like
number of representable floating point numbers between each item in x
and y.
Notes
-----
For computing the ULP difference, this API does not differentiate between
various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000
is zero).
Examples
--------
# By definition, epsilon is the smallest number such as 1 + eps != 1, so
# there should be exactly one ULP between 1 and 1 + eps
>>> nulp_diff(1, 1 + np.finfo(x.dtype).eps)
1.0
"""
import numpy as np
if dtype:
x = np.asarray(x, dtype=dtype)
y = np.asarray(y, dtype=dtype)
else:
x = np.asarray(x)
y = np.asarray(y)
t = np.common_type(x, y)
if np.iscomplexobj(x) or np.iscomplexobj(y):
raise NotImplementedError("_nulp not implemented for complex array")
x = np.array([x], dtype=t)
y = np.array([y], dtype=t)
x[np.isnan(x)] = np.nan
y[np.isnan(y)] = np.nan
if not x.shape == y.shape:
raise ValueError(f"Arrays do not have the same shape: {x.shape} - {y.shape}")
def _diff(rx, ry, vdt):
diff = np.asarray(rx - ry, dtype=vdt)
return np.abs(diff)
rx = integer_repr(x)
ry = integer_repr(y)
return _diff(rx, ry, t)
def _integer_repr(x, vdt, comp):
# Reinterpret binary representation of the float as sign-magnitude:
# take into account two-complement representation
# See also
# https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
rx = x.view(vdt)
if not (rx.size == 1):
rx[rx < 0] = comp - rx[rx < 0]
elif rx < 0:
rx = comp - rx
return rx
def integer_repr(x):
"""Return the signed-magnitude interpretation of the binary representation
of x."""
import numpy as np
if x.dtype == np.float16:
return _integer_repr(x, np.int16, np.int16(-2**15))
elif x.dtype == np.float32:
return _integer_repr(x, np.int32, np.int32(-2**31))
elif x.dtype == np.float64:
return _integer_repr(x, np.int64, np.int64(-2**63))
else:
raise ValueError(f'Unsupported dtype {x.dtype}')
@contextlib.contextmanager
def _assert_warns_context(warning_class, name=None):
__tracebackhide__ = True # Hide traceback for py.test
with suppress_warnings(_warn=False) as sup:
l = sup.record(warning_class)
yield
if not len(l) > 0:
name_str = f' when calling {name}' if name is not None else ''
raise AssertionError("No warning raised" + name_str)
def assert_warns(warning_class, *args, **kwargs):
"""
Fail unless the given callable throws the specified warning.
A warning of class warning_class should be thrown by the callable when
invoked with arguments args and keyword arguments kwargs.
If a different type of warning is thrown, it will not be caught.
If called with all arguments other than the warning class omitted, may be
used as a context manager::
with assert_warns(SomeWarning):
do_something()
The ability to be used as a context manager is new in NumPy v1.11.0.
.. deprecated:: 2.4
This is deprecated. Use `warnings.catch_warnings` or
``pytest.warns`` instead.
Parameters
----------
warning_class : class
The class defining the warning that `func` is expected to throw.
func : callable, optional
Callable to test
*args : Arguments
Arguments for `func`.
**kwargs : Kwargs
Keyword arguments for `func`.
Returns
-------
The value returned by `func`.
Examples
--------
>>> import warnings
>>> def deprecated_func(num):
... warnings.warn("Please upgrade", DeprecationWarning)
... return num*num
>>> with np.testing.assert_warns(DeprecationWarning):
... assert deprecated_func(4) == 16
>>> # or passing a func
>>> ret = np.testing.assert_warns(DeprecationWarning, deprecated_func, 4)
>>> assert ret == 16
"""
warnings.warn(
"NumPy warning suppression and assertion utilities are deprecated. "
"Use warnings.catch_warnings, warnings.filterwarnings, pytest.warns, "
"or pytest.filterwarnings instead. (Deprecated NumPy 2.4)",
DeprecationWarning, stacklevel=2)
if not args and not kwargs:
return _assert_warns_context(warning_class)
elif len(args) < 1:
if "match" in kwargs:
raise RuntimeError(
"assert_warns does not use 'match' kwarg, "
"use pytest.warns instead"
)
raise RuntimeError("assert_warns(...) needs at least one arg")
func = args[0]
args = args[1:]
with _assert_warns_context(warning_class, name=func.__name__):
return func(*args, **kwargs)
@contextlib.contextmanager
def _assert_no_warnings_context(name=None):
__tracebackhide__ = True # Hide traceback for py.test
with warnings.catch_warnings(record=True) as l:
warnings.simplefilter('always')
yield
if len(l) > 0:
name_str = f' when calling {name}' if name is not None else ''
raise AssertionError(f'Got warnings{name_str}: {l}')
def assert_no_warnings(*args, **kwargs):
"""
Fail if the given callable produces any warnings.
If called with all arguments omitted, may be used as a context manager::
with assert_no_warnings():
do_something()
The ability to be used as a context manager is new in NumPy v1.11.0.
Parameters
----------
func : callable
The callable to test.
\\*args : Arguments
Arguments passed to `func`.
\\*\\*kwargs : Kwargs
Keyword arguments passed to `func`.
Returns
-------
The value returned by `func`.
"""
if not args:
return _assert_no_warnings_context()
func = args[0]
args = args[1:]
with _assert_no_warnings_context(name=func.__name__):
return func(*args, **kwargs)
def _gen_alignment_data(dtype=float32, type='binary', max_size=24):
"""
generator producing data with different alignment and offsets
to test simd vectorization
Parameters
----------
dtype : dtype
data type to produce
type : string
'unary': create data for unary operations, creates one input
and output array
'binary': create data for unary operations, creates two input
and output array
max_size : integer
maximum size of data to produce
Returns
-------
if type is 'unary' yields one output, one input array and a message
containing information on the data
if type is 'binary' yields one output array, two input array and a message
containing information on the data
"""
ufmt = 'unary offset=(%d, %d), size=%d, dtype=%r, %s'
bfmt = 'binary offset=(%d, %d, %d), size=%d, dtype=%r, %s'
for o in range(3):
for s in range(o + 2, max(o + 3, max_size)):
if type == 'unary':
inp = lambda: arange(s, dtype=dtype)[o:]
out = empty((s,), dtype=dtype)[o:]
yield out, inp(), ufmt % (o, o, s, dtype, 'out of place')
d = inp()
yield d, d, ufmt % (o, o, s, dtype, 'in place')
yield out[1:], inp()[:-1], ufmt % \
(o + 1, o, s - 1, dtype, 'out of place')
yield out[:-1], inp()[1:], ufmt % \
(o, o + 1, s - 1, dtype, 'out of place')
yield inp()[:-1], inp()[1:], ufmt % \
(o, o + 1, s - 1, dtype, 'aliased')
yield inp()[1:], inp()[:-1], ufmt % \
(o + 1, o, s - 1, dtype, 'aliased')
if type == 'binary':
inp1 = lambda: arange(s, dtype=dtype)[o:]
inp2 = lambda: arange(s, dtype=dtype)[o:]
out = empty((s,), dtype=dtype)[o:]
yield out, inp1(), inp2(), bfmt % \
(o, o, o, s, dtype, 'out of place')
d = inp1()
yield d, d, inp2(), bfmt % \
(o, o, o, s, dtype, 'in place1')
d = inp2()
yield d, inp1(), d, bfmt % \
(o, o, o, s, dtype, 'in place2')
yield out[1:], inp1()[:-1], inp2()[:-1], bfmt % \
(o + 1, o, o, s - 1, dtype, 'out of place')
yield out[:-1], inp1()[1:], inp2()[:-1], bfmt % \
(o, o + 1, o, s - 1, dtype, 'out of place')
yield out[:-1], inp1()[:-1], inp2()[1:], bfmt % \
(o, o, o + 1, s - 1, dtype, 'out of place')
yield inp1()[1:], inp1()[:-1], inp2()[:-1], bfmt % \
(o + 1, o, o, s - 1, dtype, 'aliased')
yield inp1()[:-1], inp1()[1:], inp2()[:-1], bfmt % \
(o, o + 1, o, s - 1, dtype, 'aliased')
yield inp1()[:-1], inp1()[:-1], inp2()[1:], bfmt % \
(o, o, o + 1, s - 1, dtype, 'aliased')
class IgnoreException(Exception):
"Ignoring this exception due to disabled feature"
pass
@contextlib.contextmanager
def tempdir(*args, **kwargs):
"""Context manager to provide a temporary test folder.
All arguments are passed as this to the underlying tempfile.mkdtemp
function.
"""
tmpdir = mkdtemp(*args, **kwargs)
try:
yield tmpdir
finally:
shutil.rmtree(tmpdir)
@contextlib.contextmanager
def temppath(*args, **kwargs):
"""Context manager for temporary files.
Context manager that returns the path to a closed temporary file. Its
parameters are the same as for tempfile.mkstemp and are passed directly
to that function. The underlying file is removed when the context is
exited, so it should be closed at that time.
Windows does not allow a temporary file to be opened if it is already
open, so the underlying file must be closed after opening before it
can be opened again.
"""
fd, path = mkstemp(*args, **kwargs)
os.close(fd)
try:
yield path
finally:
os.remove(path)
class clear_and_catch_warnings(warnings.catch_warnings):
""" Context manager that resets warning registry for catching warnings
Warnings can be slippery, because, whenever a warning is triggered, Python
adds a ``__warningregistry__`` member to the *calling* module. This makes
it impossible to retrigger the warning in this module, whatever you put in
the warnings filters. This context manager accepts a sequence of `modules`
as a keyword argument to its constructor and:
* stores and removes any ``__warningregistry__`` entries in given `modules`
on entry;
* resets ``__warningregistry__`` to its previous state on exit.
This makes it possible to trigger any warning afresh inside the context
manager without disturbing the state of warnings outside.
For compatibility with Python, please consider all arguments to be
keyword-only.
Parameters
----------
record : bool, optional
Specifies whether warnings should be captured by a custom
implementation of ``warnings.showwarning()`` and be appended to a list
returned by the context manager. Otherwise None is returned by the
context manager. The objects appended to the list are arguments whose
attributes mirror the arguments to ``showwarning()``.
modules : sequence, optional
Sequence of modules for which to reset warnings registry on entry and
restore on exit. To work correctly, all 'ignore' filters should
filter by one of these modules.
Examples
--------
>>> import warnings
>>> with np.testing.clear_and_catch_warnings(
... modules=[np._core.fromnumeric]):
... warnings.simplefilter('always')
... warnings.filterwarnings('ignore', module='np._core.fromnumeric')
... # do something that raises a warning but ignore those in
... # np._core.fromnumeric
"""
class_modules = ()
def __init__(self, record=False, modules=()):
self.modules = set(modules).union(self.class_modules)
self._warnreg_copies = {}
super().__init__(record=record)
def __enter__(self):
for mod in self.modules:
if hasattr(mod, '__warningregistry__'):
mod_reg = mod.__warningregistry__
self._warnreg_copies[mod] = mod_reg.copy()
mod_reg.clear()
return super().__enter__()
def __exit__(self, *exc_info):
super().__exit__(*exc_info)
for mod in self.modules:
if hasattr(mod, '__warningregistry__'):
mod.__warningregistry__.clear()
if mod in self._warnreg_copies:
mod.__warningregistry__.update(self._warnreg_copies[mod])
class suppress_warnings:
"""
Context manager and decorator doing much the same as
``warnings.catch_warnings``.
However, it also provides a filter mechanism to work around
https://bugs.python.org/issue4180.
This bug causes Python before 3.4 to not reliably show warnings again
after they have been ignored once (even within catch_warnings). It
means that no "ignore" filter can be used easily, since following
tests might need to see the warning. Additionally it allows easier
specificity for testing warnings and can be nested.
.. deprecated:: 2.4
This is deprecated. Use `warnings.filterwarnings` or
``pytest.filterwarnings`` instead.
Parameters
----------
forwarding_rule : str, optional
One of "always", "once", "module", or "location". Analogous to
the usual warnings module filter mode, it is useful to reduce
noise mostly on the outmost level. Unsuppressed and unrecorded
warnings will be forwarded based on this rule. Defaults to "always".
"location" is equivalent to the warnings "default", match by exact
location the warning warning originated from.
Notes
-----
Filters added inside the context manager will be discarded again
when leaving it. Upon entering all filters defined outside a
context will be applied automatically.
When a recording filter is added, matching warnings are stored in the
``log`` attribute as well as in the list returned by ``record``.
If filters are added and the ``module`` keyword is given, the
warning registry of this module will additionally be cleared when
applying it, entering the context, or exiting it. This could cause
warnings to appear a second time after leaving the context if they
were configured to be printed once (default) and were already
printed before the context was entered.
Nesting this context manager will work as expected when the
forwarding rule is "always" (default). Unfiltered and unrecorded
warnings will be passed out and be matched by the outer level.
On the outmost level they will be printed (or caught by another
warnings context). The forwarding rule argument can modify this
behaviour.
Like ``catch_warnings`` this context manager is not threadsafe.
Examples
--------
With a context manager::
with np.testing.suppress_warnings() as sup:
sup.filter(DeprecationWarning, "Some text")
sup.filter(module=np.ma.core)
log = sup.record(FutureWarning, "Does this occur?")
command_giving_warnings()
# The FutureWarning was given once, the filtered warnings were
# ignored. All other warnings abide outside settings (may be
# printed/error)
assert_(len(log) == 1)
assert_(len(sup.log) == 1) # also stored in log attribute
Or as a decorator::
sup = np.testing.suppress_warnings()
sup.filter(module=np.ma.core) # module must match exactly
@sup
def some_function():
# do something which causes a warning in np.ma.core
pass
"""
def __init__(self, forwarding_rule="always", _warn=True):
if _warn:
warnings.warn(
"NumPy warning suppression and assertion utilities are deprecated. "
"Use warnings.catch_warnings, warnings.filterwarnings, pytest.warns, "
"or pytest.filterwarnings instead. (Deprecated NumPy 2.4)",
DeprecationWarning, stacklevel=2)
self._entered = False
# Suppressions are either instance or defined inside one with block:
self._suppressions = []
if forwarding_rule not in {"always", "module", "once", "location"}:
raise ValueError("unsupported forwarding rule.")
self._forwarding_rule = forwarding_rule
def _clear_registries(self):
if hasattr(warnings, "_filters_mutated"):
# clearing the registry should not be necessary on new pythons,
# instead the filters should be mutated.
warnings._filters_mutated()
return
# Simply clear the registry, this should normally be harmless,
# note that on new pythons it would be invalidated anyway.
for module in self._tmp_modules:
if hasattr(module, "__warningregistry__"):
module.__warningregistry__.clear()
def _filter(self, category=Warning, message="", module=None, record=False):
if record:
record = [] # The log where to store warnings
else:
record = None
if self._entered:
if module is None:
warnings.filterwarnings(
"always", category=category, message=message)
else:
module_regex = module.__name__.replace('.', r'\.') + '$'
warnings.filterwarnings(
"always", category=category, message=message,
module=module_regex)
self._tmp_modules.add(module)
self._clear_registries()
self._tmp_suppressions.append(
(category, message, re.compile(message, re.I), module, record))
else:
self._suppressions.append(
(category, message, re.compile(message, re.I), module, record))
return record
def filter(self, category=Warning, message="", module=None):
"""
Add a new suppressing filter or apply it if the state is entered.
Parameters
----------
category : class, optional
Warning class to filter
message : string, optional
Regular expression matching the warning message.
module : module, optional
Module to filter for. Note that the module (and its file)
must match exactly and cannot be a submodule. This may make
it unreliable for external modules.
Notes
-----
When added within a context, filters are only added inside
the context and will be forgotten when the context is exited.
"""
self._filter(category=category, message=message, module=module,
record=False)
def record(self, category=Warning, message="", module=None):
"""
Append a new recording filter or apply it if the state is entered.
All warnings matching will be appended to the ``log`` attribute.
Parameters
----------
category : class, optional
Warning class to filter
message : string, optional
Regular expression matching the warning message.
module : module, optional
Module to filter for. Note that the module (and its file)
must match exactly and cannot be a submodule. This may make
it unreliable for external modules.
Returns
-------
log : list
A list which will be filled with all matched warnings.
Notes
-----
When added within a context, filters are only added inside
the context and will be forgotten when the context is exited.
"""
return self._filter(category=category, message=message, module=module,
record=True)
def __enter__(self):
if self._entered:
raise RuntimeError("cannot enter suppress_warnings twice.")
self._orig_show = warnings.showwarning
self._filters = warnings.filters
warnings.filters = self._filters[:]
self._entered = True
self._tmp_suppressions = []
self._tmp_modules = set()
self._forwarded = set()
self.log = [] # reset global log (no need to keep same list)
for cat, mess, _, mod, log in self._suppressions:
if log is not None:
del log[:] # clear the log
if mod is None:
warnings.filterwarnings(
"always", category=cat, message=mess)
else:
module_regex = mod.__name__.replace('.', r'\.') + '$'
warnings.filterwarnings(
"always", category=cat, message=mess,
module=module_regex)
self._tmp_modules.add(mod)
warnings.showwarning = self._showwarning
self._clear_registries()
return self
def __exit__(self, *exc_info):
warnings.showwarning = self._orig_show
warnings.filters = self._filters
self._clear_registries()
self._entered = False
del self._orig_show
del self._filters
def _showwarning(self, message, category, filename, lineno,
*args, use_warnmsg=None, **kwargs):
for cat, _, pattern, mod, rec in (
self._suppressions + self._tmp_suppressions)[::-1]:
if (issubclass(category, cat) and
pattern.match(message.args[0]) is not None):
if mod is None:
# Message and category match, either recorded or ignored
if rec is not None:
msg = WarningMessage(message, category, filename,
lineno, **kwargs)
self.log.append(msg)
rec.append(msg)
return
# Use startswith, because warnings strips the c or o from
# .pyc/.pyo files.
elif mod.__file__.startswith(filename):
# The message and module (filename) match
if rec is not None:
msg = WarningMessage(message, category, filename,
lineno, **kwargs)
self.log.append(msg)
rec.append(msg)
return
# There is no filter in place, so pass to the outside handler
# unless we should only pass it once
if self._forwarding_rule == "always":
if use_warnmsg is None:
self._orig_show(message, category, filename, lineno,
*args, **kwargs)
else:
self._orig_showmsg(use_warnmsg)
return
if self._forwarding_rule == "once":
signature = (message.args, category)
elif self._forwarding_rule == "module":
signature = (message.args, category, filename)
elif self._forwarding_rule == "location":
signature = (message.args, category, filename, lineno)
if signature in self._forwarded:
return
self._forwarded.add(signature)
if use_warnmsg is None:
self._orig_show(message, category, filename, lineno, *args,
**kwargs)
else:
self._orig_showmsg(use_warnmsg)
def __call__(self, func):
"""
Function decorator to apply certain suppressions to a whole
function.
"""
@wraps(func)
def new_func(*args, **kwargs):
with self:
return func(*args, **kwargs)
return new_func
@contextlib.contextmanager
def _assert_no_gc_cycles_context(name=None):
__tracebackhide__ = True # Hide traceback for py.test
# not meaningful to test if there is no refcounting
if not HAS_REFCOUNT:
yield
return
assert_(gc.isenabled())
gc.disable()
gc_debug = gc.get_debug()
try:
for i in range(100):
if gc.collect() == 0:
break
else:
raise RuntimeError(
"Unable to fully collect garbage - perhaps a __del__ method "
"is creating more reference cycles?")
gc.set_debug(gc.DEBUG_SAVEALL)
yield
# gc.collect returns the number of unreachable objects in cycles that
# were found -- we are checking that no cycles were created in the context
n_objects_in_cycles = gc.collect()
objects_in_cycles = gc.garbage[:]
finally:
del gc.garbage[:]
gc.set_debug(gc_debug)
gc.enable()
if n_objects_in_cycles:
name_str = f' when calling {name}' if name is not None else ''
raise AssertionError(
"Reference cycles were found{}: {} objects were collected, "
"of which {} are shown below:{}"
.format(
name_str,
n_objects_in_cycles,
len(objects_in_cycles),
''.join(
"\n {} object with id={}:\n {}".format(
type(o).__name__,
id(o),
pprint.pformat(o).replace('\n', '\n ')
) for o in objects_in_cycles
)
)
)
def assert_no_gc_cycles(*args, **kwargs):
"""
Fail if the given callable produces any reference cycles.
If called with all arguments omitted, may be used as a context manager::
with assert_no_gc_cycles():
do_something()
Parameters
----------
func : callable
The callable to test.
\\*args : Arguments
Arguments passed to `func`.
\\*\\*kwargs : Kwargs
Keyword arguments passed to `func`.
Returns
-------
Nothing. The result is deliberately discarded to ensure that all cycles
are found.
"""
if not args:
return _assert_no_gc_cycles_context()
func = args[0]
args = args[1:]
with _assert_no_gc_cycles_context(name=func.__name__):
func(*args, **kwargs)
def break_cycles():
"""
Break reference cycles by calling gc.collect
Objects can call other objects' methods (for instance, another object's
__del__) inside their own __del__. On PyPy, the interpreter only runs
between calls to gc.collect, so multiple calls are needed to completely
release all cycles.
"""
gc.collect()
if IS_PYPY:
# a few more, just to make sure all the finalizers are called
gc.collect()
gc.collect()
gc.collect()
gc.collect()
def requires_memory(free_bytes):
"""Decorator to skip a test if not enough memory is available"""
import pytest
def decorator(func):
@wraps(func)
def wrapper(*a, **kw):
msg = check_free_memory(free_bytes)
if msg is not None:
pytest.skip(msg)
try:
return func(*a, **kw)
except MemoryError:
# Probably ran out of memory regardless: don't regard as failure
pytest.xfail("MemoryError raised")
return wrapper
return decorator
def check_free_memory(free_bytes):
"""
Check whether `free_bytes` amount of memory is currently free.
Returns: None if enough memory available, otherwise error message
"""
env_var = 'NPY_AVAILABLE_MEM'
env_value = os.environ.get(env_var)
if env_value is not None:
try:
mem_free = _parse_size(env_value)
except ValueError as exc:
raise ValueError(f'Invalid environment variable {env_var}: {exc}')
msg = (f'{free_bytes / 1e9} GB memory required, but environment variable '
f'NPY_AVAILABLE_MEM={env_value} set')
else:
mem_free = _get_mem_available()
if mem_free is None:
msg = ("Could not determine available memory; set NPY_AVAILABLE_MEM "
"environment variable (e.g. NPY_AVAILABLE_MEM=16GB) to run "
"the test.")
mem_free = -1
else:
free_bytes_gb = free_bytes / 1e9
mem_free_gb = mem_free / 1e9
msg = f'{free_bytes_gb} GB memory required, but {mem_free_gb} GB available'
return msg if mem_free < free_bytes else None
def _parse_size(size_str):
"""Convert memory size strings ('12 GB' etc.) to float"""
suffixes = {'': 1, 'b': 1,
'k': 1000, 'm': 1000**2, 'g': 1000**3, 't': 1000**4,
'kb': 1000, 'mb': 1000**2, 'gb': 1000**3, 'tb': 1000**4,
'kib': 1024, 'mib': 1024**2, 'gib': 1024**3, 'tib': 1024**4}
pipe_suffixes = "|".join(suffixes.keys())
size_re = re.compile(fr'^\s*(\d+|\d+\.\d+)\s*({pipe_suffixes})\s*$', re.I)
m = size_re.match(size_str.lower())
if not m or m.group(2) not in suffixes:
raise ValueError(f'value {size_str!r} not a valid size')
return int(float(m.group(1)) * suffixes[m.group(2)])
def _get_mem_available():
"""Return available memory in bytes, or None if unknown."""
try:
import psutil
return psutil.virtual_memory().available
except (ImportError, AttributeError):
pass
if sys.platform.startswith('linux'):
info = {}
with open('/proc/meminfo') as f:
for line in f:
p = line.split()
info[p[0].strip(':').lower()] = int(p[1]) * 1024
if 'memavailable' in info:
# Linux >= 3.14
return info['memavailable']
else:
return info['memfree'] + info['cached']
return None
def _no_tracing(func):
"""
Decorator to temporarily turn off tracing for the duration of a test.
Needed in tests that check refcounting, otherwise the tracing itself
influences the refcounts
"""
if not hasattr(sys, 'gettrace'):
return func
else:
@wraps(func)
def wrapper(*args, **kwargs):
original_trace = sys.gettrace()
try:
sys.settrace(None)
return func(*args, **kwargs)
finally:
sys.settrace(original_trace)
return wrapper
def _get_glibc_version():
try:
ver = os.confstr('CS_GNU_LIBC_VERSION').rsplit(' ')[1]
except Exception:
ver = '0.0'
return ver
_glibcver = _get_glibc_version()
_glibc_older_than = lambda x: (_glibcver != '0.0' and _glibcver < x)
def run_threaded(func, max_workers=8, pass_count=False,
pass_barrier=False, outer_iterations=1,
prepare_args=None):
"""Runs a function many times in parallel"""
for _ in range(outer_iterations):
with (concurrent.futures.ThreadPoolExecutor(max_workers=max_workers)
as tpe):
if prepare_args is None:
args = []
else:
args = prepare_args()
if pass_barrier:
barrier = threading.Barrier(max_workers)
args.append(barrier)
if pass_count:
all_args = [(func, i, *args) for i in range(max_workers)]
else:
all_args = [(func, *args) for i in range(max_workers)]
try:
futures = []
for arg in all_args:
futures.append(tpe.submit(*arg))
except RuntimeError as e:
import pytest
pytest.skip(f"Spawning {max_workers} threads failed with "
f"error {e!r} (likely due to resource limits on the "
"system running the tests)")
finally:
if len(futures) < max_workers and pass_barrier:
barrier.abort()
for f in futures:
f.result()
def requires_deep_recursion(func):
"""Decorator to skip test if deep recursion is not supported."""
import pytest
@wraps(func)
def wrapper(*args, **kwargs):
if IS_PYSTON:
pytest.skip("Pyston disables recursion checking")
if IS_WASM:
pytest.skip("WASM has limited stack size")
if not IS_64BIT:
pytest.skip("32 bit Python has limited stack size")
cflags = sysconfig.get_config_var('CFLAGS') or ''
config_args = sysconfig.get_config_var('CONFIG_ARGS') or ''
address_sanitizer = (
'-fsanitize=address' in cflags or
'--with-address-sanitizer' in config_args
)
thread_sanitizer = (
'-fsanitize=thread' in cflags or
'--with-thread-sanitizer' in config_args
)
if address_sanitizer or thread_sanitizer:
pytest.skip("AddressSanitizer and ThreadSanitizer do not support "
"deep recursion")
return func(*args, **kwargs)
return wrapper
| """
Utility function to facilitate testing.
"""
import concurrent.futures
import contextlib
import gc
import importlib.metadata
import importlib.util
import operator
import os
import pathlib
import platform
import pprint
import re
import shutil
import sys
import sysconfig
import threading
import warnings
from functools import partial, wraps
from io import StringIO
from tempfile import mkdtemp, mkstemp
from unittest.case import SkipTest
from warnings import WarningMessage
import numpy as np
import numpy.linalg._umath_linalg
from numpy import isfinite, isnan
from numpy._core import arange, array, array_repr, empty, float32, intp, isnat, ndarray
__all__ = [
'assert_equal', 'assert_almost_equal', 'assert_approx_equal',
'assert_array_equal', 'assert_array_less', 'assert_string_equal',
'assert_array_almost_equal', 'assert_raises', 'build_err_msg',
'decorate_methods', 'jiffies', 'memusage', 'print_assert_equal',
'rundocs', 'runstring', 'verbose', 'measure',
'assert_', 'assert_array_almost_equal_nulp', 'assert_raises_regex',
'assert_array_max_ulp', 'assert_warns', 'assert_no_warnings',
'assert_allclose', 'IgnoreException', 'clear_and_catch_warnings',
'SkipTest', 'KnownFailureException', 'temppath', 'tempdir', 'IS_PYPY',
'HAS_REFCOUNT', "IS_WASM", 'suppress_warnings', 'assert_array_compare',
'assert_no_ | [
"# numpy/numpy:numpy/_core/arrayprint.py\narray_repr",
"# numpy/numpy:numpy/_core/records.py\narray",
"# numpy/numpy:numpy/matlib.py\nempty"
] | numpy/numpy | numpy/testing/_private/utils.py |
"""
Build a c-extension module on-the-fly in tests.
See build_and_import_extensions for usage hints
"""
import os
import pathlib
import subprocess
import sys
import sysconfig
import textwrap
__all__ = ['build_and_import_extension', 'compile_extension_module']
def build_and_import_extension(
modname, functions, *, prologue="", build_dir=None,
include_dirs=None, more_init=""):
"""
Build and imports a c-extension module `modname` from a list of function
fragments `functions`.
Parameters
----------
functions : list of fragments
Each fragment is a sequence of func_name, calling convention, snippet.
prologue : string
Code to precede the rest, usually extra ``#include`` or ``#define``
macros.
build_dir : pathlib.Path
Where to build the module, usually a temporary directory
include_dirs : list
Extra directories to find include files when compiling
more_init : string
Code to appear in the module PyMODINIT_FUNC
Returns
-------
out: module
The module will have been loaded and is ready for use
Examples
--------
>>> functions = [("test_bytes", "METH_O", \"\"\"
if ( !PyBytesCheck(args)) {
Py_RETURN_FALSE;
}
Py_RETURN_TRUE;
\"\"\")]
>>> mod = build_and_import_extension("testme", functions)
>>> assert not mod.test_bytes('abc')
>>> assert mod.test_bytes(b'abc')
"""
if include_dirs is None:
include_dirs = []
body = prologue + _make_methods(functions, modname)
init = """
PyObject *mod = PyModule_Create(&moduledef);
#ifdef Py_GIL_DISABLED
PyUnstable_Module_SetGIL(mod, Py_MOD_GIL_NOT_USED);
#endif
"""
if not build_dir:
build_dir = pathlib.Path('.')
if more_init:
init += """#define INITERROR return NULL
"""
init += more_init
init += "\nreturn mod;"
source_string = _make_source(modname, init, body)
mod_so = compile_extension_module(
modname, build_dir, include_dirs, source_string)
import importlib.util
spec = importlib.util.spec_from_file_location(modname, mod_so)
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
return foo
def compile_extension_module(
name, builddir, include_dirs,
source_string, libraries=None, library_dirs=None):
"""
Build an extension module and return the filename of the resulting
native code file.
Parameters
----------
name : string
name of the module, possibly including dots if it is a module inside a
package.
builddir : pathlib.Path
Where to build the module, usually a temporary directory
include_dirs : list
Extra directories to find include files when compiling
libraries : list
Libraries to link into the extension module
library_dirs: list
Where to find the libraries, ``-L`` passed to the linker
"""
modname = name.split('.')[-1]
dirname = builddir / name
dirname.mkdir(exist_ok=True)
cfile = _convert_str_to_file(source_string, dirname)
include_dirs = include_dirs or []
libraries = libraries or []
library_dirs = library_dirs or []
return _c_compile(
cfile, outputfilename=dirname / modname,
include_dirs=include_dirs, libraries=libraries,
library_dirs=library_dirs,
)
def _convert_str_to_file(source, dirname):
"""Helper function to create a file ``source.c`` in `dirname` that contains
the string in `source`. Returns the file name
"""
filename = dirname / 'source.c'
with filename.open('w') as f:
f.write(str(source))
return filename
def _make_methods(functions, modname):
""" Turns the name, signature, code in functions into complete functions
and lists them in a methods_table. Then turns the methods_table into a
``PyMethodDef`` structure and returns the resulting code fragment ready
for compilation
"""
methods_table = []
codes = []
for funcname, flags, code in functions:
cfuncname = f"{modname}_{funcname}"
if 'METH_KEYWORDS' in flags:
signature = '(PyObject *self, PyObject *args, PyObject *kwargs)'
else:
signature = '(PyObject *self, PyObject *args)'
methods_table.append(
"{\"%s\", (PyCFunction)%s, %s}," % (funcname, cfuncname, flags))
func_code = f"""
static PyObject* {cfuncname}{signature}
{{
{code}
}}
"""
codes.append(func_code)
body = "\n".join(codes) + """
static PyMethodDef methods[] = {
%(methods)s
{ NULL }
};
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"%(modname)s", /* m_name */
NULL, /* m_doc */
-1, /* m_size */
methods, /* m_methods */
};
""" % {'methods': '\n'.join(methods_table), 'modname': modname}
return body
def _make_source(name, init, body):
""" Combines the code fragments into source code ready to be compiled
"""
code = """
#include <Python.h>
%(body)s
PyMODINIT_FUNC
PyInit_%(name)s(void) {
%(init)s
}
""" % {
'name': name, 'init': init, 'body': body,
}
return code
def _c_compile(cfile, outputfilename, include_dirs, libraries,
library_dirs):
link_extra = []
if sys.platform == 'win32':
compile_extra = ["/we4013"]
link_extra.append('/DEBUG') # generate .pdb file
elif sys.platform.startswith('linux'):
compile_extra = [
"-O0", "-g", "-Werror=implicit-function-declaration", "-fPIC"]
else:
compile_extra = []
return build(
cfile, outputfilename,
compile_extra, link_extra,
include_dirs, libraries, library_dirs)
def build(cfile, outputfilename, compile_extra, link_extra,
include_dirs, libraries, library_dirs):
"use meson to build"
build_dir = cfile.parent / "build"
os.makedirs(build_dir, exist_ok=True)
with open(cfile.parent / "meson.build", "wt") as fid:
link_dirs = ['-L' + d for d in library_dirs]
fid.write(textwrap.dedent(f"""\
project('foo', 'c')
py = import('python').find_installation(pure: false)
py.extension_module(
'{outputfilename.parts[-1]}',
'{cfile.parts[-1]}',
c_args: {compile_extra},
link_args: {link_dirs},
include_directories: {include_dirs},
)
"""))
native_file_name = cfile.parent / ".mesonpy-native-file.ini"
with open(native_file_name, "wt") as fid:
fid.write(textwrap.dedent(f"""\
[binaries]
python = '{sys.executable}'
"""))
if sys.platform == "win32":
subprocess.check_call(["meson", "setup",
"--buildtype=release",
"--vsenv", ".."],
cwd=build_dir,
)
else:
subprocess.check_call(["meson", "setup", "--vsenv",
"..", f'--native-file={os.fspath(native_file_name)}'],
cwd=build_dir
)
so_name = outputfilename.parts[-1] + get_so_suffix()
subprocess.check_call(["meson", "compile"], cwd=build_dir)
os.rename(str(build_dir / so_name), cfile.parent / so_name)
return cfile.parent / so_name
def get_so_suffix():
ret = sysconfig.get_config_var('EXT_SUFFIX')
assert ret
return ret
| """
Build a c-extension module on-the-fly in tests.
See build_and_import_extensions for usage hints
"""
import os
import pathlib
import subprocess
import sys
import sysconfig
import textwrap
__all__ = ['build_and_import_extension', 'compile_extension_module']
def build_and_import_extension(
modname, functions, *, prologue="", build_dir=None,
include_dirs=None, more_init=""):
"""
Build and imports a c-extension module `modname` from a list of function
fragments `functions`.
Parameters
----------
functions : list of fragments
Each fragment is a sequence of func_name, calling convention, snippet.
prologue : string
Code to precede the rest, usually extra ``#include`` or ``#define``
macros.
build_dir : pathlib.Path
Where to build the module, usually a temporary directory
include_dirs : list
Extra directories to find include files when compiling
more_init : string
Code to appear in the module PyMODINIT_FUNC
Returns
-------
out: module
The module will have been loaded and is ready for use
Examples
--------
>>> functions = [("test_bytes", "METH_O", \"\"\"
if ( !PyBytesCheck(args)) {
Py_RETURN_FALSE;
}
Py_RETURN_TRUE;
\"\"\")]
>>> mod = build_and_import_extension("testme", functions)
| [] | numpy/numpy | numpy/testing/_private/extbuild.py |
"""Common test support for all numpy test scripts.
This single module should provide all the common functionality for numpy tests
in a single location, so that test scripts can just import it and work right
away.
"""
from unittest import TestCase
from . import _private, overrides
from ._private import extbuild
from ._private.utils import *
from ._private.utils import _assert_valid_refcount, _gen_alignment_data
__all__ = (
_private.utils.__all__ + ['TestCase', 'overrides']
)
from numpy._pytesttester import PytestTester
test = PytestTester(__name__)
del PytestTester
| """Common test support for all numpy test scripts.
This single module should provide all the common functionality for numpy tests
in a single location, so that test scripts can just import it and work right
away.
"""
from unittest import TestCase
from . import _private, overrides
from ._private import extbuild
from ._private.utils import *
from ._private.utils import _assert_valid_refcount, _gen_alignment_data
__all__ = (
_private.utils.__all__ + ['TestCase', 'overrides']
)
from numpy._pytesttester import PytestTester
test = PytestTester(__name__)
del PytestTester
| [
"# numpy/numpy:numpy/_pytesttester.py\nPytestTester"
] | numpy/numpy | numpy/testing/__init__.py |
from numpy._core.strings import *
from numpy._core.strings import __all__, __doc__
| from numpy._core.strings import *
from numpy._core.strings import __all__, __doc__
| [] | numpy/numpy | numpy/strings/__init__.py |
from numpy._core.records import *
from numpy._core.records import __all__, __doc__
| from numpy._core.records import *
from numpy._core.records import __all__, __doc__
| [] | numpy/numpy | numpy/rec/__init__.py |
import pickle
from dataclasses import dataclass
from functools import partial
import pytest
import numpy as np
from numpy.random import MT19937, PCG64, PCG64DXSM, SFC64, Generator, Philox
from numpy.testing import assert_, assert_array_equal, assert_equal
DTYPES_BOOL_INT_UINT = (np.bool, np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64)
def params_0(f):
val = f()
assert_(np.isscalar(val))
val = f(10)
assert_(val.shape == (10,))
val = f((10, 10))
assert_(val.shape == (10, 10))
val = f((10, 10, 10))
assert_(val.shape == (10, 10, 10))
val = f(size=(5, 5))
assert_(val.shape == (5, 5))
def params_1(f, bounded=False):
a = 5.0
b = np.arange(2.0, 12.0)
c = np.arange(2.0, 102.0).reshape((10, 10))
d = np.arange(2.0, 1002.0).reshape((10, 10, 10))
e = np.array([2.0, 3.0])
g = np.arange(2.0, 12.0).reshape((1, 10, 1))
if bounded:
a = 0.5
b = b / (1.5 * b.max())
c = c / (1.5 * c.max())
d = d / (1.5 * d.max())
e = e / (1.5 * e.max())
g = g / (1.5 * g.max())
# Scalar
f(a)
# Scalar - size
f(a, size=(10, 10))
# 1d
f(b)
# 2d
f(c)
# 3d
f(d)
# 1d size
f(b, size=10)
# 2d - size - broadcast
f(e, size=(10, 2))
# 3d - size
f(g, size=(10, 10, 10))
def comp_state(state1, state2):
identical = True
if isinstance(state1, dict):
for key in state1:
identical &= comp_state(state1[key], state2[key])
elif type(state1) is not type(state2):
identical &= type(state1) is type(state2)
elif (isinstance(state1, (list, tuple, np.ndarray)) and isinstance(
state2, (list, tuple, np.ndarray))):
for s1, s2 in zip(state1, state2):
identical &= comp_state(s1, s2)
else:
identical &= state1 == state2
return identical
def warmup(rg, n=None):
if n is None:
n = 11 + np.random.randint(0, 20)
rg.standard_normal(n)
rg.standard_normal(n)
rg.standard_normal(n, dtype=np.float32)
rg.standard_normal(n, dtype=np.float32)
rg.integers(0, 2 ** 24, n, dtype=np.uint64)
rg.integers(0, 2 ** 48, n, dtype=np.uint64)
rg.standard_gamma(11.0, n)
rg.standard_gamma(11.0, n, dtype=np.float32)
rg.random(n, dtype=np.float64)
rg.random(n, dtype=np.float32)
@dataclass
class RNGData:
bit_generator: type[np.random.BitGenerator]
advance: int
seed: list[int]
rg: Generator
seed_vector_bits: int
class RNG:
@classmethod
def _create_rng(cls):
# Overridden in test classes. Place holder to silence IDE noise
bit_generator = PCG64
advance = None
seed = [12345]
rg = Generator(bit_generator(*seed))
seed_vector_bits = 64
return RNGData(bit_generator, advance, seed, rg, seed_vector_bits)
def test_init(self):
data = self._create_rng()
data.rg = Generator(data.bit_generator())
state = data.rg.bit_generator.state
data.rg.standard_normal(1)
data.rg.standard_normal(1)
data.rg.bit_generator.state = state
new_state = data.rg.bit_generator.state
assert_(comp_state(state, new_state))
def test_advance(self):
data = self._create_rng()
state = data.rg.bit_generator.state
if hasattr(data.rg.bit_generator, 'advance'):
data.rg.bit_generator.advance(data.advance)
assert_(not comp_state(state, data.rg.bit_generator.state))
else:
bitgen_name = data.rg.bit_generator.__class__.__name__
pytest.skip(f'Advance is not supported by {bitgen_name}')
def test_jump(self):
rg = self._create_rng().rg
state = rg.bit_generator.state
if hasattr(rg.bit_generator, 'jumped'):
bit_gen2 = rg.bit_generator.jumped()
jumped_state = bit_gen2.state
assert_(not comp_state(state, jumped_state))
rg.random(2 * 3 * 5 * 7 * 11 * 13 * 17)
rg.bit_generator.state = state
bit_gen3 = rg.bit_generator.jumped()
rejumped_state = bit_gen3.state
assert_(comp_state(jumped_state, rejumped_state))
else:
bitgen_name = rg.bit_generator.__class__.__name__
if bitgen_name not in ('SFC64',):
raise AttributeError(f'no "jumped" in {bitgen_name}')
pytest.skip(f'Jump is not supported by {bitgen_name}')
def test_uniform(self):
rg = self._create_rng().rg
r = rg.uniform(-1.0, 0.0, size=10)
assert_(len(r) == 10)
assert_((r > -1).all())
assert_((r <= 0).all())
def test_uniform_array(self):
rg = self._create_rng().rg
r = rg.uniform(np.array([-1.0] * 10), 0.0, size=10)
assert_(len(r) == 10)
assert_((r > -1).all())
assert_((r <= 0).all())
r = rg.uniform(np.array([-1.0] * 10),
np.array([0.0] * 10), size=10)
assert_(len(r) == 10)
assert_((r > -1).all())
assert_((r <= 0).all())
r = rg.uniform(-1.0, np.array([0.0] * 10), size=10)
assert_(len(r) == 10)
assert_((r > -1).all())
assert_((r <= 0).all())
def test_random(self):
rg = self._create_rng().rg
assert_(len(rg.random(10)) == 10)
params_0(rg.random)
def test_standard_normal_zig(self):
rg = self._create_rng().rg
assert_(len(rg.standard_normal(10)) == 10)
def test_standard_normal(self):
rg = self._create_rng().rg
assert_(len(rg.standard_normal(10)) == 10)
params_0(rg.standard_normal)
def test_standard_gamma(self):
rg = self._create_rng().rg
assert_(len(rg.standard_gamma(10, 10)) == 10)
assert_(len(rg.standard_gamma(np.array([10] * 10), 10)) == 10)
params_1(rg.standard_gamma)
def test_standard_exponential(self):
rg = self._create_rng().rg
assert_(len(rg.standard_exponential(10)) == 10)
params_0(rg.standard_exponential)
def test_standard_exponential_float(self):
rg = self._create_rng().rg
randoms = rg.standard_exponential(10, dtype='float32')
assert_(len(randoms) == 10)
assert randoms.dtype == np.float32
params_0(partial(rg.standard_exponential, dtype='float32'))
def test_standard_exponential_float_log(self):
rg = self._create_rng().rg
randoms = rg.standard_exponential(10, dtype='float32',
method='inv')
assert_(len(randoms) == 10)
assert randoms.dtype == np.float32
params_0(partial(rg.standard_exponential, dtype='float32',
method='inv'))
def test_standard_cauchy(self):
rg = self._create_rng().rg
assert_(len(rg.standard_cauchy(10)) == 10)
params_0(rg.standard_cauchy)
def test_standard_t(self):
rg = self._create_rng().rg
assert_(len(rg.standard_t(10, 10)) == 10)
params_1(rg.standard_t)
def test_binomial(self):
rg = self._create_rng().rg
assert_(rg.binomial(10, .5) >= 0)
assert_(rg.binomial(1000, .5) >= 0)
def test_reset_state(self):
rg = self._create_rng().rg
state = rg.bit_generator.state
int_1 = rg.integers(2**31)
rg.bit_generator.state = state
int_2 = rg.integers(2**31)
assert_(int_1 == int_2)
def test_entropy_init(self):
bit_generator = self._create_rng().bit_generator
rg = Generator(bit_generator())
rg2 = Generator(bit_generator())
assert_(not comp_state(rg.bit_generator.state,
rg2.bit_generator.state))
def test_seed(self):
data = self._create_rng()
rg = Generator(data.bit_generator(*data.seed))
rg2 = Generator(data.bit_generator(*data.seed))
rg.random()
rg2.random()
assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state))
def test_reset_state_gauss(self):
data = self._create_rng()
rg = Generator(data.bit_generator(*data.seed))
rg.standard_normal()
state = rg.bit_generator.state
n1 = rg.standard_normal(size=10)
rg2 = Generator(data.bit_generator())
rg2.bit_generator.state = state
n2 = rg2.standard_normal(size=10)
assert_array_equal(n1, n2)
def test_reset_state_uint32(self):
data = self._create_rng()
rg = Generator(data.bit_generator(*data.seed))
rg.integers(0, 2 ** 24, 120, dtype=np.uint32)
state = rg.bit_generator.state
n1 = rg.integers(0, 2 ** 24, 10, dtype=np.uint32)
rg2 = Generator(data.bit_generator())
rg2.bit_generator.state = state
n2 = rg2.integers(0, 2 ** 24, 10, dtype=np.uint32)
assert_array_equal(n1, n2)
def test_reset_state_float(self):
data = self._create_rng()
rg = Generator(data.bit_generator(*data.seed))
rg.random(dtype='float32')
state = rg.bit_generator.state
n1 = rg.random(size=10, dtype='float32')
rg2 = Generator(data.bit_generator())
rg2.bit_generator.state = state
n2 = rg2.random(size=10, dtype='float32')
assert_((n1 == n2).all())
def test_shuffle(self):
rg = self._create_rng().rg
original = np.arange(200, 0, -1)
permuted = rg.permutation(original)
assert_((original != permuted).any())
def test_permutation(self):
rg = self._create_rng().rg
original = np.arange(200, 0, -1)
permuted = rg.permutation(original)
assert_((original != permuted).any())
def test_beta(self):
rg = self._create_rng().rg
vals = rg.beta(2.0, 2.0, 10)
assert_(len(vals) == 10)
vals = rg.beta(np.array([2.0] * 10), 2.0)
assert_(len(vals) == 10)
vals = rg.beta(2.0, np.array([2.0] * 10))
assert_(len(vals) == 10)
vals = rg.beta(np.array([2.0] * 10), np.array([2.0] * 10))
assert_(len(vals) == 10)
vals = rg.beta(np.array([2.0] * 10), np.array([[2.0]] * 10))
assert_(vals.shape == (10, 10))
def test_bytes(self):
rg = self._create_rng().rg
vals = rg.bytes(10)
assert_(len(vals) == 10)
def test_chisquare(self):
rg = self._create_rng().rg
vals = rg.chisquare(2.0, 10)
assert_(len(vals) == 10)
params_1(rg.chisquare)
def test_exponential(self):
rg = self._create_rng().rg
vals = rg.exponential(2.0, 10)
assert_(len(vals) == 10)
params_1(rg.exponential)
def test_f(self):
rg = self._create_rng().rg
vals = rg.f(3, 1000, 10)
assert_(len(vals) == 10)
def test_gamma(self):
rg = self._create_rng().rg
vals = rg.gamma(3, 2, 10)
assert_(len(vals) == 10)
def test_geometric(self):
rg = self._create_rng().rg
vals = rg.geometric(0.5, 10)
assert_(len(vals) == 10)
params_1(rg.exponential, bounded=True)
def test_gumbel(self):
rg = self._create_rng().rg
vals = rg.gumbel(2.0, 2.0, 10)
assert_(len(vals) == 10)
def test_laplace(self):
rg = self._create_rng().rg
vals = rg.laplace(2.0, 2.0, 10)
assert_(len(vals) == 10)
def test_logitic(self):
rg = self._create_rng().rg
vals = rg.logistic(2.0, 2.0, 10)
assert_(len(vals) == 10)
def test_logseries(self):
rg = self._create_rng().rg
vals = rg.logseries(0.5, 10)
assert_(len(vals) == 10)
def test_negative_binomial(self):
rg = self._create_rng().rg
vals = rg.negative_binomial(10, 0.2, 10)
assert_(len(vals) == 10)
def test_noncentral_chisquare(self):
rg = self._create_rng().rg
vals = rg.noncentral_chisquare(10, 2, 10)
assert_(len(vals) == 10)
def test_noncentral_f(self):
rg = self._create_rng().rg
vals = rg.noncentral_f(3, 1000, 2, 10)
assert_(len(vals) == 10)
vals = rg.noncentral_f(np.array([3] * 10), 1000, 2)
assert_(len(vals) == 10)
vals = rg.noncentral_f(3, np.array([1000] * 10), 2)
assert_(len(vals) == 10)
vals = rg.noncentral_f(3, 1000, np.array([2] * 10))
assert_(len(vals) == 10)
def test_normal(self):
rg = self._create_rng().rg
vals = rg.normal(10, 0.2, 10)
assert_(len(vals) == 10)
def test_pareto(self):
rg = self._create_rng().rg
vals = rg.pareto(3.0, 10)
assert_(len(vals) == 10)
def test_poisson(self):
rg = self._create_rng().rg
vals = rg.poisson(10, 10)
assert_(len(vals) == 10)
vals = rg.poisson(np.array([10] * 10))
assert_(len(vals) == 10)
params_1(rg.poisson)
def test_power(self):
rg = self._create_rng().rg
vals = rg.power(0.2, 10)
assert_(len(vals) == 10)
def test_integers(self):
rg = self._create_rng().rg
vals = rg.integers(10, 20, 10)
assert_(len(vals) == 10)
def test_rayleigh(self):
rg = self._create_rng().rg
vals = rg.rayleigh(0.2, 10)
assert_(len(vals) == 10)
params_1(rg.rayleigh, bounded=True)
def test_vonmises(self):
rg = self._create_rng().rg
vals = rg.vonmises(10, 0.2, 10)
assert_(len(vals) == 10)
def test_wald(self):
rg = self._create_rng().rg
vals = rg.wald(1.0, 1.0, 10)
assert_(len(vals) == 10)
def test_weibull(self):
rg = self._create_rng().rg
vals = rg.weibull(1.0, 10)
assert_(len(vals) == 10)
def test_zipf(self):
rg = self._create_rng().rg
vec_1d = np.arange(2.0, 102.0)
vec_2d = np.arange(2.0, 102.0)[None, :]
mat = np.arange(2.0, 102.0, 0.01).reshape((100, 100))
vals = rg.zipf(10, 10)
assert_(len(vals) == 10)
vals = rg.zipf(vec_1d)
assert_(len(vals) == 100)
vals = rg.zipf(vec_2d)
assert_(vals.shape == (1, 100))
vals = rg.zipf(mat)
assert_(vals.shape == (100, 100))
def test_hypergeometric(self):
rg = self._create_rng().rg
vals = rg.hypergeometric(25, 25, 20)
assert_(np.isscalar(vals))
vals = rg.hypergeometric(np.array([25] * 10), 25, 20)
assert_(vals.shape == (10,))
def test_triangular(self):
rg = self._create_rng().rg
vals = rg.triangular(-5, 0, 5)
assert_(np.isscalar(vals))
vals = rg.triangular(-5, np.array([0] * 10), 5)
assert_(vals.shape == (10,))
def test_multivariate_normal(self):
rg = self._create_rng().rg
mean = [0, 0]
cov = [[1, 0], [0, 100]] # diagonal covariance
x = rg.multivariate_normal(mean, cov, 5000)
assert_(x.shape == (5000, 2))
x_zig = rg.multivariate_normal(mean, cov, 5000)
assert_(x.shape == (5000, 2))
x_inv = rg.multivariate_normal(mean, cov, 5000)
assert_(x.shape == (5000, 2))
assert_((x_zig != x_inv).any())
def test_multinomial(self):
rg = self._create_rng().rg
vals = rg.multinomial(100, [1.0 / 3, 2.0 / 3])
assert_(vals.shape == (2,))
vals = rg.multinomial(100, [1.0 / 3, 2.0 / 3], size=10)
assert_(vals.shape == (10, 2))
def test_dirichlet(self):
rg = self._create_rng().rg
s = rg.dirichlet((10, 5, 3), 20)
assert_(s.shape == (20, 3))
def test_pickle(self):
rg = self._create_rng().rg
pick = pickle.dumps(rg)
unpick = pickle.loads(pick)
assert_(type(rg) is type(unpick))
assert_(comp_state(rg.bit_generator.state,
unpick.bit_generator.state))
pick = pickle.dumps(rg)
unpick = pickle.loads(pick)
assert_(type(rg) is type(unpick))
assert_(comp_state(rg.bit_generator.state,
unpick.bit_generator.state))
def test_seed_array(self):
data = self._create_rng()
if data.seed_vector_bits is None:
bitgen_name = data.bit_generator.__name__
pytest.skip(f'Vector seeding is not supported by {bitgen_name}')
if data.seed_vector_bits == 32:
dtype = np.uint32
else:
dtype = np.uint64
seed = np.array([1], dtype=dtype)
bg = data.bit_generator(seed)
state1 = bg.state
bg = data.bit_generator(1)
state2 = bg.state
assert_(comp_state(state1, state2))
seed = np.arange(4, dtype=dtype)
bg = data.bit_generator(seed)
state1 = bg.state
bg = data.bit_generator(seed[0])
state2 = bg.state
assert_(not comp_state(state1, state2))
seed = np.arange(1500, dtype=dtype)
bg = data.bit_generator(seed)
state1 = bg.state
bg = data.bit_generator(seed[0])
state2 = bg.state
assert_(not comp_state(state1, state2))
seed = 2 ** np.mod(np.arange(1500, dtype=dtype),
data.seed_vector_bits - 1) + 1
bg = data.bit_generator(seed)
state1 = bg.state
bg = data.bit_generator(seed[0])
state2 = bg.state
assert_(not comp_state(state1, state2))
def test_uniform_float(self):
bit_generator = self._create_rng().bit_generator
rg = Generator(bit_generator(12345))
warmup(rg)
state = rg.bit_generator.state
r1 = rg.random(11, dtype=np.float32)
rg2 = Generator(bit_generator())
warmup(rg2)
rg2.bit_generator.state = state
r2 = rg2.random(11, dtype=np.float32)
assert_array_equal(r1, r2)
assert_equal(r1.dtype, np.float32)
assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state))
def test_gamma_floats(self):
bit_generator = self._create_rng().bit_generator
rg = Generator(bit_generator())
warmup(rg)
state = rg.bit_generator.state
r1 = rg.standard_gamma(4.0, 11, dtype=np.float32)
rg2 = Generator(bit_generator())
warmup(rg2)
rg2.bit_generator.state = state
r2 = rg2.standard_gamma(4.0, 11, dtype=np.float32)
assert_array_equal(r1, r2)
assert_equal(r1.dtype, np.float32)
assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state))
def test_normal_floats(self):
bit_generator = self._create_rng().bit_generator
rg = Generator(bit_generator())
warmup(rg)
state = rg.bit_generator.state
r1 = rg.standard_normal(11, dtype=np.float32)
rg2 = Generator(bit_generator())
warmup(rg2)
rg2.bit_generator.state = state
r2 = rg2.standard_normal(11, dtype=np.float32)
assert_array_equal(r1, r2)
assert_equal(r1.dtype, np.float32)
assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state))
def test_normal_zig_floats(self):
bit_generator = self._create_rng().bit_generator
rg = Generator(bit_generator())
warmup(rg)
state = rg.bit_generator.state
r1 = rg.standard_normal(11, dtype=np.float32)
rg2 = Generator(bit_generator())
warmup(rg2)
rg2.bit_generator.state = state
r2 = rg2.standard_normal(11, dtype=np.float32)
assert_array_equal(r1, r2)
assert_equal(r1.dtype, np.float32)
assert_(comp_state(rg.bit_generator.state, rg2.bit_generator.state))
def test_output_fill(self):
rg = self._create_rng().rg
state = rg.bit_generator.state
size = (31, 7, 97)
existing = np.empty(size)
rg.bit_generator.state = state
rg.standard_normal(out=existing)
rg.bit_generator.state = state
direct = rg.standard_normal(size=size)
assert_equal(direct, existing)
sized = np.empty(size)
rg.bit_generator.state = state
rg.standard_normal(out=sized, size=sized.shape)
existing = np.empty(size, dtype=np.float32)
rg.bit_generator.state = state
rg.standard_normal(out=existing, dtype=np.float32)
rg.bit_generator.state = state
direct = rg.standard_normal(size=size, dtype=np.float32)
assert_equal(direct, existing)
def test_output_filling_uniform(self):
rg = self._create_rng().rg
state = rg.bit_generator.state
size = (31, 7, 97)
existing = np.empty(size)
rg.bit_generator.state = state
rg.random(out=existing)
rg.bit_generator.state = state
direct = rg.random(size=size)
assert_equal(direct, existing)
existing = np.empty(size, dtype=np.float32)
rg.bit_generator.state = state
rg.random(out=existing, dtype=np.float32)
rg.bit_generator.state = state
direct = rg.random(size=size, dtype=np.float32)
assert_equal(direct, existing)
def test_output_filling_exponential(self):
rg = self._create_rng().rg
state = rg.bit_generator.state
size = (31, 7, 97)
existing = np.empty(size)
rg.bit_generator.state = state
rg.standard_exponential(out=existing)
rg.bit_generator.state = state
direct = rg.standard_exponential(size=size)
assert_equal(direct, existing)
existing = np.empty(size, dtype=np.float32)
rg.bit_generator.state = state
rg.standard_exponential(out=existing, dtype=np.float32)
rg.bit_generator.state = state
direct = rg.standard_exponential(size=size, dtype=np.float32)
assert_equal(direct, existing)
def test_output_filling_gamma(self):
rg = self._create_rng().rg
state = rg.bit_generator.state
size = (31, 7, 97)
existing = np.zeros(size)
rg.bit_generator.state = state
rg.standard_gamma(1.0, out=existing)
rg.bit_generator.state = state
direct = rg.standard_gamma(1.0, size=size)
assert_equal(direct, existing)
existing = np.zeros(size, dtype=np.float32)
rg.bit_generator.state = state
rg.standard_gamma(1.0, out=existing, dtype=np.float32)
rg.bit_generator.state = state
direct = rg.standard_gamma(1.0, size=size, dtype=np.float32)
assert_equal(direct, existing)
def test_output_filling_gamma_broadcast(self):
rg = self._create_rng().rg
state = rg.bit_generator.state
size = (31, 7, 97)
mu = np.arange(97.0) + 1.0
existing = np.zeros(size)
rg.bit_generator.state = state
rg.standard_gamma(mu, out=existing)
rg.bit_generator.state = state
direct = rg.standard_gamma(mu, size=size)
assert_equal(direct, existing)
existing = np.zeros(size, dtype=np.float32)
rg.bit_generator.state = state
rg.standard_gamma(mu, out=existing, dtype=np.float32)
rg.bit_generator.state = state
direct = rg.standard_gamma(mu, size=size, dtype=np.float32)
assert_equal(direct, existing)
def test_output_fill_error(self):
rg = self._create_rng().rg
size = (31, 7, 97)
existing = np.empty(size)
with pytest.raises(TypeError):
rg.standard_normal(out=existing, dtype=np.float32)
with pytest.raises(ValueError):
rg.standard_normal(out=existing[::3])
existing = np.empty(size, dtype=np.float32)
with pytest.raises(TypeError):
rg.standard_normal(out=existing, dtype=np.float64)
existing = np.zeros(size, dtype=np.float32)
with pytest.raises(TypeError):
rg.standard_gamma(1.0, out=existing, dtype=np.float64)
with pytest.raises(ValueError):
rg.standard_gamma(1.0, out=existing[::3], dtype=np.float32)
existing = np.zeros(size, dtype=np.float64)
with pytest.raises(TypeError):
rg.standard_gamma(1.0, out=existing, dtype=np.float32)
with pytest.raises(ValueError):
rg.standard_gamma(1.0, out=existing[::3])
@pytest.mark.parametrize("dtype", DTYPES_BOOL_INT_UINT)
def test_integers_broadcast(self, dtype):
rg = self._create_rng().rg
initial_state = rg.bit_generator.state
def reset_state(rng):
rng.bit_generator.state = initial_state
if dtype == np.bool:
upper = 2
lower = 0
else:
info = np.iinfo(dtype)
upper = int(info.max) + 1
lower = info.min
reset_state(rg)
rg.bit_generator.state = initial_state
a = rg.integers(lower, [upper] * 10, dtype=dtype)
reset_state(rg)
b = rg.integers([lower] * 10, upper, dtype=dtype)
assert_equal(a, b)
reset_state(rg)
c = rg.integers(lower, upper, size=10, dtype=dtype)
assert_equal(a, c)
reset_state(rg)
d = rg.integers(np.array(
[lower] * 10), np.array([upper], dtype=object), size=10,
dtype=dtype)
assert_equal(a, d)
reset_state(rg)
e = rg.integers(
np.array([lower] * 10), np.array([upper] * 10), size=10,
dtype=dtype)
assert_equal(a, e)
reset_state(rg)
a = rg.integers(0, upper, size=10, dtype=dtype)
reset_state(rg)
b = rg.integers([upper] * 10, dtype=dtype)
assert_equal(a, b)
@pytest.mark.parametrize("dtype", DTYPES_BOOL_INT_UINT)
def test_integers_numpy(self, dtype):
rg = self._create_rng().rg
high = np.array([1])
low = np.array([0])
out = rg.integers(low, high, dtype=dtype)
assert out.shape == (1,)
out = rg.integers(low[0], high, dtype=dtype)
assert out.shape == (1,)
out = rg.integers(low, high[0], dtype=dtype)
assert out.shape == (1,)
@pytest.mark.parametrize("dtype", DTYPES_BOOL_INT_UINT)
def test_integers_broadcast_errors(self, dtype):
rg = self._create_rng().rg
if dtype == np.bool:
upper = 2
lower = 0
else:
info = np.iinfo(dtype)
upper = int(info.max) + 1
lower = info.min
with pytest.raises(ValueError):
rg.integers(lower, [upper + 1] * 10, dtype=dtype)
with pytest.raises(ValueError):
rg.integers(lower - 1, [upper] * 10, dtype=dtype)
with pytest.raises(ValueError):
rg.integers([lower - 1], [upper] * 10, dtype=dtype)
with pytest.raises(ValueError):
rg.integers([0], [0], dtype=dtype)
class TestMT19937(RNG):
@classmethod
def _create_rng(cls):
bit_generator = MT19937
advance = None
seed = [2 ** 21 + 2 ** 16 + 2 ** 5 + 1]
rg = Generator(bit_generator(*seed))
seed_vector_bits = 32
return RNGData(bit_generator, advance, seed, rg, seed_vector_bits)
def test_numpy_state(self):
rg = self._create_rng().rg
nprg = np.random.RandomState()
nprg.standard_normal(99)
state = nprg.get_state()
rg.bit_generator.state = state
state2 = rg.bit_generator.state
assert_((state[1] == state2['state']['key']).all())
assert_(state[2] == state2['state']['pos'])
class TestPhilox(RNG):
@classmethod
def _create_rng(cls):
bit_generator = Philox
advance = 2**63 + 2**31 + 2**15 + 1
seed = [12345]
rg = Generator(bit_generator(*seed))
seed_vector_bits = 64
return RNGData(bit_generator, advance, seed, rg, seed_vector_bits)
class TestSFC64(RNG):
@classmethod
def _create_rng(cls):
bit_generator = SFC64
advance = None
seed = [12345]
rg = Generator(bit_generator(*seed))
seed_vector_bits = 192
return RNGData(bit_generator, advance, seed, rg, seed_vector_bits)
class TestPCG64(RNG):
@classmethod
def _create_rng(cls):
bit_generator = PCG64
advance = 2**63 + 2**31 + 2**15 + 1
seed = [12345]
rg = Generator(bit_generator(*seed))
seed_vector_bits = 64
return RNGData(bit_generator, advance, seed, rg, seed_vector_bits)
class TestPCG64DXSM(RNG):
@classmethod
def _create_rng(cls):
bit_generator = PCG64DXSM
advance = 2**63 + 2**31 + 2**15 + 1
seed = [12345]
rg = Generator(bit_generator(*seed))
seed_vector_bits = 64
return RNGData(bit_generator, advance, seed, rg, seed_vector_bits)
class TestDefaultRNG(RNG):
@classmethod
def _create_rng(cls):
# This will duplicate some tests that directly instantiate a fresh
# Generator(), but that's okay.
bit_generator = PCG64
advance = 2**63 + 2**31 + 2**15 + 1
seed = [12345]
rg = np.random.default_rng(*seed)
seed_vector_bits = 64
return RNGData(bit_generator, advance, seed, rg, seed_vector_bits)
def test_default_is_pcg64(self):
# In order to change the default BitGenerator, we'll go through
# a deprecation cycle to move to a different function.
rg = self._create_rng().rg
assert_(isinstance(rg.bit_generator, PCG64))
def test_seed(self):
np.random.default_rng()
np.random.default_rng(None)
np.random.default_rng(12345)
np.random.default_rng(0)
np.random.default_rng(43660444402423911716352051725018508569)
np.random.default_rng([43660444402423911716352051725018508569,
279705150948142787361475340226491943209])
with pytest.raises(ValueError):
np.random.default_rng(-1)
with pytest.raises(ValueError):
np.random.default_rng([12345, -1])
| import pickle
from dataclasses import dataclass
from functools import partial
import pytest
import numpy as np
from numpy.random import MT19937, PCG64, PCG64DXSM, SFC64, Generator, Philox
from numpy.testing import assert_, assert_array_equal, assert_equal
DTYPES_BOOL_INT_UINT = (np.bool, np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64)
def params_0(f):
val = f()
assert_(np.isscalar(val))
val = f(10)
assert_(val.shape == (10,))
val = f((10, 10))
assert_(val.shape == (10, 10))
val = f((10, 10, 10))
assert_(val.shape == (10, 10, 10))
val = f(size=(5, 5))
assert_(val.shape == (5, 5))
def params_1(f, bounded=False):
a = 5.0
b = np.arange(2.0, 12.0)
c = np.arange(2.0, 102.0).reshape((10, 10))
d = np.arange(2.0, 1002.0).reshape((10, 10, 10))
e = np.array([2.0, 3.0])
g = np.arange(2.0, 12.0).reshape((1, 10, 1))
if bounded:
a = 0.5
b = b / (1.5 * b.max())
c = c / (1.5 * c.max())
| [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_"
] | numpy/numpy | numpy/random/tests/test_smoke.py |
import numpy as np
from numpy.random import SeedSequence
from numpy.testing import assert_array_compare, assert_array_equal
def test_reference_data():
""" Check that SeedSequence generates data the same as the C++ reference.
https://gist.github.com/imneme/540829265469e673d045
"""
inputs = [
[3735928559, 195939070, 229505742, 305419896],
[3668361503, 4165561550, 1661411377, 3634257570],
[164546577, 4166754639, 1765190214, 1303880213],
[446610472, 3941463886, 522937693, 1882353782],
[1864922766, 1719732118, 3882010307, 1776744564],
[4141682960, 3310988675, 553637289, 902896340],
[1134851934, 2352871630, 3699409824, 2648159817],
[1240956131, 3107113773, 1283198141, 1924506131],
[2669565031, 579818610, 3042504477, 2774880435],
[2766103236, 2883057919, 4029656435, 862374500],
]
outputs = [
[3914649087, 576849849, 3593928901, 2229911004],
[2240804226, 3691353228, 1365957195, 2654016646],
[3562296087, 3191708229, 1147942216, 3726991905],
[1403443605, 3591372999, 1291086759, 441919183],
[1086200464, 2191331643, 560336446, 3658716651],
[3249937430, 2346751812, 847844327, 2996632307],
[2584285912, 4034195531, 3523502488, 169742686],
[959045797, 3875435559, 1886309314, 359682705],
[3978441347, 432478529, 3223635119, 138903045],
[296367413, 4262059219, 13109864, 3283683422],
]
outputs64 = [
[2477551240072187391, 9577394838764454085],
[15854241394484835714, 11398914698975566411],
[13708282465491374871, 16007308345579681096],
[15424829579845884309, 1898028439751125927],
[9411697742461147792, 15714068361935982142],
[10079222287618677782, 12870437757549876199],
[17326737873898640088, 729039288628699544],
[16644868984619524261, 1544825456798124994],
[1857481142255628931, 596584038813451439],
[18305404959516669237, 14103312907920476776],
]
for seed, expected, expected64 in zip(inputs, outputs, outputs64):
expected = np.array(expected, dtype=np.uint32)
ss = SeedSequence(seed)
state = ss.generate_state(len(expected))
assert_array_equal(state, expected)
state64 = ss.generate_state(len(expected64), dtype=np.uint64)
assert_array_equal(state64, expected64)
def test_zero_padding():
""" Ensure that the implicit zero-padding does not cause problems.
"""
# Ensure that large integers are inserted in little-endian fashion to avoid
# trailing 0s.
ss0 = SeedSequence(42)
ss1 = SeedSequence(42 << 32)
assert_array_compare(
np.not_equal,
ss0.generate_state(4),
ss1.generate_state(4))
# Ensure backwards compatibility with the original 0.17 release for small
# integers and no spawn key.
expected42 = np.array([3444837047, 2669555309, 2046530742, 3581440988],
dtype=np.uint32)
assert_array_equal(SeedSequence(42).generate_state(4), expected42)
# Regression test for gh-16539 to ensure that the implicit 0s don't
# conflict with spawn keys.
assert_array_compare(
np.not_equal,
SeedSequence(42, spawn_key=(0,)).generate_state(4),
expected42)
| import numpy as np
from numpy.random import SeedSequence
from numpy.testing import assert_array_compare, assert_array_equal
def test_reference_data():
""" Check that SeedSequence generates data the same as the C++ reference.
https://gist.github.com/imneme/540829265469e673d045
"""
inputs = [
[3735928559, 195939070, 229505742, 305419896],
[3668361503, 4165561550, 1661411377, 3634257570],
[164546577, 4166754639, 1765190214, 1303880213],
[446610472, 3941463886, 522937693, 1882353782],
[1864922766, 1719732118, 3882010307, 1776744564],
[4141682960, 3310988675, 553637289, 902896340],
[1134851934, 2352871630, 3699409824, 2648159817],
[1240956131, 3107113773, 1283198141, 1924506131],
[2669565031, 579818610, 3042504477, 2774880435],
[2766103236, 2883057919, 4029656435, 862374500],
]
outputs = [
[3914649087, 576849849, 3593928901, 2229911004],
[2240804226, 3691353228, 1365957195, 2654016646],
[3562296087, 3191708229, 1147942216, 3726991905],
[14 | [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_array_compare"
] | numpy/numpy | numpy/random/tests/test_seed_sequence.py |
import inspect
import sys
import pytest
import numpy as np
from numpy import random
from numpy.testing import assert_, assert_array_equal, assert_raises
class TestRegression:
def test_VonMises_range(self):
# Make sure generated random variables are in [-pi, pi].
# Regression test for ticket #986.
for mu in np.linspace(-7., 7., 5):
r = random.mtrand.vonmises(mu, 1, 50)
assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
def test_hypergeometric_range(self):
# Test for ticket #921
assert_(np.all(np.random.hypergeometric(3, 18, 11, size=10) < 4))
assert_(np.all(np.random.hypergeometric(18, 3, 11, size=10) > 0))
# Test for ticket #5623
args = [
(2**20 - 2, 2**20 - 2, 2**20 - 2), # Check for 32-bit systems
]
is_64bits = sys.maxsize > 2**32
if is_64bits and sys.platform != 'win32':
# Check for 64-bit systems
args.append((2**40 - 2, 2**40 - 2, 2**40 - 2))
for arg in args:
assert_(np.random.hypergeometric(*arg) > 0)
def test_logseries_convergence(self):
# Test for ticket #923
N = 1000
np.random.seed(0)
rvsn = np.random.logseries(0.8, size=N)
# these two frequency counts should be close to theoretical
# numbers with this large sample
# theoretical large N result is 0.49706795
freq = np.sum(rvsn == 1) / N
msg = f'Frequency was {freq:f}, should be > 0.45'
assert_(freq > 0.45, msg)
# theoretical large N result is 0.19882718
freq = np.sum(rvsn == 2) / N
msg = f'Frequency was {freq:f}, should be < 0.23'
assert_(freq < 0.23, msg)
def test_shuffle_mixed_dimension(self):
# Test for trac ticket #2074
for t in [[1, 2, 3, None],
[(1, 1), (2, 2), (3, 3), None],
[1, (2, 2), (3, 3), None],
[(1, 1), 2, 3, None]]:
rng = np.random.RandomState(12345)
shuffled = list(t)
rng.shuffle(shuffled)
expected = np.array([t[0], t[3], t[1], t[2]], dtype=object)
assert_array_equal(np.array(shuffled, dtype=object), expected)
def test_call_within_randomstate(self):
# Check that custom RandomState does not call into global state
m = np.random.RandomState()
res = np.array([0, 8, 7, 2, 1, 9, 4, 7, 0, 3])
for i in range(3):
np.random.seed(i)
m.seed(4321)
# If m.state is not honored, the result will change
assert_array_equal(m.choice(10, size=10, p=np.ones(10) / 10.), res)
def test_multivariate_normal_size_types(self):
# Test for multivariate_normal issue with 'size' argument.
# Check that the multivariate_normal size argument can be a
# numpy integer.
np.random.multivariate_normal([0], [[0]], size=1)
np.random.multivariate_normal([0], [[0]], size=np.int_(1))
np.random.multivariate_normal([0], [[0]], size=np.int64(1))
def test_beta_small_parameters(self):
# Test that beta with small a and b parameters does not produce
# NaNs due to roundoff errors causing 0 / 0, gh-5851
np.random.seed(1234567890)
x = np.random.beta(0.0001, 0.0001, size=100)
assert_(not np.any(np.isnan(x)), 'Nans in np.random.beta')
def test_choice_sum_of_probs_tolerance(self):
# The sum of probs should be 1.0 with some tolerance.
# For low precision dtypes the tolerance was too tight.
# See numpy github issue 6123.
np.random.seed(1234)
a = [1, 2, 3]
counts = [4, 4, 2]
for dt in np.float16, np.float32, np.float64:
probs = np.array(counts, dtype=dt) / sum(counts)
c = np.random.choice(a, p=probs)
assert_(c in a)
assert_raises(ValueError, np.random.choice, a, p=probs * 0.9)
def test_shuffle_of_array_of_different_length_strings(self):
# Test that permuting an array of different length strings
# will not cause a segfault on garbage collection
# Tests gh-7710
np.random.seed(1234)
a = np.array(['a', 'a' * 1000])
for _ in range(100):
np.random.shuffle(a)
# Force Garbage Collection - should not segfault.
import gc
gc.collect()
def test_shuffle_of_array_of_objects(self):
# Test that permuting an array of objects will not cause
# a segfault on garbage collection.
# See gh-7719
np.random.seed(1234)
a = np.array([np.arange(1), np.arange(4)], dtype=object)
for _ in range(1000):
np.random.shuffle(a)
# Force Garbage Collection - should not segfault.
import gc
gc.collect()
def test_permutation_subclass(self):
class N(np.ndarray):
pass
rng = np.random.RandomState(1)
orig = np.arange(3).view(N)
perm = rng.permutation(orig)
assert_array_equal(perm, np.array([0, 2, 1]))
assert_array_equal(orig, np.arange(3).view(N))
class M:
a = np.arange(5)
def __array__(self, dtype=None, copy=None):
return self.a
rng = np.random.RandomState(1)
m = M()
perm = rng.permutation(m)
assert_array_equal(perm, np.array([2, 1, 4, 0, 3]))
assert_array_equal(m.__array__(), np.arange(5))
@pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
@pytest.mark.parametrize(
"cls",
[
random.Generator,
random.MT19937,
random.PCG64,
random.PCG64DXSM,
random.Philox,
random.RandomState,
random.SFC64,
random.BitGenerator,
random.SeedSequence,
random.bit_generator.SeedlessSeedSequence,
],
)
def test_inspect_signature(self, cls: type) -> None:
assert hasattr(cls, "__text_signature__")
try:
inspect.signature(cls)
except ValueError:
pytest.fail(f"invalid signature: {cls.__module__}.{cls.__qualname__}")
| import inspect
import sys
import pytest
import numpy as np
from numpy import random
from numpy.testing import assert_, assert_array_equal, assert_raises
class TestRegression:
def test_VonMises_range(self):
# Make sure generated random variables are in [-pi, pi].
# Regression test for ticket #986.
for mu in np.linspace(-7., 7., 5):
r = random.mtrand.vonmises(mu, 1, 50)
assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
def test_hypergeometric_range(self):
# Test for ticket #921
assert_(np.all(np.random.hypergeometric(3, 18, 11, size=10) < 4))
assert_(np.all(np.random.hypergeometric(18, 3, 11, size=10) > 0))
# Test for ticket #5623
args = [
(2**20 - 2, 2**20 - 2, 2**20 - 2), # Check for 32-bit systems
]
is_64bits = sys.maxsize > 2**32
if is_64bits and sys.platform != 'win32':
# Check for 64-bit systems
args.append((2**40 - 2, 2**40 - 2, 2**40 - 2))
for arg in args:
assert_(np.random.hypergeometric(*arg) > 0)
def test_logseries_ | [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_"
] | numpy/numpy | numpy/random/tests/test_regression.py |
import sys
import pytest
import numpy as np
from numpy import random
from numpy.testing import assert_, assert_array_equal, assert_raises
class TestRegression:
def test_VonMises_range(self):
# Make sure generated random variables are in [-pi, pi].
# Regression test for ticket #986.
for mu in np.linspace(-7., 7., 5):
r = random.vonmises(mu, 1, 50)
assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
def test_hypergeometric_range(self):
# Test for ticket #921
assert_(np.all(random.hypergeometric(3, 18, 11, size=10) < 4))
assert_(np.all(random.hypergeometric(18, 3, 11, size=10) > 0))
# Test for ticket #5623
args = [
(2**20 - 2, 2**20 - 2, 2**20 - 2), # Check for 32-bit systems
]
is_64bits = sys.maxsize > 2**32
if is_64bits and sys.platform != 'win32':
# Check for 64-bit systems
args.append((2**40 - 2, 2**40 - 2, 2**40 - 2))
for arg in args:
assert_(random.hypergeometric(*arg) > 0)
def test_logseries_convergence(self):
# Test for ticket #923
N = 1000
random.seed(0)
rvsn = random.logseries(0.8, size=N)
# these two frequency counts should be close to theoretical
# numbers with this large sample
# theoretical large N result is 0.49706795
freq = np.sum(rvsn == 1) / N
msg = f'Frequency was {freq:f}, should be > 0.45'
assert_(freq > 0.45, msg)
# theoretical large N result is 0.19882718
freq = np.sum(rvsn == 2) / N
msg = f'Frequency was {freq:f}, should be < 0.23'
assert_(freq < 0.23, msg)
def test_shuffle_mixed_dimension(self):
# Test for trac ticket #2074
for t in [[1, 2, 3, None],
[(1, 1), (2, 2), (3, 3), None],
[1, (2, 2), (3, 3), None],
[(1, 1), 2, 3, None]]:
rng = random.RandomState(12345)
shuffled = list(t)
rng.shuffle(shuffled)
expected = np.array([t[0], t[3], t[1], t[2]], dtype=object)
assert_array_equal(np.array(shuffled, dtype=object), expected)
def test_call_within_randomstate(self):
# Check that custom RandomState does not call into global state
m = random.RandomState()
res = np.array([0, 8, 7, 2, 1, 9, 4, 7, 0, 3])
for i in range(3):
random.seed(i)
m.seed(4321)
# If m.state is not honored, the result will change
assert_array_equal(m.choice(10, size=10, p=np.ones(10) / 10.), res)
def test_multivariate_normal_size_types(self):
# Test for multivariate_normal issue with 'size' argument.
# Check that the multivariate_normal size argument can be a
# numpy integer.
random.multivariate_normal([0], [[0]], size=1)
random.multivariate_normal([0], [[0]], size=np.int_(1))
random.multivariate_normal([0], [[0]], size=np.int64(1))
def test_beta_small_parameters(self):
# Test that beta with small a and b parameters does not produce
# NaNs due to roundoff errors causing 0 / 0, gh-5851
random.seed(1234567890)
x = random.beta(0.0001, 0.0001, size=100)
assert_(not np.any(np.isnan(x)), 'Nans in random.beta')
def test_choice_sum_of_probs_tolerance(self):
# The sum of probs should be 1.0 with some tolerance.
# For low precision dtypes the tolerance was too tight.
# See numpy github issue 6123.
random.seed(1234)
a = [1, 2, 3]
counts = [4, 4, 2]
for dt in np.float16, np.float32, np.float64:
probs = np.array(counts, dtype=dt) / sum(counts)
c = random.choice(a, p=probs)
assert_(c in a)
assert_raises(ValueError, random.choice, a, p=probs * 0.9)
def test_shuffle_of_array_of_different_length_strings(self):
# Test that permuting an array of different length strings
# will not cause a segfault on garbage collection
# Tests gh-7710
random.seed(1234)
a = np.array(['a', 'a' * 1000])
for _ in range(100):
random.shuffle(a)
# Force Garbage Collection - should not segfault.
import gc
gc.collect()
def test_shuffle_of_array_of_objects(self):
# Test that permuting an array of objects will not cause
# a segfault on garbage collection.
# See gh-7719
random.seed(1234)
a = np.array([np.arange(1), np.arange(4)], dtype=object)
for _ in range(1000):
random.shuffle(a)
# Force Garbage Collection - should not segfault.
import gc
gc.collect()
def test_permutation_subclass(self):
class N(np.ndarray):
pass
rng = random.RandomState(1)
orig = np.arange(3).view(N)
perm = rng.permutation(orig)
assert_array_equal(perm, np.array([0, 2, 1]))
assert_array_equal(orig, np.arange(3).view(N))
class M:
a = np.arange(5)
def __array__(self, dtype=None, copy=None):
return self.a
rng = random.RandomState(1)
m = M()
perm = rng.permutation(m)
assert_array_equal(perm, np.array([2, 1, 4, 0, 3]))
assert_array_equal(m.__array__(), np.arange(5))
def test_warns_byteorder(self):
# GH 13159
other_byteord_dt = '<i4' if sys.byteorder == 'big' else '>i4'
with pytest.deprecated_call(match='non-native byteorder is not'):
random.randint(0, 200, size=10, dtype=other_byteord_dt)
def test_named_argument_initialization(self):
# GH 13669
rs1 = np.random.RandomState(123456789)
rs2 = np.random.RandomState(seed=123456789)
assert rs1.randint(0, 100) == rs2.randint(0, 100)
def test_choice_retun_dtype(self):
# GH 9867, now long since the NumPy default changed.
c = np.random.choice(10, p=[.1] * 10, size=2)
assert c.dtype == np.dtype(np.long)
c = np.random.choice(10, p=[.1] * 10, replace=False, size=2)
assert c.dtype == np.dtype(np.long)
c = np.random.choice(10, size=2)
assert c.dtype == np.dtype(np.long)
c = np.random.choice(10, replace=False, size=2)
assert c.dtype == np.dtype(np.long)
@pytest.mark.skipif(np.iinfo('l').max < 2**32,
reason='Cannot test with 32-bit C long')
def test_randint_117(self):
# GH 14189
rng = random.RandomState(0)
expected = np.array([2357136044, 2546248239, 3071714933, 3626093760,
2588848963, 3684848379, 2340255427, 3638918503,
1819583497, 2678185683], dtype='int64')
actual = rng.randint(2**32, size=10)
assert_array_equal(actual, expected)
def test_p_zero_stream(self):
# Regression test for gh-14522. Ensure that future versions
# generate the same variates as version 1.16.
rng = random.RandomState(12345)
assert_array_equal(rng.binomial(1, [0, 0.25, 0.5, 0.75, 1]),
[0, 0, 0, 1, 1])
def test_n_zero_stream(self):
# Regression test for gh-14522. Ensure that future versions
# generate the same variates as version 1.16.
rng = random.RandomState(8675309)
expected = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[3, 4, 2, 3, 3, 1, 5, 3, 1, 3]])
assert_array_equal(rng.binomial([[0], [10]], 0.25, size=(2, 10)),
expected)
def test_multinomial_empty():
# gh-20483
# Ensure that empty p-vals are correctly handled
assert random.multinomial(10, []).shape == (0,)
assert random.multinomial(3, [], size=(7, 5, 3)).shape == (7, 5, 3, 0)
def test_multinomial_1d_pval():
# gh-20483
with pytest.raises(TypeError, match="pvals must be a 1-d"):
random.multinomial(10, 0.3)
| import sys
import pytest
import numpy as np
from numpy import random
from numpy.testing import assert_, assert_array_equal, assert_raises
class TestRegression:
def test_VonMises_range(self):
# Make sure generated random variables are in [-pi, pi].
# Regression test for ticket #986.
for mu in np.linspace(-7., 7., 5):
r = random.vonmises(mu, 1, 50)
assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
def test_hypergeometric_range(self):
# Test for ticket #921
assert_(np.all(random.hypergeometric(3, 18, 11, size=10) < 4))
assert_(np.all(random.hypergeometric(18, 3, 11, size=10) > 0))
# Test for ticket #5623
args = [
(2**20 - 2, 2**20 - 2, 2**20 - 2), # Check for 32-bit systems
]
is_64bits = sys.maxsize > 2**32
if is_64bits and sys.platform != 'win32':
# Check for 64-bit systems
args.append((2**40 - 2, 2**40 - 2, 2**40 - 2))
for arg in args:
assert_(random.hypergeometric(*arg) > 0)
def test_logseries_convergence(self):
| [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_"
] | numpy/numpy | numpy/random/tests/test_randomstate_regression.py |
import hashlib
import pickle
import sys
import warnings
import pytest
import numpy as np
from numpy import random
from numpy.random import MT19937, PCG64
from numpy.testing import (
IS_WASM,
assert_,
assert_array_almost_equal,
assert_array_equal,
assert_equal,
assert_no_warnings,
assert_raises,
)
INT_FUNCS = {'binomial': (100.0, 0.6),
'geometric': (.5,),
'hypergeometric': (20, 20, 10),
'logseries': (.5,),
'multinomial': (20, np.ones(6) / 6.0),
'negative_binomial': (100, .5),
'poisson': (10.0,),
'zipf': (2,),
}
if np.iinfo(np.long).max < 2**32:
# Windows and some 32-bit platforms, e.g., ARM
INT_FUNC_HASHES = {'binomial': '2fbead005fc63942decb5326d36a1f32fe2c9d32c904ee61e46866b88447c263', # noqa: E501
'logseries': '23ead5dcde35d4cfd4ef2c105e4c3d43304b45dc1b1444b7823b9ee4fa144ebb', # noqa: E501
'geometric': '0d764db64f5c3bad48c8c33551c13b4d07a1e7b470f77629bef6c985cac76fcf', # noqa: E501
'hypergeometric': '7b59bf2f1691626c5815cdcd9a49e1dd68697251d4521575219e4d2a1b8b2c67', # noqa: E501
'multinomial': 'd754fa5b92943a38ec07630de92362dd2e02c43577fc147417dc5b9db94ccdd3', # noqa: E501
'negative_binomial': '8eb216f7cb2a63cf55605422845caaff002fddc64a7dc8b2d45acd477a49e824', # noqa: E501
'poisson': '70c891d76104013ebd6f6bcf30d403a9074b886ff62e4e6b8eb605bf1a4673b7', # noqa: E501
'zipf': '01f074f97517cd5d21747148ac6ca4074dde7fcb7acbaec0a936606fecacd93f', # noqa: E501
}
else:
INT_FUNC_HASHES = {'binomial': '8626dd9d052cb608e93d8868de0a7b347258b199493871a1dc56e2a26cacb112', # noqa: E501
'geometric': '8edd53d272e49c4fc8fbbe6c7d08d563d62e482921f3131d0a0e068af30f0db9', # noqa: E501
'hypergeometric': '83496cc4281c77b786c9b7ad88b74d42e01603a55c60577ebab81c3ba8d45657', # noqa: E501
'logseries': '65878a38747c176bc00e930ebafebb69d4e1e16cd3a704e264ea8f5e24f548db', # noqa: E501
'multinomial': '7a984ae6dca26fd25374479e118b22f55db0aedccd5a0f2584ceada33db98605', # noqa: E501
'negative_binomial': 'd636d968e6a24ae92ab52fe11c46ac45b0897e98714426764e820a7d77602a61', # noqa: E501
'poisson': '956552176f77e7c9cb20d0118fc9cf690be488d790ed4b4c4747b965e61b0bb4', # noqa: E501
'zipf': 'f84ba7feffda41e606e20b28dfc0f1ea9964a74574513d4a4cbc98433a8bfa45', # noqa: E501
}
@pytest.fixture(scope='module', params=INT_FUNCS)
def int_func(request):
return (request.param, INT_FUNCS[request.param],
INT_FUNC_HASHES[request.param])
@pytest.fixture
def restore_singleton_bitgen():
"""Ensures that the singleton bitgen is restored after a test"""
orig_bitgen = np.random.get_bit_generator()
yield
np.random.set_bit_generator(orig_bitgen)
def assert_mt19937_state_equal(a, b):
assert_equal(a['bit_generator'], b['bit_generator'])
assert_array_equal(a['state']['key'], b['state']['key'])
assert_array_equal(a['state']['pos'], b['state']['pos'])
assert_equal(a['has_gauss'], b['has_gauss'])
assert_equal(a['gauss'], b['gauss'])
class TestSeed:
def test_scalar(self):
s = random.RandomState(0)
assert_equal(s.randint(1000), 684)
s = random.RandomState(4294967295)
assert_equal(s.randint(1000), 419)
def test_array(self):
s = random.RandomState(range(10))
assert_equal(s.randint(1000), 468)
s = random.RandomState(np.arange(10))
assert_equal(s.randint(1000), 468)
s = random.RandomState([0])
assert_equal(s.randint(1000), 973)
s = random.RandomState([4294967295])
assert_equal(s.randint(1000), 265)
def test_invalid_scalar(self):
# seed must be an unsigned 32 bit integer
assert_raises(TypeError, random.RandomState, -0.5)
assert_raises(ValueError, random.RandomState, -1)
def test_invalid_array(self):
# seed must be an unsigned 32 bit integer
assert_raises(TypeError, random.RandomState, [-0.5])
assert_raises(ValueError, random.RandomState, [-1])
assert_raises(ValueError, random.RandomState, [4294967296])
assert_raises(ValueError, random.RandomState, [1, 2, 4294967296])
assert_raises(ValueError, random.RandomState, [1, -2, 4294967296])
def test_invalid_array_shape(self):
# gh-9832
assert_raises(ValueError, random.RandomState, np.array([],
dtype=np.int64))
assert_raises(ValueError, random.RandomState, [[1, 2, 3]])
assert_raises(ValueError, random.RandomState, [[1, 2, 3],
[4, 5, 6]])
def test_cannot_seed(self):
rs = random.RandomState(PCG64(0))
with assert_raises(TypeError):
rs.seed(1234)
def test_invalid_initialization(self):
assert_raises(ValueError, random.RandomState, MT19937)
class TestBinomial:
def test_n_zero(self):
# Tests the corner case of n == 0 for the binomial distribution.
# binomial(0, p) should be zero for any p in [0, 1].
# This test addresses issue #3480.
zeros = np.zeros(2, dtype='int')
for p in [0, .5, 1]:
assert_(random.binomial(0, p) == 0)
assert_array_equal(random.binomial(zeros, p), zeros)
def test_p_is_nan(self):
# Issue #4571.
assert_raises(ValueError, random.binomial, 1, np.nan)
class TestMultinomial:
def test_basic(self):
random.multinomial(100, [0.2, 0.8])
def test_zero_probability(self):
random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0])
def test_int_negative_interval(self):
assert_(-5 <= random.randint(-5, -1) < -1)
x = random.randint(-5, -1, 5)
assert_(np.all(-5 <= x))
assert_(np.all(x < -1))
def test_size(self):
# gh-3173
p = [0.5, 0.5]
assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(random.multinomial(1, p, [2, 2]).shape, (2, 2, 2))
assert_equal(random.multinomial(1, p, (2, 2)).shape, (2, 2, 2))
assert_equal(random.multinomial(1, p, np.array((2, 2))).shape,
(2, 2, 2))
assert_raises(TypeError, random.multinomial, 1, p,
float(1))
def test_invalid_prob(self):
assert_raises(ValueError, random.multinomial, 100, [1.1, 0.2])
assert_raises(ValueError, random.multinomial, 100, [-.1, 0.9])
def test_invalid_n(self):
assert_raises(ValueError, random.multinomial, -1, [0.8, 0.2])
def test_p_non_contiguous(self):
p = np.arange(15.)
p /= np.sum(p[1::3])
pvals = p[1::3]
rng = random.RandomState(1432985819)
non_contig = rng.multinomial(100, pvals=pvals)
rng = random.RandomState(1432985819)
contig = rng.multinomial(100, pvals=np.ascontiguousarray(pvals))
assert_array_equal(non_contig, contig)
def test_multinomial_pvals_float32(self):
x = np.array([9.9e-01, 9.9e-01, 1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09,
1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09], dtype=np.float32)
pvals = x / x.sum()
match = r"[\w\s]*pvals array is cast to 64-bit floating"
with pytest.raises(ValueError, match=match):
random.multinomial(1, pvals)
def test_multinomial_n_float(self):
# Non-index integer types should gracefully truncate floats
random.multinomial(100.5, [0.2, 0.8])
class TestSetState:
def _create_state(self):
seed = 1234567890
random_state = random.RandomState(seed)
state = random_state.get_state()
return random_state, state
def test_basic(self):
random_state, state = self._create_state()
old = random_state.tomaxint(16)
random_state.set_state(state)
new = random_state.tomaxint(16)
assert_(np.all(old == new))
def test_gaussian_reset(self):
# Make sure the cached every-other-Gaussian is reset.
random_state, state = self._create_state()
old = random_state.standard_normal(size=3)
random_state.set_state(state)
new = random_state.standard_normal(size=3)
assert_(np.all(old == new))
def test_gaussian_reset_in_media_res(self):
# When the state is saved with a cached Gaussian, make sure the
# cached Gaussian is restored.
random_state, state = self._create_state()
random_state.standard_normal()
state = random_state.get_state()
old = random_state.standard_normal(size=3)
random_state.set_state(state)
new = random_state.standard_normal(size=3)
assert_(np.all(old == new))
def test_backwards_compatibility(self):
# Make sure we can accept old state tuples that do not have the
# cached Gaussian value.
random_state, state = self._create_state()
old_state = state[:-2]
x1 = random_state.standard_normal(size=16)
random_state.set_state(old_state)
x2 = random_state.standard_normal(size=16)
random_state.set_state(state)
x3 = random_state.standard_normal(size=16)
assert_(np.all(x1 == x2))
assert_(np.all(x1 == x3))
def test_negative_binomial(self):
# Ensure that the negative binomial results take floating point
# arguments without truncation.
random_state, _ = self._create_state()
random_state.negative_binomial(0.5, 0.5)
def test_get_state_warning(self):
rs = random.RandomState(PCG64())
with pytest.warns(RuntimeWarning):
state = rs.get_state()
assert isinstance(state, dict)
assert state['bit_generator'] == 'PCG64'
def test_invalid_legacy_state_setting(self):
random_state, state = self._create_state()
state = random_state.get_state()
new_state = ('Unknown', ) + state[1:]
assert_raises(ValueError, random_state.set_state, new_state)
assert_raises(TypeError, random_state.set_state,
np.array(new_state, dtype=object))
state = random_state.get_state(legacy=False)
del state['bit_generator']
assert_raises(ValueError, random_state.set_state, state)
def test_pickle(self):
random_state, _ = self._create_state()
random_state.seed(0)
random_state.random_sample(100)
random_state.standard_normal()
pickled = random_state.get_state(legacy=False)
assert_equal(pickled['has_gauss'], 1)
rs_unpick = pickle.loads(pickle.dumps(random_state))
unpickled = rs_unpick.get_state(legacy=False)
assert_mt19937_state_equal(pickled, unpickled)
def test_state_setting(self):
random_state, state = self._create_state()
attr_state = random_state.__getstate__()
random_state.standard_normal()
random_state.__setstate__(attr_state)
state = random_state.get_state(legacy=False)
assert_mt19937_state_equal(attr_state, state)
def test_repr(self):
random_state, _ = self._create_state()
assert repr(random_state).startswith('RandomState(MT19937)')
class TestRandint:
# valid integer/boolean types
itype = [np.bool, np.int8, np.uint8, np.int16, np.uint16,
np.int32, np.uint32, np.int64, np.uint64]
def test_unsupported_type(self):
rng = np.random.RandomState()
assert_raises(TypeError, rng.randint, 1, dtype=float)
def test_bounds_checking(self):
rng = np.random.RandomState()
for dt in self.itype:
lbnd = 0 if dt is np.bool else np.iinfo(dt).min
ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
assert_raises(ValueError, rng.randint, lbnd - 1, ubnd, dtype=dt)
assert_raises(ValueError, rng.randint, lbnd, ubnd + 1, dtype=dt)
assert_raises(ValueError, rng.randint, ubnd, lbnd, dtype=dt)
assert_raises(ValueError, rng.randint, 1, 0, dtype=dt)
def test_rng_zero_and_extremes(self):
rng = np.random.RandomState()
for dt in self.itype:
lbnd = 0 if dt is np.bool else np.iinfo(dt).min
ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
tgt = ubnd - 1
assert_equal(rng.randint(tgt, tgt + 1, size=1000, dtype=dt), tgt)
tgt = lbnd
assert_equal(rng.randint(tgt, tgt + 1, size=1000, dtype=dt), tgt)
tgt = (lbnd + ubnd) // 2
assert_equal(rng.randint(tgt, tgt + 1, size=1000, dtype=dt), tgt)
def test_full_range(self):
# Test for ticket #1690
rng = np.random.RandomState()
for dt in self.itype:
lbnd = 0 if dt is np.bool else np.iinfo(dt).min
ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
try:
rng.randint(lbnd, ubnd, dtype=dt)
except Exception as e:
raise AssertionError("No error should have been raised, "
"but one was with the following "
"message:\n\n%s" % str(e))
def test_in_bounds_fuzz(self):
# Don't use fixed seed
rng = np.random.RandomState()
for dt in self.itype[1:]:
for ubnd in [4, 8, 16]:
vals = rng.randint(2, ubnd, size=2**16, dtype=dt)
assert_(vals.max() < ubnd)
assert_(vals.min() >= 2)
vals = rng.randint(0, 2, size=2**16, dtype=np.bool)
assert_(vals.max() < 2)
assert_(vals.min() >= 0)
def test_repeatability(self):
# We use a sha256 hash of generated sequences of 1000 samples
# in the range [0, 6) for all but bool, where the range
# is [0, 2). Hashes are for little endian numbers.
tgt = {'bool': '509aea74d792fb931784c4b0135392c65aec64beee12b0cc167548a2c3d31e71', # noqa: E501
'int16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4', # noqa: E501
'int32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f', # noqa: E501
'int64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e', # noqa: E501
'int8': '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404', # noqa: E501
'uint16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4', # noqa: E501
'uint32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f', # noqa: E501
'uint64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e', # noqa: E501
'uint8': '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404'} # noqa: E501
for dt in self.itype[1:]:
rng = random.RandomState(1234)
# view as little endian for hash
if sys.byteorder == 'little':
val = rng.randint(0, 6, size=1000, dtype=dt)
else:
val = rng.randint(0, 6, size=1000, dtype=dt).byteswap()
res = hashlib.sha256(val.view(np.int8)).hexdigest()
assert_(tgt[np.dtype(dt).name] == res)
# bools do not depend on endianness
rng = random.RandomState(1234)
val = rng.randint(0, 2, size=1000, dtype=bool).view(np.int8)
res = hashlib.sha256(val).hexdigest()
assert_(tgt[np.dtype(bool).name] == res)
@pytest.mark.skipif(np.iinfo('l').max < 2**32,
reason='Cannot test with 32-bit C long')
def test_repeatability_32bit_boundary_broadcasting(self):
desired = np.array([[[3992670689, 2438360420, 2557845020],
[4107320065, 4142558326, 3216529513],
[1605979228, 2807061240, 665605495]],
[[3211410639, 4128781000, 457175120],
[1712592594, 1282922662, 3081439808],
[3997822960, 2008322436, 1563495165]],
[[1398375547, 4269260146, 115316740],
[3414372578, 3437564012, 2112038651],
[3572980305, 2260248732, 3908238631]],
[[2561372503, 223155946, 3127879445],
[ 441282060, 3514786552, 2148440361],
[1629275283, 3479737011, 3003195987]],
[[ 412181688, 940383289, 3047321305],
[2978368172, 764731833, 2282559898],
[ 105711276, 720447391, 3596512484]]])
for size in [None, (5, 3, 3)]:
rng = random.RandomState(12345)
x = rng.randint([[-1], [0], [1]], [2**32 - 1, 2**32, 2**32 + 1],
size=size)
assert_array_equal(x, desired if size is not None else desired[0])
def test_int64_uint64_corner_case(self):
# When stored in Numpy arrays, `lbnd` is casted
# as np.int64, and `ubnd` is casted as np.uint64.
# Checking whether `lbnd` >= `ubnd` used to be
# done solely via direct comparison, which is incorrect
# because when Numpy tries to compare both numbers,
# it casts both to np.float64 because there is
# no integer superset of np.int64 and np.uint64. However,
# `ubnd` is too large to be represented in np.float64,
# causing it be round down to np.iinfo(np.int64).max,
# leading to a ValueError because `lbnd` now equals
# the new `ubnd`.
dt = np.int64
tgt = np.iinfo(np.int64).max
lbnd = np.int64(np.iinfo(np.int64).max)
ubnd = np.uint64(np.iinfo(np.int64).max + 1)
# None of these function calls should
# generate a ValueError now.
actual = random.randint(lbnd, ubnd, dtype=dt)
assert_equal(actual, tgt)
def test_respect_dtype_singleton(self):
# See gh-7203
rng = np.random.RandomState()
for dt in self.itype:
lbnd = 0 if dt is np.bool else np.iinfo(dt).min
ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
sample = rng.randint(lbnd, ubnd, dtype=dt)
assert_equal(sample.dtype, np.dtype(dt))
for dt in (bool, int):
# The legacy random generation forces the use of "long" on this
# branch even when the input is `int` and the default dtype
# for int changed (dtype=int is also the functions default)
op_dtype = "long" if dt is int else "bool"
lbnd = 0 if dt is bool else np.iinfo(op_dtype).min
ubnd = 2 if dt is bool else np.iinfo(op_dtype).max + 1
sample = rng.randint(lbnd, ubnd, dtype=dt)
assert_(not hasattr(sample, 'dtype'))
assert_equal(type(sample), dt)
class TestRandomDist:
# Make sure the random distribution returns the correct value for a
# given seed
seed = 1234567890
def test_rand(self):
rng = random.RandomState(self.seed)
actual = rng.rand(3, 2)
desired = np.array([[0.61879477158567997, 0.59162362775974664],
[0.88868358904449662, 0.89165480011560816],
[0.4575674820298663, 0.7781880808593471]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_rand_singleton(self):
rng = random.RandomState(self.seed)
actual = rng.rand()
desired = 0.61879477158567997
assert_array_almost_equal(actual, desired, decimal=15)
def test_randn(self):
rng = random.RandomState(self.seed)
actual = rng.randn(3, 2)
desired = np.array([[1.34016345771863121, 1.73759122771936081],
[1.498988344300628, -0.2286433324536169],
[2.031033998682787, 2.17032494605655257]])
assert_array_almost_equal(actual, desired, decimal=15)
rng = random.RandomState(self.seed)
actual = rng.randn()
assert_array_almost_equal(actual, desired[0, 0], decimal=15)
def test_randint(self):
rng = random.RandomState(self.seed)
actual = rng.randint(-99, 99, size=(3, 2))
desired = np.array([[31, 3],
[-52, 41],
[-48, -66]])
assert_array_equal(actual, desired)
def test_random_integers(self):
rng = random.RandomState(self.seed)
with pytest.warns(DeprecationWarning):
actual = rng.random_integers(-99, 99, size=(3, 2))
desired = np.array([[31, 3],
[-52, 41],
[-48, -66]])
assert_array_equal(actual, desired)
rng = random.RandomState(self.seed)
with pytest.warns(DeprecationWarning):
actual = rng.random_integers(198, size=(3, 2))
assert_array_equal(actual, desired + 100)
def test_tomaxint(self):
rs = random.RandomState(self.seed)
actual = rs.tomaxint(size=(3, 2))
if np.iinfo(np.long).max == 2147483647:
desired = np.array([[1328851649, 731237375],
[1270502067, 320041495],
[1908433478, 499156889]], dtype=np.int64)
else:
desired = np.array([[5707374374421908479, 5456764827585442327],
[8196659375100692377, 8224063923314595285],
[4220315081820346526, 7177518203184491332]],
dtype=np.int64)
assert_equal(actual, desired)
rs.seed(self.seed)
actual = rs.tomaxint()
assert_equal(actual, desired[0, 0])
def test_random_integers_max_int(self):
# Tests whether random_integers can generate the
# maximum allowed Python int that can be converted
# into a C long. Previous implementations of this
# method have thrown an OverflowError when attempting
# to generate this integer.
with pytest.warns(DeprecationWarning):
actual = random.random_integers(np.iinfo('l').max,
np.iinfo('l').max)
desired = np.iinfo('l').max
assert_equal(actual, desired)
with pytest.warns(DeprecationWarning):
typer = np.dtype('l').type
actual = random.random_integers(typer(np.iinfo('l').max),
typer(np.iinfo('l').max))
assert_equal(actual, desired)
def test_random_integers_deprecated(self):
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
# DeprecationWarning raised with high == None
assert_raises(DeprecationWarning,
random.random_integers,
np.iinfo('l').max)
# DeprecationWarning raised with high != None
assert_raises(DeprecationWarning,
random.random_integers,
np.iinfo('l').max, np.iinfo('l').max)
def test_random_sample(self):
rng = random.RandomState(self.seed)
actual = rng.random_sample((3, 2))
desired = np.array([[0.61879477158567997, 0.59162362775974664],
[0.88868358904449662, 0.89165480011560816],
[0.4575674820298663, 0.7781880808593471]])
assert_array_almost_equal(actual, desired, decimal=15)
rng = random.RandomState(self.seed)
actual = rng.random_sample()
assert_array_almost_equal(actual, desired[0, 0], decimal=15)
def test_choice_uniform_replace(self):
rng = random.RandomState(self.seed)
actual = rng.choice(4, 4)
desired = np.array([2, 3, 2, 3])
assert_array_equal(actual, desired)
def test_choice_nonuniform_replace(self):
rng = random.RandomState(self.seed)
actual = rng.choice(4, 4, p=[0.4, 0.4, 0.1, 0.1])
desired = np.array([1, 1, 2, 2])
assert_array_equal(actual, desired)
def test_choice_uniform_noreplace(self):
rng = random.RandomState(self.seed)
actual = rng.choice(4, 3, replace=False)
desired = np.array([0, 1, 3])
assert_array_equal(actual, desired)
def test_choice_nonuniform_noreplace(self):
rng = random.RandomState(self.seed)
actual = rng.choice(4, 3, replace=False, p=[0.1, 0.3, 0.5, 0.1])
desired = np.array([2, 3, 1])
assert_array_equal(actual, desired)
def test_choice_noninteger(self):
rng = random.RandomState(self.seed)
actual = rng.choice(['a', 'b', 'c', 'd'], 4)
desired = np.array(['c', 'd', 'c', 'd'])
assert_array_equal(actual, desired)
def test_choice_exceptions(self):
sample = random.choice
assert_raises(ValueError, sample, -1, 3)
assert_raises(ValueError, sample, 3., 3)
assert_raises(ValueError, sample, [[1, 2], [3, 4]], 3)
assert_raises(ValueError, sample, [], 3)
assert_raises(ValueError, sample, [1, 2, 3, 4], 3,
p=[[0.25, 0.25], [0.25, 0.25]])
assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4, 0.2])
assert_raises(ValueError, sample, [1, 2], 3, p=[1.1, -0.1])
assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4])
assert_raises(ValueError, sample, [1, 2, 3], 4, replace=False)
# gh-13087
assert_raises(ValueError, sample, [1, 2, 3], -2, replace=False)
assert_raises(ValueError, sample, [1, 2, 3], (-1,), replace=False)
assert_raises(ValueError, sample, [1, 2, 3], (-1, 1), replace=False)
assert_raises(ValueError, sample, [1, 2, 3], 2,
replace=False, p=[1, 0, 0])
def test_choice_return_shape(self):
p = [0.1, 0.9]
# Check scalar
assert_(np.isscalar(random.choice(2, replace=True)))
assert_(np.isscalar(random.choice(2, replace=False)))
assert_(np.isscalar(random.choice(2, replace=True, p=p)))
assert_(np.isscalar(random.choice(2, replace=False, p=p)))
assert_(np.isscalar(random.choice([1, 2], replace=True)))
assert_(random.choice([None], replace=True) is None)
a = np.array([1, 2])
arr = np.empty(1, dtype=object)
arr[0] = a
assert_(random.choice(arr, replace=True) is a)
# Check 0-d array
s = ()
assert_(not np.isscalar(random.choice(2, s, replace=True)))
assert_(not np.isscalar(random.choice(2, s, replace=False)))
assert_(not np.isscalar(random.choice(2, s, replace=True, p=p)))
assert_(not np.isscalar(random.choice(2, s, replace=False, p=p)))
assert_(not np.isscalar(random.choice([1, 2], s, replace=True)))
assert_(random.choice([None], s, replace=True).ndim == 0)
a = np.array([1, 2])
arr = np.empty(1, dtype=object)
arr[0] = a
assert_(random.choice(arr, s, replace=True).item() is a)
# Check multi dimensional array
s = (2, 3)
p = [0.1, 0.1, 0.1, 0.1, 0.4, 0.2]
assert_equal(random.choice(6, s, replace=True).shape, s)
assert_equal(random.choice(6, s, replace=False).shape, s)
assert_equal(random.choice(6, s, replace=True, p=p).shape, s)
assert_equal(random.choice(6, s, replace=False, p=p).shape, s)
assert_equal(random.choice(np.arange(6), s, replace=True).shape, s)
# Check zero-size
assert_equal(random.randint(0, 0, size=(3, 0, 4)).shape, (3, 0, 4))
assert_equal(random.randint(0, -10, size=0).shape, (0,))
assert_equal(random.randint(10, 10, size=0).shape, (0,))
assert_equal(random.choice(0, size=0).shape, (0,))
assert_equal(random.choice([], size=(0,)).shape, (0,))
assert_equal(random.choice(['a', 'b'], size=(3, 0, 4)).shape,
(3, 0, 4))
assert_raises(ValueError, random.choice, [], 10)
def test_choice_nan_probabilities(self):
a = np.array([42, 1, 2])
p = [None, None, None]
assert_raises(ValueError, random.choice, a, p=p)
def test_choice_p_non_contiguous(self):
p = np.ones(10) / 5
p[1::2] = 3.0
rng = random.RandomState(self.seed)
non_contig = rng.choice(5, 3, p=p[::2])
rng = random.RandomState(self.seed)
contig = rng.choice(5, 3, p=np.ascontiguousarray(p[::2]))
assert_array_equal(non_contig, contig)
def test_bytes(self):
rng = random.RandomState(self.seed)
actual = rng.bytes(10)
desired = b'\x82Ui\x9e\xff\x97+Wf\xa5'
assert_equal(actual, desired)
def test_shuffle(self):
# Test lists, arrays (of various dtypes), and multidimensional versions
# of both, c-contiguous or not:
for conv in [lambda x: np.array([]),
lambda x: x,
lambda x: np.asarray(x).astype(np.int8),
lambda x: np.asarray(x).astype(np.float32),
lambda x: np.asarray(x).astype(np.complex64),
lambda x: np.asarray(x).astype(object),
lambda x: [(i, i) for i in x],
lambda x: np.asarray([[i, i] for i in x]),
lambda x: np.vstack([x, x]).T,
# gh-11442
lambda x: (np.asarray([(i, i) for i in x],
[("a", int), ("b", int)])
.view(np.recarray)),
# gh-4270
lambda x: np.asarray([(i, i) for i in x],
[("a", object, (1,)),
("b", np.int32, (1,))])]:
rng = random.RandomState(self.seed)
alist = conv([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
rng.shuffle(alist)
actual = alist
desired = conv([0, 1, 9, 6, 2, 4, 5, 8, 7, 3])
assert_array_equal(actual, desired)
def test_shuffle_masked(self):
# gh-3263
a = np.ma.masked_values(np.reshape(range(20), (5, 4)) % 3 - 1, -1)
b = np.ma.masked_values(np.arange(20) % 3 - 1, -1)
a_orig = a.copy()
b_orig = b.copy()
for i in range(50):
random.shuffle(a)
assert_equal(
sorted(a.data[~a.mask]), sorted(a_orig.data[~a_orig.mask]))
random.shuffle(b)
assert_equal(
sorted(b.data[~b.mask]), sorted(b_orig.data[~b_orig.mask]))
def test_shuffle_invalid_objects(self):
x = np.array(3)
assert_raises(TypeError, random.shuffle, x)
def test_permutation(self):
rng = random.RandomState(self.seed)
alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
actual = rng.permutation(alist)
desired = [0, 1, 9, 6, 2, 4, 5, 8, 7, 3]
assert_array_equal(actual, desired)
rng = random.RandomState(self.seed)
arr_2d = np.atleast_2d([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]).T
actual = rng.permutation(arr_2d)
assert_array_equal(actual, np.atleast_2d(desired).T)
rng = random.RandomState(self.seed)
bad_x_str = "abcd"
assert_raises(IndexError, random.permutation, bad_x_str)
rng = random.RandomState(self.seed)
bad_x_float = 1.2
assert_raises(IndexError, random.permutation, bad_x_float)
integer_val = 10
desired = [9, 0, 8, 5, 1, 3, 4, 7, 6, 2]
rng = random.RandomState(self.seed)
actual = rng.permutation(integer_val)
assert_array_equal(actual, desired)
def test_beta(self):
rng = random.RandomState(self.seed)
actual = rng.beta(.1, .9, size=(3, 2))
desired = np.array(
[[1.45341850513746058e-02, 5.31297615662868145e-04],
[1.85366619058432324e-06, 4.19214516800110563e-03],
[1.58405155108498093e-04, 1.26252891949397652e-04]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_binomial(self):
rng = random.RandomState(self.seed)
actual = rng.binomial(100.123, .456, size=(3, 2))
desired = np.array([[37, 43],
[42, 48],
[46, 45]])
assert_array_equal(actual, desired)
rng = random.RandomState(self.seed)
actual = rng.binomial(100.123, .456)
desired = 37
assert_array_equal(actual, desired)
def test_chisquare(self):
rng = random.RandomState(self.seed)
actual = rng.chisquare(50, size=(3, 2))
desired = np.array([[63.87858175501090585, 68.68407748911370447],
[65.77116116901505904, 47.09686762438974483],
[72.3828403199695174, 74.18408615260374006]])
assert_array_almost_equal(actual, desired, decimal=13)
def test_dirichlet(self):
rng = random.RandomState(self.seed)
alpha = np.array([51.72840233779265162, 39.74494232180943953])
actual = rng.dirichlet(alpha, size=(3, 2))
desired = np.array([[[0.54539444573611562, 0.45460555426388438],
[0.62345816822039413, 0.37654183177960598]],
[[0.55206000085785778, 0.44793999914214233],
[0.58964023305154301, 0.41035976694845688]],
[[0.59266909280647828, 0.40733090719352177],
[0.56974431743975207, 0.43025568256024799]]])
assert_array_almost_equal(actual, desired, decimal=15)
bad_alpha = np.array([5.4e-01, -1.0e-16])
assert_raises(ValueError, random.dirichlet, bad_alpha)
rng = random.RandomState(self.seed)
alpha = np.array([51.72840233779265162, 39.74494232180943953])
actual = rng.dirichlet(alpha)
assert_array_almost_equal(actual, desired[0, 0], decimal=15)
def test_dirichlet_size(self):
# gh-3173
p = np.array([51.72840233779265162, 39.74494232180943953])
assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(random.dirichlet(p, [2, 2]).shape, (2, 2, 2))
assert_equal(random.dirichlet(p, (2, 2)).shape, (2, 2, 2))
assert_equal(random.dirichlet(p, np.array((2, 2))).shape, (2, 2, 2))
assert_raises(TypeError, random.dirichlet, p, float(1))
def test_dirichlet_bad_alpha(self):
# gh-2089
alpha = np.array([5.4e-01, -1.0e-16])
assert_raises(ValueError, random.dirichlet, alpha)
def test_dirichlet_alpha_non_contiguous(self):
a = np.array([51.72840233779265162, -1.0, 39.74494232180943953])
alpha = a[::2]
rng = random.RandomState(self.seed)
non_contig = rng.dirichlet(alpha, size=(3, 2))
rng = random.RandomState(self.seed)
contig = rng.dirichlet(np.ascontiguousarray(alpha),
size=(3, 2))
assert_array_almost_equal(non_contig, contig)
def test_exponential(self):
rng = random.RandomState(self.seed)
actual = rng.exponential(1.1234, size=(3, 2))
desired = np.array([[1.08342649775011624, 1.00607889924557314],
[2.46628830085216721, 2.49668106809923884],
[0.68717433461363442, 1.69175666993575979]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_exponential_0(self):
assert_equal(random.exponential(scale=0), 0)
assert_raises(ValueError, random.exponential, scale=-0.)
def test_f(self):
rng = random.RandomState(self.seed)
actual = rng.f(12, 77, size=(3, 2))
desired = np.array([[1.21975394418575878, 1.75135759791559775],
[1.44803115017146489, 1.22108959480396262],
[1.02176975757740629, 1.34431827623300415]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_gamma(self):
rng = random.RandomState(self.seed)
actual = rng.gamma(5, 3, size=(3, 2))
desired = np.array([[24.60509188649287182, 28.54993563207210627],
[26.13476110204064184, 12.56988482927716078],
[31.71863275789960568, 33.30143302795922011]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_gamma_0(self):
assert_equal(random.gamma(shape=0, scale=0), 0)
assert_raises(ValueError, random.gamma, shape=-0., scale=-0.)
def test_geometric(self):
rng = random.RandomState(self.seed)
actual = rng.geometric(.123456789, size=(3, 2))
desired = np.array([[8, 7],
[17, 17],
[5, 12]])
assert_array_equal(actual, desired)
def test_geometric_exceptions(self):
assert_raises(ValueError, random.geometric, 1.1)
assert_raises(ValueError, random.geometric, [1.1] * 10)
assert_raises(ValueError, random.geometric, -0.1)
assert_raises(ValueError, random.geometric, [-0.1] * 10)
with warnings.catch_warnings():
warnings.simplefilter('ignore', RuntimeWarning)
assert_raises(ValueError, random.geometric, np.nan)
assert_raises(ValueError, random.geometric, [np.nan] * 10)
def test_gumbel(self):
rng = random.RandomState(self.seed)
actual = rng.gumbel(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[0.19591898743416816, 0.34405539668096674],
[-1.4492522252274278, -1.47374816298446865],
[1.10651090478803416, -0.69535848626236174]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_gumbel_0(self):
assert_equal(random.gumbel(scale=0), 0)
assert_raises(ValueError, random.gumbel, scale=-0.)
def test_hypergeometric(self):
rng = random.RandomState(self.seed)
actual = rng.hypergeometric(10.1, 5.5, 14, size=(3, 2))
desired = np.array([[10, 10],
[10, 10],
[9, 9]])
assert_array_equal(actual, desired)
# Test nbad = 0
actual = rng.hypergeometric(5, 0, 3, size=4)
desired = np.array([3, 3, 3, 3])
assert_array_equal(actual, desired)
actual = rng.hypergeometric(15, 0, 12, size=4)
desired = np.array([12, 12, 12, 12])
assert_array_equal(actual, desired)
# Test ngood = 0
actual = rng.hypergeometric(0, 5, 3, size=4)
desired = np.array([0, 0, 0, 0])
assert_array_equal(actual, desired)
actual = rng.hypergeometric(0, 15, 12, size=4)
desired = np.array([0, 0, 0, 0])
assert_array_equal(actual, desired)
def test_laplace(self):
rng = random.RandomState(self.seed)
actual = rng.laplace(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[0.66599721112760157, 0.52829452552221945],
[3.12791959514407125, 3.18202813572992005],
[-0.05391065675859356, 1.74901336242837324]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_laplace_0(self):
assert_equal(random.laplace(scale=0), 0)
assert_raises(ValueError, random.laplace, scale=-0.)
def test_logistic(self):
rng = random.RandomState(self.seed)
actual = rng.logistic(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[1.09232835305011444, 0.8648196662399954],
[4.27818590694950185, 4.33897006346929714],
[-0.21682183359214885, 2.63373365386060332]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_lognormal(self):
rng = random.RandomState(self.seed)
actual = rng.lognormal(mean=.123456789, sigma=2.0, size=(3, 2))
desired = np.array([[16.50698631688883822, 36.54846706092654784],
[22.67886599981281748, 0.71617561058995771],
[65.72798501792723869, 86.84341601437161273]])
assert_array_almost_equal(actual, desired, decimal=13)
def test_lognormal_0(self):
assert_equal(random.lognormal(sigma=0), 1)
assert_raises(ValueError, random.lognormal, sigma=-0.)
def test_logseries(self):
rng = random.RandomState(self.seed)
actual = rng.logseries(p=.923456789, size=(3, 2))
desired = np.array([[2, 2],
[6, 17],
[3, 6]])
assert_array_equal(actual, desired)
def test_logseries_zero(self):
assert random.logseries(0) == 1
@pytest.mark.parametrize("value", [np.nextafter(0., -1), 1., np.nan, 5.])
def test_logseries_exceptions(self, value):
with np.errstate(invalid="ignore"):
with pytest.raises(ValueError):
random.logseries(value)
with pytest.raises(ValueError):
# contiguous path:
random.logseries(np.array([value] * 10))
with pytest.raises(ValueError):
# non-contiguous path:
random.logseries(np.array([value] * 10)[::2])
def test_multinomial(self):
rng = random.RandomState(self.seed)
actual = rng.multinomial(20, [1 / 6.] * 6, size=(3, 2))
desired = np.array([[[4, 3, 5, 4, 2, 2],
[5, 2, 8, 2, 2, 1]],
[[3, 4, 3, 6, 0, 4],
[2, 1, 4, 3, 6, 4]],
[[4, 4, 2, 5, 2, 3],
[4, 3, 4, 2, 3, 4]]])
assert_array_equal(actual, desired)
def test_multivariate_normal(self):
rng = random.RandomState(self.seed)
mean = (.123456789, 10)
cov = [[1, 0], [0, 1]]
size = (3, 2)
actual = rng.multivariate_normal(mean, cov, size)
desired = np.array([[[1.463620246718631, 11.73759122771936],
[1.622445133300628, 9.771356667546383]],
[[2.154490787682787, 12.170324946056553],
[1.719909438201865, 9.230548443648306]],
[[0.689515026297799, 9.880729819607714],
[-0.023054015651998, 9.201096623542879]]])
assert_array_almost_equal(actual, desired, decimal=15)
# Check for default size, was raising deprecation warning
actual = rng.multivariate_normal(mean, cov)
desired = np.array([0.895289569463708, 9.17180864067987])
assert_array_almost_equal(actual, desired, decimal=15)
# Check that non positive-semidefinite covariance warns with
# RuntimeWarning
mean = [0, 0]
cov = [[1, 2], [2, 1]]
pytest.warns(RuntimeWarning, rng.multivariate_normal, mean, cov)
# and that it doesn't warn with RuntimeWarning check_valid='ignore'
assert_no_warnings(rng.multivariate_normal, mean, cov,
check_valid='ignore')
# and that it raises with RuntimeWarning check_valid='raises'
assert_raises(ValueError, rng.multivariate_normal, mean, cov,
check_valid='raise')
cov = np.array([[1, 0.1], [0.1, 1]], dtype=np.float32)
with warnings.catch_warnings():
warnings.simplefilter('error', RuntimeWarning)
rng.multivariate_normal(mean, cov)
mu = np.zeros(2)
cov = np.eye(2)
assert_raises(ValueError, rng.multivariate_normal, mean, cov,
check_valid='other')
assert_raises(ValueError, rng.multivariate_normal,
np.zeros((2, 1, 1)), cov)
assert_raises(ValueError, rng.multivariate_normal,
mu, np.empty((3, 2)))
assert_raises(ValueError, rng.multivariate_normal,
mu, np.eye(3))
def test_negative_binomial(self):
rng = random.RandomState(self.seed)
actual = rng.negative_binomial(n=100, p=.12345, size=(3, 2))
desired = np.array([[848, 841],
[892, 611],
[779, 647]])
assert_array_equal(actual, desired)
def test_negative_binomial_exceptions(self):
with warnings.catch_warnings():
warnings.simplefilter('ignore', RuntimeWarning)
assert_raises(ValueError, random.negative_binomial, 100, np.nan)
assert_raises(ValueError, random.negative_binomial, 100,
[np.nan] * 10)
def test_noncentral_chisquare(self):
rng = random.RandomState(self.seed)
actual = rng.noncentral_chisquare(df=5, nonc=5, size=(3, 2))
desired = np.array([[23.91905354498517511, 13.35324692733826346],
[31.22452661329736401, 16.60047399466177254],
[5.03461598262724586, 17.94973089023519464]])
assert_array_almost_equal(actual, desired, decimal=14)
actual = rng.noncentral_chisquare(df=.5, nonc=.2, size=(3, 2))
desired = np.array([[1.47145377828516666, 0.15052899268012659],
[0.00943803056963588, 1.02647251615666169],
[0.332334982684171, 0.15451287602753125]])
assert_array_almost_equal(actual, desired, decimal=14)
rng = random.RandomState(self.seed)
actual = rng.noncentral_chisquare(df=5, nonc=0, size=(3, 2))
desired = np.array([[9.597154162763948, 11.725484450296079],
[10.413711048138335, 3.694475922923986],
[13.484222138963087, 14.377255424602957]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_noncentral_f(self):
rng = random.RandomState(self.seed)
actual = rng.noncentral_f(dfnum=5, dfden=2, nonc=1,
size=(3, 2))
desired = np.array([[1.40598099674926669, 0.34207973179285761],
[3.57715069265772545, 7.92632662577829805],
[0.43741599463544162, 1.1774208752428319]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_noncentral_f_nan(self):
random.seed(self.seed)
actual = random.noncentral_f(dfnum=5, dfden=2, nonc=np.nan)
assert np.isnan(actual)
def test_normal(self):
rng = random.RandomState(self.seed)
actual = rng.normal(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[2.80378370443726244, 3.59863924443872163],
[3.121433477601256, -0.33382987590723379],
[4.18552478636557357, 4.46410668111310471]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_normal_0(self):
assert_equal(random.normal(scale=0), 0)
assert_raises(ValueError, random.normal, scale=-0.)
def test_pareto(self):
rng = random.RandomState(self.seed)
actual = rng.pareto(a=.123456789, size=(3, 2))
desired = np.array(
[[2.46852460439034849e+03, 1.41286880810518346e+03],
[5.28287797029485181e+07, 6.57720981047328785e+07],
[1.40840323350391515e+02, 1.98390255135251704e+05]])
# For some reason on 32-bit x86 Ubuntu 12.10 the [1, 0] entry in this
# matrix differs by 24 nulps. Discussion:
# https://mail.python.org/pipermail/numpy-discussion/2012-September/063801.html
# Consensus is that this is probably some gcc quirk that affects
# rounding but not in any important way, so we just use a looser
# tolerance on this test:
np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=30)
def test_poisson(self):
rng = random.RandomState(self.seed)
actual = rng.poisson(lam=.123456789, size=(3, 2))
desired = np.array([[0, 0],
[1, 0],
[0, 0]])
assert_array_equal(actual, desired)
def test_poisson_exceptions(self):
lambig = np.iinfo('l').max
lamneg = -1
assert_raises(ValueError, random.poisson, lamneg)
assert_raises(ValueError, random.poisson, [lamneg] * 10)
assert_raises(ValueError, random.poisson, lambig)
assert_raises(ValueError, random.poisson, [lambig] * 10)
with warnings.catch_warnings():
warnings.simplefilter('ignore', RuntimeWarning)
assert_raises(ValueError, random.poisson, np.nan)
assert_raises(ValueError, random.poisson, [np.nan] * 10)
def test_power(self):
rng = random.RandomState(self.seed)
actual = rng.power(a=.123456789, size=(3, 2))
desired = np.array([[0.02048932883240791, 0.01424192241128213],
[0.38446073748535298, 0.39499689943484395],
[0.00177699707563439, 0.13115505880863756]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_rayleigh(self):
rng = random.RandomState(self.seed)
actual = rng.rayleigh(scale=10, size=(3, 2))
desired = np.array([[13.8882496494248393, 13.383318339044731],
[20.95413364294492098, 21.08285015800712614],
[11.06066537006854311, 17.35468505778271009]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_rayleigh_0(self):
assert_equal(random.rayleigh(scale=0), 0)
assert_raises(ValueError, random.rayleigh, scale=-0.)
def test_standard_cauchy(self):
rng = random.RandomState(self.seed)
actual = rng.standard_cauchy(size=(3, 2))
desired = np.array([[0.77127660196445336, -6.55601161955910605],
[0.93582023391158309, -2.07479293013759447],
[-4.74601644297011926, 0.18338989290760804]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_exponential(self):
rng = random.RandomState(self.seed)
actual = rng.standard_exponential(size=(3, 2))
desired = np.array([[0.96441739162374596, 0.89556604882105506],
[2.1953785836319808, 2.22243285392490542],
[0.6116915921431676, 1.50592546727413201]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_gamma(self):
rng = random.RandomState(self.seed)
actual = rng.standard_gamma(shape=3, size=(3, 2))
desired = np.array([[5.50841531318455058, 6.62953470301903103],
[5.93988484943779227, 2.31044849402133989],
[7.54838614231317084, 8.012756093271868]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_standard_gamma_0(self):
assert_equal(random.standard_gamma(shape=0), 0)
assert_raises(ValueError, random.standard_gamma, shape=-0.)
def test_standard_normal(self):
rng = random.RandomState(self.seed)
actual = rng.standard_normal(size=(3, 2))
desired = np.array([[1.34016345771863121, 1.73759122771936081],
[1.498988344300628, -0.2286433324536169],
[2.031033998682787, 2.17032494605655257]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_randn_singleton(self):
rng = random.RandomState(self.seed)
actual = rng.randn()
desired = np.array(1.34016345771863121)
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_t(self):
rng = random.RandomState(self.seed)
actual = rng.standard_t(df=10, size=(3, 2))
desired = np.array([[0.97140611862659965, -0.08830486548450577],
[1.36311143689505321, -0.55317463909867071],
[-0.18473749069684214, 0.61181537341755321]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_triangular(self):
rng = random.RandomState(self.seed)
actual = rng.triangular(left=5.12, mode=10.23, right=20.34,
size=(3, 2))
desired = np.array([[12.68117178949215784, 12.4129206149193152],
[16.20131377335158263, 16.25692138747600524],
[11.20400690911820263, 14.4978144835829923]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_uniform(self):
rng = random.RandomState(self.seed)
actual = rng.uniform(low=1.23, high=10.54, size=(3, 2))
desired = np.array([[6.99097932346268003, 6.73801597444323974],
[9.50364421400426274, 9.53130618907631089],
[5.48995325769805476, 8.47493103280052118]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_uniform_range_bounds(self):
fmin = np.finfo('float').min
fmax = np.finfo('float').max
func = random.uniform
assert_raises(OverflowError, func, -np.inf, 0)
assert_raises(OverflowError, func, 0, np.inf)
assert_raises(OverflowError, func, fmin, fmax)
assert_raises(OverflowError, func, [-np.inf], [0])
assert_raises(OverflowError, func, [0], [np.inf])
# (fmax / 1e17) - fmin is within range, so this should not throw
# account for i386 extended precision DBL_MAX / 1e17 + DBL_MAX >
# DBL_MAX by increasing fmin a bit
random.uniform(low=np.nextafter(fmin, 1), high=fmax / 1e17)
def test_scalar_exception_propagation(self):
# Tests that exceptions are correctly propagated in distributions
# when called with objects that throw exceptions when converted to
# scalars.
#
# Regression test for gh: 8865
class ThrowingFloat(np.ndarray):
def __float__(self):
raise TypeError
throwing_float = np.array(1.0).view(ThrowingFloat)
assert_raises(TypeError, random.uniform, throwing_float,
throwing_float)
class ThrowingInteger(np.ndarray):
def __int__(self):
raise TypeError
throwing_int = np.array(1).view(ThrowingInteger)
assert_raises(TypeError, random.hypergeometric, throwing_int, 1, 1)
def test_vonmises(self):
rng = random.RandomState(self.seed)
actual = rng.vonmises(mu=1.23, kappa=1.54, size=(3, 2))
desired = np.array([[2.28567572673902042, 2.89163838442285037],
[0.38198375564286025, 2.57638023113890746],
[1.19153771588353052, 1.83509849681825354]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_vonmises_small(self):
# check infinite loop, gh-4720
random.seed(self.seed)
r = random.vonmises(mu=0., kappa=1.1e-8, size=10**6)
assert_(np.isfinite(r).all())
def test_vonmises_large(self):
# guard against changes in RandomState when Generator is fixed
rng = random.RandomState(self.seed)
actual = rng.vonmises(mu=0., kappa=1e7, size=3)
desired = np.array([4.634253748521111e-04,
3.558873596114509e-04,
-2.337119622577433e-04])
assert_array_almost_equal(actual, desired, decimal=8)
def test_vonmises_nan(self):
random.seed(self.seed)
r = random.vonmises(mu=0., kappa=np.nan)
assert_(np.isnan(r))
def test_wald(self):
rng = random.RandomState(self.seed)
actual = rng.wald(mean=1.23, scale=1.54, size=(3, 2))
desired = np.array([[3.82935265715889983, 5.13125249184285526],
[0.35045403618358717, 1.50832396872003538],
[0.24124319895843183, 0.22031101461955038]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_weibull(self):
rng = random.RandomState(self.seed)
actual = rng.weibull(a=1.23, size=(3, 2))
desired = np.array([[0.97097342648766727, 0.91422896443565516],
[1.89517770034962929, 1.91414357960479564],
[0.67057783752390987, 1.39494046635066793]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_weibull_0(self):
random.seed(self.seed)
assert_equal(random.weibull(a=0, size=12), np.zeros(12))
assert_raises(ValueError, random.weibull, a=-0.)
def test_zipf(self):
rng = random.RandomState(self.seed)
actual = rng.zipf(a=1.23, size=(3, 2))
desired = np.array([[66, 29],
[1, 1],
[3, 13]])
assert_array_equal(actual, desired)
class TestBroadcast:
# tests that functions that broadcast behave
# correctly when presented with non-scalar arguments
seed = 123456789
def test_uniform(self):
low = [0]
high = [1]
desired = np.array([0.53283302478975902,
0.53413660089041659,
0.50955303552646702])
rng = random.RandomState(self.seed)
actual = rng.uniform(low * 3, high)
assert_array_almost_equal(actual, desired, decimal=14)
rng = random.RandomState(self.seed)
actual = rng.uniform(low, high * 3)
assert_array_almost_equal(actual, desired, decimal=14)
def test_normal(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([2.2129019979039612,
2.1283977976520019,
1.8417114045748335])
rng = random.RandomState(self.seed)
actual = rng.normal(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.normal, loc * 3, bad_scale)
rng = random.RandomState(self.seed)
actual = rng.normal(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.normal, loc, bad_scale * 3)
def test_beta(self):
a = [1]
b = [2]
bad_a = [-1]
bad_b = [-2]
desired = np.array([0.19843558305989056,
0.075230336409423643,
0.24976865978980844])
rng = random.RandomState(self.seed)
actual = rng.beta(a * 3, b)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.beta, bad_a * 3, b)
assert_raises(ValueError, rng.beta, a * 3, bad_b)
rng = random.RandomState(self.seed)
actual = rng.beta(a, b * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.beta, bad_a, b * 3)
assert_raises(ValueError, rng.beta, a, bad_b * 3)
def test_exponential(self):
scale = [1]
bad_scale = [-1]
desired = np.array([0.76106853658845242,
0.76386282278691653,
0.71243813125891797])
rng = random.RandomState(self.seed)
actual = rng.exponential(scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.exponential, bad_scale * 3)
def test_standard_gamma(self):
shape = [1]
bad_shape = [-1]
desired = np.array([0.76106853658845242,
0.76386282278691653,
0.71243813125891797])
rng = random.RandomState(self.seed)
actual = rng.standard_gamma(shape * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.standard_gamma, bad_shape * 3)
def test_gamma(self):
shape = [1]
scale = [2]
bad_shape = [-1]
bad_scale = [-2]
desired = np.array([1.5221370731769048,
1.5277256455738331,
1.4248762625178359])
rng = random.RandomState(self.seed)
actual = rng.gamma(shape * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.gamma, bad_shape * 3, scale)
assert_raises(ValueError, rng.gamma, shape * 3, bad_scale)
rng = random.RandomState(self.seed)
actual = rng.gamma(shape, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.gamma, bad_shape, scale * 3)
assert_raises(ValueError, rng.gamma, shape, bad_scale * 3)
def test_f(self):
dfnum = [1]
dfden = [2]
bad_dfnum = [-1]
bad_dfden = [-2]
desired = np.array([0.80038951638264799,
0.86768719635363512,
2.7251095168386801])
rng = random.RandomState(self.seed)
actual = rng.f(dfnum * 3, dfden)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.f, bad_dfnum * 3, dfden)
assert_raises(ValueError, rng.f, dfnum * 3, bad_dfden)
rng = random.RandomState(self.seed)
actual = rng.f(dfnum, dfden * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.f, bad_dfnum, dfden * 3)
assert_raises(ValueError, rng.f, dfnum, bad_dfden * 3)
def test_noncentral_f(self):
dfnum = [2]
dfden = [3]
nonc = [4]
bad_dfnum = [0]
bad_dfden = [-1]
bad_nonc = [-2]
desired = np.array([9.1393943263705211,
13.025456344595602,
8.8018098359100545])
rng = random.RandomState(self.seed)
actual = rng.noncentral_f(dfnum * 3, dfden, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert np.all(np.isnan(rng.noncentral_f(dfnum, dfden, [np.nan] * 3)))
assert_raises(ValueError, rng.noncentral_f, bad_dfnum * 3, dfden, nonc)
assert_raises(ValueError, rng.noncentral_f, dfnum * 3, bad_dfden, nonc)
assert_raises(ValueError, rng.noncentral_f, dfnum * 3, dfden, bad_nonc)
rng = random.RandomState(self.seed)
actual = rng.noncentral_f(dfnum, dfden * 3, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.noncentral_f, bad_dfnum, dfden * 3, nonc)
assert_raises(ValueError, rng.noncentral_f, dfnum, bad_dfden * 3, nonc)
assert_raises(ValueError, rng.noncentral_f, dfnum, dfden * 3, bad_nonc)
rng = random.RandomState(self.seed)
actual = rng.noncentral_f(dfnum, dfden, nonc * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.noncentral_f, bad_dfnum, dfden, nonc * 3)
assert_raises(ValueError, rng.noncentral_f, dfnum, bad_dfden, nonc * 3)
assert_raises(ValueError, rng.noncentral_f, dfnum, dfden, bad_nonc * 3)
def test_noncentral_f_small_df(self):
rng = random.RandomState(self.seed)
desired = np.array([6.869638627492048, 0.785880199263955])
actual = rng.noncentral_f(0.9, 0.9, 2, size=2)
assert_array_almost_equal(actual, desired, decimal=14)
def test_chisquare(self):
df = [1]
bad_df = [-1]
desired = np.array([0.57022801133088286,
0.51947702108840776,
0.1320969254923558])
rng = random.RandomState(self.seed)
actual = rng.chisquare(df * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.chisquare, bad_df * 3)
def test_noncentral_chisquare(self):
df = [1]
nonc = [2]
bad_df = [-1]
bad_nonc = [-2]
desired = np.array([9.0015599467913763,
4.5804135049718742,
6.0872302432834564])
rng = random.RandomState(self.seed)
actual = rng.noncentral_chisquare(df * 3, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.noncentral_chisquare, bad_df * 3, nonc)
assert_raises(ValueError, rng.noncentral_chisquare, df * 3, bad_nonc)
rng = random.RandomState(self.seed)
actual = rng.noncentral_chisquare(df, nonc * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.noncentral_chisquare, bad_df, nonc * 3)
assert_raises(ValueError, rng.noncentral_chisquare, df, bad_nonc * 3)
def test_standard_t(self):
df = [1]
bad_df = [-1]
desired = np.array([3.0702872575217643,
5.8560725167361607,
1.0274791436474273])
rng = random.RandomState(self.seed)
actual = rng.standard_t(df * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.standard_t, bad_df * 3)
assert_raises(ValueError, random.standard_t, bad_df * 3)
def test_vonmises(self):
mu = [2]
kappa = [1]
bad_kappa = [-1]
desired = np.array([2.9883443664201312,
-2.7064099483995943,
-1.8672476700665914])
rng = random.RandomState(self.seed)
actual = rng.vonmises(mu * 3, kappa)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.vonmises, mu * 3, bad_kappa)
rng = random.RandomState(self.seed)
actual = rng.vonmises(mu, kappa * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.vonmises, mu, bad_kappa * 3)
def test_pareto(self):
a = [1]
bad_a = [-1]
desired = np.array([1.1405622680198362,
1.1465519762044529,
1.0389564467453547])
rng = random.RandomState(self.seed)
actual = rng.pareto(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.pareto, bad_a * 3)
assert_raises(ValueError, random.pareto, bad_a * 3)
def test_weibull(self):
a = [1]
bad_a = [-1]
desired = np.array([0.76106853658845242,
0.76386282278691653,
0.71243813125891797])
rng = random.RandomState(self.seed)
actual = rng.weibull(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.weibull, bad_a * 3)
assert_raises(ValueError, random.weibull, bad_a * 3)
def test_power(self):
a = [1]
bad_a = [-1]
desired = np.array([0.53283302478975902,
0.53413660089041659,
0.50955303552646702])
rng = random.RandomState(self.seed)
actual = rng.power(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.power, bad_a * 3)
assert_raises(ValueError, random.power, bad_a * 3)
def test_laplace(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([0.067921356028507157,
0.070715642226971326,
0.019290950698972624])
rng = random.RandomState(self.seed)
actual = rng.laplace(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.laplace, loc * 3, bad_scale)
rng = random.RandomState(self.seed)
actual = rng.laplace(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.laplace, loc, bad_scale * 3)
def test_gumbel(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([0.2730318639556768,
0.26936705726291116,
0.33906220393037939])
rng = random.RandomState(self.seed)
actual = rng.gumbel(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.gumbel, loc * 3, bad_scale)
rng = random.RandomState(self.seed)
actual = rng.gumbel(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.gumbel, loc, bad_scale * 3)
def test_logistic(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([0.13152135837586171,
0.13675915696285773,
0.038216792802833396])
rng = random.RandomState(self.seed)
actual = rng.logistic(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.logistic, loc * 3, bad_scale)
rng = random.RandomState(self.seed)
actual = rng.logistic(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.logistic, loc, bad_scale * 3)
assert_equal(rng.logistic(1.0, 0.0), 1.0)
def test_lognormal(self):
mean = [0]
sigma = [1]
bad_sigma = [-1]
desired = np.array([9.1422086044848427,
8.4013952870126261,
6.3073234116578671])
rng = random.RandomState(self.seed)
actual = rng.lognormal(mean * 3, sigma)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.lognormal, mean * 3, bad_sigma)
assert_raises(ValueError, random.lognormal, mean * 3, bad_sigma)
rng = random.RandomState(self.seed)
actual = rng.lognormal(mean, sigma * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.lognormal, mean, bad_sigma * 3)
assert_raises(ValueError, random.lognormal, mean, bad_sigma * 3)
def test_rayleigh(self):
scale = [1]
bad_scale = [-1]
desired = np.array([1.2337491937897689,
1.2360119924878694,
1.1936818095781789])
rng = random.RandomState(self.seed)
actual = rng.rayleigh(scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.rayleigh, bad_scale * 3)
def test_wald(self):
mean = [0.5]
scale = [1]
bad_mean = [0]
bad_scale = [-2]
desired = np.array([0.11873681120271318,
0.12450084820795027,
0.9096122728408238])
rng = random.RandomState(self.seed)
actual = rng.wald(mean * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.wald, bad_mean * 3, scale)
assert_raises(ValueError, rng.wald, mean * 3, bad_scale)
assert_raises(ValueError, random.wald, bad_mean * 3, scale)
assert_raises(ValueError, random.wald, mean * 3, bad_scale)
rng = random.RandomState(self.seed)
actual = rng.wald(mean, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.wald, bad_mean, scale * 3)
assert_raises(ValueError, rng.wald, mean, bad_scale * 3)
assert_raises(ValueError, rng.wald, 0.0, 1)
assert_raises(ValueError, rng.wald, 0.5, 0.0)
def test_triangular(self):
left = [1]
right = [3]
mode = [2]
bad_left_one = [3]
bad_mode_one = [4]
bad_left_two, bad_mode_two = right * 2
desired = np.array([2.03339048710429,
2.0347400359389356,
2.0095991069536208])
rng = random.RandomState(self.seed)
actual = rng.triangular(left * 3, mode, right)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.triangular, bad_left_one * 3, mode, right)
assert_raises(ValueError, rng.triangular, left * 3, bad_mode_one, right)
assert_raises(ValueError, rng.triangular, bad_left_two * 3, bad_mode_two,
right)
rng = random.RandomState(self.seed)
actual = rng.triangular(left, mode * 3, right)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.triangular, bad_left_one, mode * 3, right)
assert_raises(ValueError, rng.triangular, left, bad_mode_one * 3, right)
assert_raises(ValueError, rng.triangular, bad_left_two, bad_mode_two * 3,
right)
rng = random.RandomState(self.seed)
actual = rng.triangular(left, mode, right * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.triangular, bad_left_one, mode, right * 3)
assert_raises(ValueError, rng.triangular, left, bad_mode_one, right * 3)
assert_raises(ValueError, rng.triangular, bad_left_two, bad_mode_two,
right * 3)
assert_raises(ValueError, rng.triangular, 10., 0., 20.)
assert_raises(ValueError, rng.triangular, 10., 25., 20.)
assert_raises(ValueError, rng.triangular, 10., 10., 10.)
def test_binomial(self):
n = [1]
p = [0.5]
bad_n = [-1]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([1, 1, 1])
rng = random.RandomState(self.seed)
actual = rng.binomial(n * 3, p)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.binomial, bad_n * 3, p)
assert_raises(ValueError, rng.binomial, n * 3, bad_p_one)
assert_raises(ValueError, rng.binomial, n * 3, bad_p_two)
rng = random.RandomState(self.seed)
actual = rng.binomial(n, p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.binomial, bad_n, p * 3)
assert_raises(ValueError, rng.binomial, n, bad_p_one * 3)
assert_raises(ValueError, rng.binomial, n, bad_p_two * 3)
def test_negative_binomial(self):
n = [1]
p = [0.5]
bad_n = [-1]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([1, 0, 1])
rng = random.RandomState(self.seed)
actual = rng.negative_binomial(n * 3, p)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.negative_binomial, bad_n * 3, p)
assert_raises(ValueError, rng.negative_binomial, n * 3, bad_p_one)
assert_raises(ValueError, rng.negative_binomial, n * 3, bad_p_two)
rng = random.RandomState(self.seed)
actual = rng.negative_binomial(n, p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.negative_binomial, bad_n, p * 3)
assert_raises(ValueError, rng.negative_binomial, n, bad_p_one * 3)
assert_raises(ValueError, rng.negative_binomial, n, bad_p_two * 3)
def test_poisson(self):
max_lam = random.RandomState()._poisson_lam_max
lam = [1]
bad_lam_one = [-1]
bad_lam_two = [max_lam * 2]
desired = np.array([1, 1, 0])
rng = random.RandomState(self.seed)
actual = rng.poisson(lam * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.poisson, bad_lam_one * 3)
assert_raises(ValueError, rng.poisson, bad_lam_two * 3)
def test_zipf(self):
a = [2]
bad_a = [0]
desired = np.array([2, 2, 1])
rng = random.RandomState(self.seed)
actual = rng.zipf(a * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.zipf, bad_a * 3)
with np.errstate(invalid='ignore'):
assert_raises(ValueError, rng.zipf, np.nan)
assert_raises(ValueError, rng.zipf, [0, 0, np.nan])
def test_geometric(self):
p = [0.5]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([2, 2, 2])
rng = random.RandomState(self.seed)
actual = rng.geometric(p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.geometric, bad_p_one * 3)
assert_raises(ValueError, rng.geometric, bad_p_two * 3)
def test_hypergeometric(self):
ngood = [1]
nbad = [2]
nsample = [2]
bad_ngood = [-1]
bad_nbad = [-2]
bad_nsample_one = [0]
bad_nsample_two = [4]
desired = np.array([1, 1, 1])
rng = random.RandomState(self.seed)
actual = rng.hypergeometric(ngood * 3, nbad, nsample)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.hypergeometric, bad_ngood * 3, nbad, nsample)
assert_raises(ValueError, rng.hypergeometric, ngood * 3, bad_nbad, nsample)
assert_raises(ValueError, rng.hypergeometric, ngood * 3, nbad, bad_nsample_one)
assert_raises(ValueError, rng.hypergeometric, ngood * 3, nbad, bad_nsample_two)
rng = random.RandomState(self.seed)
actual = rng.hypergeometric(ngood, nbad * 3, nsample)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.hypergeometric, bad_ngood, nbad * 3, nsample)
assert_raises(ValueError, rng.hypergeometric, ngood, bad_nbad * 3, nsample)
assert_raises(ValueError, rng.hypergeometric, ngood, nbad * 3, bad_nsample_one)
assert_raises(ValueError, rng.hypergeometric, ngood, nbad * 3, bad_nsample_two)
rng = random.RandomState(self.seed)
actual = rng.hypergeometric(ngood, nbad, nsample * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.hypergeometric, bad_ngood, nbad, nsample * 3)
assert_raises(ValueError, rng.hypergeometric, ngood, bad_nbad, nsample * 3)
assert_raises(ValueError, rng.hypergeometric, ngood, nbad, bad_nsample_one * 3)
assert_raises(ValueError, rng.hypergeometric, ngood, nbad, bad_nsample_two * 3)
assert_raises(ValueError, rng.hypergeometric, -1, 10, 20)
assert_raises(ValueError, rng.hypergeometric, 10, -1, 20)
assert_raises(ValueError, rng.hypergeometric, 10, 10, 0)
assert_raises(ValueError, rng.hypergeometric, 10, 10, 25)
def test_logseries(self):
p = [0.5]
bad_p_one = [2]
bad_p_two = [-1]
desired = np.array([1, 1, 1])
rng = random.RandomState(self.seed)
actual = rng.logseries(p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.logseries, bad_p_one * 3)
assert_raises(ValueError, rng.logseries, bad_p_two * 3)
@pytest.mark.skipif(IS_WASM, reason="can't start thread")
class TestThread:
# make sure each state produces the same sequence even in threads
seeds = range(4)
def check_function(self, function, sz):
from threading import Thread
out1 = np.empty((len(self.seeds),) + sz)
out2 = np.empty((len(self.seeds),) + sz)
# threaded generation
t = [Thread(target=function, args=(random.RandomState(s), o))
for s, o in zip(self.seeds, out1)]
[x.start() for x in t]
[x.join() for x in t]
# the same serial
for s, o in zip(self.seeds, out2):
function(random.RandomState(s), o)
# these platforms change x87 fpu precision mode in threads
if np.intp().dtype.itemsize == 4 and sys.platform == "win32":
assert_array_almost_equal(out1, out2)
else:
assert_array_equal(out1, out2)
def test_normal(self):
def gen_random(state, out):
out[...] = state.normal(size=10000)
self.check_function(gen_random, sz=(10000,))
def test_exp(self):
def gen_random(state, out):
out[...] = state.exponential(scale=np.ones((100, 1000)))
self.check_function(gen_random, sz=(100, 1000))
def test_multinomial(self):
def gen_random(state, out):
out[...] = state.multinomial(10, [1 / 6.] * 6, size=10000)
self.check_function(gen_random, sz=(10000, 6))
# See Issue #4263
class TestSingleEltArrayInput:
def _create_arrays(self):
return np.array([2]), np.array([3]), np.array([4]), (1,)
def test_one_arg_funcs(self):
argOne, _, _, tgtShape = self._create_arrays()
funcs = (random.exponential, random.standard_gamma,
random.chisquare, random.standard_t,
random.pareto, random.weibull,
random.power, random.rayleigh,
random.poisson, random.zipf,
random.geometric, random.logseries)
probfuncs = (random.geometric, random.logseries)
for func in funcs:
if func in probfuncs: # p < 1.0
out = func(np.array([0.5]))
else:
out = func(argOne)
assert_equal(out.shape, tgtShape)
def test_two_arg_funcs(self):
argOne, argTwo, _, tgtShape = self._create_arrays()
funcs = (random.uniform, random.normal,
random.beta, random.gamma,
random.f, random.noncentral_chisquare,
random.vonmises, random.laplace,
random.gumbel, random.logistic,
random.lognormal, random.wald,
random.binomial, random.negative_binomial)
probfuncs = (random.binomial, random.negative_binomial)
for func in funcs:
if func in probfuncs: # p <= 1
argTwo = np.array([0.5])
else:
argTwo = argTwo
out = func(argOne, argTwo)
assert_equal(out.shape, tgtShape)
out = func(argOne[0], argTwo)
assert_equal(out.shape, tgtShape)
out = func(argOne, argTwo[0])
assert_equal(out.shape, tgtShape)
def test_three_arg_funcs(self):
argOne, argTwo, argThree, tgtShape = self._create_arrays()
funcs = [random.noncentral_f, random.triangular,
random.hypergeometric]
for func in funcs:
out = func(argOne, argTwo, argThree)
assert_equal(out.shape, tgtShape)
out = func(argOne[0], argTwo, argThree)
assert_equal(out.shape, tgtShape)
out = func(argOne, argTwo[0], argThree)
assert_equal(out.shape, tgtShape)
# Ensure returned array dtype is correct for platform
def test_integer_dtype(int_func):
random.seed(123456789)
fname, args, sha256 = int_func
f = getattr(random, fname)
actual = f(*args, size=2)
assert_(actual.dtype == np.dtype('l'))
def test_integer_repeat(int_func):
rng = random.RandomState(123456789)
fname, args, sha256 = int_func
f = getattr(rng, fname)
val = f(*args, size=1000000)
if sys.byteorder != 'little':
val = val.byteswap()
res = hashlib.sha256(val.view(np.int8)).hexdigest()
assert_(res == sha256)
def test_broadcast_size_error():
# GH-16833
with pytest.raises(ValueError):
random.binomial(1, [0.3, 0.7], size=(2, 1))
with pytest.raises(ValueError):
random.binomial([1, 2], 0.3, size=(2, 1))
with pytest.raises(ValueError):
random.binomial([1, 2], [0.3, 0.7], size=(2, 1))
def test_randomstate_ctor_old_style_pickle():
rs = np.random.RandomState(MT19937(0))
rs.standard_normal(1)
# Directly call reduce which is used in pickling
ctor, args, state_a = rs.__reduce__()
# Simulate unpickling an old pickle that only has the name
assert args[0].__class__.__name__ == "MT19937"
b = ctor(*("MT19937",))
b.set_state(state_a)
state_b = b.get_state(legacy=False)
assert_equal(state_a['bit_generator'], state_b['bit_generator'])
assert_array_equal(state_a['state']['key'], state_b['state']['key'])
assert_array_equal(state_a['state']['pos'], state_b['state']['pos'])
assert_equal(state_a['has_gauss'], state_b['has_gauss'])
assert_equal(state_a['gauss'], state_b['gauss'])
@pytest.mark.thread_unsafe(reason="np.random.set_bit_generator affects global state")
def test_hot_swap(restore_singleton_bitgen):
# GH 21808
def_bg = np.random.default_rng(0)
bg = def_bg.bit_generator
np.random.set_bit_generator(bg)
assert isinstance(np.random.mtrand._rand._bit_generator, type(bg))
second_bg = np.random.get_bit_generator()
assert bg is second_bg
@pytest.mark.thread_unsafe(reason="np.random.set_bit_generator affects global state")
def test_seed_alt_bit_gen(restore_singleton_bitgen):
# GH 21808
bg = PCG64(0)
np.random.set_bit_generator(bg)
state = np.random.get_state(legacy=False)
np.random.seed(1)
new_state = np.random.get_state(legacy=False)
print(state)
print(new_state)
assert state["bit_generator"] == "PCG64"
assert state["state"]["state"] != new_state["state"]["state"]
assert state["state"]["inc"] != new_state["state"]["inc"]
@pytest.mark.thread_unsafe(reason="np.random.set_bit_generator affects global state")
def test_state_error_alt_bit_gen(restore_singleton_bitgen):
# GH 21808
state = np.random.get_state()
bg = PCG64(0)
np.random.set_bit_generator(bg)
with pytest.raises(ValueError, match="state must be for a PCG64"):
np.random.set_state(state)
@pytest.mark.thread_unsafe(reason="np.random.set_bit_generator affects global state")
def test_swap_worked(restore_singleton_bitgen):
# GH 21808
np.random.seed(98765)
vals = np.random.randint(0, 2 ** 30, 10)
bg = PCG64(0)
state = bg.state
np.random.set_bit_generator(bg)
state_direct = np.random.get_state(legacy=False)
for field in state:
assert state[field] == state_direct[field]
np.random.seed(98765)
pcg_vals = np.random.randint(0, 2 ** 30, 10)
assert not np.all(vals == pcg_vals)
new_state = bg.state
assert new_state["state"]["state"] != state["state"]["state"]
assert new_state["state"]["inc"] == new_state["state"]["inc"]
@pytest.mark.thread_unsafe(reason="np.random.set_bit_generator affects global state")
def test_swapped_singleton_against_direct(restore_singleton_bitgen):
np.random.set_bit_generator(PCG64(98765))
singleton_vals = np.random.randint(0, 2 ** 30, 10)
rg = np.random.RandomState(PCG64(98765))
non_singleton_vals = rg.randint(0, 2 ** 30, 10)
assert_equal(non_singleton_vals, singleton_vals)
| import hashlib
import pickle
import sys
import warnings
import pytest
import numpy as np
from numpy import random
from numpy.random import MT19937, PCG64
from numpy.testing import (
IS_WASM,
assert_,
assert_array_almost_equal,
assert_array_equal,
assert_equal,
assert_no_warnings,
assert_raises,
)
INT_FUNCS = {'binomial': (100.0, 0.6),
'geometric': (.5,),
'hypergeometric': (20, 20, 10),
'logseries': (.5,),
'multinomial': (20, np.ones(6) / 6.0),
'negative_binomial': (100, .5),
'poisson': (10.0,),
'zipf': (2,),
}
if np.iinfo(np.long).max < 2**32:
# Windows and some 32-bit platforms, e.g., ARM
INT_FUNC_HASHES = {'binomial': '2fbead005fc63942decb5326d36a1f32fe2c9d32c904ee61e46866b88447c263', # noqa: E501
'logseries': '23ead5dcde35d4cfd4ef2c105e4c3d43304b45dc1b1444b7823b9ee4fa144ebb', | [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_equal"
] | numpy/numpy | numpy/random/tests/test_randomstate.py |
import sys
import warnings
import pytest
import numpy as np
from numpy import random
from numpy.testing import (
IS_WASM,
assert_,
assert_array_almost_equal,
assert_array_equal,
assert_equal,
assert_no_warnings,
assert_raises,
)
class TestSeed:
def test_scalar(self):
s = np.random.RandomState(0)
assert_equal(s.randint(1000), 684)
s = np.random.RandomState(4294967295)
assert_equal(s.randint(1000), 419)
def test_array(self):
s = np.random.RandomState(range(10))
assert_equal(s.randint(1000), 468)
s = np.random.RandomState(np.arange(10))
assert_equal(s.randint(1000), 468)
s = np.random.RandomState([0])
assert_equal(s.randint(1000), 973)
s = np.random.RandomState([4294967295])
assert_equal(s.randint(1000), 265)
def test_invalid_scalar(self):
# seed must be an unsigned 32 bit integer
assert_raises(TypeError, np.random.RandomState, -0.5)
assert_raises(ValueError, np.random.RandomState, -1)
def test_invalid_array(self):
# seed must be an unsigned 32 bit integer
assert_raises(TypeError, np.random.RandomState, [-0.5])
assert_raises(ValueError, np.random.RandomState, [-1])
assert_raises(ValueError, np.random.RandomState, [4294967296])
assert_raises(ValueError, np.random.RandomState, [1, 2, 4294967296])
assert_raises(ValueError, np.random.RandomState, [1, -2, 4294967296])
def test_invalid_array_shape(self):
# gh-9832
assert_raises(ValueError, np.random.RandomState,
np.array([], dtype=np.int64))
assert_raises(ValueError, np.random.RandomState, [[1, 2, 3]])
assert_raises(ValueError, np.random.RandomState, [[1, 2, 3],
[4, 5, 6]])
class TestBinomial:
def test_n_zero(self):
# Tests the corner case of n == 0 for the binomial distribution.
# binomial(0, p) should be zero for any p in [0, 1].
# This test addresses issue #3480.
zeros = np.zeros(2, dtype='int')
for p in [0, .5, 1]:
assert_(random.binomial(0, p) == 0)
assert_array_equal(random.binomial(zeros, p), zeros)
def test_p_is_nan(self):
# Issue #4571.
assert_raises(ValueError, random.binomial, 1, np.nan)
class TestMultinomial:
def test_basic(self):
random.multinomial(100, [0.2, 0.8])
def test_zero_probability(self):
random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0])
def test_int_negative_interval(self):
assert_(-5 <= random.randint(-5, -1) < -1)
x = random.randint(-5, -1, 5)
assert_(np.all(-5 <= x))
assert_(np.all(x < -1))
def test_size(self):
# gh-3173
p = [0.5, 0.5]
assert_equal(np.random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(np.random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(np.random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(np.random.multinomial(1, p, [2, 2]).shape, (2, 2, 2))
assert_equal(np.random.multinomial(1, p, (2, 2)).shape, (2, 2, 2))
assert_equal(np.random.multinomial(1, p, np.array((2, 2))).shape,
(2, 2, 2))
assert_raises(TypeError, np.random.multinomial, 1, p,
float(1))
def test_multidimensional_pvals(self):
assert_raises(ValueError, np.random.multinomial, 10, [[0, 1]])
assert_raises(ValueError, np.random.multinomial, 10, [[0], [1]])
assert_raises(ValueError, np.random.multinomial, 10, [[[0], [1]], [[1], [0]]])
assert_raises(ValueError, np.random.multinomial, 10, np.array([[0, 1], [1, 0]]))
class TestSetState:
def _create_rng(self):
seed = 1234567890
prng = random.RandomState(seed)
state = prng.get_state()
return prng, state
def test_basic(self):
prng, state = self._create_rng()
old = prng.tomaxint(16)
prng.set_state(state)
new = prng.tomaxint(16)
assert_(np.all(old == new))
def test_gaussian_reset(self):
# Make sure the cached every-other-Gaussian is reset.
prng, state = self._create_rng()
old = prng.standard_normal(size=3)
prng.set_state(state)
new = prng.standard_normal(size=3)
assert_(np.all(old == new))
def test_gaussian_reset_in_media_res(self):
# When the state is saved with a cached Gaussian, make sure the
# cached Gaussian is restored.
prng, state = self._create_rng()
prng.standard_normal()
state = prng.get_state()
old = prng.standard_normal(size=3)
prng.set_state(state)
new = prng.standard_normal(size=3)
assert_(np.all(old == new))
def test_backwards_compatibility(self):
# Make sure we can accept old state tuples that do not have the
# cached Gaussian value.
prng, state = self._create_rng()
old_state = state[:-2]
x1 = prng.standard_normal(size=16)
prng.set_state(old_state)
x2 = prng.standard_normal(size=16)
prng.set_state(state)
x3 = prng.standard_normal(size=16)
assert_(np.all(x1 == x2))
assert_(np.all(x1 == x3))
def test_negative_binomial(self):
# Ensure that the negative binomial results take floating point
# arguments without truncation.
prng, _ = self._create_rng()
prng.negative_binomial(0.5, 0.5)
def test_set_invalid_state(self):
# gh-25402
prng, _ = self._create_rng()
with pytest.raises(IndexError):
prng.set_state(())
class TestRandint:
# valid integer/boolean types
itype = [np.bool, np.int8, np.uint8, np.int16, np.uint16,
np.int32, np.uint32, np.int64, np.uint64]
def test_unsupported_type(self):
rng = random.RandomState()
assert_raises(TypeError, rng.randint, 1, dtype=float)
def test_bounds_checking(self):
rng = random.RandomState()
for dt in self.itype:
lbnd = 0 if dt is np.bool else np.iinfo(dt).min
ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
assert_raises(ValueError, rng.randint, lbnd - 1, ubnd, dtype=dt)
assert_raises(ValueError, rng.randint, lbnd, ubnd + 1, dtype=dt)
assert_raises(ValueError, rng.randint, ubnd, lbnd, dtype=dt)
assert_raises(ValueError, rng.randint, 1, 0, dtype=dt)
def test_rng_zero_and_extremes(self):
rng = random.RandomState()
for dt in self.itype:
lbnd = 0 if dt is np.bool else np.iinfo(dt).min
ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
tgt = ubnd - 1
assert_equal(rng.randint(tgt, tgt + 1, size=1000, dtype=dt), tgt)
tgt = lbnd
assert_equal(rng.randint(tgt, tgt + 1, size=1000, dtype=dt), tgt)
tgt = (lbnd + ubnd) // 2
assert_equal(rng.randint(tgt, tgt + 1, size=1000, dtype=dt), tgt)
def test_full_range(self):
# Test for ticket #1690
rng = random.RandomState()
for dt in self.itype:
lbnd = 0 if dt is np.bool else np.iinfo(dt).min
ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
try:
rng.randint(lbnd, ubnd, dtype=dt)
except Exception as e:
raise AssertionError("No error should have been raised, "
"but one was with the following "
"message:\n\n%s" % str(e))
def test_in_bounds_fuzz(self):
# Don't use fixed seed
rng = random.RandomState()
for dt in self.itype[1:]:
for ubnd in [4, 8, 16]:
vals = rng.randint(2, ubnd, size=2**16, dtype=dt)
assert_(vals.max() < ubnd)
assert_(vals.min() >= 2)
vals = rng.randint(0, 2, size=2**16, dtype=np.bool)
assert_(vals.max() < 2)
assert_(vals.min() >= 0)
def test_repeatability(self):
import hashlib
# We use a sha256 hash of generated sequences of 1000 samples
# in the range [0, 6) for all but bool, where the range
# is [0, 2). Hashes are for little endian numbers.
tgt = {'bool': '509aea74d792fb931784c4b0135392c65aec64beee12b0cc167548a2c3d31e71', # noqa: E501
'int16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4', # noqa: E501
'int32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f', # noqa: E501
'int64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e', # noqa: E501
'int8': '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404', # noqa: E501
'uint16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4', # noqa: E501
'uint32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f', # noqa: E501
'uint64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e', # noqa: E501
'uint8': '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404'} # noqa: E501
for dt in self.itype[1:]:
rng = random.RandomState(1234)
# view as little endian for hash
if sys.byteorder == 'little':
val = rng.randint(0, 6, size=1000, dtype=dt)
else:
val = rng.randint(0, 6, size=1000, dtype=dt).byteswap()
res = hashlib.sha256(val.view(np.int8)).hexdigest()
assert_(tgt[np.dtype(dt).name] == res)
# bools do not depend on endianness
rng = random.RandomState(1234)
val = rng.randint(0, 2, size=1000, dtype=bool).view(np.int8)
res = hashlib.sha256(val).hexdigest()
assert_(tgt[np.dtype(bool).name] == res)
def test_int64_uint64_corner_case(self):
# When stored in Numpy arrays, `lbnd` is casted
# as np.int64, and `ubnd` is casted as np.uint64.
# Checking whether `lbnd` >= `ubnd` used to be
# done solely via direct comparison, which is incorrect
# because when Numpy tries to compare both numbers,
# it casts both to np.float64 because there is
# no integer superset of np.int64 and np.uint64. However,
# `ubnd` is too large to be represented in np.float64,
# causing it be round down to np.iinfo(np.int64).max,
# leading to a ValueError because `lbnd` now equals
# the new `ubnd`.
dt = np.int64
tgt = np.iinfo(np.int64).max
lbnd = np.int64(np.iinfo(np.int64).max)
ubnd = np.uint64(np.iinfo(np.int64).max + 1)
# None of these function calls should
# generate a ValueError now.
actual = np.random.randint(lbnd, ubnd, dtype=dt)
assert_equal(actual, tgt)
def test_respect_dtype_singleton(self):
# See gh-7203
rng = random.RandomState()
for dt in self.itype:
lbnd = 0 if dt is np.bool else np.iinfo(dt).min
ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
sample = rng.randint(lbnd, ubnd, dtype=dt)
assert_equal(sample.dtype, np.dtype(dt))
for dt in (bool, int):
# The legacy rng uses "long" as the default integer:
lbnd = 0 if dt is bool else np.iinfo("long").min
ubnd = 2 if dt is bool else np.iinfo("long").max + 1
# gh-7284: Ensure that we get Python data types
sample = rng.randint(lbnd, ubnd, dtype=dt)
assert_(not hasattr(sample, 'dtype'))
assert_equal(type(sample), dt)
class TestRandomDist:
# Make sure the random distribution returns the correct value for a
# given seed
seed = 1234567890
def test_rand(self):
rng = random.RandomState(self.seed)
actual = rng.rand(3, 2)
desired = np.array([[0.61879477158567997, 0.59162362775974664],
[0.88868358904449662, 0.89165480011560816],
[0.4575674820298663, 0.7781880808593471]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_randn(self):
rng = random.RandomState(self.seed)
actual = rng.randn(3, 2)
desired = np.array([[1.34016345771863121, 1.73759122771936081],
[1.498988344300628, -0.2286433324536169],
[2.031033998682787, 2.17032494605655257]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_randint(self):
rng = random.RandomState(self.seed)
actual = rng.randint(-99, 99, size=(3, 2))
desired = np.array([[31, 3],
[-52, 41],
[-48, -66]])
assert_array_equal(actual, desired)
def test_random_integers(self):
rng = random.RandomState(self.seed)
with pytest.warns(DeprecationWarning):
actual = rng.random_integers(-99, 99, size=(3, 2))
desired = np.array([[31, 3],
[-52, 41],
[-48, -66]])
assert_array_equal(actual, desired)
def test_random_integers_max_int(self):
# Tests whether random_integers can generate the
# maximum allowed Python int that can be converted
# into a C long. Previous implementations of this
# method have thrown an OverflowError when attempting
# to generate this integer.
with pytest.warns(DeprecationWarning):
actual = np.random.random_integers(np.iinfo('l').max,
np.iinfo('l').max)
desired = np.iinfo('l').max
assert_equal(actual, desired)
def test_random_integers_deprecated(self):
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
# DeprecationWarning raised with high == None
assert_raises(DeprecationWarning,
np.random.random_integers,
np.iinfo('l').max)
# DeprecationWarning raised with high != None
assert_raises(DeprecationWarning,
np.random.random_integers,
np.iinfo('l').max, np.iinfo('l').max)
def test_random(self):
rng = random.RandomState(self.seed)
actual = rng.random((3, 2))
desired = np.array([[0.61879477158567997, 0.59162362775974664],
[0.88868358904449662, 0.89165480011560816],
[0.4575674820298663, 0.7781880808593471]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_choice_uniform_replace(self):
rng = random.RandomState(self.seed)
actual = rng.choice(4, 4)
desired = np.array([2, 3, 2, 3])
assert_array_equal(actual, desired)
def test_choice_nonuniform_replace(self):
rng = random.RandomState(self.seed)
actual = rng.choice(4, 4, p=[0.4, 0.4, 0.1, 0.1])
desired = np.array([1, 1, 2, 2])
assert_array_equal(actual, desired)
def test_choice_uniform_noreplace(self):
rng = random.RandomState(self.seed)
actual = rng.choice(4, 3, replace=False)
desired = np.array([0, 1, 3])
assert_array_equal(actual, desired)
def test_choice_nonuniform_noreplace(self):
rng = random.RandomState(self.seed)
actual = rng.choice(4, 3, replace=False,
p=[0.1, 0.3, 0.5, 0.1])
desired = np.array([2, 3, 1])
assert_array_equal(actual, desired)
def test_choice_noninteger(self):
rng = random.RandomState(self.seed)
actual = rng.choice(['a', 'b', 'c', 'd'], 4)
desired = np.array(['c', 'd', 'c', 'd'])
assert_array_equal(actual, desired)
def test_choice_exceptions(self):
sample = np.random.choice
assert_raises(ValueError, sample, -1, 3)
assert_raises(ValueError, sample, 3., 3)
assert_raises(ValueError, sample, [[1, 2], [3, 4]], 3)
assert_raises(ValueError, sample, [], 3)
assert_raises(ValueError, sample, [1, 2, 3, 4], 3,
p=[[0.25, 0.25], [0.25, 0.25]])
assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4, 0.2])
assert_raises(ValueError, sample, [1, 2], 3, p=[1.1, -0.1])
assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4])
assert_raises(ValueError, sample, [1, 2, 3], 4, replace=False)
# gh-13087
assert_raises(ValueError, sample, [1, 2, 3], -2, replace=False)
assert_raises(ValueError, sample, [1, 2, 3], (-1,), replace=False)
assert_raises(ValueError, sample, [1, 2, 3], (-1, 1), replace=False)
assert_raises(ValueError, sample, [1, 2, 3], 2,
replace=False, p=[1, 0, 0])
def test_choice_return_shape(self):
p = [0.1, 0.9]
# Check scalar
assert_(np.isscalar(np.random.choice(2, replace=True)))
assert_(np.isscalar(np.random.choice(2, replace=False)))
assert_(np.isscalar(np.random.choice(2, replace=True, p=p)))
assert_(np.isscalar(np.random.choice(2, replace=False, p=p)))
assert_(np.isscalar(np.random.choice([1, 2], replace=True)))
assert_(np.random.choice([None], replace=True) is None)
a = np.array([1, 2])
arr = np.empty(1, dtype=object)
arr[0] = a
assert_(np.random.choice(arr, replace=True) is a)
# Check 0-d array
s = ()
assert_(not np.isscalar(np.random.choice(2, s, replace=True)))
assert_(not np.isscalar(np.random.choice(2, s, replace=False)))
assert_(not np.isscalar(np.random.choice(2, s, replace=True, p=p)))
assert_(not np.isscalar(np.random.choice(2, s, replace=False, p=p)))
assert_(not np.isscalar(np.random.choice([1, 2], s, replace=True)))
assert_(np.random.choice([None], s, replace=True).ndim == 0)
a = np.array([1, 2])
arr = np.empty(1, dtype=object)
arr[0] = a
assert_(np.random.choice(arr, s, replace=True).item() is a)
# Check multi dimensional array
s = (2, 3)
p = [0.1, 0.1, 0.1, 0.1, 0.4, 0.2]
assert_equal(np.random.choice(6, s, replace=True).shape, s)
assert_equal(np.random.choice(6, s, replace=False).shape, s)
assert_equal(np.random.choice(6, s, replace=True, p=p).shape, s)
assert_equal(np.random.choice(6, s, replace=False, p=p).shape, s)
assert_equal(np.random.choice(np.arange(6), s, replace=True).shape, s)
# Check zero-size
assert_equal(np.random.randint(0, 0, size=(3, 0, 4)).shape, (3, 0, 4))
assert_equal(np.random.randint(0, -10, size=0).shape, (0,))
assert_equal(np.random.randint(10, 10, size=0).shape, (0,))
assert_equal(np.random.choice(0, size=0).shape, (0,))
assert_equal(np.random.choice([], size=(0,)).shape, (0,))
assert_equal(np.random.choice(['a', 'b'], size=(3, 0, 4)).shape,
(3, 0, 4))
assert_raises(ValueError, np.random.choice, [], 10)
def test_choice_nan_probabilities(self):
a = np.array([42, 1, 2])
p = [None, None, None]
assert_raises(ValueError, np.random.choice, a, p=p)
def test_bytes(self):
rng = random.RandomState(self.seed)
actual = rng.bytes(10)
desired = b'\x82Ui\x9e\xff\x97+Wf\xa5'
assert_equal(actual, desired)
def test_shuffle(self):
# Test lists, arrays (of various dtypes), and multidimensional versions
# of both, c-contiguous or not:
for conv in [lambda x: np.array([]),
lambda x: x,
lambda x: np.asarray(x).astype(np.int8),
lambda x: np.asarray(x).astype(np.float32),
lambda x: np.asarray(x).astype(np.complex64),
lambda x: np.asarray(x).astype(object),
lambda x: [(i, i) for i in x],
lambda x: np.asarray([[i, i] for i in x]),
lambda x: np.vstack([x, x]).T,
# gh-11442
lambda x: (np.asarray([(i, i) for i in x],
[("a", int), ("b", int)])
.view(np.recarray)),
# gh-4270
lambda x: np.asarray([(i, i) for i in x],
[("a", object), ("b", np.int32)])]:
rng = random.RandomState(self.seed)
alist = conv([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
rng.shuffle(alist)
actual = alist
desired = conv([0, 1, 9, 6, 2, 4, 5, 8, 7, 3])
assert_array_equal(actual, desired)
def test_shuffle_masked(self):
# gh-3263
a = np.ma.masked_values(np.reshape(range(20), (5, 4)) % 3 - 1, -1)
b = np.ma.masked_values(np.arange(20) % 3 - 1, -1)
a_orig = a.copy()
b_orig = b.copy()
for i in range(50):
np.random.shuffle(a)
assert_equal(
sorted(a.data[~a.mask]), sorted(a_orig.data[~a_orig.mask]))
np.random.shuffle(b)
assert_equal(
sorted(b.data[~b.mask]), sorted(b_orig.data[~b_orig.mask]))
@pytest.mark.parametrize("random",
[np.random, np.random.RandomState(), np.random.default_rng()])
def test_shuffle_untyped_warning(self, random):
# Create a dict works like a sequence but isn't one
values = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}
with pytest.warns(UserWarning,
match="you are shuffling a 'dict' object") as rec:
random.shuffle(values)
assert "test_random" in rec[0].filename
@pytest.mark.parametrize("random",
[np.random, np.random.RandomState(), np.random.default_rng()])
@pytest.mark.parametrize("use_array_like", [True, False])
def test_shuffle_no_object_unpacking(self, random, use_array_like):
class MyArr(np.ndarray):
pass
items = [
None, np.array([3]), np.float64(3), np.array(10), np.float64(7)
]
arr = np.array(items, dtype=object)
item_ids = {id(i) for i in items}
if use_array_like:
arr = arr.view(MyArr)
# The array was created fine, and did not modify any objects:
assert all(id(i) in item_ids for i in arr)
if use_array_like and not isinstance(random, np.random.Generator):
# The old API gives incorrect results, but warns about it.
with pytest.warns(UserWarning,
match="Shuffling a one dimensional array.*"):
random.shuffle(arr)
else:
random.shuffle(arr)
assert all(id(i) in item_ids for i in arr)
def test_shuffle_memoryview(self):
# gh-18273
# allow graceful handling of memoryviews
# (treat the same as arrays)
rng = random.RandomState(self.seed)
a = np.arange(5).data
rng.shuffle(a)
assert_equal(np.asarray(a), [0, 1, 4, 3, 2])
rng = random.RandomState(self.seed)
rng.shuffle(a)
assert_equal(np.asarray(a), [0, 1, 2, 3, 4])
rng = np.random.default_rng(self.seed)
rng.shuffle(a)
assert_equal(np.asarray(a), [4, 1, 0, 3, 2])
def test_shuffle_not_writeable(self):
a = np.zeros(3)
a.flags.writeable = False
with pytest.raises(ValueError, match='read-only'):
np.random.shuffle(a)
def test_beta(self):
rng = random.RandomState(self.seed)
actual = rng.beta(.1, .9, size=(3, 2))
desired = np.array(
[[1.45341850513746058e-02, 5.31297615662868145e-04],
[1.85366619058432324e-06, 4.19214516800110563e-03],
[1.58405155108498093e-04, 1.26252891949397652e-04]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_binomial(self):
rng = random.RandomState(self.seed)
actual = rng.binomial(100, .456, size=(3, 2))
desired = np.array([[37, 43],
[42, 48],
[46, 45]])
assert_array_equal(actual, desired)
def test_chisquare(self):
rng = random.RandomState(self.seed)
actual = rng.chisquare(50, size=(3, 2))
desired = np.array([[63.87858175501090585, 68.68407748911370447],
[65.77116116901505904, 47.09686762438974483],
[72.3828403199695174, 74.18408615260374006]])
assert_array_almost_equal(actual, desired, decimal=13)
def test_dirichlet(self):
rng = random.RandomState(self.seed)
alpha = np.array([51.72840233779265162, 39.74494232180943953])
actual = rng.dirichlet(alpha, size=(3, 2))
desired = np.array([[[0.54539444573611562, 0.45460555426388438],
[0.62345816822039413, 0.37654183177960598]],
[[0.55206000085785778, 0.44793999914214233],
[0.58964023305154301, 0.41035976694845688]],
[[0.59266909280647828, 0.40733090719352177],
[0.56974431743975207, 0.43025568256024799]]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_dirichlet_size(self):
# gh-3173
p = np.array([51.72840233779265162, 39.74494232180943953])
assert_equal(np.random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(np.random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(np.random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(np.random.dirichlet(p, [2, 2]).shape, (2, 2, 2))
assert_equal(np.random.dirichlet(p, (2, 2)).shape, (2, 2, 2))
assert_equal(np.random.dirichlet(p, np.array((2, 2))).shape, (2, 2, 2))
assert_raises(TypeError, np.random.dirichlet, p, float(1))
def test_dirichlet_bad_alpha(self):
# gh-2089
alpha = np.array([5.4e-01, -1.0e-16])
assert_raises(ValueError, np.random.mtrand.dirichlet, alpha)
# gh-15876
assert_raises(ValueError, random.dirichlet, [[5, 1]])
assert_raises(ValueError, random.dirichlet, [[5], [1]])
assert_raises(ValueError, random.dirichlet, [[[5], [1]], [[1], [5]]])
assert_raises(ValueError, random.dirichlet, np.array([[5, 1], [1, 5]]))
def test_exponential(self):
rng = random.RandomState(self.seed)
actual = rng.exponential(1.1234, size=(3, 2))
desired = np.array([[1.08342649775011624, 1.00607889924557314],
[2.46628830085216721, 2.49668106809923884],
[0.68717433461363442, 1.69175666993575979]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_exponential_0(self):
assert_equal(np.random.exponential(scale=0), 0)
assert_raises(ValueError, np.random.exponential, scale=-0.)
def test_f(self):
rng = random.RandomState(self.seed)
actual = rng.f(12, 77, size=(3, 2))
desired = np.array([[1.21975394418575878, 1.75135759791559775],
[1.44803115017146489, 1.22108959480396262],
[1.02176975757740629, 1.34431827623300415]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_gamma(self):
rng = random.RandomState(self.seed)
actual = rng.gamma(5, 3, size=(3, 2))
desired = np.array([[24.60509188649287182, 28.54993563207210627],
[26.13476110204064184, 12.56988482927716078],
[31.71863275789960568, 33.30143302795922011]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_gamma_0(self):
assert_equal(np.random.gamma(shape=0, scale=0), 0)
assert_raises(ValueError, np.random.gamma, shape=-0., scale=-0.)
def test_geometric(self):
rng = random.RandomState(self.seed)
actual = rng.geometric(.123456789, size=(3, 2))
desired = np.array([[8, 7],
[17, 17],
[5, 12]])
assert_array_equal(actual, desired)
def test_gumbel(self):
rng = random.RandomState(self.seed)
actual = rng.gumbel(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[0.19591898743416816, 0.34405539668096674],
[-1.4492522252274278, -1.47374816298446865],
[1.10651090478803416, -0.69535848626236174]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_gumbel_0(self):
assert_equal(np.random.gumbel(scale=0), 0)
assert_raises(ValueError, np.random.gumbel, scale=-0.)
def test_hypergeometric(self):
rng = random.RandomState(self.seed)
actual = rng.hypergeometric(10, 5, 14, size=(3, 2))
desired = np.array([[10, 10],
[10, 10],
[9, 9]])
assert_array_equal(actual, desired)
# Test nbad = 0
actual = rng.hypergeometric(5, 0, 3, size=4)
desired = np.array([3, 3, 3, 3])
assert_array_equal(actual, desired)
actual = rng.hypergeometric(15, 0, 12, size=4)
desired = np.array([12, 12, 12, 12])
assert_array_equal(actual, desired)
# Test ngood = 0
actual = rng.hypergeometric(0, 5, 3, size=4)
desired = np.array([0, 0, 0, 0])
assert_array_equal(actual, desired)
actual = rng.hypergeometric(0, 15, 12, size=4)
desired = np.array([0, 0, 0, 0])
assert_array_equal(actual, desired)
def test_laplace(self):
rng = random.RandomState(self.seed)
actual = rng.laplace(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[0.66599721112760157, 0.52829452552221945],
[3.12791959514407125, 3.18202813572992005],
[-0.05391065675859356, 1.74901336242837324]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_laplace_0(self):
assert_equal(np.random.laplace(scale=0), 0)
assert_raises(ValueError, np.random.laplace, scale=-0.)
def test_logistic(self):
rng = random.RandomState(self.seed)
actual = rng.logistic(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[1.09232835305011444, 0.8648196662399954],
[4.27818590694950185, 4.33897006346929714],
[-0.21682183359214885, 2.63373365386060332]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_lognormal(self):
rng = random.RandomState(self.seed)
actual = rng.lognormal(mean=.123456789, sigma=2.0, size=(3, 2))
desired = np.array([[16.50698631688883822, 36.54846706092654784],
[22.67886599981281748, 0.71617561058995771],
[65.72798501792723869, 86.84341601437161273]])
assert_array_almost_equal(actual, desired, decimal=13)
def test_lognormal_0(self):
assert_equal(np.random.lognormal(sigma=0), 1)
assert_raises(ValueError, np.random.lognormal, sigma=-0.)
def test_logseries(self):
rng = random.RandomState(self.seed)
actual = rng.logseries(p=.923456789, size=(3, 2))
desired = np.array([[2, 2],
[6, 17],
[3, 6]])
assert_array_equal(actual, desired)
def test_multinomial(self):
rng = random.RandomState(self.seed)
actual = rng.multinomial(20, [1 / 6.] * 6, size=(3, 2))
desired = np.array([[[4, 3, 5, 4, 2, 2],
[5, 2, 8, 2, 2, 1]],
[[3, 4, 3, 6, 0, 4],
[2, 1, 4, 3, 6, 4]],
[[4, 4, 2, 5, 2, 3],
[4, 3, 4, 2, 3, 4]]])
assert_array_equal(actual, desired)
def test_multivariate_normal(self):
rng = random.RandomState(self.seed)
mean = (.123456789, 10)
cov = [[1, 0], [0, 1]]
size = (3, 2)
actual = rng.multivariate_normal(mean, cov, size)
desired = np.array([[[1.463620246718631, 11.73759122771936],
[1.622445133300628, 9.771356667546383]],
[[2.154490787682787, 12.170324946056553],
[1.719909438201865, 9.230548443648306]],
[[0.689515026297799, 9.880729819607714],
[-0.023054015651998, 9.201096623542879]]])
assert_array_almost_equal(actual, desired, decimal=15)
# Check for default size, was raising deprecation warning
actual = rng.multivariate_normal(mean, cov)
desired = np.array([0.895289569463708, 9.17180864067987])
assert_array_almost_equal(actual, desired, decimal=15)
# Check that non positive-semidefinite covariance warns with
# RuntimeWarning
mean = [0, 0]
cov = [[1, 2], [2, 1]]
pytest.warns(RuntimeWarning, rng.multivariate_normal, mean, cov)
# and that it doesn't warn with RuntimeWarning check_valid='ignore'
assert_no_warnings(rng.multivariate_normal, mean, cov,
check_valid='ignore')
# and that it raises with RuntimeWarning check_valid='raises'
assert_raises(ValueError, rng.multivariate_normal, mean, cov,
check_valid='raise')
cov = np.array([[1, 0.1], [0.1, 1]], dtype=np.float32)
with warnings.catch_warnings():
warnings.simplefilter('error')
rng.multivariate_normal(mean, cov)
def test_negative_binomial(self):
rng = random.RandomState(self.seed)
actual = rng.negative_binomial(n=100, p=.12345, size=(3, 2))
desired = np.array([[848, 841],
[892, 611],
[779, 647]])
assert_array_equal(actual, desired)
def test_noncentral_chisquare(self):
rng = random.RandomState(self.seed)
actual = rng.noncentral_chisquare(df=5, nonc=5, size=(3, 2))
desired = np.array([[23.91905354498517511, 13.35324692733826346],
[31.22452661329736401, 16.60047399466177254],
[5.03461598262724586, 17.94973089023519464]])
assert_array_almost_equal(actual, desired, decimal=14)
actual = rng.noncentral_chisquare(df=.5, nonc=.2, size=(3, 2))
desired = np.array([[1.47145377828516666, 0.15052899268012659],
[0.00943803056963588, 1.02647251615666169],
[0.332334982684171, 0.15451287602753125]])
assert_array_almost_equal(actual, desired, decimal=14)
rng = random.RandomState(self.seed)
actual = rng.noncentral_chisquare(df=5, nonc=0, size=(3, 2))
desired = np.array([[9.597154162763948, 11.725484450296079],
[10.413711048138335, 3.694475922923986],
[13.484222138963087, 14.377255424602957]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_noncentral_f(self):
rng = random.RandomState(self.seed)
actual = rng.noncentral_f(dfnum=5, dfden=2, nonc=1,
size=(3, 2))
desired = np.array([[1.40598099674926669, 0.34207973179285761],
[3.57715069265772545, 7.92632662577829805],
[0.43741599463544162, 1.1774208752428319]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_normal(self):
rng = random.RandomState(self.seed)
actual = rng.normal(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[2.80378370443726244, 3.59863924443872163],
[3.121433477601256, -0.33382987590723379],
[4.18552478636557357, 4.46410668111310471]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_normal_0(self):
assert_equal(np.random.normal(scale=0), 0)
assert_raises(ValueError, np.random.normal, scale=-0.)
def test_pareto(self):
rng = random.RandomState(self.seed)
actual = rng.pareto(a=.123456789, size=(3, 2))
desired = np.array(
[[2.46852460439034849e+03, 1.41286880810518346e+03],
[5.28287797029485181e+07, 6.57720981047328785e+07],
[1.40840323350391515e+02, 1.98390255135251704e+05]])
# For some reason on 32-bit x86 Ubuntu 12.10 the [1, 0] entry in this
# matrix differs by 24 nulps. Discussion:
# https://mail.python.org/pipermail/numpy-discussion/2012-September/063801.html
# Consensus is that this is probably some gcc quirk that affects
# rounding but not in any important way, so we just use a looser
# tolerance on this test:
np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=30)
def test_poisson(self):
rng = random.RandomState(self.seed)
actual = rng.poisson(lam=.123456789, size=(3, 2))
desired = np.array([[0, 0],
[1, 0],
[0, 0]])
assert_array_equal(actual, desired)
def test_poisson_exceptions(self):
lambig = np.iinfo('l').max
lamneg = -1
assert_raises(ValueError, np.random.poisson, lamneg)
assert_raises(ValueError, np.random.poisson, [lamneg] * 10)
assert_raises(ValueError, np.random.poisson, lambig)
assert_raises(ValueError, np.random.poisson, [lambig] * 10)
def test_power(self):
rng = random.RandomState(self.seed)
actual = rng.power(a=.123456789, size=(3, 2))
desired = np.array([[0.02048932883240791, 0.01424192241128213],
[0.38446073748535298, 0.39499689943484395],
[0.00177699707563439, 0.13115505880863756]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_rayleigh(self):
rng = random.RandomState(self.seed)
actual = rng.rayleigh(scale=10, size=(3, 2))
desired = np.array([[13.8882496494248393, 13.383318339044731],
[20.95413364294492098, 21.08285015800712614],
[11.06066537006854311, 17.35468505778271009]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_rayleigh_0(self):
assert_equal(np.random.rayleigh(scale=0), 0)
assert_raises(ValueError, np.random.rayleigh, scale=-0.)
def test_standard_cauchy(self):
rng = random.RandomState(self.seed)
actual = rng.standard_cauchy(size=(3, 2))
desired = np.array([[0.77127660196445336, -6.55601161955910605],
[0.93582023391158309, -2.07479293013759447],
[-4.74601644297011926, 0.18338989290760804]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_exponential(self):
rng = random.RandomState(self.seed)
actual = rng.standard_exponential(size=(3, 2))
desired = np.array([[0.96441739162374596, 0.89556604882105506],
[2.1953785836319808, 2.22243285392490542],
[0.6116915921431676, 1.50592546727413201]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_gamma(self):
rng = random.RandomState(self.seed)
actual = rng.standard_gamma(shape=3, size=(3, 2))
desired = np.array([[5.50841531318455058, 6.62953470301903103],
[5.93988484943779227, 2.31044849402133989],
[7.54838614231317084, 8.012756093271868]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_standard_gamma_0(self):
assert_equal(np.random.standard_gamma(shape=0), 0)
assert_raises(ValueError, np.random.standard_gamma, shape=-0.)
def test_standard_normal(self):
rng = random.RandomState(self.seed)
actual = rng.standard_normal(size=(3, 2))
desired = np.array([[1.34016345771863121, 1.73759122771936081],
[1.498988344300628, -0.2286433324536169],
[2.031033998682787, 2.17032494605655257]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_t(self):
rng = random.RandomState(self.seed)
actual = rng.standard_t(df=10, size=(3, 2))
desired = np.array([[0.97140611862659965, -0.08830486548450577],
[1.36311143689505321, -0.55317463909867071],
[-0.18473749069684214, 0.61181537341755321]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_triangular(self):
rng = random.RandomState(self.seed)
actual = rng.triangular(left=5.12, mode=10.23, right=20.34,
size=(3, 2))
desired = np.array([[12.68117178949215784, 12.4129206149193152],
[16.20131377335158263, 16.25692138747600524],
[11.20400690911820263, 14.4978144835829923]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_uniform(self):
rng = random.RandomState(self.seed)
actual = rng.uniform(low=1.23, high=10.54, size=(3, 2))
desired = np.array([[6.99097932346268003, 6.73801597444323974],
[9.50364421400426274, 9.53130618907631089],
[5.48995325769805476, 8.47493103280052118]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_uniform_range_bounds(self):
fmin = np.finfo('float').min
fmax = np.finfo('float').max
func = np.random.uniform
assert_raises(OverflowError, func, -np.inf, 0)
assert_raises(OverflowError, func, 0, np.inf)
assert_raises(OverflowError, func, fmin, fmax)
assert_raises(OverflowError, func, [-np.inf], [0])
assert_raises(OverflowError, func, [0], [np.inf])
# (fmax / 1e17) - fmin is within range, so this should not throw
# account for i386 extended precision DBL_MAX / 1e17 + DBL_MAX >
# DBL_MAX by increasing fmin a bit
np.random.uniform(low=np.nextafter(fmin, 1), high=fmax / 1e17)
def test_scalar_exception_propagation(self):
# Tests that exceptions are correctly propagated in distributions
# when called with objects that throw exceptions when converted to
# scalars.
#
# Regression test for gh: 8865
class ThrowingFloat(np.ndarray):
def __float__(self):
raise TypeError
throwing_float = np.array(1.0).view(ThrowingFloat)
assert_raises(TypeError, np.random.uniform, throwing_float,
throwing_float)
class ThrowingInteger(np.ndarray):
def __int__(self):
raise TypeError
__index__ = __int__
throwing_int = np.array(1).view(ThrowingInteger)
assert_raises(TypeError, np.random.hypergeometric, throwing_int, 1, 1)
def test_vonmises(self):
rng = random.RandomState(self.seed)
actual = rng.vonmises(mu=1.23, kappa=1.54, size=(3, 2))
desired = np.array([[2.28567572673902042, 2.89163838442285037],
[0.38198375564286025, 2.57638023113890746],
[1.19153771588353052, 1.83509849681825354]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_vonmises_small(self):
# check infinite loop, gh-4720
np.random.seed(self.seed)
r = np.random.vonmises(mu=0., kappa=1.1e-8, size=10**6)
np.testing.assert_(np.isfinite(r).all())
def test_wald(self):
rng = random.RandomState(self.seed)
actual = rng.wald(mean=1.23, scale=1.54, size=(3, 2))
desired = np.array([[3.82935265715889983, 5.13125249184285526],
[0.35045403618358717, 1.50832396872003538],
[0.24124319895843183, 0.22031101461955038]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_weibull(self):
rng = random.RandomState(self.seed)
actual = rng.weibull(a=1.23, size=(3, 2))
desired = np.array([[0.97097342648766727, 0.91422896443565516],
[1.89517770034962929, 1.91414357960479564],
[0.67057783752390987, 1.39494046635066793]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_weibull_0(self):
np.random.seed(self.seed)
assert_equal(np.random.weibull(a=0, size=12), np.zeros(12))
assert_raises(ValueError, np.random.weibull, a=-0.)
def test_zipf(self):
rng = random.RandomState(self.seed)
actual = rng.zipf(a=1.23, size=(3, 2))
desired = np.array([[66, 29],
[1, 1],
[3, 13]])
assert_array_equal(actual, desired)
class TestBroadcast:
# tests that functions that broadcast behave
# correctly when presented with non-scalar arguments
seed = 123456789
# TODO: Include test for randint once it can broadcast
# Can steal the test written in PR #6938
def test_uniform(self):
low = [0]
high = [1]
desired = np.array([0.53283302478975902,
0.53413660089041659,
0.50955303552646702])
rng = random.RandomState(self.seed)
actual = rng.uniform(low * 3, high)
assert_array_almost_equal(actual, desired, decimal=14)
rng = random.RandomState(self.seed)
actual = rng.uniform(low, high * 3)
assert_array_almost_equal(actual, desired, decimal=14)
def test_normal(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([2.2129019979039612,
2.1283977976520019,
1.8417114045748335])
rng = random.RandomState(self.seed)
actual = rng.normal(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.normal, loc * 3, bad_scale)
rng = random.RandomState(self.seed)
actual = rng.normal(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.normal, loc, bad_scale * 3)
def test_beta(self):
a = [1]
b = [2]
bad_a = [-1]
bad_b = [-2]
desired = np.array([0.19843558305989056,
0.075230336409423643,
0.24976865978980844])
rng = random.RandomState(self.seed)
actual = rng.beta(a * 3, b)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.beta, bad_a * 3, b)
assert_raises(ValueError, rng.beta, a * 3, bad_b)
rng = random.RandomState(self.seed)
actual = rng.beta(a, b * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.beta, bad_a, b * 3)
assert_raises(ValueError, rng.beta, a, bad_b * 3)
def test_exponential(self):
scale = [1]
bad_scale = [-1]
desired = np.array([0.76106853658845242,
0.76386282278691653,
0.71243813125891797])
rng = random.RandomState(self.seed)
actual = rng.exponential(scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.exponential, bad_scale * 3)
def test_standard_gamma(self):
shape = [1]
bad_shape = [-1]
desired = np.array([0.76106853658845242,
0.76386282278691653,
0.71243813125891797])
rng = random.RandomState(self.seed)
actual = rng.standard_gamma(shape * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.standard_gamma, bad_shape * 3)
def test_gamma(self):
shape = [1]
scale = [2]
bad_shape = [-1]
bad_scale = [-2]
desired = np.array([1.5221370731769048,
1.5277256455738331,
1.4248762625178359])
rng = random.RandomState(self.seed)
actual = rng.gamma(shape * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.gamma, bad_shape * 3, scale)
assert_raises(ValueError, rng.gamma, shape * 3, bad_scale)
rng = random.RandomState(self.seed)
actual = rng.gamma(shape, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.gamma, bad_shape, scale * 3)
assert_raises(ValueError, rng.gamma, shape, bad_scale * 3)
def test_f(self):
dfnum = [1]
dfden = [2]
bad_dfnum = [-1]
bad_dfden = [-2]
desired = np.array([0.80038951638264799,
0.86768719635363512,
2.7251095168386801])
rng = random.RandomState(self.seed)
actual = rng.f(dfnum * 3, dfden)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.f, bad_dfnum * 3, dfden)
assert_raises(ValueError, rng.f, dfnum * 3, bad_dfden)
rng = random.RandomState(self.seed)
actual = rng.f(dfnum, dfden * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.f, bad_dfnum, dfden * 3)
assert_raises(ValueError, rng.f, dfnum, bad_dfden * 3)
def test_noncentral_f(self):
dfnum = [2]
dfden = [3]
nonc = [4]
bad_dfnum = [0]
bad_dfden = [-1]
bad_nonc = [-2]
desired = np.array([9.1393943263705211,
13.025456344595602,
8.8018098359100545])
rng = random.RandomState(self.seed)
actual = rng.noncentral_f(dfnum * 3, dfden, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.noncentral_f, bad_dfnum * 3, dfden, nonc)
assert_raises(ValueError, rng.noncentral_f, dfnum * 3, bad_dfden, nonc)
assert_raises(ValueError, rng.noncentral_f, dfnum * 3, dfden, bad_nonc)
rng = random.RandomState(self.seed)
actual = rng.noncentral_f(dfnum, dfden * 3, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.noncentral_f, bad_dfnum, dfden * 3, nonc)
assert_raises(ValueError, rng.noncentral_f, dfnum, bad_dfden * 3, nonc)
assert_raises(ValueError, rng.noncentral_f, dfnum, dfden * 3, bad_nonc)
rng = random.RandomState(self.seed)
actual = rng.noncentral_f(dfnum, dfden, nonc * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.noncentral_f, bad_dfnum, dfden, nonc * 3)
assert_raises(ValueError, rng.noncentral_f, dfnum, bad_dfden, nonc * 3)
assert_raises(ValueError, rng.noncentral_f, dfnum, dfden, bad_nonc * 3)
def test_noncentral_f_small_df(self):
rng = random.RandomState(self.seed)
desired = np.array([6.869638627492048, 0.785880199263955])
actual = rng.noncentral_f(0.9, 0.9, 2, size=2)
assert_array_almost_equal(actual, desired, decimal=14)
def test_chisquare(self):
df = [1]
bad_df = [-1]
desired = np.array([0.57022801133088286,
0.51947702108840776,
0.1320969254923558])
rng = random.RandomState(self.seed)
actual = rng.chisquare(df * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.chisquare, bad_df * 3)
def test_noncentral_chisquare(self):
df = [1]
nonc = [2]
bad_df = [-1]
bad_nonc = [-2]
desired = np.array([9.0015599467913763,
4.5804135049718742,
6.0872302432834564])
rng = random.RandomState(self.seed)
actual = rng.noncentral_chisquare(df * 3, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.noncentral_chisquare, bad_df * 3, nonc)
assert_raises(ValueError, rng.noncentral_chisquare, df * 3, bad_nonc)
rng = random.RandomState(self.seed)
actual = rng.noncentral_chisquare(df, nonc * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.noncentral_chisquare, bad_df, nonc * 3)
assert_raises(ValueError, rng.noncentral_chisquare, df, bad_nonc * 3)
def test_standard_t(self):
df = [1]
bad_df = [-1]
desired = np.array([3.0702872575217643,
5.8560725167361607,
1.0274791436474273])
rng = random.RandomState(self.seed)
actual = rng.standard_t(df * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.standard_t, bad_df * 3)
def test_vonmises(self):
mu = [2]
kappa = [1]
bad_kappa = [-1]
desired = np.array([2.9883443664201312,
-2.7064099483995943,
-1.8672476700665914])
rng = random.RandomState(self.seed)
actual = rng.vonmises(mu * 3, kappa)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.vonmises, mu * 3, bad_kappa)
rng = random.RandomState(self.seed)
actual = rng.vonmises(mu, kappa * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.vonmises, mu, bad_kappa * 3)
def test_pareto(self):
a = [1]
bad_a = [-1]
desired = np.array([1.1405622680198362,
1.1465519762044529,
1.0389564467453547])
rng = random.RandomState(self.seed)
actual = rng.pareto(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.pareto, bad_a * 3)
def test_weibull(self):
a = [1]
bad_a = [-1]
desired = np.array([0.76106853658845242,
0.76386282278691653,
0.71243813125891797])
rng = random.RandomState(self.seed)
actual = rng.weibull(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.weibull, bad_a * 3)
def test_power(self):
a = [1]
bad_a = [-1]
desired = np.array([0.53283302478975902,
0.53413660089041659,
0.50955303552646702])
rng = random.RandomState(self.seed)
actual = rng.power(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.power, bad_a * 3)
def test_laplace(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([0.067921356028507157,
0.070715642226971326,
0.019290950698972624])
rng = random.RandomState(self.seed)
actual = rng.laplace(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.laplace, loc * 3, bad_scale)
rng = random.RandomState(self.seed)
actual = rng.laplace(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.laplace, loc, bad_scale * 3)
def test_gumbel(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([0.2730318639556768,
0.26936705726291116,
0.33906220393037939])
rng = random.RandomState(self.seed)
actual = rng.gumbel(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.gumbel, loc * 3, bad_scale)
rng = random.RandomState(self.seed)
actual = rng.gumbel(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.gumbel, loc, bad_scale * 3)
def test_logistic(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([0.13152135837586171,
0.13675915696285773,
0.038216792802833396])
rng = random.RandomState(self.seed)
actual = rng.logistic(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.logistic, loc * 3, bad_scale)
rng = random.RandomState(self.seed)
actual = rng.logistic(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.logistic, loc, bad_scale * 3)
def test_lognormal(self):
mean = [0]
sigma = [1]
bad_sigma = [-1]
desired = np.array([9.1422086044848427,
8.4013952870126261,
6.3073234116578671])
rng = random.RandomState(self.seed)
actual = rng.lognormal(mean * 3, sigma)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.lognormal, mean * 3, bad_sigma)
rng = random.RandomState(self.seed)
actual = rng.lognormal(mean, sigma * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.lognormal, mean, bad_sigma * 3)
def test_rayleigh(self):
scale = [1]
bad_scale = [-1]
desired = np.array([1.2337491937897689,
1.2360119924878694,
1.1936818095781789])
rng = random.RandomState(self.seed)
actual = rng.rayleigh(scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.rayleigh, bad_scale * 3)
def test_wald(self):
mean = [0.5]
scale = [1]
bad_mean = [0]
bad_scale = [-2]
desired = np.array([0.11873681120271318,
0.12450084820795027,
0.9096122728408238])
rng = random.RandomState(self.seed)
actual = rng.wald(mean * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.wald, bad_mean * 3, scale)
assert_raises(ValueError, rng.wald, mean * 3, bad_scale)
rng = random.RandomState(self.seed)
actual = rng.wald(mean, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.wald, bad_mean, scale * 3)
assert_raises(ValueError, rng.wald, mean, bad_scale * 3)
assert_raises(ValueError, rng.wald, 0.0, 1)
assert_raises(ValueError, rng.wald, 0.5, 0.0)
def test_triangular(self):
left = [1]
right = [3]
mode = [2]
bad_left_one = [3]
bad_mode_one = [4]
bad_left_two, bad_mode_two = right * 2
desired = np.array([2.03339048710429,
2.0347400359389356,
2.0095991069536208])
rng = random.RandomState(self.seed)
actual = rng.triangular(left * 3, mode, right)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.triangular, bad_left_one * 3, mode, right)
assert_raises(ValueError, rng.triangular, left * 3, bad_mode_one, right)
assert_raises(ValueError, rng.triangular, bad_left_two * 3, bad_mode_two,
right)
rng = random.RandomState(self.seed)
actual = rng.triangular(left, mode * 3, right)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.triangular, bad_left_one, mode * 3, right)
assert_raises(ValueError, rng.triangular, left, bad_mode_one * 3, right)
assert_raises(ValueError, rng.triangular, bad_left_two, bad_mode_two * 3,
right)
rng = random.RandomState(self.seed)
actual = rng.triangular(left, mode, right * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, rng.triangular, bad_left_one, mode, right * 3)
assert_raises(ValueError, rng.triangular, left, bad_mode_one, right * 3)
assert_raises(ValueError, rng.triangular, bad_left_two, bad_mode_two,
right * 3)
def test_binomial(self):
n = [1]
p = [0.5]
bad_n = [-1]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([1, 1, 1])
rng = random.RandomState(self.seed)
actual = rng.binomial(n * 3, p)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.binomial, bad_n * 3, p)
assert_raises(ValueError, rng.binomial, n * 3, bad_p_one)
assert_raises(ValueError, rng.binomial, n * 3, bad_p_two)
rng = random.RandomState(self.seed)
actual = rng.binomial(n, p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.binomial, bad_n, p * 3)
assert_raises(ValueError, rng.binomial, n, bad_p_one * 3)
assert_raises(ValueError, rng.binomial, n, bad_p_two * 3)
def test_negative_binomial(self):
n = [1]
p = [0.5]
bad_n = [-1]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([1, 0, 1])
rng = random.RandomState(self.seed)
actual = rng.negative_binomial(n * 3, p)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.negative_binomial, bad_n * 3, p)
assert_raises(ValueError, rng.negative_binomial, n * 3, bad_p_one)
assert_raises(ValueError, rng.negative_binomial, n * 3, bad_p_two)
rng = random.RandomState(self.seed)
actual = rng.negative_binomial(n, p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.negative_binomial, bad_n, p * 3)
assert_raises(ValueError, rng.negative_binomial, n, bad_p_one * 3)
assert_raises(ValueError, rng.negative_binomial, n, bad_p_two * 3)
def test_poisson(self):
max_lam = np.random.RandomState()._poisson_lam_max
lam = [1]
bad_lam_one = [-1]
bad_lam_two = [max_lam * 2]
desired = np.array([1, 1, 0])
rng = random.RandomState(self.seed)
actual = rng.poisson(lam * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.poisson, bad_lam_one * 3)
assert_raises(ValueError, rng.poisson, bad_lam_two * 3)
def test_zipf(self):
a = [2]
bad_a = [0]
desired = np.array([2, 2, 1])
rng = random.RandomState(self.seed)
actual = rng.zipf(a * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.zipf, bad_a * 3)
with np.errstate(invalid='ignore'):
assert_raises(ValueError, rng.zipf, np.nan)
assert_raises(ValueError, rng.zipf, [0, 0, np.nan])
def test_geometric(self):
p = [0.5]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([2, 2, 2])
rng = random.RandomState(self.seed)
actual = rng.geometric(p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.geometric, bad_p_one * 3)
assert_raises(ValueError, rng.geometric, bad_p_two * 3)
def test_hypergeometric(self):
ngood = [1]
nbad = [2]
nsample = [2]
bad_ngood = [-1]
bad_nbad = [-2]
bad_nsample_one = [0]
bad_nsample_two = [4]
desired = np.array([1, 1, 1])
rng = random.RandomState(self.seed)
actual = rng.hypergeometric(ngood * 3, nbad, nsample)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.hypergeometric, bad_ngood * 3, nbad, nsample)
assert_raises(ValueError, rng.hypergeometric, ngood * 3, bad_nbad, nsample)
assert_raises(ValueError, rng.hypergeometric, ngood * 3, nbad, bad_nsample_one)
assert_raises(ValueError, rng.hypergeometric, ngood * 3, nbad, bad_nsample_two)
rng = random.RandomState(self.seed)
actual = rng.hypergeometric(ngood, nbad * 3, nsample)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.hypergeometric, bad_ngood, nbad * 3, nsample)
assert_raises(ValueError, rng.hypergeometric, ngood, bad_nbad * 3, nsample)
assert_raises(ValueError, rng.hypergeometric, ngood, nbad * 3, bad_nsample_one)
assert_raises(ValueError, rng.hypergeometric, ngood, nbad * 3, bad_nsample_two)
rng = random.RandomState(self.seed)
actual = rng.hypergeometric(ngood, nbad, nsample * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.hypergeometric, bad_ngood, nbad, nsample * 3)
assert_raises(ValueError, rng.hypergeometric, ngood, bad_nbad, nsample * 3)
assert_raises(ValueError, rng.hypergeometric, ngood, nbad, bad_nsample_one * 3)
assert_raises(ValueError, rng.hypergeometric, ngood, nbad, bad_nsample_two * 3)
def test_logseries(self):
p = [0.5]
bad_p_one = [2]
bad_p_two = [-1]
desired = np.array([1, 1, 1])
rng = random.RandomState(self.seed)
actual = rng.logseries(p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, rng.logseries, bad_p_one * 3)
assert_raises(ValueError, rng.logseries, bad_p_two * 3)
@pytest.mark.skipif(IS_WASM, reason="can't start thread")
class TestThread:
# make sure each state produces the same sequence even in threads
seeds = range(4)
def check_function(self, function, sz):
from threading import Thread
out1 = np.empty((len(self.seeds),) + sz)
out2 = np.empty((len(self.seeds),) + sz)
# threaded generation
t = [Thread(target=function, args=(np.random.RandomState(s), o))
for s, o in zip(self.seeds, out1)]
[x.start() for x in t]
[x.join() for x in t]
# the same serial
for s, o in zip(self.seeds, out2):
function(np.random.RandomState(s), o)
# these platforms change x87 fpu precision mode in threads
if np.intp().dtype.itemsize == 4 and sys.platform == "win32":
assert_array_almost_equal(out1, out2)
else:
assert_array_equal(out1, out2)
def test_normal(self):
def gen_random(state, out):
out[...] = state.normal(size=10000)
self.check_function(gen_random, sz=(10000,))
def test_exp(self):
def gen_random(state, out):
out[...] = state.exponential(scale=np.ones((100, 1000)))
self.check_function(gen_random, sz=(100, 1000))
def test_multinomial(self):
def gen_random(state, out):
out[...] = state.multinomial(10, [1 / 6.] * 6, size=10000)
self.check_function(gen_random, sz=(10000, 6))
# See Issue #4263
class TestSingleEltArrayInput:
def _create_arrays(self):
return np.array([2]), np.array([3]), np.array([4]), (1,)
def test_one_arg_funcs(self):
argOne, _, _, tgtShape = self._create_arrays()
funcs = (np.random.exponential, np.random.standard_gamma,
np.random.chisquare, np.random.standard_t,
np.random.pareto, np.random.weibull,
np.random.power, np.random.rayleigh,
np.random.poisson, np.random.zipf,
np.random.geometric, np.random.logseries)
probfuncs = (np.random.geometric, np.random.logseries)
for func in funcs:
if func in probfuncs: # p < 1.0
out = func(np.array([0.5]))
else:
out = func(argOne)
assert_equal(out.shape, tgtShape)
def test_two_arg_funcs(self):
argOne, argTwo, _, tgtShape = self._create_arrays()
funcs = (np.random.uniform, np.random.normal,
np.random.beta, np.random.gamma,
np.random.f, np.random.noncentral_chisquare,
np.random.vonmises, np.random.laplace,
np.random.gumbel, np.random.logistic,
np.random.lognormal, np.random.wald,
np.random.binomial, np.random.negative_binomial)
probfuncs = (np.random.binomial, np.random.negative_binomial)
for func in funcs:
if func in probfuncs: # p <= 1
argTwo = np.array([0.5])
else:
argTwo = argTwo
out = func(argOne, argTwo)
assert_equal(out.shape, tgtShape)
out = func(argOne[0], argTwo)
assert_equal(out.shape, tgtShape)
out = func(argOne, argTwo[0])
assert_equal(out.shape, tgtShape)
def test_randint(self):
_, _, _, tgtShape = self._create_arrays()
itype = [bool, np.int8, np.uint8, np.int16, np.uint16,
np.int32, np.uint32, np.int64, np.uint64]
func = np.random.randint
high = np.array([1])
low = np.array([0])
for dt in itype:
out = func(low, high, dtype=dt)
assert_equal(out.shape, tgtShape)
out = func(low[0], high, dtype=dt)
assert_equal(out.shape, tgtShape)
out = func(low, high[0], dtype=dt)
assert_equal(out.shape, tgtShape)
def test_three_arg_funcs(self):
argOne, argTwo, argThree, tgtShape = self._create_arrays()
funcs = [np.random.noncentral_f, np.random.triangular,
np.random.hypergeometric]
for func in funcs:
out = func(argOne, argTwo, argThree)
assert_equal(out.shape, tgtShape)
out = func(argOne[0], argTwo, argThree)
assert_equal(out.shape, tgtShape)
out = func(argOne, argTwo[0], argThree)
assert_equal(out.shape, tgtShape)
| import sys
import warnings
import pytest
import numpy as np
from numpy import random
from numpy.testing import (
IS_WASM,
assert_,
assert_array_almost_equal,
assert_array_equal,
assert_equal,
assert_no_warnings,
assert_raises,
)
class TestSeed:
def test_scalar(self):
s = np.random.RandomState(0)
assert_equal(s.randint(1000), 684)
s = np.random.RandomState(4294967295)
assert_equal(s.randint(1000), 419)
def test_array(self):
s = np.random.RandomState(range(10))
assert_equal(s.randint(1000), 468)
s = np.random.RandomState(np.arange(10))
assert_equal(s.randint(1000), 468)
s = np.random.RandomState([0])
assert_equal(s.randint(1000), 973)
s = np.random.RandomState([4294967295])
assert_equal(s.randint(1000), 265)
def test_invalid_scalar(self):
# seed must be an unsigned 32 bit integer
assert_raises(TypeError, np.random.RandomState, -0.5)
assert_raises(ValueError, np.random.RandomState, -1)
def test_invalid_array(self):
# seed must be an unsigned 32 bit integer
| [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_equal"
] | numpy/numpy | numpy/random/tests/test_random.py |
import pytest
import numpy as np
from numpy.random import MT19937, Generator
from numpy.testing import assert_, assert_array_equal
class TestRegression:
def _create_generator(self):
return Generator(MT19937(121263137472525314065))
def test_vonmises_range(self):
# Make sure generated random variables are in [-pi, pi].
# Regression test for ticket #986.
mt19937 = self._create_generator()
for mu in np.linspace(-7., 7., 5):
r = mt19937.vonmises(mu, 1, 50)
assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
def test_hypergeometric_range(self):
# Test for ticket #921
mt19937 = self._create_generator()
assert_(np.all(mt19937.hypergeometric(3, 18, 11, size=10) < 4))
assert_(np.all(mt19937.hypergeometric(18, 3, 11, size=10) > 0))
# Test for ticket #5623
args = (2**20 - 2, 2**20 - 2, 2**20 - 2) # Check for 32-bit systems
assert_(mt19937.hypergeometric(*args) > 0)
def test_logseries_convergence(self):
# Test for ticket #923
mt19937 = self._create_generator()
N = 1000
rvsn = mt19937.logseries(0.8, size=N)
# these two frequency counts should be close to theoretical
# numbers with this large sample
# theoretical large N result is 0.49706795
freq = np.sum(rvsn == 1) / N
msg = f'Frequency was {freq:f}, should be > 0.45'
assert_(freq > 0.45, msg)
# theoretical large N result is 0.19882718
freq = np.sum(rvsn == 2) / N
msg = f'Frequency was {freq:f}, should be < 0.23'
assert_(freq < 0.23, msg)
def test_shuffle_mixed_dimension(self):
# Test for trac ticket #2074
for t in [[1, 2, 3, None],
[(1, 1), (2, 2), (3, 3), None],
[1, (2, 2), (3, 3), None],
[(1, 1), 2, 3, None]]:
mt19937 = Generator(MT19937(12345))
shuffled = np.array(t, dtype=object)
mt19937.shuffle(shuffled)
expected = np.array([t[2], t[0], t[3], t[1]], dtype=object)
assert_array_equal(np.array(shuffled, dtype=object), expected)
def test_call_within_randomstate(self):
# Check that custom BitGenerator does not call into global state
res = np.array([1, 8, 0, 1, 5, 3, 3, 8, 1, 4])
for i in range(3):
mt19937 = Generator(MT19937(i))
m = Generator(MT19937(4321))
# If m.state is not honored, the result will change
assert_array_equal(m.choice(10, size=10, p=np.ones(10) / 10.), res)
def test_multivariate_normal_size_types(self):
# Test for multivariate_normal issue with 'size' argument.
# Check that the multivariate_normal size argument can be a
# numpy integer.
mt19937 = self._create_generator()
mt19937.multivariate_normal([0], [[0]], size=1)
mt19937.multivariate_normal([0], [[0]], size=np.int_(1))
mt19937.multivariate_normal([0], [[0]], size=np.int64(1))
def test_beta_small_parameters(self):
# Test that beta with small a and b parameters does not produce
# NaNs due to roundoff errors causing 0 / 0, gh-5851
mt19937 = self._create_generator()
x = mt19937.beta(0.0001, 0.0001, size=100)
assert_(not np.any(np.isnan(x)), 'Nans in mt19937.beta')
def test_beta_very_small_parameters(self):
# gh-24203: beta would hang with very small parameters.
mt19937 = self._create_generator()
mt19937.beta(1e-49, 1e-40)
def test_beta_ridiculously_small_parameters(self):
# gh-24266: beta would generate nan when the parameters
# were subnormal or a small multiple of the smallest normal.
mt19937 = self._create_generator()
tiny = np.finfo(1.0).tiny
x = mt19937.beta(tiny / 32, tiny / 40, size=50)
assert not np.any(np.isnan(x))
def test_beta_expected_zero_frequency(self):
# gh-24475: For small a and b (e.g. a=0.0025, b=0.0025), beta
# would generate too many zeros.
mt19937 = self._create_generator()
a = 0.0025
b = 0.0025
n = 1000000
x = mt19937.beta(a, b, size=n)
nzeros = np.count_nonzero(x == 0)
# beta CDF at x = np.finfo(np.double).smallest_subnormal/2
# is p = 0.0776169083131899, e.g,
#
# import numpy as np
# from mpmath import mp
# mp.dps = 160
# x = mp.mpf(np.finfo(np.float64).smallest_subnormal)/2
# # CDF of the beta distribution at x:
# p = mp.betainc(a, b, x1=0, x2=x, regularized=True)
# n = 1000000
# exprected_freq = float(n*p)
#
expected_freq = 77616.90831318991
assert 0.95 * expected_freq < nzeros < 1.05 * expected_freq
def test_choice_sum_of_probs_tolerance(self):
# The sum of probs should be 1.0 with some tolerance.
# For low precision dtypes the tolerance was too tight.
# See numpy github issue 6123.
mt19937 = self._create_generator()
a = [1, 2, 3]
counts = [4, 4, 2]
for dt in np.float16, np.float32, np.float64:
probs = np.array(counts, dtype=dt) / sum(counts)
c = mt19937.choice(a, p=probs)
assert_(c in a)
with pytest.raises(ValueError):
mt19937.choice(a, p=probs * 0.9)
def test_shuffle_of_array_of_different_length_strings(self):
# Test that permuting an array of different length strings
# will not cause a segfault on garbage collection
# Tests gh-7710
mt19937 = self._create_generator()
a = np.array(['a', 'a' * 1000])
for _ in range(100):
mt19937.shuffle(a)
# Force Garbage Collection - should not segfault.
import gc
gc.collect()
def test_shuffle_of_array_of_objects(self):
# Test that permuting an array of objects will not cause
# a segfault on garbage collection.
# See gh-7719
mt19937 = self._create_generator()
a = np.array([np.arange(1), np.arange(4)], dtype=object)
for _ in range(1000):
mt19937.shuffle(a)
# Force Garbage Collection - should not segfault.
import gc
gc.collect()
def test_permutation_subclass(self):
class N(np.ndarray):
pass
mt19937 = Generator(MT19937(1))
orig = np.arange(3).view(N)
perm = mt19937.permutation(orig)
assert_array_equal(perm, np.array([2, 0, 1]))
assert_array_equal(orig, np.arange(3).view(N))
class M:
a = np.arange(5)
def __array__(self, dtype=None, copy=None):
return self.a
mt19937 = Generator(MT19937(1))
m = M()
perm = mt19937.permutation(m)
assert_array_equal(perm, np.array([4, 1, 3, 0, 2]))
assert_array_equal(m.__array__(), np.arange(5))
def test_gamma_0(self):
mt19937 = self._create_generator()
assert mt19937.standard_gamma(0.0) == 0.0
assert_array_equal(mt19937.standard_gamma([0.0]), 0.0)
actual = mt19937.standard_gamma([0.0], dtype='float')
expected = np.array([0.], dtype=np.float32)
assert_array_equal(actual, expected)
def test_geometric_tiny_prob(self):
# Regression test for gh-17007.
# When p = 1e-30, the probability that a sample will exceed 2**63-1
# is 0.9999999999907766, so we expect the result to be all 2**63-1.
mt19937 = self._create_generator()
assert_array_equal(mt19937.geometric(p=1e-30, size=3),
np.iinfo(np.int64).max)
def test_zipf_large_parameter(self):
# Regression test for part of gh-9829: a call such as rng.zipf(10000)
# would hang.
mt19937 = self._create_generator()
n = 8
sample = mt19937.zipf(10000, size=n)
assert_array_equal(sample, np.ones(n, dtype=np.int64))
def test_zipf_a_near_1(self):
# Regression test for gh-9829: a call such as rng.zipf(1.0000000000001)
# would hang.
mt19937 = self._create_generator()
n = 100000
sample = mt19937.zipf(1.0000000000001, size=n)
# Not much of a test, but let's do something more than verify that
# it doesn't hang. Certainly for a monotonically decreasing
# discrete distribution truncated to signed 64 bit integers, more
# than half should be less than 2**62.
assert np.count_nonzero(sample < 2**62) > n / 2
| import pytest
import numpy as np
from numpy.random import MT19937, Generator
from numpy.testing import assert_, assert_array_equal
class TestRegression:
def _create_generator(self):
return Generator(MT19937(121263137472525314065))
def test_vonmises_range(self):
# Make sure generated random variables are in [-pi, pi].
# Regression test for ticket #986.
mt19937 = self._create_generator()
for mu in np.linspace(-7., 7., 5):
r = mt19937.vonmises(mu, 1, 50)
assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
def test_hypergeometric_range(self):
# Test for ticket #921
mt19937 = self._create_generator()
assert_(np.all(mt19937.hypergeometric(3, 18, 11, size=10) < 4))
assert_(np.all(mt19937.hypergeometric(18, 3, 11, size=10) > 0))
# Test for ticket #5623
args = (2**20 - 2, 2**20 - 2, 2**20 - 2) # Check for 32-bit systems
assert_(mt19937.hypergeometric(*args) > 0)
def test_logseries_convergence(self):
# Test for ticket #923
mt19937 = self._create_generator()
N = 1000
rvsn = mt19937.log | [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_"
] | numpy/numpy | numpy/random/tests/test_generator_mt19937_regressions.py |
import hashlib
import os.path
import sys
import warnings
import pytest
import numpy as np
from numpy.exceptions import AxisError
from numpy.linalg import LinAlgError
from numpy.random import MT19937, Generator, RandomState, SeedSequence
from numpy.testing import (
IS_WASM,
assert_,
assert_allclose,
assert_array_almost_equal,
assert_array_equal,
assert_equal,
assert_no_warnings,
assert_raises,
)
random = Generator(MT19937())
JUMP_TEST_DATA = [
{
"seed": 0,
"steps": 10,
"initial": {"key_sha256": "bb1636883c2707b51c5b7fc26c6927af4430f2e0785a8c7bc886337f919f9edf", "pos": 9}, # noqa: E501
"jumped": {"key_sha256": "ff682ac12bb140f2d72fba8d3506cf4e46817a0db27aae1683867629031d8d55", "pos": 598}, # noqa: E501
},
{
"seed": 384908324,
"steps": 312,
"initial": {"key_sha256": "16b791a1e04886ccbbb4d448d6ff791267dc458ae599475d08d5cced29d11614", "pos": 311}, # noqa: E501
"jumped": {"key_sha256": "a0110a2cf23b56be0feaed8f787a7fc84bef0cb5623003d75b26bdfa1c18002c", "pos": 276}, # noqa: E501
},
{
"seed": [839438204, 980239840, 859048019, 821],
"steps": 511,
"initial": {"key_sha256": "d306cf01314d51bd37892d874308200951a35265ede54d200f1e065004c3e9ea", "pos": 510}, # noqa: E501
"jumped": {"key_sha256": "0e00ab449f01a5195a83b4aee0dfbc2ce8d46466a640b92e33977d2e42f777f8", "pos": 475}, # noqa: E501
},
]
@pytest.fixture(scope='module', params=[True, False])
def endpoint(request):
return request.param
class TestSeed:
def test_scalar(self):
s = Generator(MT19937(0))
assert_equal(s.integers(1000), 479)
s = Generator(MT19937(4294967295))
assert_equal(s.integers(1000), 324)
def test_array(self):
s = Generator(MT19937(range(10)))
assert_equal(s.integers(1000), 465)
s = Generator(MT19937(np.arange(10)))
assert_equal(s.integers(1000), 465)
s = Generator(MT19937([0]))
assert_equal(s.integers(1000), 479)
s = Generator(MT19937([4294967295]))
assert_equal(s.integers(1000), 324)
def test_seedsequence(self):
s = MT19937(SeedSequence(0))
assert_equal(s.random_raw(1), 2058676884)
def test_invalid_scalar(self):
# seed must be an unsigned 32 bit integer
assert_raises(TypeError, MT19937, -0.5)
assert_raises(ValueError, MT19937, -1)
def test_invalid_array(self):
# seed must be an unsigned integer
assert_raises(TypeError, MT19937, [-0.5])
assert_raises(ValueError, MT19937, [-1])
assert_raises(ValueError, MT19937, [1, -2, 4294967296])
def test_noninstantized_bitgen(self):
assert_raises(ValueError, Generator, MT19937)
class TestBinomial:
def test_n_zero(self):
# Tests the corner case of n == 0 for the binomial distribution.
# binomial(0, p) should be zero for any p in [0, 1].
# This test addresses issue #3480.
zeros = np.zeros(2, dtype='int')
for p in [0, .5, 1]:
assert_(random.binomial(0, p) == 0)
assert_array_equal(random.binomial(zeros, p), zeros)
def test_p_is_nan(self):
# Issue #4571.
assert_raises(ValueError, random.binomial, 1, np.nan)
def test_p_extremely_small(self):
n = 50000000000
p = 5e-17
sample_size = 20000000
x = random.binomial(n, p, size=sample_size)
sample_mean = x.mean()
expected_mean = n * p
sigma = np.sqrt(n * p * (1 - p) / sample_size)
# Note: the parameters were chosen so that expected_mean - 6*sigma
# is a positive value. The first `assert` below validates that
# assumption (in case someone edits the parameters in the future).
# The second `assert` is the actual test.
low_bound = expected_mean - 6 * sigma
assert low_bound > 0, "bad test params: 6-sigma lower bound is negative"
test_msg = (f"sample mean {sample_mean} deviates from the expected mean "
f"{expected_mean} by more than 6*sigma")
assert abs(expected_mean - sample_mean) < 6 * sigma, test_msg
class TestMultinomial:
def test_basic(self):
random.multinomial(100, [0.2, 0.8])
def test_zero_probability(self):
random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0])
def test_int_negative_interval(self):
assert_(-5 <= random.integers(-5, -1) < -1)
x = random.integers(-5, -1, 5)
assert_(np.all(-5 <= x))
assert_(np.all(x < -1))
def test_size(self):
# gh-3173
p = [0.5, 0.5]
assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(random.multinomial(1, p, np.uint32(1)).shape, (1, 2))
assert_equal(random.multinomial(1, p, [2, 2]).shape, (2, 2, 2))
assert_equal(random.multinomial(1, p, (2, 2)).shape, (2, 2, 2))
assert_equal(random.multinomial(1, p, np.array((2, 2))).shape,
(2, 2, 2))
assert_raises(TypeError, random.multinomial, 1, p,
float(1))
def test_invalid_prob(self):
assert_raises(ValueError, random.multinomial, 100, [1.1, 0.2])
assert_raises(ValueError, random.multinomial, 100, [-.1, 0.9])
def test_invalid_n(self):
assert_raises(ValueError, random.multinomial, -1, [0.8, 0.2])
assert_raises(ValueError, random.multinomial, [-1] * 10, [0.8, 0.2])
def test_p_non_contiguous(self):
p = np.arange(15.)
p /= np.sum(p[1::3])
pvals = p[1::3]
random = Generator(MT19937(1432985819))
non_contig = random.multinomial(100, pvals=pvals)
random = Generator(MT19937(1432985819))
contig = random.multinomial(100, pvals=np.ascontiguousarray(pvals))
assert_array_equal(non_contig, contig)
def test_multinomial_pvals_float32(self):
x = np.array([9.9e-01, 9.9e-01, 1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09,
1.0e-09, 1.0e-09, 1.0e-09, 1.0e-09], dtype=np.float32)
pvals = x / x.sum()
random = Generator(MT19937(1432985819))
match = r"[\w\s]*pvals array is cast to 64-bit floating"
with pytest.raises(ValueError, match=match):
random.multinomial(1, pvals)
class TestMultivariateHypergeometric:
seed = 8675309
def test_argument_validation(self):
# Error cases...
# `colors` must be a 1-d sequence
assert_raises(ValueError, random.multivariate_hypergeometric,
10, 4)
# Negative nsample
assert_raises(ValueError, random.multivariate_hypergeometric,
[2, 3, 4], -1)
# Negative color
assert_raises(ValueError, random.multivariate_hypergeometric,
[-1, 2, 3], 2)
# nsample exceeds sum(colors)
assert_raises(ValueError, random.multivariate_hypergeometric,
[2, 3, 4], 10)
# nsample exceeds sum(colors) (edge case of empty colors)
assert_raises(ValueError, random.multivariate_hypergeometric,
[], 1)
# Validation errors associated with very large values in colors.
assert_raises(ValueError, random.multivariate_hypergeometric,
[999999999, 101], 5, 1, 'marginals')
int64_info = np.iinfo(np.int64)
max_int64 = int64_info.max
max_int64_index = max_int64 // int64_info.dtype.itemsize
assert_raises(ValueError, random.multivariate_hypergeometric,
[max_int64_index - 100, 101], 5, 1, 'count')
@pytest.mark.parametrize('method', ['count', 'marginals'])
def test_edge_cases(self, method):
# Set the seed, but in fact, all the results in this test are
# deterministic, so we don't really need this.
random = Generator(MT19937(self.seed))
x = random.multivariate_hypergeometric([0, 0, 0], 0, method=method)
assert_array_equal(x, [0, 0, 0])
x = random.multivariate_hypergeometric([], 0, method=method)
assert_array_equal(x, [])
x = random.multivariate_hypergeometric([], 0, size=1, method=method)
assert_array_equal(x, np.empty((1, 0), dtype=np.int64))
x = random.multivariate_hypergeometric([1, 2, 3], 0, method=method)
assert_array_equal(x, [0, 0, 0])
x = random.multivariate_hypergeometric([9, 0, 0], 3, method=method)
assert_array_equal(x, [3, 0, 0])
colors = [1, 1, 0, 1, 1]
x = random.multivariate_hypergeometric(colors, sum(colors),
method=method)
assert_array_equal(x, colors)
x = random.multivariate_hypergeometric([3, 4, 5], 12, size=3,
method=method)
assert_array_equal(x, [[3, 4, 5]] * 3)
# Cases for nsample:
# nsample < 10
# 10 <= nsample < colors.sum()/2
# colors.sum()/2 < nsample < colors.sum() - 10
# colors.sum() - 10 < nsample < colors.sum()
@pytest.mark.parametrize('nsample', [8, 25, 45, 55])
@pytest.mark.parametrize('method', ['count', 'marginals'])
@pytest.mark.parametrize('size', [5, (2, 3), 150000])
def test_typical_cases(self, nsample, method, size):
random = Generator(MT19937(self.seed))
colors = np.array([10, 5, 20, 25])
sample = random.multivariate_hypergeometric(colors, nsample, size,
method=method)
if isinstance(size, int):
expected_shape = (size,) + colors.shape
else:
expected_shape = size + colors.shape
assert_equal(sample.shape, expected_shape)
assert_((sample >= 0).all())
assert_((sample <= colors).all())
assert_array_equal(sample.sum(axis=-1),
np.full(size, fill_value=nsample, dtype=int))
if isinstance(size, int) and size >= 100000:
# This sample is large enough to compare its mean to
# the expected values.
assert_allclose(sample.mean(axis=0),
nsample * colors / colors.sum(),
rtol=1e-3, atol=0.005)
def test_repeatability1(self):
random = Generator(MT19937(self.seed))
sample = random.multivariate_hypergeometric([3, 4, 5], 5, size=5,
method='count')
expected = np.array([[2, 1, 2],
[2, 1, 2],
[1, 1, 3],
[2, 0, 3],
[2, 1, 2]])
assert_array_equal(sample, expected)
def test_repeatability2(self):
random = Generator(MT19937(self.seed))
sample = random.multivariate_hypergeometric([20, 30, 50], 50,
size=5,
method='marginals')
expected = np.array([[ 9, 17, 24],
[ 7, 13, 30],
[ 9, 15, 26],
[ 9, 17, 24],
[12, 14, 24]])
assert_array_equal(sample, expected)
def test_repeatability3(self):
random = Generator(MT19937(self.seed))
sample = random.multivariate_hypergeometric([20, 30, 50], 12,
size=5,
method='marginals')
expected = np.array([[2, 3, 7],
[5, 3, 4],
[2, 5, 5],
[5, 3, 4],
[1, 5, 6]])
assert_array_equal(sample, expected)
class TestSetState:
def _create_rng(self):
seed = 1234567890
rg = Generator(MT19937(seed))
bit_generator = rg.bit_generator
state = bit_generator.state
legacy_state = (state['bit_generator'],
state['state']['key'],
state['state']['pos'])
return rg, bit_generator, state
def test_gaussian_reset(self):
# Make sure the cached every-other-Gaussian is reset.
rg, bit_generator, state = self._create_rng()
old = rg.standard_normal(size=3)
bit_generator.state = state
new = rg.standard_normal(size=3)
assert_(np.all(old == new))
def test_gaussian_reset_in_media_res(self):
# When the state is saved with a cached Gaussian, make sure the
# cached Gaussian is restored.
rg, bit_generator, state = self._create_rng()
rg.standard_normal()
state = bit_generator.state
old = rg.standard_normal(size=3)
bit_generator.state = state
new = rg.standard_normal(size=3)
assert_(np.all(old == new))
def test_negative_binomial(self):
# Ensure that the negative binomial results take floating point
# arguments without truncation.
rg, _, _ = self._create_rng()
rg.negative_binomial(0.5, 0.5)
class TestIntegers:
rfunc = random.integers
# valid integer/boolean types
itype = [bool, np.int8, np.uint8, np.int16, np.uint16,
np.int32, np.uint32, np.int64, np.uint64]
def test_unsupported_type(self, endpoint):
assert_raises(TypeError, self.rfunc, 1, endpoint=endpoint, dtype=float)
def test_bounds_checking(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
assert_raises(ValueError, self.rfunc, lbnd - 1, ubnd,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, lbnd, ubnd + 1,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, ubnd, lbnd,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, 1, 0, endpoint=endpoint,
dtype=dt)
assert_raises(ValueError, self.rfunc, [lbnd - 1], ubnd,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, [lbnd], [ubnd + 1],
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, [ubnd], [lbnd],
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, 1, [0],
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, [ubnd + 1], [ubnd],
endpoint=endpoint, dtype=dt)
def test_bounds_checking_array(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + (not endpoint)
assert_raises(ValueError, self.rfunc, [lbnd - 1] * 2, [ubnd] * 2,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, [lbnd] * 2,
[ubnd + 1] * 2, endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, ubnd, [lbnd] * 2,
endpoint=endpoint, dtype=dt)
assert_raises(ValueError, self.rfunc, [1] * 2, 0,
endpoint=endpoint, dtype=dt)
def test_rng_zero_and_extremes(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
is_open = not endpoint
tgt = ubnd - 1
assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
endpoint=endpoint, dtype=dt), tgt)
assert_equal(self.rfunc([tgt], tgt + is_open, size=1000,
endpoint=endpoint, dtype=dt), tgt)
tgt = lbnd
assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
endpoint=endpoint, dtype=dt), tgt)
assert_equal(self.rfunc(tgt, [tgt + is_open], size=1000,
endpoint=endpoint, dtype=dt), tgt)
tgt = (lbnd + ubnd) // 2
assert_equal(self.rfunc(tgt, tgt + is_open, size=1000,
endpoint=endpoint, dtype=dt), tgt)
assert_equal(self.rfunc([tgt], [tgt + is_open],
size=1000, endpoint=endpoint, dtype=dt),
tgt)
def test_rng_zero_and_extremes_array(self, endpoint):
size = 1000
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
tgt = ubnd - 1
assert_equal(self.rfunc([tgt], [tgt + 1],
size=size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
tgt = lbnd
assert_equal(self.rfunc([tgt], [tgt + 1],
size=size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
tgt = (lbnd + ubnd) // 2
assert_equal(self.rfunc([tgt], [tgt + 1],
size=size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, dtype=dt), tgt)
assert_equal(self.rfunc(
[tgt] * size, [tgt + 1] * size, size=size, dtype=dt), tgt)
def test_full_range(self, endpoint):
# Test for ticket #1690
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
try:
self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
except Exception as e:
raise AssertionError("No error should have been raised, "
"but one was with the following "
"message:\n\n%s" % str(e))
def test_full_range_array(self, endpoint):
# Test for ticket #1690
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
try:
self.rfunc([lbnd] * 2, [ubnd], endpoint=endpoint, dtype=dt)
except Exception as e:
raise AssertionError("No error should have been raised, "
"but one was with the following "
"message:\n\n%s" % str(e))
def test_in_bounds_fuzz(self, endpoint):
# Don't use fixed seed
random = Generator(MT19937())
for dt in self.itype[1:]:
for ubnd in [4, 8, 16]:
vals = self.rfunc(2, ubnd - endpoint, size=2 ** 16,
endpoint=endpoint, dtype=dt)
assert_(vals.max() < ubnd)
assert_(vals.min() >= 2)
vals = self.rfunc(0, 2 - endpoint, size=2 ** 16, endpoint=endpoint,
dtype=bool)
assert_(vals.max() < 2)
assert_(vals.min() >= 0)
def test_scalar_array_equiv(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
size = 1000
random = Generator(MT19937(1234))
scalar = random.integers(lbnd, ubnd, size=size, endpoint=endpoint,
dtype=dt)
random = Generator(MT19937(1234))
scalar_array = random.integers([lbnd], [ubnd], size=size,
endpoint=endpoint, dtype=dt)
random = Generator(MT19937(1234))
array = random.integers([lbnd] * size, [ubnd] *
size, size=size, endpoint=endpoint, dtype=dt)
assert_array_equal(scalar, scalar_array)
assert_array_equal(scalar, array)
def test_repeatability(self, endpoint):
# We use a sha256 hash of generated sequences of 1000 samples
# in the range [0, 6) for all but bool, where the range
# is [0, 2). Hashes are for little endian numbers.
tgt = {'bool': '053594a9b82d656f967c54869bc6970aa0358cf94ad469c81478459c6a90eee3', # noqa: E501
'int16': '54de9072b6ee9ff7f20b58329556a46a447a8a29d67db51201bf88baa6e4e5d4', # noqa: E501
'int32': 'd3a0d5efb04542b25ac712e50d21f39ac30f312a5052e9bbb1ad3baa791ac84b', # noqa: E501
'int64': '14e224389ac4580bfbdccb5697d6190b496f91227cf67df60989de3d546389b1', # noqa: E501
'int8': '0e203226ff3fbbd1580f15da4621e5f7164d0d8d6b51696dd42d004ece2cbec1', # noqa: E501
'uint16': '54de9072b6ee9ff7f20b58329556a46a447a8a29d67db51201bf88baa6e4e5d4', # noqa: E501
'uint32': 'd3a0d5efb04542b25ac712e50d21f39ac30f312a5052e9bbb1ad3baa791ac84b', # noqa: E501
'uint64': '14e224389ac4580bfbdccb5697d6190b496f91227cf67df60989de3d546389b1', # noqa: E501
'uint8': '0e203226ff3fbbd1580f15da4621e5f7164d0d8d6b51696dd42d004ece2cbec1'} # noqa: E501
for dt in self.itype[1:]:
random = Generator(MT19937(1234))
# view as little endian for hash
if sys.byteorder == 'little':
val = random.integers(0, 6 - endpoint, size=1000, endpoint=endpoint,
dtype=dt)
else:
val = random.integers(0, 6 - endpoint, size=1000, endpoint=endpoint,
dtype=dt).byteswap()
res = hashlib.sha256(val).hexdigest()
assert_(tgt[np.dtype(dt).name] == res)
# bools do not depend on endianness
random = Generator(MT19937(1234))
val = random.integers(0, 2 - endpoint, size=1000, endpoint=endpoint,
dtype=bool).view(np.int8)
res = hashlib.sha256(val).hexdigest()
assert_(tgt[np.dtype(bool).name] == res)
def test_repeatability_broadcasting(self, endpoint):
for dt in self.itype:
lbnd = 0 if dt in (bool, np.bool) else np.iinfo(dt).min
ubnd = 2 if dt in (bool, np.bool) else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
# view as little endian for hash
random = Generator(MT19937(1234))
val = random.integers(lbnd, ubnd, size=1000, endpoint=endpoint,
dtype=dt)
random = Generator(MT19937(1234))
val_bc = random.integers([lbnd] * 1000, ubnd, endpoint=endpoint,
dtype=dt)
assert_array_equal(val, val_bc)
random = Generator(MT19937(1234))
val_bc = random.integers([lbnd] * 1000, [ubnd] * 1000,
endpoint=endpoint, dtype=dt)
assert_array_equal(val, val_bc)
@pytest.mark.parametrize(
'bound, expected',
[(2**32 - 1, np.array([517043486, 1364798665, 1733884389, 1353720612,
3769704066, 1170797179, 4108474671])),
(2**32, np.array([517043487, 1364798666, 1733884390, 1353720613,
3769704067, 1170797180, 4108474672])),
(2**32 + 1, np.array([517043487, 1733884390, 3769704068, 4108474673,
1831631863, 1215661561, 3869512430]))]
)
def test_repeatability_32bit_boundary(self, bound, expected):
for size in [None, len(expected)]:
random = Generator(MT19937(1234))
x = random.integers(bound, size=size)
assert_equal(x, expected if size is not None else expected[0])
def test_repeatability_32bit_boundary_broadcasting(self):
desired = np.array([[[1622936284, 3620788691, 1659384060],
[1417365545, 760222891, 1909653332],
[3788118662, 660249498, 4092002593]],
[[3625610153, 2979601262, 3844162757],
[ 685800658, 120261497, 2694012896],
[1207779440, 1586594375, 3854335050]],
[[3004074748, 2310761796, 3012642217],
[2067714190, 2786677879, 1363865881],
[ 791663441, 1867303284, 2169727960]],
[[1939603804, 1250951100, 298950036],
[1040128489, 3791912209, 3317053765],
[3155528714, 61360675, 2305155588]],
[[ 817688762, 1335621943, 3288952434],
[1770890872, 1102951817, 1957607470],
[3099996017, 798043451, 48334215]]])
for size in [None, (5, 3, 3)]:
random = Generator(MT19937(12345))
x = random.integers([[-1], [0], [1]],
[2**32 - 1, 2**32, 2**32 + 1],
size=size)
assert_array_equal(x, desired if size is not None else desired[0])
def test_int64_uint64_broadcast_exceptions(self, endpoint):
configs = {np.uint64: ((0, 2**65), (-1, 2**62), (10, 9), (0, 0)),
np.int64: ((0, 2**64), (-(2**64), 2**62), (10, 9), (0, 0),
(-2**63 - 1, -2**63 - 1))}
for dtype in configs:
for config in configs[dtype]:
low, high = config
high = high - endpoint
low_a = np.array([[low] * 10])
high_a = np.array([high] * 10)
assert_raises(ValueError, random.integers, low, high,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low_a, high,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low, high_a,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low_a, high_a,
endpoint=endpoint, dtype=dtype)
low_o = np.array([[low] * 10], dtype=object)
high_o = np.array([high] * 10, dtype=object)
assert_raises(ValueError, random.integers, low_o, high,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low, high_o,
endpoint=endpoint, dtype=dtype)
assert_raises(ValueError, random.integers, low_o, high_o,
endpoint=endpoint, dtype=dtype)
def test_int64_uint64_corner_case(self, endpoint):
# When stored in Numpy arrays, `lbnd` is casted
# as np.int64, and `ubnd` is casted as np.uint64.
# Checking whether `lbnd` >= `ubnd` used to be
# done solely via direct comparison, which is incorrect
# because when Numpy tries to compare both numbers,
# it casts both to np.float64 because there is
# no integer superset of np.int64 and np.uint64. However,
# `ubnd` is too large to be represented in np.float64,
# causing it be round down to np.iinfo(np.int64).max,
# leading to a ValueError because `lbnd` now equals
# the new `ubnd`.
dt = np.int64
tgt = np.iinfo(np.int64).max
lbnd = np.int64(np.iinfo(np.int64).max)
ubnd = np.uint64(np.iinfo(np.int64).max + 1 - endpoint)
# None of these function calls should
# generate a ValueError now.
actual = random.integers(lbnd, ubnd, endpoint=endpoint, dtype=dt)
assert_equal(actual, tgt)
def test_respect_dtype_singleton(self, endpoint):
# See gh-7203
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
dt = np.bool if dt is bool else dt
sample = self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
assert_equal(sample.dtype, dt)
for dt in (bool, int):
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
# gh-7284: Ensure that we get Python data types
sample = self.rfunc(lbnd, ubnd, endpoint=endpoint, dtype=dt)
assert not hasattr(sample, 'dtype')
assert_equal(type(sample), dt)
def test_respect_dtype_array(self, endpoint):
# See gh-7203
for dt in self.itype:
lbnd = 0 if dt is bool else np.iinfo(dt).min
ubnd = 2 if dt is bool else np.iinfo(dt).max + 1
ubnd = ubnd - 1 if endpoint else ubnd
dt = np.bool if dt is bool else dt
sample = self.rfunc([lbnd], [ubnd], endpoint=endpoint, dtype=dt)
assert_equal(sample.dtype, dt)
sample = self.rfunc([lbnd] * 2, [ubnd] * 2, endpoint=endpoint,
dtype=dt)
assert_equal(sample.dtype, dt)
def test_zero_size(self, endpoint):
# See gh-7203
for dt in self.itype:
sample = self.rfunc(0, 0, (3, 0, 4), endpoint=endpoint, dtype=dt)
assert sample.shape == (3, 0, 4)
assert sample.dtype == dt
assert self.rfunc(0, -10, 0, endpoint=endpoint,
dtype=dt).shape == (0,)
assert_equal(random.integers(0, 0, size=(3, 0, 4)).shape,
(3, 0, 4))
assert_equal(random.integers(0, -10, size=0).shape, (0,))
assert_equal(random.integers(10, 10, size=0).shape, (0,))
def test_error_byteorder(self):
other_byteord_dt = '<i4' if sys.byteorder == 'big' else '>i4'
with pytest.raises(ValueError):
random.integers(0, 200, size=10, dtype=other_byteord_dt)
# chi2max is the maximum acceptable chi-squared value.
@pytest.mark.slow
@pytest.mark.parametrize('sample_size,high,dtype,chi2max',
[(5000000, 5, np.int8, 125.0), # p-value ~4.6e-25
(5000000, 7, np.uint8, 150.0), # p-value ~7.7e-30
(10000000, 2500, np.int16, 3300.0), # p-value ~3.0e-25
(50000000, 5000, np.uint16, 6500.0), # p-value ~3.5e-25
])
def test_integers_small_dtype_chisquared(self, sample_size, high,
dtype, chi2max):
# Regression test for gh-14774.
samples = random.integers(high, size=sample_size, dtype=dtype)
values, counts = np.unique(samples, return_counts=True)
expected = sample_size / high
chi2 = ((counts - expected)**2 / expected).sum()
assert chi2 < chi2max
class TestRandomDist:
# Make sure the random distribution returns the correct value for a
# given seed
seed = 1234567890
def test_integers(self):
random = Generator(MT19937(self.seed))
actual = random.integers(-99, 99, size=(3, 2))
desired = np.array([[-80, -56], [41, 37], [-83, -16]])
assert_array_equal(actual, desired)
def test_integers_masked(self):
# Test masked rejection sampling algorithm to generate array of
# uint32 in an interval.
random = Generator(MT19937(self.seed))
actual = random.integers(0, 99, size=(3, 2), dtype=np.uint32)
desired = np.array([[9, 21], [70, 68], [8, 41]], dtype=np.uint32)
assert_array_equal(actual, desired)
def test_integers_closed(self):
random = Generator(MT19937(self.seed))
actual = random.integers(-99, 99, size=(3, 2), endpoint=True)
desired = np.array([[-80, -56], [41, 38], [-83, -15]])
assert_array_equal(actual, desired)
def test_integers_max_int(self):
# Tests whether integers with closed=True can generate the
# maximum allowed Python int that can be converted
# into a C long. Previous implementations of this
# method have thrown an OverflowError when attempting
# to generate this integer.
actual = random.integers(np.iinfo('l').max, np.iinfo('l').max,
endpoint=True)
desired = np.iinfo('l').max
assert_equal(actual, desired)
def test_random(self):
random = Generator(MT19937(self.seed))
actual = random.random((3, 2))
desired = np.array([[0.096999199829214, 0.707517457682192],
[0.084364834598269, 0.767731206553125],
[0.665069021359413, 0.715487190596693]])
assert_array_almost_equal(actual, desired, decimal=15)
random = Generator(MT19937(self.seed))
actual = random.random()
assert_array_almost_equal(actual, desired[0, 0], decimal=15)
def test_random_float(self):
random = Generator(MT19937(self.seed))
actual = random.random((3, 2))
desired = np.array([[0.0969992 , 0.70751746], # noqa: E203
[0.08436483, 0.76773121],
[0.66506902, 0.71548719]])
assert_array_almost_equal(actual, desired, decimal=7)
def test_random_float_scalar(self):
random = Generator(MT19937(self.seed))
actual = random.random(dtype=np.float32)
desired = 0.0969992
assert_array_almost_equal(actual, desired, decimal=7)
@pytest.mark.parametrize('dtype, uint_view_type',
[(np.float32, np.uint32),
(np.float64, np.uint64)])
def test_random_distribution_of_lsb(self, dtype, uint_view_type):
random = Generator(MT19937(self.seed))
sample = random.random(100000, dtype=dtype)
num_ones_in_lsb = np.count_nonzero(sample.view(uint_view_type) & 1)
# The probability of a 1 in the least significant bit is 0.25.
# With a sample size of 100000, the probability that num_ones_in_lsb
# is outside the following range is less than 5e-11.
assert 24100 < num_ones_in_lsb < 25900
def test_random_unsupported_type(self):
assert_raises(TypeError, random.random, dtype='int32')
def test_choice_uniform_replace(self):
random = Generator(MT19937(self.seed))
actual = random.choice(4, 4)
desired = np.array([0, 0, 2, 2], dtype=np.int64)
assert_array_equal(actual, desired)
def test_choice_nonuniform_replace(self):
random = Generator(MT19937(self.seed))
actual = random.choice(4, 4, p=[0.4, 0.4, 0.1, 0.1])
desired = np.array([0, 1, 0, 1], dtype=np.int64)
assert_array_equal(actual, desired)
def test_choice_uniform_noreplace(self):
random = Generator(MT19937(self.seed))
actual = random.choice(4, 3, replace=False)
desired = np.array([2, 0, 3], dtype=np.int64)
assert_array_equal(actual, desired)
actual = random.choice(4, 4, replace=False, shuffle=False)
desired = np.arange(4, dtype=np.int64)
assert_array_equal(actual, desired)
def test_choice_nonuniform_noreplace(self):
random = Generator(MT19937(self.seed))
actual = random.choice(4, 3, replace=False, p=[0.1, 0.3, 0.5, 0.1])
desired = np.array([0, 2, 3], dtype=np.int64)
assert_array_equal(actual, desired)
def test_choice_noninteger(self):
random = Generator(MT19937(self.seed))
actual = random.choice(['a', 'b', 'c', 'd'], 4)
desired = np.array(['a', 'a', 'c', 'c'])
assert_array_equal(actual, desired)
def test_choice_multidimensional_default_axis(self):
random = Generator(MT19937(self.seed))
actual = random.choice([[0, 1], [2, 3], [4, 5], [6, 7]], 3)
desired = np.array([[0, 1], [0, 1], [4, 5]])
assert_array_equal(actual, desired)
def test_choice_multidimensional_custom_axis(self):
random = Generator(MT19937(self.seed))
actual = random.choice([[0, 1], [2, 3], [4, 5], [6, 7]], 1, axis=1)
desired = np.array([[0], [2], [4], [6]])
assert_array_equal(actual, desired)
def test_choice_exceptions(self):
sample = random.choice
assert_raises(ValueError, sample, -1, 3)
assert_raises(ValueError, sample, 3., 3)
assert_raises(ValueError, sample, [], 3)
assert_raises(ValueError, sample, [1, 2, 3, 4], 3,
p=[[0.25, 0.25], [0.25, 0.25]])
assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4, 0.2])
assert_raises(ValueError, sample, [1, 2], 3, p=[1.1, -0.1])
assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4])
assert_raises(ValueError, sample, [1, 2, 3], 4, replace=False)
# gh-13087
assert_raises(ValueError, sample, [1, 2, 3], -2, replace=False)
assert_raises(ValueError, sample, [1, 2, 3], (-1,), replace=False)
assert_raises(ValueError, sample, [1, 2, 3], (-1, 1), replace=False)
assert_raises(ValueError, sample, [1, 2, 3], 2,
replace=False, p=[1, 0, 0])
def test_choice_return_shape(self):
p = [0.1, 0.9]
# Check scalar
assert_(np.isscalar(random.choice(2, replace=True)))
assert_(np.isscalar(random.choice(2, replace=False)))
assert_(np.isscalar(random.choice(2, replace=True, p=p)))
assert_(np.isscalar(random.choice(2, replace=False, p=p)))
assert_(np.isscalar(random.choice([1, 2], replace=True)))
assert_(random.choice([None], replace=True) is None)
a = np.array([1, 2])
arr = np.empty(1, dtype=object)
arr[0] = a
assert_(random.choice(arr, replace=True) is a)
# Check 0-d array
s = ()
assert_(not np.isscalar(random.choice(2, s, replace=True)))
assert_(not np.isscalar(random.choice(2, s, replace=False)))
assert_(not np.isscalar(random.choice(2, s, replace=True, p=p)))
assert_(not np.isscalar(random.choice(2, s, replace=False, p=p)))
assert_(not np.isscalar(random.choice([1, 2], s, replace=True)))
assert_(random.choice([None], s, replace=True).ndim == 0)
a = np.array([1, 2])
arr = np.empty(1, dtype=object)
arr[0] = a
assert_(random.choice(arr, s, replace=True).item() is a)
# Check multi dimensional array
s = (2, 3)
p = [0.1, 0.1, 0.1, 0.1, 0.4, 0.2]
assert_equal(random.choice(6, s, replace=True).shape, s)
assert_equal(random.choice(6, s, replace=False).shape, s)
assert_equal(random.choice(6, s, replace=True, p=p).shape, s)
assert_equal(random.choice(6, s, replace=False, p=p).shape, s)
assert_equal(random.choice(np.arange(6), s, replace=True).shape, s)
# Check zero-size
assert_equal(random.integers(0, 0, size=(3, 0, 4)).shape, (3, 0, 4))
assert_equal(random.integers(0, -10, size=0).shape, (0,))
assert_equal(random.integers(10, 10, size=0).shape, (0,))
assert_equal(random.choice(0, size=0).shape, (0,))
assert_equal(random.choice([], size=(0,)).shape, (0,))
assert_equal(random.choice(['a', 'b'], size=(3, 0, 4)).shape,
(3, 0, 4))
assert_raises(ValueError, random.choice, [], 10)
def test_choice_nan_probabilities(self):
a = np.array([42, 1, 2])
p = [None, None, None]
assert_raises(ValueError, random.choice, a, p=p)
def test_choice_p_non_contiguous(self):
p = np.ones(10) / 5
p[1::2] = 3.0
random = Generator(MT19937(self.seed))
non_contig = random.choice(5, 3, p=p[::2])
random = Generator(MT19937(self.seed))
contig = random.choice(5, 3, p=np.ascontiguousarray(p[::2]))
assert_array_equal(non_contig, contig)
def test_choice_return_type(self):
# gh 9867
p = np.ones(4) / 4.
actual = random.choice(4, 2)
assert actual.dtype == np.int64
actual = random.choice(4, 2, replace=False)
assert actual.dtype == np.int64
actual = random.choice(4, 2, p=p)
assert actual.dtype == np.int64
actual = random.choice(4, 2, p=p, replace=False)
assert actual.dtype == np.int64
def test_choice_large_sample(self):
choice_hash = '4266599d12bfcfb815213303432341c06b4349f5455890446578877bb322e222'
random = Generator(MT19937(self.seed))
actual = random.choice(10000, 5000, replace=False)
if sys.byteorder != 'little':
actual = actual.byteswap()
res = hashlib.sha256(actual.view(np.int8)).hexdigest()
assert_(choice_hash == res)
def test_choice_array_size_empty_tuple(self):
random = Generator(MT19937(self.seed))
assert_array_equal(random.choice([1, 2, 3], size=()), np.array(1),
strict=True)
assert_array_equal(random.choice([[1, 2, 3]], size=()), [1, 2, 3])
assert_array_equal(random.choice([[1]], size=()), [1], strict=True)
assert_array_equal(random.choice([[1]], size=(), axis=1), [1],
strict=True)
def test_bytes(self):
random = Generator(MT19937(self.seed))
actual = random.bytes(10)
desired = b'\x86\xf0\xd4\x18\xe1\x81\t8%\xdd'
assert_equal(actual, desired)
def test_shuffle(self):
# Test lists, arrays (of various dtypes), and multidimensional versions
# of both, c-contiguous or not:
for conv in [lambda x: np.array([]),
lambda x: x,
lambda x: np.asarray(x).astype(np.int8),
lambda x: np.asarray(x).astype(np.float32),
lambda x: np.asarray(x).astype(np.complex64),
lambda x: np.asarray(x).astype(object),
lambda x: [(i, i) for i in x],
lambda x: np.asarray([[i, i] for i in x]),
lambda x: np.vstack([x, x]).T,
# gh-11442
lambda x: (np.asarray([(i, i) for i in x],
[("a", int), ("b", int)])
.view(np.recarray)),
# gh-4270
lambda x: np.asarray([(i, i) for i in x],
[("a", object, (1,)),
("b", np.int32, (1,))])]:
random = Generator(MT19937(self.seed))
alist = conv([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
random.shuffle(alist)
actual = alist
desired = conv([4, 1, 9, 8, 0, 5, 3, 6, 2, 7])
assert_array_equal(actual, desired)
def test_shuffle_custom_axis(self):
random = Generator(MT19937(self.seed))
actual = np.arange(16).reshape((4, 4))
random.shuffle(actual, axis=1)
desired = np.array([[ 0, 3, 1, 2],
[ 4, 7, 5, 6],
[ 8, 11, 9, 10],
[12, 15, 13, 14]])
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
actual = np.arange(16).reshape((4, 4))
random.shuffle(actual, axis=-1)
assert_array_equal(actual, desired)
def test_shuffle_custom_axis_empty(self):
random = Generator(MT19937(self.seed))
desired = np.array([]).reshape((0, 6))
for axis in (0, 1):
actual = np.array([]).reshape((0, 6))
random.shuffle(actual, axis=axis)
assert_array_equal(actual, desired)
def test_shuffle_axis_nonsquare(self):
y1 = np.arange(20).reshape(2, 10)
y2 = y1.copy()
random = Generator(MT19937(self.seed))
random.shuffle(y1, axis=1)
random = Generator(MT19937(self.seed))
random.shuffle(y2.T)
assert_array_equal(y1, y2)
def test_shuffle_masked(self):
# gh-3263
a = np.ma.masked_values(np.reshape(range(20), (5, 4)) % 3 - 1, -1)
b = np.ma.masked_values(np.arange(20) % 3 - 1, -1)
a_orig = a.copy()
b_orig = b.copy()
for i in range(50):
random.shuffle(a)
assert_equal(
sorted(a.data[~a.mask]), sorted(a_orig.data[~a_orig.mask]))
random.shuffle(b)
assert_equal(
sorted(b.data[~b.mask]), sorted(b_orig.data[~b_orig.mask]))
def test_shuffle_exceptions(self):
random = Generator(MT19937(self.seed))
arr = np.arange(10)
assert_raises(AxisError, random.shuffle, arr, 1)
arr = np.arange(9).reshape((3, 3))
assert_raises(AxisError, random.shuffle, arr, 3)
assert_raises(TypeError, random.shuffle, arr, slice(1, 2, None))
arr = [[1, 2, 3], [4, 5, 6]]
assert_raises(NotImplementedError, random.shuffle, arr, 1)
arr = np.array(3)
assert_raises(TypeError, random.shuffle, arr)
arr = np.ones((3, 2))
assert_raises(AxisError, random.shuffle, arr, 2)
def test_shuffle_not_writeable(self):
random = Generator(MT19937(self.seed))
a = np.zeros(5)
a.flags.writeable = False
with pytest.raises(ValueError, match='read-only'):
random.shuffle(a)
def test_permutation(self):
random = Generator(MT19937(self.seed))
alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
actual = random.permutation(alist)
desired = [4, 1, 9, 8, 0, 5, 3, 6, 2, 7]
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
arr_2d = np.atleast_2d([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]).T
actual = random.permutation(arr_2d)
assert_array_equal(actual, np.atleast_2d(desired).T)
bad_x_str = "abcd"
assert_raises(AxisError, random.permutation, bad_x_str)
bad_x_float = 1.2
assert_raises(AxisError, random.permutation, bad_x_float)
random = Generator(MT19937(self.seed))
integer_val = 10
desired = [3, 0, 8, 7, 9, 4, 2, 5, 1, 6]
actual = random.permutation(integer_val)
assert_array_equal(actual, desired)
def test_permutation_custom_axis(self):
a = np.arange(16).reshape((4, 4))
desired = np.array([[ 0, 3, 1, 2],
[ 4, 7, 5, 6],
[ 8, 11, 9, 10],
[12, 15, 13, 14]])
random = Generator(MT19937(self.seed))
actual = random.permutation(a, axis=1)
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
actual = random.permutation(a, axis=-1)
assert_array_equal(actual, desired)
def test_permutation_exceptions(self):
random = Generator(MT19937(self.seed))
arr = np.arange(10)
assert_raises(AxisError, random.permutation, arr, 1)
arr = np.arange(9).reshape((3, 3))
assert_raises(AxisError, random.permutation, arr, 3)
assert_raises(TypeError, random.permutation, arr, slice(1, 2, None))
@pytest.mark.parametrize("dtype", [int, object])
@pytest.mark.parametrize("axis, expected",
[(None, np.array([[3, 7, 0, 9, 10, 11],
[8, 4, 2, 5, 1, 6]])),
(0, np.array([[6, 1, 2, 9, 10, 11],
[0, 7, 8, 3, 4, 5]])),
(1, np.array([[ 5, 3, 4, 0, 2, 1],
[11, 9, 10, 6, 8, 7]]))])
def test_permuted(self, dtype, axis, expected):
random = Generator(MT19937(self.seed))
x = np.arange(12).reshape(2, 6).astype(dtype)
random.permuted(x, axis=axis, out=x)
assert_array_equal(x, expected)
random = Generator(MT19937(self.seed))
x = np.arange(12).reshape(2, 6).astype(dtype)
y = random.permuted(x, axis=axis)
assert y.dtype == dtype
assert_array_equal(y, expected)
def test_permuted_with_strides(self):
random = Generator(MT19937(self.seed))
x0 = np.arange(22).reshape(2, 11)
x1 = x0.copy()
x = x0[:, ::3]
y = random.permuted(x, axis=1, out=x)
expected = np.array([[0, 9, 3, 6],
[14, 20, 11, 17]])
assert_array_equal(y, expected)
x1[:, ::3] = expected
# Verify that the original x0 was modified in-place as expected.
assert_array_equal(x1, x0)
def test_permuted_empty(self):
y = random.permuted([])
assert_array_equal(y, [])
@pytest.mark.parametrize('outshape', [(2, 3), 5])
def test_permuted_out_with_wrong_shape(self, outshape):
a = np.array([1, 2, 3])
out = np.zeros(outshape, dtype=a.dtype)
with pytest.raises(ValueError, match='same shape'):
random.permuted(a, out=out)
def test_permuted_out_with_wrong_type(self):
out = np.zeros((3, 5), dtype=np.int32)
x = np.ones((3, 5))
with pytest.raises(TypeError, match='Cannot cast'):
random.permuted(x, axis=1, out=out)
def test_permuted_not_writeable(self):
x = np.zeros((2, 5))
x.flags.writeable = False
with pytest.raises(ValueError, match='read-only'):
random.permuted(x, axis=1, out=x)
def test_beta(self):
random = Generator(MT19937(self.seed))
actual = random.beta(.1, .9, size=(3, 2))
desired = np.array(
[[1.083029353267698e-10, 2.449965303168024e-11],
[2.397085162969853e-02, 3.590779671820755e-08],
[2.830254190078299e-04, 1.744709918330393e-01]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_binomial(self):
random = Generator(MT19937(self.seed))
actual = random.binomial(100.123, .456, size=(3, 2))
desired = np.array([[42, 41],
[42, 48],
[44, 50]])
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
actual = random.binomial(100.123, .456)
desired = 42
assert_array_equal(actual, desired)
def test_chisquare(self):
random = Generator(MT19937(self.seed))
actual = random.chisquare(50, size=(3, 2))
desired = np.array([[32.9850547060149, 39.0219480493301],
[56.2006134779419, 57.3474165711485],
[55.4243733880198, 55.4209797925213]])
assert_array_almost_equal(actual, desired, decimal=13)
def test_dirichlet(self):
random = Generator(MT19937(self.seed))
alpha = np.array([51.72840233779265162, 39.74494232180943953])
actual = random.dirichlet(alpha, size=(3, 2))
desired = np.array([[[0.5439892869558927, 0.45601071304410745],
[0.5588917345860708, 0.4411082654139292 ]], # noqa: E202
[[0.5632074165063435, 0.43679258349365657],
[0.54862581112627, 0.45137418887373015]],
[[0.49961831357047226, 0.5003816864295278 ], # noqa: E202
[0.52374806183482, 0.47625193816517997]]])
assert_array_almost_equal(actual, desired, decimal=15)
bad_alpha = np.array([5.4e-01, -1.0e-16])
assert_raises(ValueError, random.dirichlet, bad_alpha)
random = Generator(MT19937(self.seed))
alpha = np.array([51.72840233779265162, 39.74494232180943953])
actual = random.dirichlet(alpha)
assert_array_almost_equal(actual, desired[0, 0], decimal=15)
def test_dirichlet_size(self):
# gh-3173
p = np.array([51.72840233779265162, 39.74494232180943953])
assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2))
assert_equal(random.dirichlet(p, [2, 2]).shape, (2, 2, 2))
assert_equal(random.dirichlet(p, (2, 2)).shape, (2, 2, 2))
assert_equal(random.dirichlet(p, np.array((2, 2))).shape, (2, 2, 2))
assert_raises(TypeError, random.dirichlet, p, float(1))
def test_dirichlet_bad_alpha(self):
# gh-2089
alpha = np.array([5.4e-01, -1.0e-16])
assert_raises(ValueError, random.dirichlet, alpha)
# gh-15876
assert_raises(ValueError, random.dirichlet, [[5, 1]])
assert_raises(ValueError, random.dirichlet, [[5], [1]])
assert_raises(ValueError, random.dirichlet, [[[5], [1]], [[1], [5]]])
assert_raises(ValueError, random.dirichlet, np.array([[5, 1], [1, 5]]))
def test_dirichlet_alpha_non_contiguous(self):
a = np.array([51.72840233779265162, -1.0, 39.74494232180943953])
alpha = a[::2]
random = Generator(MT19937(self.seed))
non_contig = random.dirichlet(alpha, size=(3, 2))
random = Generator(MT19937(self.seed))
contig = random.dirichlet(np.ascontiguousarray(alpha),
size=(3, 2))
assert_array_almost_equal(non_contig, contig)
def test_dirichlet_small_alpha(self):
eps = 1.0e-9 # 1.0e-10 -> runtime x 10; 1e-11 -> runtime x 200, etc.
alpha = eps * np.array([1., 1.0e-3])
random = Generator(MT19937(self.seed))
actual = random.dirichlet(alpha, size=(3, 2))
expected = np.array([
[[1., 0.],
[1., 0.]],
[[1., 0.],
[1., 0.]],
[[1., 0.],
[1., 0.]]
])
assert_array_almost_equal(actual, expected, decimal=15)
@pytest.mark.slow
@pytest.mark.thread_unsafe(reason="crashes with low memory")
def test_dirichlet_moderately_small_alpha(self):
# Use alpha.max() < 0.1 to trigger stick breaking code path
alpha = np.array([0.02, 0.04, 0.03])
exact_mean = alpha / alpha.sum()
random = Generator(MT19937(self.seed))
sample = random.dirichlet(alpha, size=20000000)
sample_mean = sample.mean(axis=0)
assert_allclose(sample_mean, exact_mean, rtol=1e-3)
# This set of parameters includes inputs with alpha.max() >= 0.1 and
# alpha.max() < 0.1 to exercise both generation methods within the
# dirichlet code.
@pytest.mark.parametrize(
'alpha',
[[5, 9, 0, 8],
[0.5, 0, 0, 0],
[1, 5, 0, 0, 1.5, 0, 0, 0],
[0.01, 0.03, 0, 0.005],
[1e-5, 0, 0, 0],
[0.002, 0.015, 0, 0, 0.04, 0, 0, 0],
[0.0],
[0, 0, 0]],
)
def test_dirichlet_multiple_zeros_in_alpha(self, alpha):
alpha = np.array(alpha)
y = random.dirichlet(alpha)
assert_equal(y[alpha == 0], 0.0)
def test_exponential(self):
random = Generator(MT19937(self.seed))
actual = random.exponential(1.1234, size=(3, 2))
desired = np.array([[0.098845481066258, 1.560752510746964],
[0.075730916041636, 1.769098974710777],
[1.488602544592235, 2.49684815275751 ]]) # noqa: E202
assert_array_almost_equal(actual, desired, decimal=15)
def test_exponential_0(self):
assert_equal(random.exponential(scale=0), 0)
assert_raises(ValueError, random.exponential, scale=-0.)
def test_f(self):
random = Generator(MT19937(self.seed))
actual = random.f(12, 77, size=(3, 2))
desired = np.array([[0.461720027077085, 1.100441958872451],
[1.100337455217484, 0.91421736740018 ], # noqa: E202
[0.500811891303113, 0.826802454552058]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_gamma(self):
random = Generator(MT19937(self.seed))
actual = random.gamma(5, 3, size=(3, 2))
desired = np.array([[ 5.03850858902096, 7.9228656732049 ], # noqa: E202
[18.73983605132985, 19.57961681699238],
[18.17897755150825, 18.17653912505234]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_gamma_0(self):
assert_equal(random.gamma(shape=0, scale=0), 0)
assert_raises(ValueError, random.gamma, shape=-0., scale=-0.)
def test_geometric(self):
random = Generator(MT19937(self.seed))
actual = random.geometric(.123456789, size=(3, 2))
desired = np.array([[1, 11],
[1, 12],
[11, 17]])
assert_array_equal(actual, desired)
def test_geometric_exceptions(self):
assert_raises(ValueError, random.geometric, 1.1)
assert_raises(ValueError, random.geometric, [1.1] * 10)
assert_raises(ValueError, random.geometric, -0.1)
assert_raises(ValueError, random.geometric, [-0.1] * 10)
with np.errstate(invalid='ignore'):
assert_raises(ValueError, random.geometric, np.nan)
assert_raises(ValueError, random.geometric, [np.nan] * 10)
def test_gumbel(self):
random = Generator(MT19937(self.seed))
actual = random.gumbel(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[ 4.688397515056245, -0.289514845417841],
[ 4.981176042584683, -0.633224272589149],
[-0.055915275687488, -0.333962478257953]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_gumbel_0(self):
assert_equal(random.gumbel(scale=0), 0)
assert_raises(ValueError, random.gumbel, scale=-0.)
def test_hypergeometric(self):
random = Generator(MT19937(self.seed))
actual = random.hypergeometric(10.1, 5.5, 14, size=(3, 2))
desired = np.array([[ 9, 9],
[ 9, 9],
[10, 9]])
assert_array_equal(actual, desired)
# Test nbad = 0
actual = random.hypergeometric(5, 0, 3, size=4)
desired = np.array([3, 3, 3, 3])
assert_array_equal(actual, desired)
actual = random.hypergeometric(15, 0, 12, size=4)
desired = np.array([12, 12, 12, 12])
assert_array_equal(actual, desired)
# Test ngood = 0
actual = random.hypergeometric(0, 5, 3, size=4)
desired = np.array([0, 0, 0, 0])
assert_array_equal(actual, desired)
actual = random.hypergeometric(0, 15, 12, size=4)
desired = np.array([0, 0, 0, 0])
assert_array_equal(actual, desired)
def test_laplace(self):
random = Generator(MT19937(self.seed))
actual = random.laplace(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[-3.156353949272393, 1.195863024830054],
[-3.435458081645966, 1.656882398925444],
[ 0.924824032467446, 1.251116432209336]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_laplace_0(self):
assert_equal(random.laplace(scale=0), 0)
assert_raises(ValueError, random.laplace, scale=-0.)
def test_logistic(self):
random = Generator(MT19937(self.seed))
actual = random.logistic(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[-4.338584631510999, 1.890171436749954],
[-4.64547787337966 , 2.514545562919217], # noqa: E203
[ 1.495389489198666, 1.967827627577474]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_lognormal(self):
random = Generator(MT19937(self.seed))
actual = random.lognormal(mean=.123456789, sigma=2.0, size=(3, 2))
desired = np.array([[ 0.0268252166335, 13.9534486483053],
[ 0.1204014788936, 2.2422077497792],
[ 4.2484199496128, 12.0093343977523]])
assert_array_almost_equal(actual, desired, decimal=13)
def test_lognormal_0(self):
assert_equal(random.lognormal(sigma=0), 1)
assert_raises(ValueError, random.lognormal, sigma=-0.)
def test_logseries(self):
random = Generator(MT19937(self.seed))
actual = random.logseries(p=.923456789, size=(3, 2))
desired = np.array([[14, 17],
[3, 18],
[5, 1]])
assert_array_equal(actual, desired)
def test_logseries_zero(self):
random = Generator(MT19937(self.seed))
assert random.logseries(0) == 1
@pytest.mark.parametrize("value", [np.nextafter(0., -1), 1., np.nan, 5.])
def test_logseries_exceptions(self, value):
random = Generator(MT19937(self.seed))
with np.errstate(invalid="ignore"):
with pytest.raises(ValueError):
random.logseries(value)
with pytest.raises(ValueError):
# contiguous path:
random.logseries(np.array([value] * 10))
with pytest.raises(ValueError):
# non-contiguous path:
random.logseries(np.array([value] * 10)[::2])
def test_multinomial(self):
random = Generator(MT19937(self.seed))
actual = random.multinomial(20, [1 / 6.] * 6, size=(3, 2))
desired = np.array([[[1, 5, 1, 6, 4, 3],
[4, 2, 6, 2, 4, 2]],
[[5, 3, 2, 6, 3, 1],
[4, 4, 0, 2, 3, 7]],
[[6, 3, 1, 5, 3, 2],
[5, 5, 3, 1, 2, 4]]])
assert_array_equal(actual, desired)
@pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
@pytest.mark.parametrize("method", ["svd", "eigh", "cholesky"])
def test_multivariate_normal(self, method):
random = Generator(MT19937(self.seed))
mean = (.123456789, 10)
cov = [[1, 0], [0, 1]]
size = (3, 2)
actual = random.multivariate_normal(mean, cov, size, method=method)
desired = np.array([[[-1.747478062846581, 11.25613495182354 ], # noqa: E202
[-0.9967333370066214, 10.342002097029821]],
[[ 0.7850019631242964, 11.181113712443013],
[ 0.8901349653255224, 8.873825399642492]],
[[ 0.7130260107430003, 9.551628690083056],
[ 0.7127098726541128, 11.991709234143173]]])
assert_array_almost_equal(actual, desired, decimal=15)
# Check for default size, was raising deprecation warning
actual = random.multivariate_normal(mean, cov, method=method)
desired = np.array([0.233278563284287, 9.424140804347195])
assert_array_almost_equal(actual, desired, decimal=15)
# Check that non symmetric covariance input raises exception when
# check_valid='raises' if using default svd method.
mean = [0, 0]
cov = [[1, 2], [1, 2]]
assert_raises(ValueError, random.multivariate_normal, mean, cov,
check_valid='raise')
# Check that non positive-semidefinite covariance warns with
# RuntimeWarning
cov = [[1, 2], [2, 1]]
pytest.warns(RuntimeWarning, random.multivariate_normal, mean, cov)
pytest.warns(RuntimeWarning, random.multivariate_normal, mean, cov,
method='eigh')
assert_raises(LinAlgError, random.multivariate_normal, mean, cov,
method='cholesky')
# and that it doesn't warn with RuntimeWarning check_valid='ignore'
assert_no_warnings(random.multivariate_normal, mean, cov,
check_valid='ignore')
# and that it raises with RuntimeWarning check_valid='raises'
assert_raises(ValueError, random.multivariate_normal, mean, cov,
check_valid='raise')
assert_raises(ValueError, random.multivariate_normal, mean, cov,
check_valid='raise', method='eigh')
# check degenerate samples from singular covariance matrix
cov = [[1, 1], [1, 1]]
if method in ('svd', 'eigh'):
samples = random.multivariate_normal(mean, cov, size=(3, 2),
method=method)
assert_array_almost_equal(samples[..., 0], samples[..., 1],
decimal=6)
else:
assert_raises(LinAlgError, random.multivariate_normal, mean, cov,
method='cholesky')
cov = np.array([[1, 0.1], [0.1, 1]], dtype=np.float32)
with warnings.catch_warnings():
warnings.simplefilter("error")
random.multivariate_normal(mean, cov, method=method)
mu = np.zeros(2)
cov = np.eye(2)
assert_raises(ValueError, random.multivariate_normal, mean, cov,
check_valid='other')
assert_raises(ValueError, random.multivariate_normal,
np.zeros((2, 1, 1)), cov)
assert_raises(ValueError, random.multivariate_normal,
mu, np.empty((3, 2)))
assert_raises(ValueError, random.multivariate_normal,
mu, np.eye(3))
@pytest.mark.parametrize('mean, cov', [([0], [[1 + 1j]]), ([0j], [[1]])])
def test_multivariate_normal_disallow_complex(self, mean, cov):
random = Generator(MT19937(self.seed))
with pytest.raises(TypeError, match="must not be complex"):
random.multivariate_normal(mean, cov)
@pytest.mark.parametrize("method", ["svd", "eigh", "cholesky"])
def test_multivariate_normal_basic_stats(self, method):
random = Generator(MT19937(self.seed))
n_s = 1000
mean = np.array([1, 2])
cov = np.array([[2, 1], [1, 2]])
s = random.multivariate_normal(mean, cov, size=(n_s,), method=method)
s_center = s - mean
cov_emp = (s_center.T @ s_center) / (n_s - 1)
# these are pretty loose and are only designed to detect major errors
assert np.all(np.abs(s_center.mean(-2)) < 0.1)
assert np.all(np.abs(cov_emp - cov) < 0.2)
def test_negative_binomial(self):
random = Generator(MT19937(self.seed))
actual = random.negative_binomial(n=100, p=.12345, size=(3, 2))
desired = np.array([[543, 727],
[775, 760],
[600, 674]])
assert_array_equal(actual, desired)
def test_negative_binomial_exceptions(self):
with np.errstate(invalid='ignore'):
assert_raises(ValueError, random.negative_binomial, 100, np.nan)
assert_raises(ValueError, random.negative_binomial, 100,
[np.nan] * 10)
def test_negative_binomial_p0_exception(self):
# Verify that p=0 raises an exception.
with assert_raises(ValueError):
x = random.negative_binomial(1, 0)
def test_negative_binomial_invalid_p_n_combination(self):
# Verify that values of p and n that would result in an overflow
# or infinite loop raise an exception.
with np.errstate(invalid='ignore'):
assert_raises(ValueError, random.negative_binomial, 2**62, 0.1)
assert_raises(ValueError, random.negative_binomial, [2**62], [0.1])
def test_noncentral_chisquare(self):
random = Generator(MT19937(self.seed))
actual = random.noncentral_chisquare(df=5, nonc=5, size=(3, 2))
desired = np.array([[ 1.70561552362133, 15.97378184942111],
[13.71483425173724, 20.17859633310629],
[11.3615477156643 , 3.67891108738029]]) # noqa: E203
assert_array_almost_equal(actual, desired, decimal=14)
actual = random.noncentral_chisquare(df=.5, nonc=.2, size=(3, 2))
desired = np.array([[9.41427665607629e-04, 1.70473157518850e-04],
[1.14554372041263e+00, 1.38187755933435e-03],
[1.90659181905387e+00, 1.21772577941822e+00]])
assert_array_almost_equal(actual, desired, decimal=14)
random = Generator(MT19937(self.seed))
actual = random.noncentral_chisquare(df=5, nonc=0, size=(3, 2))
desired = np.array([[0.82947954590419, 1.80139670767078],
[6.58720057417794, 7.00491463609814],
[6.31101879073157, 6.30982307753005]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_noncentral_f(self):
random = Generator(MT19937(self.seed))
actual = random.noncentral_f(dfnum=5, dfden=2, nonc=1,
size=(3, 2))
desired = np.array([[0.060310671139 , 0.23866058175939], # noqa: E203
[0.86860246709073, 0.2668510459738 ], # noqa: E202
[0.23375780078364, 1.88922102885943]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_noncentral_f_nan(self):
random = Generator(MT19937(self.seed))
actual = random.noncentral_f(dfnum=5, dfden=2, nonc=np.nan)
assert np.isnan(actual)
def test_normal(self):
random = Generator(MT19937(self.seed))
actual = random.normal(loc=.123456789, scale=2.0, size=(3, 2))
desired = np.array([[-3.618412914693162, 2.635726692647081],
[-2.116923463013243, 0.807460983059643],
[ 1.446547137248593, 2.485684213886024]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_normal_0(self):
assert_equal(random.normal(scale=0), 0)
assert_raises(ValueError, random.normal, scale=-0.)
def test_pareto(self):
random = Generator(MT19937(self.seed))
actual = random.pareto(a=.123456789, size=(3, 2))
desired = np.array([[1.0394926776069018e+00, 7.7142534343505773e+04],
[7.2640150889064703e-01, 3.4650454783825594e+05],
[4.5852344481994740e+04, 6.5851383009539105e+07]])
# For some reason on 32-bit x86 Ubuntu 12.10 the [1, 0] entry in this
# matrix differs by 24 nulps. Discussion:
# https://mail.python.org/pipermail/numpy-discussion/2012-September/063801.html
# Consensus is that this is probably some gcc quirk that affects
# rounding but not in any important way, so we just use a looser
# tolerance on this test:
np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=30)
def test_poisson(self):
random = Generator(MT19937(self.seed))
actual = random.poisson(lam=.123456789, size=(3, 2))
desired = np.array([[0, 0],
[0, 0],
[0, 0]])
assert_array_equal(actual, desired)
def test_poisson_exceptions(self):
lambig = np.iinfo('int64').max
lamneg = -1
assert_raises(ValueError, random.poisson, lamneg)
assert_raises(ValueError, random.poisson, [lamneg] * 10)
assert_raises(ValueError, random.poisson, lambig)
assert_raises(ValueError, random.poisson, [lambig] * 10)
with np.errstate(invalid='ignore'):
assert_raises(ValueError, random.poisson, np.nan)
assert_raises(ValueError, random.poisson, [np.nan] * 10)
def test_power(self):
random = Generator(MT19937(self.seed))
actual = random.power(a=.123456789, size=(3, 2))
desired = np.array([[1.977857368842754e-09, 9.806792196620341e-02],
[2.482442984543471e-10, 1.527108843266079e-01],
[8.188283434244285e-02, 3.950547209346948e-01]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_rayleigh(self):
random = Generator(MT19937(self.seed))
actual = random.rayleigh(scale=10, size=(3, 2))
desired = np.array([[4.19494429102666, 16.66920198906598],
[3.67184544902662, 17.74695521962917],
[16.27935397855501, 21.08355560691792]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_rayleigh_0(self):
assert_equal(random.rayleigh(scale=0), 0)
assert_raises(ValueError, random.rayleigh, scale=-0.)
def test_standard_cauchy(self):
random = Generator(MT19937(self.seed))
actual = random.standard_cauchy(size=(3, 2))
desired = np.array([[-1.489437778266206, -3.275389641569784],
[ 0.560102864910406, -0.680780916282552],
[-1.314912905226277, 0.295852965660225]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_exponential(self):
random = Generator(MT19937(self.seed))
actual = random.standard_exponential(size=(3, 2), method='inv')
desired = np.array([[0.102031839440643, 1.229350298474972],
[0.088137284693098, 1.459859985522667],
[1.093830802293668, 1.256977002164613]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_expoential_type_error(self):
assert_raises(TypeError, random.standard_exponential, dtype=np.int32)
def test_standard_gamma(self):
random = Generator(MT19937(self.seed))
actual = random.standard_gamma(shape=3, size=(3, 2))
desired = np.array([[0.62970724056362, 1.22379851271008],
[3.899412530884 , 4.12479964250139], # noqa: E203
[3.74994102464584, 3.74929307690815]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_standard_gammma_scalar_float(self):
random = Generator(MT19937(self.seed))
actual = random.standard_gamma(3, dtype=np.float32)
desired = 2.9242148399353027
assert_array_almost_equal(actual, desired, decimal=6)
def test_standard_gamma_float(self):
random = Generator(MT19937(self.seed))
actual = random.standard_gamma(shape=3, size=(3, 2))
desired = np.array([[0.62971, 1.2238],
[3.89941, 4.1248],
[3.74994, 3.74929]])
assert_array_almost_equal(actual, desired, decimal=5)
def test_standard_gammma_float_out(self):
actual = np.zeros((3, 2), dtype=np.float32)
random = Generator(MT19937(self.seed))
random.standard_gamma(10.0, out=actual, dtype=np.float32)
desired = np.array([[10.14987, 7.87012],
[ 9.46284, 12.56832],
[13.82495, 7.81533]], dtype=np.float32)
assert_array_almost_equal(actual, desired, decimal=5)
random = Generator(MT19937(self.seed))
random.standard_gamma(10.0, out=actual, size=(3, 2), dtype=np.float32)
assert_array_almost_equal(actual, desired, decimal=5)
def test_standard_gamma_unknown_type(self):
assert_raises(TypeError, random.standard_gamma, 1.,
dtype='int32')
def test_out_size_mismatch(self):
out = np.zeros(10)
assert_raises(ValueError, random.standard_gamma, 10.0, size=20,
out=out)
assert_raises(ValueError, random.standard_gamma, 10.0, size=(10, 1),
out=out)
def test_standard_gamma_0(self):
assert_equal(random.standard_gamma(shape=0), 0)
assert_raises(ValueError, random.standard_gamma, shape=-0.)
def test_standard_normal(self):
random = Generator(MT19937(self.seed))
actual = random.standard_normal(size=(3, 2))
desired = np.array([[-1.870934851846581, 1.25613495182354 ], # noqa: E202
[-1.120190126006621, 0.342002097029821],
[ 0.661545174124296, 1.181113712443012]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_standard_normal_unsupported_type(self):
assert_raises(TypeError, random.standard_normal, dtype=np.int32)
def test_standard_t(self):
random = Generator(MT19937(self.seed))
actual = random.standard_t(df=10, size=(3, 2))
desired = np.array([[-1.484666193042647, 0.30597891831161],
[ 1.056684299648085, -0.407312602088507],
[ 0.130704414281157, -2.038053410490321]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_triangular(self):
random = Generator(MT19937(self.seed))
actual = random.triangular(left=5.12, mode=10.23, right=20.34,
size=(3, 2))
desired = np.array([[ 7.86664070590917, 13.6313848513185 ], # noqa: E202
[ 7.68152445215983, 14.36169131136546],
[13.16105603911429, 13.72341621856971]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_uniform(self):
random = Generator(MT19937(self.seed))
actual = random.uniform(low=1.23, high=10.54, size=(3, 2))
desired = np.array([[2.13306255040998 , 7.816987531021207], # noqa: E203
[2.015436610109887, 8.377577533009589],
[7.421792588856135, 7.891185744455209]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_uniform_range_bounds(self):
fmin = np.finfo('float').min
fmax = np.finfo('float').max
func = random.uniform
assert_raises(OverflowError, func, -np.inf, 0)
assert_raises(OverflowError, func, 0, np.inf)
assert_raises(OverflowError, func, fmin, fmax)
assert_raises(OverflowError, func, [-np.inf], [0])
assert_raises(OverflowError, func, [0], [np.inf])
# (fmax / 1e17) - fmin is within range, so this should not throw
# account for i386 extended precision DBL_MAX / 1e17 + DBL_MAX >
# DBL_MAX by increasing fmin a bit
random.uniform(low=np.nextafter(fmin, 1), high=fmax / 1e17)
def test_uniform_zero_range(self):
func = random.uniform
result = func(1.5, 1.5)
assert_allclose(result, 1.5)
result = func([0.0, np.pi], [0.0, np.pi])
assert_allclose(result, [0.0, np.pi])
result = func([[2145.12], [2145.12]], [2145.12, 2145.12])
assert_allclose(result, 2145.12 + np.zeros((2, 2)))
def test_uniform_neg_range(self):
func = random.uniform
assert_raises(ValueError, func, 2, 1)
assert_raises(ValueError, func, [1, 2], [1, 1])
assert_raises(ValueError, func, [[0, 1], [2, 3]], 2)
def test_scalar_exception_propagation(self):
# Tests that exceptions are correctly propagated in distributions
# when called with objects that throw exceptions when converted to
# scalars.
#
# Regression test for gh: 8865
class ThrowingFloat(np.ndarray):
def __float__(self):
raise TypeError
throwing_float = np.array(1.0).view(ThrowingFloat)
assert_raises(TypeError, random.uniform, throwing_float,
throwing_float)
class ThrowingInteger(np.ndarray):
def __int__(self):
raise TypeError
throwing_int = np.array(1).view(ThrowingInteger)
assert_raises(TypeError, random.hypergeometric, throwing_int, 1, 1)
def test_vonmises(self):
random = Generator(MT19937(self.seed))
actual = random.vonmises(mu=1.23, kappa=1.54, size=(3, 2))
desired = np.array([[ 1.107972248690106, 2.841536476232361],
[ 1.832602376042457, 1.945511926976032],
[-0.260147475776542, 2.058047492231698]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_vonmises_small(self):
# check infinite loop, gh-4720
random = Generator(MT19937(self.seed))
r = random.vonmises(mu=0., kappa=1.1e-8, size=10**6)
assert_(np.isfinite(r).all())
def test_vonmises_nan(self):
random = Generator(MT19937(self.seed))
r = random.vonmises(mu=0., kappa=np.nan)
assert_(np.isnan(r))
@pytest.mark.parametrize("kappa", [1e4, 1e15])
def test_vonmises_large_kappa(self, kappa):
random = Generator(MT19937(self.seed))
rs = RandomState(random.bit_generator)
state = random.bit_generator.state
random_state_vals = rs.vonmises(0, kappa, size=10)
random.bit_generator.state = state
gen_vals = random.vonmises(0, kappa, size=10)
if kappa < 1e6:
assert_allclose(random_state_vals, gen_vals)
else:
assert np.all(random_state_vals != gen_vals)
@pytest.mark.parametrize("mu", [-7., -np.pi, -3.1, np.pi, 3.2])
@pytest.mark.parametrize("kappa", [1e-9, 1e-6, 1, 1e3, 1e15])
def test_vonmises_large_kappa_range(self, mu, kappa):
random = Generator(MT19937(self.seed))
r = random.vonmises(mu, kappa, 50)
assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
def test_wald(self):
random = Generator(MT19937(self.seed))
actual = random.wald(mean=1.23, scale=1.54, size=(3, 2))
desired = np.array([[0.26871721804551, 3.2233942732115 ], # noqa: E202
[2.20328374987066, 2.40958405189353],
[2.07093587449261, 0.73073890064369]])
assert_array_almost_equal(actual, desired, decimal=14)
def test_wald_nonnegative(self):
random = Generator(MT19937(self.seed))
samples = random.wald(mean=1e9, scale=2.25, size=1000)
assert_(np.all(samples >= 0.0))
def test_weibull(self):
random = Generator(MT19937(self.seed))
actual = random.weibull(a=1.23, size=(3, 2))
desired = np.array([[0.138613914769468, 1.306463419753191],
[0.111623365934763, 1.446570494646721],
[1.257145775276011, 1.914247725027957]])
assert_array_almost_equal(actual, desired, decimal=15)
def test_weibull_0(self):
random = Generator(MT19937(self.seed))
assert_equal(random.weibull(a=0, size=12), np.zeros(12))
assert_raises(ValueError, random.weibull, a=-0.)
def test_zipf(self):
random = Generator(MT19937(self.seed))
actual = random.zipf(a=1.23, size=(3, 2))
desired = np.array([[ 1, 1],
[ 10, 867],
[354, 2]])
assert_array_equal(actual, desired)
class TestBroadcast:
# tests that functions that broadcast behave
# correctly when presented with non-scalar arguments
seed = 123456789
def test_uniform(self):
random = Generator(MT19937(self.seed))
low = [0]
high = [1]
uniform = random.uniform
desired = np.array([0.16693771389729, 0.19635129550675, 0.75563050964095])
random = Generator(MT19937(self.seed))
actual = random.uniform(low * 3, high)
assert_array_almost_equal(actual, desired, decimal=14)
random = Generator(MT19937(self.seed))
actual = random.uniform(low, high * 3)
assert_array_almost_equal(actual, desired, decimal=14)
def test_normal(self):
loc = [0]
scale = [1]
bad_scale = [-1]
random = Generator(MT19937(self.seed))
desired = np.array([-0.38736406738527, 0.79594375042255, 0.0197076236097])
random = Generator(MT19937(self.seed))
actual = random.normal(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.normal, loc * 3, bad_scale)
random = Generator(MT19937(self.seed))
normal = random.normal
actual = normal(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, normal, loc, bad_scale * 3)
def test_beta(self):
a = [1]
b = [2]
bad_a = [-1]
bad_b = [-2]
desired = np.array([0.18719338682602, 0.73234824491364, 0.17928615186455])
random = Generator(MT19937(self.seed))
beta = random.beta
actual = beta(a * 3, b)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, beta, bad_a * 3, b)
assert_raises(ValueError, beta, a * 3, bad_b)
random = Generator(MT19937(self.seed))
actual = random.beta(a, b * 3)
assert_array_almost_equal(actual, desired, decimal=14)
def test_exponential(self):
scale = [1]
bad_scale = [-1]
desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
random = Generator(MT19937(self.seed))
actual = random.exponential(scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.exponential, bad_scale * 3)
def test_standard_gamma(self):
shape = [1]
bad_shape = [-1]
desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
random = Generator(MT19937(self.seed))
std_gamma = random.standard_gamma
actual = std_gamma(shape * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, std_gamma, bad_shape * 3)
def test_gamma(self):
shape = [1]
scale = [2]
bad_shape = [-1]
bad_scale = [-2]
desired = np.array([1.34491986425611, 0.42760990636187, 1.4355697857258])
random = Generator(MT19937(self.seed))
gamma = random.gamma
actual = gamma(shape * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, gamma, bad_shape * 3, scale)
assert_raises(ValueError, gamma, shape * 3, bad_scale)
random = Generator(MT19937(self.seed))
gamma = random.gamma
actual = gamma(shape, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, gamma, bad_shape, scale * 3)
assert_raises(ValueError, gamma, shape, bad_scale * 3)
def test_f(self):
dfnum = [1]
dfden = [2]
bad_dfnum = [-1]
bad_dfden = [-2]
desired = np.array([0.07765056244107, 7.72951397913186, 0.05786093891763])
random = Generator(MT19937(self.seed))
f = random.f
actual = f(dfnum * 3, dfden)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, f, bad_dfnum * 3, dfden)
assert_raises(ValueError, f, dfnum * 3, bad_dfden)
random = Generator(MT19937(self.seed))
f = random.f
actual = f(dfnum, dfden * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, f, bad_dfnum, dfden * 3)
assert_raises(ValueError, f, dfnum, bad_dfden * 3)
def test_noncentral_f(self):
dfnum = [2]
dfden = [3]
nonc = [4]
bad_dfnum = [0]
bad_dfden = [-1]
bad_nonc = [-2]
desired = np.array([2.02434240411421, 12.91838601070124, 1.24395160354629])
random = Generator(MT19937(self.seed))
nonc_f = random.noncentral_f
actual = nonc_f(dfnum * 3, dfden, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert np.all(np.isnan(nonc_f(dfnum, dfden, [np.nan] * 3)))
assert_raises(ValueError, nonc_f, bad_dfnum * 3, dfden, nonc)
assert_raises(ValueError, nonc_f, dfnum * 3, bad_dfden, nonc)
assert_raises(ValueError, nonc_f, dfnum * 3, dfden, bad_nonc)
random = Generator(MT19937(self.seed))
nonc_f = random.noncentral_f
actual = nonc_f(dfnum, dfden * 3, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, nonc_f, bad_dfnum, dfden * 3, nonc)
assert_raises(ValueError, nonc_f, dfnum, bad_dfden * 3, nonc)
assert_raises(ValueError, nonc_f, dfnum, dfden * 3, bad_nonc)
random = Generator(MT19937(self.seed))
nonc_f = random.noncentral_f
actual = nonc_f(dfnum, dfden, nonc * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, nonc_f, bad_dfnum, dfden, nonc * 3)
assert_raises(ValueError, nonc_f, dfnum, bad_dfden, nonc * 3)
assert_raises(ValueError, nonc_f, dfnum, dfden, bad_nonc * 3)
def test_noncentral_f_small_df(self):
random = Generator(MT19937(self.seed))
desired = np.array([0.04714867120827, 0.1239390327694])
actual = random.noncentral_f(0.9, 0.9, 2, size=2)
assert_array_almost_equal(actual, desired, decimal=14)
def test_chisquare(self):
df = [1]
bad_df = [-1]
desired = np.array([0.05573640064251, 1.47220224353539, 2.9469379318589])
random = Generator(MT19937(self.seed))
actual = random.chisquare(df * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.chisquare, bad_df * 3)
def test_noncentral_chisquare(self):
df = [1]
nonc = [2]
bad_df = [-1]
bad_nonc = [-2]
desired = np.array([0.07710766249436, 5.27829115110304, 0.630732147399])
random = Generator(MT19937(self.seed))
nonc_chi = random.noncentral_chisquare
actual = nonc_chi(df * 3, nonc)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, nonc_chi, bad_df * 3, nonc)
assert_raises(ValueError, nonc_chi, df * 3, bad_nonc)
random = Generator(MT19937(self.seed))
nonc_chi = random.noncentral_chisquare
actual = nonc_chi(df, nonc * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, nonc_chi, bad_df, nonc * 3)
assert_raises(ValueError, nonc_chi, df, bad_nonc * 3)
def test_standard_t(self):
df = [1]
bad_df = [-1]
desired = np.array([-1.39498829447098, -1.23058658835223, 0.17207021065983])
random = Generator(MT19937(self.seed))
actual = random.standard_t(df * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.standard_t, bad_df * 3)
def test_vonmises(self):
mu = [2]
kappa = [1]
bad_kappa = [-1]
desired = np.array([2.25935584988528, 2.23326261461399, -2.84152146503326])
random = Generator(MT19937(self.seed))
actual = random.vonmises(mu * 3, kappa)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.vonmises, mu * 3, bad_kappa)
random = Generator(MT19937(self.seed))
actual = random.vonmises(mu, kappa * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.vonmises, mu, bad_kappa * 3)
def test_pareto(self):
a = [1]
bad_a = [-1]
desired = np.array([0.95905052946317, 0.2383810889437, 1.04988745750013])
random = Generator(MT19937(self.seed))
actual = random.pareto(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.pareto, bad_a * 3)
def test_weibull(self):
a = [1]
bad_a = [-1]
desired = np.array([0.67245993212806, 0.21380495318094, 0.7177848928629])
random = Generator(MT19937(self.seed))
actual = random.weibull(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.weibull, bad_a * 3)
def test_power(self):
a = [1]
bad_a = [-1]
desired = np.array([0.48954864361052, 0.19249412888486, 0.51216834058807])
random = Generator(MT19937(self.seed))
actual = random.power(a * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.power, bad_a * 3)
def test_laplace(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([-1.09698732625119, -0.93470271947368, 0.71592671378202])
random = Generator(MT19937(self.seed))
laplace = random.laplace
actual = laplace(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, laplace, loc * 3, bad_scale)
random = Generator(MT19937(self.seed))
laplace = random.laplace
actual = laplace(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, laplace, loc, bad_scale * 3)
def test_gumbel(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([1.70020068231762, 1.52054354273631, -0.34293267607081])
random = Generator(MT19937(self.seed))
gumbel = random.gumbel
actual = gumbel(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, gumbel, loc * 3, bad_scale)
random = Generator(MT19937(self.seed))
gumbel = random.gumbel
actual = gumbel(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, gumbel, loc, bad_scale * 3)
def test_logistic(self):
loc = [0]
scale = [1]
bad_scale = [-1]
desired = np.array([-1.607487640433, -1.40925686003678, 1.12887112820397])
random = Generator(MT19937(self.seed))
actual = random.logistic(loc * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.logistic, loc * 3, bad_scale)
random = Generator(MT19937(self.seed))
actual = random.logistic(loc, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.logistic, loc, bad_scale * 3)
assert_equal(random.logistic(1.0, 0.0), 1.0)
def test_lognormal(self):
mean = [0]
sigma = [1]
bad_sigma = [-1]
desired = np.array([0.67884390500697, 2.21653186290321, 1.01990310084276])
random = Generator(MT19937(self.seed))
lognormal = random.lognormal
actual = lognormal(mean * 3, sigma)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, lognormal, mean * 3, bad_sigma)
random = Generator(MT19937(self.seed))
actual = random.lognormal(mean, sigma * 3)
assert_raises(ValueError, random.lognormal, mean, bad_sigma * 3)
def test_rayleigh(self):
scale = [1]
bad_scale = [-1]
desired = np.array(
[1.1597068009872629,
0.6539188836253857,
1.1981526554349398]
)
random = Generator(MT19937(self.seed))
actual = random.rayleigh(scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.rayleigh, bad_scale * 3)
def test_wald(self):
mean = [0.5]
scale = [1]
bad_mean = [0]
bad_scale = [-2]
desired = np.array([0.38052407392905, 0.50701641508592, 0.484935249864])
random = Generator(MT19937(self.seed))
actual = random.wald(mean * 3, scale)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.wald, bad_mean * 3, scale)
assert_raises(ValueError, random.wald, mean * 3, bad_scale)
random = Generator(MT19937(self.seed))
actual = random.wald(mean, scale * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, random.wald, bad_mean, scale * 3)
assert_raises(ValueError, random.wald, mean, bad_scale * 3)
def test_triangular(self):
left = [1]
right = [3]
mode = [2]
bad_left_one = [3]
bad_mode_one = [4]
bad_left_two, bad_mode_two = right * 2
desired = np.array([1.57781954604754, 1.62665986867957, 2.30090130831326])
random = Generator(MT19937(self.seed))
triangular = random.triangular
actual = triangular(left * 3, mode, right)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, triangular, bad_left_one * 3, mode, right)
assert_raises(ValueError, triangular, left * 3, bad_mode_one, right)
assert_raises(ValueError, triangular, bad_left_two * 3, bad_mode_two,
right)
random = Generator(MT19937(self.seed))
triangular = random.triangular
actual = triangular(left, mode * 3, right)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, triangular, bad_left_one, mode * 3, right)
assert_raises(ValueError, triangular, left, bad_mode_one * 3, right)
assert_raises(ValueError, triangular, bad_left_two, bad_mode_two * 3,
right)
random = Generator(MT19937(self.seed))
triangular = random.triangular
actual = triangular(left, mode, right * 3)
assert_array_almost_equal(actual, desired, decimal=14)
assert_raises(ValueError, triangular, bad_left_one, mode, right * 3)
assert_raises(ValueError, triangular, left, bad_mode_one, right * 3)
assert_raises(ValueError, triangular, bad_left_two, bad_mode_two,
right * 3)
assert_raises(ValueError, triangular, 10., 0., 20.)
assert_raises(ValueError, triangular, 10., 25., 20.)
assert_raises(ValueError, triangular, 10., 10., 10.)
def test_binomial(self):
n = [1]
p = [0.5]
bad_n = [-1]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([0, 0, 1])
random = Generator(MT19937(self.seed))
binom = random.binomial
actual = binom(n * 3, p)
assert_array_equal(actual, desired)
assert_raises(ValueError, binom, bad_n * 3, p)
assert_raises(ValueError, binom, n * 3, bad_p_one)
assert_raises(ValueError, binom, n * 3, bad_p_two)
random = Generator(MT19937(self.seed))
actual = random.binomial(n, p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, binom, bad_n, p * 3)
assert_raises(ValueError, binom, n, bad_p_one * 3)
assert_raises(ValueError, binom, n, bad_p_two * 3)
def test_negative_binomial(self):
n = [1]
p = [0.5]
bad_n = [-1]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([0, 2, 1], dtype=np.int64)
random = Generator(MT19937(self.seed))
neg_binom = random.negative_binomial
actual = neg_binom(n * 3, p)
assert_array_equal(actual, desired)
assert_raises(ValueError, neg_binom, bad_n * 3, p)
assert_raises(ValueError, neg_binom, n * 3, bad_p_one)
assert_raises(ValueError, neg_binom, n * 3, bad_p_two)
random = Generator(MT19937(self.seed))
neg_binom = random.negative_binomial
actual = neg_binom(n, p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, neg_binom, bad_n, p * 3)
assert_raises(ValueError, neg_binom, n, bad_p_one * 3)
assert_raises(ValueError, neg_binom, n, bad_p_two * 3)
def test_poisson(self):
lam = [1]
bad_lam_one = [-1]
desired = np.array([0, 0, 3])
random = Generator(MT19937(self.seed))
max_lam = random._poisson_lam_max
bad_lam_two = [max_lam * 2]
poisson = random.poisson
actual = poisson(lam * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, poisson, bad_lam_one * 3)
assert_raises(ValueError, poisson, bad_lam_two * 3)
def test_zipf(self):
a = [2]
bad_a = [0]
desired = np.array([1, 8, 1])
random = Generator(MT19937(self.seed))
zipf = random.zipf
actual = zipf(a * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, zipf, bad_a * 3)
with np.errstate(invalid='ignore'):
assert_raises(ValueError, zipf, np.nan)
assert_raises(ValueError, zipf, [0, 0, np.nan])
def test_geometric(self):
p = [0.5]
bad_p_one = [-1]
bad_p_two = [1.5]
desired = np.array([1, 1, 3])
random = Generator(MT19937(self.seed))
geometric = random.geometric
actual = geometric(p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, geometric, bad_p_one * 3)
assert_raises(ValueError, geometric, bad_p_two * 3)
def test_hypergeometric(self):
ngood = [1]
nbad = [2]
nsample = [2]
bad_ngood = [-1]
bad_nbad = [-2]
bad_nsample_one = [-1]
bad_nsample_two = [4]
desired = np.array([0, 0, 1])
random = Generator(MT19937(self.seed))
actual = random.hypergeometric(ngood * 3, nbad, nsample)
assert_array_equal(actual, desired)
assert_raises(ValueError, random.hypergeometric, bad_ngood * 3, nbad, nsample)
assert_raises(ValueError, random.hypergeometric, ngood * 3, bad_nbad, nsample)
assert_raises(ValueError, random.hypergeometric, ngood * 3, nbad, bad_nsample_one) # noqa: E501
assert_raises(ValueError, random.hypergeometric, ngood * 3, nbad, bad_nsample_two) # noqa: E501
random = Generator(MT19937(self.seed))
actual = random.hypergeometric(ngood, nbad * 3, nsample)
assert_array_equal(actual, desired)
assert_raises(ValueError, random.hypergeometric, bad_ngood, nbad * 3, nsample)
assert_raises(ValueError, random.hypergeometric, ngood, bad_nbad * 3, nsample)
assert_raises(ValueError, random.hypergeometric, ngood, nbad * 3, bad_nsample_one) # noqa: E501
assert_raises(ValueError, random.hypergeometric, ngood, nbad * 3, bad_nsample_two) # noqa: E501
random = Generator(MT19937(self.seed))
hypergeom = random.hypergeometric
actual = hypergeom(ngood, nbad, nsample * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, hypergeom, bad_ngood, nbad, nsample * 3)
assert_raises(ValueError, hypergeom, ngood, bad_nbad, nsample * 3)
assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_one * 3)
assert_raises(ValueError, hypergeom, ngood, nbad, bad_nsample_two * 3)
assert_raises(ValueError, hypergeom, -1, 10, 20)
assert_raises(ValueError, hypergeom, 10, -1, 20)
assert_raises(ValueError, hypergeom, 10, 10, -1)
assert_raises(ValueError, hypergeom, 10, 10, 25)
# ValueError for arguments that are too big.
assert_raises(ValueError, hypergeom, 2**30, 10, 20)
assert_raises(ValueError, hypergeom, 999, 2**31, 50)
assert_raises(ValueError, hypergeom, 999, [2**29, 2**30], 1000)
def test_logseries(self):
p = [0.5]
bad_p_one = [2]
bad_p_two = [-1]
desired = np.array([1, 1, 1])
random = Generator(MT19937(self.seed))
logseries = random.logseries
actual = logseries(p * 3)
assert_array_equal(actual, desired)
assert_raises(ValueError, logseries, bad_p_one * 3)
assert_raises(ValueError, logseries, bad_p_two * 3)
def test_multinomial(self):
random = Generator(MT19937(self.seed))
actual = random.multinomial([5, 20], [1 / 6.] * 6, size=(3, 2))
desired = np.array([[[0, 0, 2, 1, 2, 0],
[2, 3, 6, 4, 2, 3]],
[[1, 0, 1, 0, 2, 1],
[7, 2, 2, 1, 4, 4]],
[[0, 2, 0, 1, 2, 0],
[3, 2, 3, 3, 4, 5]]], dtype=np.int64)
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
actual = random.multinomial([5, 20], [1 / 6.] * 6)
desired = np.array([[0, 0, 2, 1, 2, 0],
[2, 3, 6, 4, 2, 3]], dtype=np.int64)
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
actual = random.multinomial([5, 20], [[1 / 6.] * 6] * 2)
desired = np.array([[0, 0, 2, 1, 2, 0],
[2, 3, 6, 4, 2, 3]], dtype=np.int64)
assert_array_equal(actual, desired)
random = Generator(MT19937(self.seed))
actual = random.multinomial([[5], [20]], [[1 / 6.] * 6] * 2)
desired = np.array([[[0, 0, 2, 1, 2, 0],
[0, 0, 2, 1, 1, 1]],
[[4, 2, 3, 3, 5, 3],
[7, 2, 2, 1, 4, 4]]], dtype=np.int64)
assert_array_equal(actual, desired)
@pytest.mark.parametrize("n", [10,
np.array([10, 10]),
np.array([[[10]], [[10]]])
]
)
def test_multinomial_pval_broadcast(self, n):
random = Generator(MT19937(self.seed))
pvals = np.array([1 / 4] * 4)
actual = random.multinomial(n, pvals)
n_shape = () if isinstance(n, int) else n.shape
expected_shape = n_shape + (4,)
assert actual.shape == expected_shape
pvals = np.vstack([pvals, pvals])
actual = random.multinomial(n, pvals)
expected_shape = np.broadcast_shapes(n_shape, pvals.shape[:-1]) + (4,)
assert actual.shape == expected_shape
pvals = np.vstack([[pvals], [pvals]])
actual = random.multinomial(n, pvals)
expected_shape = np.broadcast_shapes(n_shape, pvals.shape[:-1])
assert actual.shape == expected_shape + (4,)
actual = random.multinomial(n, pvals, size=(3, 2) + expected_shape)
assert actual.shape == (3, 2) + expected_shape + (4,)
with pytest.raises(ValueError):
# Ensure that size is not broadcast
actual = random.multinomial(n, pvals, size=(1,) * 6)
def test_invalid_pvals_broadcast(self):
random = Generator(MT19937(self.seed))
pvals = [[1 / 6] * 6, [1 / 4] * 6]
assert_raises(ValueError, random.multinomial, 1, pvals)
assert_raises(ValueError, random.multinomial, 6, 0.5)
def test_empty_outputs(self):
random = Generator(MT19937(self.seed))
actual = random.multinomial(np.empty((10, 0, 6), "i8"), [1 / 6] * 6)
assert actual.shape == (10, 0, 6, 6)
actual = random.multinomial(12, np.empty((10, 0, 10)))
assert actual.shape == (10, 0, 10)
actual = random.multinomial(np.empty((3, 0, 7), "i8"),
np.empty((3, 0, 7, 4)))
assert actual.shape == (3, 0, 7, 4)
@pytest.mark.skipif(IS_WASM, reason="can't start thread")
class TestThread:
# make sure each state produces the same sequence even in threads
seeds = range(4)
def check_function(self, function, sz):
from threading import Thread
out1 = np.empty((len(self.seeds),) + sz)
out2 = np.empty((len(self.seeds),) + sz)
# threaded generation
t = [Thread(target=function, args=(Generator(MT19937(s)), o))
for s, o in zip(self.seeds, out1)]
[x.start() for x in t]
[x.join() for x in t]
# the same serial
for s, o in zip(self.seeds, out2):
function(Generator(MT19937(s)), o)
# these platforms change x87 fpu precision mode in threads
if np.intp().dtype.itemsize == 4 and sys.platform == "win32":
assert_array_almost_equal(out1, out2)
else:
assert_array_equal(out1, out2)
def test_normal(self):
def gen_random(state, out):
out[...] = state.normal(size=10000)
self.check_function(gen_random, sz=(10000,))
def test_exp(self):
def gen_random(state, out):
out[...] = state.exponential(scale=np.ones((100, 1000)))
self.check_function(gen_random, sz=(100, 1000))
def test_multinomial(self):
def gen_random(state, out):
out[...] = state.multinomial(10, [1 / 6.] * 6, size=10000)
self.check_function(gen_random, sz=(10000, 6))
# See Issue #4263
class TestSingleEltArrayInput:
def _create_arrays(self):
return np.array([2]), np.array([3]), np.array([4]), (1,)
def test_one_arg_funcs(self):
argOne, _, _, tgtShape = self._create_arrays()
funcs = (random.exponential, random.standard_gamma,
random.chisquare, random.standard_t,
random.pareto, random.weibull,
random.power, random.rayleigh,
random.poisson, random.zipf,
random.geometric, random.logseries)
probfuncs = (random.geometric, random.logseries)
for func in funcs:
if func in probfuncs: # p < 1.0
out = func(np.array([0.5]))
else:
out = func(argOne)
assert_equal(out.shape, tgtShape)
def test_two_arg_funcs(self):
argOne, argTwo, _, tgtShape = self._create_arrays()
funcs = (random.uniform, random.normal,
random.beta, random.gamma,
random.f, random.noncentral_chisquare,
random.vonmises, random.laplace,
random.gumbel, random.logistic,
random.lognormal, random.wald,
random.binomial, random.negative_binomial)
probfuncs = (random.binomial, random.negative_binomial)
for func in funcs:
if func in probfuncs: # p <= 1
argTwo = np.array([0.5])
else:
argTwo = argTwo
out = func(argOne, argTwo)
assert_equal(out.shape, tgtShape)
out = func(argOne[0], argTwo)
assert_equal(out.shape, tgtShape)
out = func(argOne, argTwo[0])
assert_equal(out.shape, tgtShape)
def test_integers(self, endpoint):
_, _, _, tgtShape = self._create_arrays()
itype = [np.bool, np.int8, np.uint8, np.int16, np.uint16,
np.int32, np.uint32, np.int64, np.uint64]
func = random.integers
high = np.array([1])
low = np.array([0])
for dt in itype:
out = func(low, high, endpoint=endpoint, dtype=dt)
assert_equal(out.shape, tgtShape)
out = func(low[0], high, endpoint=endpoint, dtype=dt)
assert_equal(out.shape, tgtShape)
out = func(low, high[0], endpoint=endpoint, dtype=dt)
assert_equal(out.shape, tgtShape)
def test_three_arg_funcs(self):
argOne, argTwo, argThree, tgtShape = self._create_arrays()
funcs = [random.noncentral_f, random.triangular,
random.hypergeometric]
for func in funcs:
out = func(argOne, argTwo, argThree)
assert_equal(out.shape, tgtShape)
out = func(argOne[0], argTwo, argThree)
assert_equal(out.shape, tgtShape)
out = func(argOne, argTwo[0], argThree)
assert_equal(out.shape, tgtShape)
@pytest.mark.parametrize("config", JUMP_TEST_DATA)
def test_jumped(config):
# Each config contains the initial seed, a number of raw steps
# the sha256 hashes of the initial and the final states' keys and
# the position of the initial and the final state.
# These were produced using the original C implementation.
seed = config["seed"]
steps = config["steps"]
mt19937 = MT19937(seed)
# Burn step
mt19937.random_raw(steps)
key = mt19937.state["state"]["key"]
if sys.byteorder == 'big':
key = key.byteswap()
sha256 = hashlib.sha256(key)
assert mt19937.state["state"]["pos"] == config["initial"]["pos"]
assert sha256.hexdigest() == config["initial"]["key_sha256"]
jumped = mt19937.jumped()
key = jumped.state["state"]["key"]
if sys.byteorder == 'big':
key = key.byteswap()
sha256 = hashlib.sha256(key)
assert jumped.state["state"]["pos"] == config["jumped"]["pos"]
assert sha256.hexdigest() == config["jumped"]["key_sha256"]
def test_broadcast_size_error():
mu = np.ones(3)
sigma = np.ones((4, 3))
size = (10, 4, 2)
assert random.normal(mu, sigma, size=(5, 4, 3)).shape == (5, 4, 3)
with pytest.raises(ValueError):
random.normal(mu, sigma, size=size)
with pytest.raises(ValueError):
random.normal(mu, sigma, size=(1, 3))
with pytest.raises(ValueError):
random.normal(mu, sigma, size=(4, 1, 1))
# 1 arg
shape = np.ones((4, 3))
with pytest.raises(ValueError):
random.standard_gamma(shape, size=size)
with pytest.raises(ValueError):
random.standard_gamma(shape, size=(3,))
with pytest.raises(ValueError):
random.standard_gamma(shape, size=3)
# Check out
out = np.empty(size)
with pytest.raises(ValueError):
random.standard_gamma(shape, out=out)
# 2 arg
with pytest.raises(ValueError):
random.binomial(1, [0.3, 0.7], size=(2, 1))
with pytest.raises(ValueError):
random.binomial([1, 2], 0.3, size=(2, 1))
with pytest.raises(ValueError):
random.binomial([1, 2], [0.3, 0.7], size=(2, 1))
with pytest.raises(ValueError):
random.multinomial([2, 2], [.3, .7], size=(2, 1))
# 3 arg
a = random.chisquare(5, size=3)
b = random.chisquare(5, size=(4, 3))
c = random.chisquare(5, size=(5, 4, 3))
assert random.noncentral_f(a, b, c).shape == (5, 4, 3)
with pytest.raises(ValueError, match=r"Output size \(6, 5, 1, 1\) is"):
random.noncentral_f(a, b, c, size=(6, 5, 1, 1))
def test_broadcast_size_scalar():
mu = np.ones(3)
sigma = np.ones(3)
random.normal(mu, sigma, size=3)
with pytest.raises(ValueError):
random.normal(mu, sigma, size=2)
def test_ragged_shuffle():
# GH 18142
seq = [[], [], 1]
gen = Generator(MT19937(0))
assert_no_warnings(gen.shuffle, seq)
assert seq == [1, [], []]
@pytest.mark.parametrize("high", [-2, [-2]])
@pytest.mark.parametrize("endpoint", [True, False])
def test_single_arg_integer_exception(high, endpoint):
# GH 14333
gen = Generator(MT19937(0))
msg = 'high < 0' if endpoint else 'high <= 0'
with pytest.raises(ValueError, match=msg):
gen.integers(high, endpoint=endpoint)
msg = 'low > high' if endpoint else 'low >= high'
with pytest.raises(ValueError, match=msg):
gen.integers(-1, high, endpoint=endpoint)
with pytest.raises(ValueError, match=msg):
gen.integers([-1], high, endpoint=endpoint)
@pytest.mark.parametrize("dtype", ["f4", "f8"])
def test_c_contig_req_out(dtype):
# GH 18704
out = np.empty((2, 3), order="F", dtype=dtype)
shape = [1, 2, 3]
with pytest.raises(ValueError, match="Supplied output array"):
random.standard_gamma(shape, out=out, dtype=dtype)
with pytest.raises(ValueError, match="Supplied output array"):
random.standard_gamma(shape, out=out, size=out.shape, dtype=dtype)
@pytest.mark.parametrize("dtype", ["f4", "f8"])
@pytest.mark.parametrize("order", ["F", "C"])
@pytest.mark.parametrize("dist", [random.standard_normal, random.random])
def test_contig_req_out(dist, order, dtype):
# GH 18704
out = np.empty((2, 3), dtype=dtype, order=order)
variates = dist(out=out, dtype=dtype)
assert variates is out
variates = dist(out=out, dtype=dtype, size=out.shape)
assert variates is out
def test_generator_ctor_old_style_pickle():
rg = np.random.Generator(np.random.PCG64DXSM(0))
rg.standard_normal(1)
# Directly call reduce which is used in pickling
ctor, (bit_gen, ), _ = rg.__reduce__()
# Simulate unpickling an old pickle that only has the name
assert bit_gen.__class__.__name__ == "PCG64DXSM"
print(ctor)
b = ctor(*("PCG64DXSM",))
print(b)
b.bit_generator.state = bit_gen.state
state_b = b.bit_generator.state
assert bit_gen.state == state_b
def test_pickle_preserves_seed_sequence():
# GH 26234
# Add explicit test that bit generators preserve seed sequences
import pickle
rg = np.random.Generator(np.random.PCG64DXSM(20240411))
ss = rg.bit_generator.seed_seq
rg_plk = pickle.loads(pickle.dumps(rg))
ss_plk = rg_plk.bit_generator.seed_seq
assert_equal(ss.state, ss_plk.state)
assert_equal(ss.pool, ss_plk.pool)
rg.bit_generator.seed_seq.spawn(10)
rg_plk = pickle.loads(pickle.dumps(rg))
ss_plk = rg_plk.bit_generator.seed_seq
assert_equal(ss.state, ss_plk.state)
@pytest.mark.parametrize("version", [121, 126])
def test_legacy_pickle(version):
# Pickling format was changes in 1.22.x and in 2.0.x
import gzip
import pickle
base_path = os.path.split(os.path.abspath(__file__))[0]
pkl_file = os.path.join(
base_path, "data", f"generator_pcg64_np{version}.pkl.gz"
)
with gzip.open(pkl_file) as gz:
rg = pickle.load(gz)
state = rg.bit_generator.state['state']
assert isinstance(rg, Generator)
assert isinstance(rg.bit_generator, np.random.PCG64)
assert state['state'] == 35399562948360463058890781895381311971
assert state['inc'] == 87136372517582989555478159403783844777
| import hashlib
import os.path
import sys
import warnings
import pytest
import numpy as np
from numpy.exceptions import AxisError
from numpy.linalg import LinAlgError
from numpy.random import MT19937, Generator, RandomState, SeedSequence
from numpy.testing import (
IS_WASM,
assert_,
assert_allclose,
assert_array_almost_equal,
assert_array_equal,
assert_equal,
assert_no_warnings,
assert_raises,
)
random = Generator(MT19937())
JUMP_TEST_DATA = [
{
"seed": 0,
"steps": 10,
"initial": {"key_sha256": "bb1636883c2707b51c5b7fc26c6927af4430f2e0785a8c7bc886337f919f9edf", "pos": 9}, # noqa: E501
"jumped": {"key_sha256": "ff682ac12bb140f2d72fba8d3506cf4e46817a0db27aae1683867629031d8d55", "pos": 598}, # noqa: E501
},
{
"seed": 384908324,
"steps": 312,
"initial": {"key_sha256": "16b791a1e04886ccbbb4d448d6ff791267dc458ae599475d08d5cced29d11614", "pos": 311}, # noqa: E501
"jumped": {"key_sha256": "a0110a2cf23b56be0feaed8f787a7fc84bef0cb5623003d75b26bdfa1c18 | [
"# numpy/numpy:numpy/exceptions.py\nAxisError",
"# numpy/numpy:numpy/linalg/_linalg.py\nLinAlgError",
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_equal"
] | numpy/numpy | numpy/random/tests/test_generator_mt19937.py |
import os
import shutil
import subprocess
import sys
import sysconfig
import warnings
from importlib.util import module_from_spec, spec_from_file_location
import pytest
import numpy as np
from numpy.testing import IS_EDITABLE, IS_WASM
try:
import cffi
except ImportError:
cffi = None
if sys.flags.optimize > 1:
# no docstrings present to inspect when PYTHONOPTIMIZE/Py_OptimizeFlag > 1
# cffi cannot succeed
cffi = None
try:
with warnings.catch_warnings(record=True) as w:
# numba issue gh-4733
warnings.filterwarnings('always', '', DeprecationWarning)
import numba
except (ImportError, SystemError):
# Certain numpy/numba versions trigger a SystemError due to a numba bug
numba = None
try:
import cython
from Cython.Compiler.Version import version as cython_version
except ImportError:
cython = None
else:
from numpy._utils import _pep440
# Note: keep in sync with the one in pyproject.toml
required_version = '3.0.6'
if _pep440.parse(cython_version) < _pep440.Version(required_version):
# too old or wrong cython, skip the test
cython = None
@pytest.mark.skipif(
IS_EDITABLE,
reason='Editable install cannot find .pxd headers'
)
@pytest.mark.skipif(
sys.platform == "win32" and sys.maxsize < 2**32,
reason="Failing in 32-bit Windows wheel build job, skip for now"
)
@pytest.mark.skipif(IS_WASM, reason="Can't start subprocess")
@pytest.mark.skipif(cython is None, reason="requires cython")
@pytest.mark.skipif(sysconfig.get_platform() == 'win-arm64',
reason='Meson unable to find MSVC linker on win-arm64')
@pytest.mark.slow
@pytest.mark.thread_unsafe(
reason="building cython code in a subprocess doesn't make sense to do in many "
"threads and sometimes crashes"
)
def test_cython(tmp_path):
import glob
# build the examples in a temporary directory
srcdir = os.path.join(os.path.dirname(__file__), '..')
shutil.copytree(srcdir, tmp_path / 'random')
build_dir = tmp_path / 'random' / '_examples' / 'cython'
target_dir = build_dir / "build"
os.makedirs(target_dir, exist_ok=True)
# Ensure we use the correct Python interpreter even when `meson` is
# installed in a different Python environment (see gh-24956)
native_file = str(build_dir / 'interpreter-native-file.ini')
with open(native_file, 'w') as f:
f.write("[binaries]\n")
f.write(f"python = '{sys.executable}'\n")
f.write(f"python3 = '{sys.executable}'")
if sys.platform == "win32":
subprocess.check_call(["meson", "setup",
"--buildtype=release",
"--vsenv", "--native-file", native_file,
str(build_dir)],
cwd=target_dir,
)
else:
subprocess.check_call(["meson", "setup",
"--native-file", native_file, str(build_dir)],
cwd=target_dir
)
subprocess.check_call(["meson", "compile", "-vv"], cwd=target_dir)
# gh-16162: make sure numpy's __init__.pxd was used for cython
# not really part of this test, but it is a convenient place to check
g = glob.glob(str(target_dir / "*" / "extending.pyx.c"))
with open(g[0]) as fid:
txt_to_find = 'NumPy API declarations from "numpy/__init__'
for line in fid:
if txt_to_find in line:
break
else:
assert False, f"Could not find '{txt_to_find}' in C file, wrong pxd used"
# import without adding the directory to sys.path
suffix = sysconfig.get_config_var('EXT_SUFFIX')
def load(modname):
so = (target_dir / modname).with_suffix(suffix)
spec = spec_from_file_location(modname, so)
mod = module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
# test that the module can be imported
load("extending")
load("extending_cpp")
# actually test the cython c-extension
extending_distributions = load("extending_distributions")
from numpy.random import PCG64
values = extending_distributions.uniforms_ex(PCG64(0), 10, 'd')
assert values.shape == (10,)
assert values.dtype == np.float64
@pytest.mark.skipif(numba is None or cffi is None,
reason="requires numba and cffi")
def test_numba():
from numpy.random._examples.numba import extending # noqa: F401
@pytest.mark.skipif(cffi is None, reason="requires cffi")
def test_cffi():
from numpy.random._examples.cffi import extending # noqa: F401
| import os
import shutil
import subprocess
import sys
import sysconfig
import warnings
from importlib.util import module_from_spec, spec_from_file_location
import pytest
import numpy as np
from numpy.testing import IS_EDITABLE, IS_WASM
try:
import cffi
except ImportError:
cffi = None
if sys.flags.optimize > 1:
# no docstrings present to inspect when PYTHONOPTIMIZE/Py_OptimizeFlag > 1
# cffi cannot succeed
cffi = None
try:
with warnings.catch_warnings(record=True) as w:
# numba issue gh-4733
warnings.filterwarnings('always', '', DeprecationWarning)
import numba
except (ImportError, SystemError):
# Certain numpy/numba versions trigger a SystemError due to a numba bug
numba = None
try:
import cython
from Cython.Compiler.Version import version as cython_version
except ImportError:
cython = None
else:
from numpy._utils import _pep440
# Note: keep in sync with the one in pyproject.toml
required_version = '3.0.6'
if _pep440.parse(cython_version) < _pep440.Version(required_version):
# too old or wrong cython, skip the test
cython = None
@pytest.mark.skipif(
IS_EDITABLE,
reason='Editable install cannot find .pxd headers'
)
@pytest.mark.skipif(
sys.platform == "win32" and sys.maxsize < 2**32,
reason="F | [] | numpy/numpy | numpy/random/tests/test_extending.py |
import os
import sys
from os.path import join
import pytest
import numpy as np
from numpy.random import (
MT19937,
PCG64,
PCG64DXSM,
SFC64,
Generator,
Philox,
RandomState,
SeedSequence,
default_rng,
)
from numpy.random._common import interface
from numpy.testing import (
assert_allclose,
assert_array_equal,
assert_equal,
assert_raises,
)
try:
import cffi # noqa: F401
MISSING_CFFI = False
except ImportError:
MISSING_CFFI = True
try:
import ctypes # noqa: F401
MISSING_CTYPES = False
except ImportError:
MISSING_CTYPES = False
if sys.flags.optimize > 1:
# no docstrings present to inspect when PYTHONOPTIMIZE/Py_OptimizeFlag > 1
# cffi cannot succeed
MISSING_CFFI = True
pwd = os.path.dirname(os.path.abspath(__file__))
def assert_state_equal(actual, target):
for key in actual:
if isinstance(actual[key], dict):
assert_state_equal(actual[key], target[key])
elif isinstance(actual[key], np.ndarray):
assert_array_equal(actual[key], target[key])
else:
assert actual[key] == target[key]
def uint32_to_float32(u):
return ((u >> np.uint32(8)) * (1.0 / 2**24)).astype(np.float32)
def uniform32_from_uint64(x):
x = np.uint64(x)
upper = np.array(x >> np.uint64(32), dtype=np.uint32)
lower = np.uint64(0xffffffff)
lower = np.array(x & lower, dtype=np.uint32)
joined = np.column_stack([lower, upper]).ravel()
return uint32_to_float32(joined)
def uniform32_from_uint53(x):
x = np.uint64(x) >> np.uint64(16)
x = np.uint32(x & np.uint64(0xffffffff))
return uint32_to_float32(x)
def uniform32_from_uint32(x):
return uint32_to_float32(x)
def uniform32_from_uint(x, bits):
if bits == 64:
return uniform32_from_uint64(x)
elif bits == 53:
return uniform32_from_uint53(x)
elif bits == 32:
return uniform32_from_uint32(x)
else:
raise NotImplementedError
def uniform_from_uint(x, bits):
if bits in (64, 63, 53):
return uniform_from_uint64(x)
elif bits == 32:
return uniform_from_uint32(x)
def uniform_from_uint64(x):
return (x >> np.uint64(11)) * (1.0 / 9007199254740992.0)
def uniform_from_uint32(x):
out = np.empty(len(x) // 2)
for i in range(0, len(x), 2):
a = x[i] >> 5
b = x[i + 1] >> 6
out[i // 2] = (a * 67108864.0 + b) / 9007199254740992.0
return out
def uniform_from_dsfmt(x):
return x.view(np.double) - 1.0
def gauss_from_uint(x, n, bits):
if bits in (64, 63):
doubles = uniform_from_uint64(x)
elif bits == 32:
doubles = uniform_from_uint32(x)
else: # bits == 'dsfmt'
doubles = uniform_from_dsfmt(x)
gauss = []
loc = 0
x1 = x2 = 0.0
while len(gauss) < n:
r2 = 2
while r2 >= 1.0 or r2 == 0.0:
x1 = 2.0 * doubles[loc] - 1.0
x2 = 2.0 * doubles[loc + 1] - 1.0
r2 = x1 * x1 + x2 * x2
loc += 2
f = np.sqrt(-2.0 * np.log(r2) / r2)
gauss.append(f * x2)
gauss.append(f * x1)
return gauss[:n]
def test_seedsequence():
from numpy.random.bit_generator import (
ISeedSequence,
ISpawnableSeedSequence,
SeedlessSeedSequence,
)
s1 = SeedSequence(range(10), spawn_key=(1, 2), pool_size=6)
s1.spawn(10)
s2 = SeedSequence(**s1.state)
assert_equal(s1.state, s2.state)
assert_equal(s1.n_children_spawned, s2.n_children_spawned)
# The interfaces cannot be instantiated themselves.
assert_raises(TypeError, ISeedSequence)
assert_raises(TypeError, ISpawnableSeedSequence)
dummy = SeedlessSeedSequence()
assert_raises(NotImplementedError, dummy.generate_state, 10)
assert len(dummy.spawn(10)) == 10
def test_generator_spawning():
""" Test spawning new generators and bit_generators directly.
"""
rng = np.random.default_rng()
seq = rng.bit_generator.seed_seq
new_ss = seq.spawn(5)
expected_keys = [seq.spawn_key + (i,) for i in range(5)]
assert [c.spawn_key for c in new_ss] == expected_keys
new_bgs = rng.bit_generator.spawn(5)
expected_keys = [seq.spawn_key + (i,) for i in range(5, 10)]
assert [bg.seed_seq.spawn_key for bg in new_bgs] == expected_keys
new_rngs = rng.spawn(5)
expected_keys = [seq.spawn_key + (i,) for i in range(10, 15)]
found_keys = [rng.bit_generator.seed_seq.spawn_key for rng in new_rngs]
assert found_keys == expected_keys
# Sanity check that streams are actually different:
assert new_rngs[0].uniform() != new_rngs[1].uniform()
def test_spawn_negative_n_children():
"""Test that spawn raises ValueError for negative n_children."""
from numpy.random.bit_generator import SeedlessSeedSequence
rng = np.random.default_rng(42)
seq = rng.bit_generator.seed_seq
# Test SeedSequence.spawn
with pytest.raises(ValueError, match="n_children must be non-negative"):
seq.spawn(-1)
# Test SeedlessSeedSequence.spawn
seedless = SeedlessSeedSequence()
with pytest.raises(ValueError, match="n_children must be non-negative"):
seedless.spawn(-1)
# Test BitGenerator.spawn
with pytest.raises(ValueError, match="n_children must be non-negative"):
rng.bit_generator.spawn(-1)
# Test Generator.spawn
with pytest.raises(ValueError, match="n_children must be non-negative"):
rng.spawn(-1)
def test_non_spawnable():
from numpy.random.bit_generator import ISeedSequence
class FakeSeedSequence:
def generate_state(self, n_words, dtype=np.uint32):
return np.zeros(n_words, dtype=dtype)
ISeedSequence.register(FakeSeedSequence)
rng = np.random.default_rng(FakeSeedSequence())
with pytest.raises(TypeError, match="The underlying SeedSequence"):
rng.spawn(5)
with pytest.raises(TypeError, match="The underlying SeedSequence"):
rng.bit_generator.spawn(5)
class Base:
dtype = np.uint64
data2 = data1 = {}
@classmethod
def setup_class(cls):
cls.bit_generator = PCG64
cls.bits = 64
cls.dtype = np.uint64
cls.seed_error_type = TypeError
cls.invalid_init_types = []
cls.invalid_init_values = []
@classmethod
def _read_csv(cls, filename):
with open(filename) as csv:
seed = csv.readline()
seed = seed.split(',')
seed = [int(s.strip(), 0) for s in seed[1:]]
data = []
for line in csv:
data.append(int(line.split(',')[-1].strip(), 0))
return {'seed': seed, 'data': np.array(data, dtype=cls.dtype)}
def test_raw(self):
bit_generator = self.bit_generator(*self.data1['seed'])
uints = bit_generator.random_raw(1000)
assert_equal(uints, self.data1['data'])
bit_generator = self.bit_generator(*self.data1['seed'])
uints = bit_generator.random_raw()
assert_equal(uints, self.data1['data'][0])
bit_generator = self.bit_generator(*self.data2['seed'])
uints = bit_generator.random_raw(1000)
assert_equal(uints, self.data2['data'])
def test_random_raw(self):
bit_generator = self.bit_generator(*self.data1['seed'])
uints = bit_generator.random_raw(output=False)
assert uints is None
uints = bit_generator.random_raw(1000, output=False)
assert uints is None
def test_gauss_inv(self):
n = 25
rs = RandomState(self.bit_generator(*self.data1['seed']))
gauss = rs.standard_normal(n)
assert_allclose(gauss,
gauss_from_uint(self.data1['data'], n, self.bits))
rs = RandomState(self.bit_generator(*self.data2['seed']))
gauss = rs.standard_normal(25)
assert_allclose(gauss,
gauss_from_uint(self.data2['data'], n, self.bits))
def test_uniform_double(self):
rs = Generator(self.bit_generator(*self.data1['seed']))
vals = uniform_from_uint(self.data1['data'], self.bits)
uniforms = rs.random(len(vals))
assert_allclose(uniforms, vals)
assert_equal(uniforms.dtype, np.float64)
rs = Generator(self.bit_generator(*self.data2['seed']))
vals = uniform_from_uint(self.data2['data'], self.bits)
uniforms = rs.random(len(vals))
assert_allclose(uniforms, vals)
assert_equal(uniforms.dtype, np.float64)
def test_uniform_float(self):
rs = Generator(self.bit_generator(*self.data1['seed']))
vals = uniform32_from_uint(self.data1['data'], self.bits)
uniforms = rs.random(len(vals), dtype=np.float32)
assert_allclose(uniforms, vals)
assert_equal(uniforms.dtype, np.float32)
rs = Generator(self.bit_generator(*self.data2['seed']))
vals = uniform32_from_uint(self.data2['data'], self.bits)
uniforms = rs.random(len(vals), dtype=np.float32)
assert_allclose(uniforms, vals)
assert_equal(uniforms.dtype, np.float32)
def test_repr(self):
rs = Generator(self.bit_generator(*self.data1['seed']))
assert 'Generator' in repr(rs)
assert f'{id(rs):#x}'.upper().replace('X', 'x') in repr(rs)
def test_str(self):
rs = Generator(self.bit_generator(*self.data1['seed']))
assert 'Generator' in str(rs)
assert str(self.bit_generator.__name__) in str(rs)
assert f'{id(rs):#x}'.upper().replace('X', 'x') not in str(rs)
def test_pickle(self):
import pickle
bit_generator = self.bit_generator(*self.data1['seed'])
state = bit_generator.state
bitgen_pkl = pickle.dumps(bit_generator)
reloaded = pickle.loads(bitgen_pkl)
reloaded_state = reloaded.state
assert_array_equal(Generator(bit_generator).standard_normal(1000),
Generator(reloaded).standard_normal(1000))
assert bit_generator is not reloaded
assert_state_equal(reloaded_state, state)
ss = SeedSequence(100)
aa = pickle.loads(pickle.dumps(ss))
assert_equal(ss.state, aa.state)
def test_pickle_preserves_seed_sequence(self):
# GH 26234
# Add explicit test that bit generators preserve seed sequences
import pickle
bit_generator = self.bit_generator(*self.data1['seed'])
ss = bit_generator.seed_seq
bg_plk = pickle.loads(pickle.dumps(bit_generator))
ss_plk = bg_plk.seed_seq
assert_equal(ss.state, ss_plk.state)
assert_equal(ss.pool, ss_plk.pool)
bit_generator.seed_seq.spawn(10)
bg_plk = pickle.loads(pickle.dumps(bit_generator))
ss_plk = bg_plk.seed_seq
assert_equal(ss.state, ss_plk.state)
assert_equal(ss.n_children_spawned, ss_plk.n_children_spawned)
def test_invalid_state_type(self):
bit_generator = self.bit_generator(*self.data1['seed'])
with pytest.raises(TypeError):
bit_generator.state = {'1'}
def test_invalid_state_value(self):
bit_generator = self.bit_generator(*self.data1['seed'])
state = bit_generator.state
state['bit_generator'] = 'otherBitGenerator'
with pytest.raises(ValueError):
bit_generator.state = state
def test_invalid_init_type(self):
bit_generator = self.bit_generator
for st in self.invalid_init_types:
with pytest.raises(TypeError):
bit_generator(*st)
def test_invalid_init_values(self):
bit_generator = self.bit_generator
for st in self.invalid_init_values:
with pytest.raises((ValueError, OverflowError)):
bit_generator(*st)
def test_benchmark(self):
bit_generator = self.bit_generator(*self.data1['seed'])
bit_generator._benchmark(1)
bit_generator._benchmark(1, 'double')
with pytest.raises(ValueError):
bit_generator._benchmark(1, 'int32')
@pytest.mark.skipif(MISSING_CFFI, reason='cffi not available')
def test_cffi(self):
bit_generator = self.bit_generator(*self.data1['seed'])
cffi_interface = bit_generator.cffi
assert isinstance(cffi_interface, interface)
other_cffi_interface = bit_generator.cffi
assert other_cffi_interface is cffi_interface
@pytest.mark.skipif(MISSING_CTYPES, reason='ctypes not available')
def test_ctypes(self):
bit_generator = self.bit_generator(*self.data1['seed'])
ctypes_interface = bit_generator.ctypes
assert isinstance(ctypes_interface, interface)
other_ctypes_interface = bit_generator.ctypes
assert other_ctypes_interface is ctypes_interface
def test_getstate(self):
bit_generator = self.bit_generator(*self.data1['seed'])
state = bit_generator.state
alt_state = bit_generator.__getstate__()
assert isinstance(alt_state, tuple)
assert_state_equal(state, alt_state[0])
assert isinstance(alt_state[1], SeedSequence)
class TestPhilox(Base):
@classmethod
def setup_class(cls):
cls.bit_generator = Philox
cls.bits = 64
cls.dtype = np.uint64
cls.data1 = cls._read_csv(
join(pwd, './data/philox-testset-1.csv'))
cls.data2 = cls._read_csv(
join(pwd, './data/philox-testset-2.csv'))
cls.seed_error_type = TypeError
cls.invalid_init_types = []
cls.invalid_init_values = [(1, None, 1), (-1,), (None, None, 2 ** 257 + 1)]
def test_set_key(self):
bit_generator = self.bit_generator(*self.data1['seed'])
state = bit_generator.state
keyed = self.bit_generator(counter=state['state']['counter'],
key=state['state']['key'])
assert_state_equal(bit_generator.state, keyed.state)
class TestPCG64(Base):
@classmethod
def setup_class(cls):
cls.bit_generator = PCG64
cls.bits = 64
cls.dtype = np.uint64
cls.data1 = cls._read_csv(join(pwd, './data/pcg64-testset-1.csv'))
cls.data2 = cls._read_csv(join(pwd, './data/pcg64-testset-2.csv'))
cls.seed_error_type = (ValueError, TypeError)
cls.invalid_init_types = [(3.2,), ([None],), (1, None)]
cls.invalid_init_values = [(-1,)]
def test_advance_symmetry(self):
rs = Generator(self.bit_generator(*self.data1['seed']))
state = rs.bit_generator.state
step = -0x9e3779b97f4a7c150000000000000000
rs.bit_generator.advance(step)
val_neg = rs.integers(10)
rs.bit_generator.state = state
rs.bit_generator.advance(2**128 + step)
val_pos = rs.integers(10)
rs.bit_generator.state = state
rs.bit_generator.advance(10 * 2**128 + step)
val_big = rs.integers(10)
assert val_neg == val_pos
assert val_big == val_pos
def test_advange_large(self):
rs = Generator(self.bit_generator(38219308213743))
pcg = rs.bit_generator
state = pcg.state["state"]
initial_state = 287608843259529770491897792873167516365
assert state["state"] == initial_state
pcg.advance(sum(2**i for i in (96, 64, 32, 16, 8, 4, 2, 1)))
state = pcg.state["state"]
advanced_state = 135275564607035429730177404003164635391
assert state["state"] == advanced_state
class TestPCG64DXSM(Base):
@classmethod
def setup_class(cls):
cls.bit_generator = PCG64DXSM
cls.bits = 64
cls.dtype = np.uint64
cls.data1 = cls._read_csv(join(pwd, './data/pcg64dxsm-testset-1.csv'))
cls.data2 = cls._read_csv(join(pwd, './data/pcg64dxsm-testset-2.csv'))
cls.seed_error_type = (ValueError, TypeError)
cls.invalid_init_types = [(3.2,), ([None],), (1, None)]
cls.invalid_init_values = [(-1,)]
def test_advance_symmetry(self):
rs = Generator(self.bit_generator(*self.data1['seed']))
state = rs.bit_generator.state
step = -0x9e3779b97f4a7c150000000000000000
rs.bit_generator.advance(step)
val_neg = rs.integers(10)
rs.bit_generator.state = state
rs.bit_generator.advance(2**128 + step)
val_pos = rs.integers(10)
rs.bit_generator.state = state
rs.bit_generator.advance(10 * 2**128 + step)
val_big = rs.integers(10)
assert val_neg == val_pos
assert val_big == val_pos
def test_advange_large(self):
rs = Generator(self.bit_generator(38219308213743))
pcg = rs.bit_generator
state = pcg.state
initial_state = 287608843259529770491897792873167516365
assert state["state"]["state"] == initial_state
pcg.advance(sum(2**i for i in (96, 64, 32, 16, 8, 4, 2, 1)))
state = pcg.state["state"]
advanced_state = 277778083536782149546677086420637664879
assert state["state"] == advanced_state
class TestMT19937(Base):
@classmethod
def setup_class(cls):
cls.bit_generator = MT19937
cls.bits = 32
cls.dtype = np.uint32
cls.data1 = cls._read_csv(join(pwd, './data/mt19937-testset-1.csv'))
cls.data2 = cls._read_csv(join(pwd, './data/mt19937-testset-2.csv'))
cls.seed_error_type = ValueError
cls.invalid_init_types = []
cls.invalid_init_values = [(-1,)]
def test_seed_float_array(self):
assert_raises(TypeError, self.bit_generator, np.array([np.pi]))
assert_raises(TypeError, self.bit_generator, np.array([-np.pi]))
assert_raises(TypeError, self.bit_generator, np.array([np.pi, -np.pi]))
assert_raises(TypeError, self.bit_generator, np.array([0, np.pi]))
assert_raises(TypeError, self.bit_generator, [np.pi])
assert_raises(TypeError, self.bit_generator, [0, np.pi])
def test_state_tuple(self):
rs = Generator(self.bit_generator(*self.data1['seed']))
bit_generator = rs.bit_generator
state = bit_generator.state
desired = rs.integers(2 ** 16)
tup = (state['bit_generator'], state['state']['key'],
state['state']['pos'])
bit_generator.state = tup
actual = rs.integers(2 ** 16)
assert_equal(actual, desired)
tup = tup + (0, 0.0)
bit_generator.state = tup
actual = rs.integers(2 ** 16)
assert_equal(actual, desired)
class TestSFC64(Base):
@classmethod
def setup_class(cls):
cls.bit_generator = SFC64
cls.bits = 64
cls.dtype = np.uint64
cls.data1 = cls._read_csv(
join(pwd, './data/sfc64-testset-1.csv'))
cls.data2 = cls._read_csv(
join(pwd, './data/sfc64-testset-2.csv'))
cls.seed_error_type = (ValueError, TypeError)
cls.invalid_init_types = [(3.2,), ([None],), (1, None)]
cls.invalid_init_values = [(-1,)]
def test_legacy_pickle(self):
# Pickling format was changed in 2.0.x
import gzip
import pickle
expected_state = np.array(
[
9957867060933711493,
532597980065565856,
14769588338631205282,
13
],
dtype=np.uint64
)
base_path = os.path.split(os.path.abspath(__file__))[0]
pkl_file = os.path.join(base_path, "data", "sfc64_np126.pkl.gz")
with gzip.open(pkl_file) as gz:
sfc = pickle.load(gz)
assert isinstance(sfc, SFC64)
assert_equal(sfc.state["state"]["state"], expected_state)
class TestDefaultRNG:
def test_seed(self):
for args in [(), (None,), (1234,), ([1234, 5678],)]:
rg = default_rng(*args)
assert isinstance(rg.bit_generator, PCG64)
def test_passthrough(self):
bg = Philox()
rg = default_rng(bg)
assert rg.bit_generator is bg
rg2 = default_rng(rg)
assert rg2 is rg
assert rg2.bit_generator is bg
@pytest.mark.thread_unsafe(
reason="np.random.set_bit_generator affects global state"
)
def test_coercion_RandomState_Generator(self):
# use default_rng to coerce RandomState to Generator
rs = RandomState(1234)
rg = default_rng(rs)
assert isinstance(rg.bit_generator, MT19937)
assert rg.bit_generator is rs._bit_generator
# RandomState with a non MT19937 bit generator
_original = np.random.get_bit_generator()
bg = PCG64(12342298)
np.random.set_bit_generator(bg)
rs = np.random.mtrand._rand
rg = default_rng(rs)
assert rg.bit_generator is bg
# vital to get global state back to original, otherwise
# other tests start to fail.
np.random.set_bit_generator(_original)
| import os
import sys
from os.path import join
import pytest
import numpy as np
from numpy.random import (
MT19937,
PCG64,
PCG64DXSM,
SFC64,
Generator,
Philox,
RandomState,
SeedSequence,
default_rng,
)
from numpy.random._common import interface
from numpy.testing import (
assert_allclose,
assert_array_equal,
assert_equal,
assert_raises,
)
try:
import cffi # noqa: F401
MISSING_CFFI = False
except ImportError:
MISSING_CFFI = True
try:
import ctypes # noqa: F401
MISSING_CTYPES = False
except ImportError:
MISSING_CTYPES = False
if sys.flags.optimize > 1:
# no docstrings present to inspect when PYTHONOPTIMIZE/Py_OptimizeFlag > 1
# cffi cannot succeed
MISSING_CFFI = True
pwd = os.path.dirname(os.path.abspath(__file__))
def assert_state_equal(actual, target):
for key in actual:
if isinstance(actual[key], dict):
assert_state_equal(actual[key], target[key])
elif isinstance(actual[key], np.ndarray):
assert_array_equal(actual[key], target[key])
else:
assert actual[key] == target[key]
def uint32_to_float32(u):
return ((u >> np.uint | [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_allclose"
] | numpy/numpy | numpy/random/tests/test_direct.py |
from ._generator import Generator
from ._mt19937 import MT19937
from ._pcg64 import PCG64, PCG64DXSM
from ._philox import Philox
from ._sfc64 import SFC64
from .bit_generator import BitGenerator
from .mtrand import RandomState
BitGenerators = {'MT19937': MT19937,
'PCG64': PCG64,
'PCG64DXSM': PCG64DXSM,
'Philox': Philox,
'SFC64': SFC64,
}
def __bit_generator_ctor(bit_generator: str | type[BitGenerator] = 'MT19937'):
"""
Pickling helper function that returns a bit generator object
Parameters
----------
bit_generator : type[BitGenerator] or str
BitGenerator class or string containing the name of the BitGenerator
Returns
-------
BitGenerator
BitGenerator instance
"""
if isinstance(bit_generator, type):
bit_gen_class = bit_generator
elif bit_generator in BitGenerators:
bit_gen_class = BitGenerators[bit_generator]
else:
raise ValueError(
str(bit_generator) + ' is not a known BitGenerator module.'
)
return bit_gen_class()
def __generator_ctor(bit_generator_name="MT19937",
bit_generator_ctor=__bit_generator_ctor):
"""
Pickling helper function that returns a Generator object
Parameters
----------
bit_generator_name : str or BitGenerator
String containing the core BitGenerator's name or a
BitGenerator instance
bit_generator_ctor : callable, optional
Callable function that takes bit_generator_name as its only argument
and returns an instantized bit generator.
Returns
-------
rg : Generator
Generator using the named core BitGenerator
"""
if isinstance(bit_generator_name, BitGenerator):
return Generator(bit_generator_name)
# Legacy path that uses a bit generator name and ctor
return Generator(bit_generator_ctor(bit_generator_name))
def __randomstate_ctor(bit_generator_name="MT19937",
bit_generator_ctor=__bit_generator_ctor):
"""
Pickling helper function that returns a legacy RandomState-like object
Parameters
----------
bit_generator_name : str
String containing the core BitGenerator's name
bit_generator_ctor : callable, optional
Callable function that takes bit_generator_name as its only argument
and returns an instantized bit generator.
Returns
-------
rs : RandomState
Legacy RandomState using the named core BitGenerator
"""
if isinstance(bit_generator_name, BitGenerator):
return RandomState(bit_generator_name)
return RandomState(bit_generator_ctor(bit_generator_name))
| from ._generator import Generator
from ._mt19937 import MT19937
from ._pcg64 import PCG64, PCG64DXSM
from ._philox import Philox
from ._sfc64 import SFC64
from .bit_generator import BitGenerator
from .mtrand import RandomState
BitGenerators = {'MT19937': MT19937,
'PCG64': PCG64,
'PCG64DXSM': PCG64DXSM,
'Philox': Philox,
'SFC64': SFC64,
}
def __bit_generator_ctor(bit_generator: str | type[BitGenerator] = 'MT19937'):
"""
Pickling helper function that returns a bit generator object
Parameters
----------
bit_generator : type[BitGenerator] or str
BitGenerator class or string containing the name of the BitGenerator
Returns
-------
BitGenerator
BitGenerator instance
"""
if isinstance(bit_generator, type):
bit_gen_class = bit_generator
elif bit_generator in BitGenerators:
bit_gen_class = BitGenerators[bit_generator]
else:
raise ValueError(
str(bit_generator) + ' is not a known BitGenerator module.'
)
return bit_gen_class()
def __generator_ctor(bit_generator_name="MT19937",
| [] | numpy/numpy | numpy/random/_pickle.py |
r"""
Building the required library in this example requires a source distribution
of NumPy or clone of the NumPy git repository since distributions.c is not
included in binary distributions.
On *nix, execute in numpy/random/src/distributions
export ${PYTHON_VERSION}=3.8 # Python version
export PYTHON_INCLUDE=#path to Python's include folder, usually \
${PYTHON_HOME}/include/python${PYTHON_VERSION}m
export NUMPY_INCLUDE=#path to numpy's include folder, usually \
${PYTHON_HOME}/lib/python${PYTHON_VERSION}/site-packages/numpy/_core/include
gcc -shared -o libdistributions.so -fPIC distributions.c \
-I${NUMPY_INCLUDE} -I${PYTHON_INCLUDE}
mv libdistributions.so ../../_examples/numba/
On Windows
rem PYTHON_HOME and PYTHON_VERSION are setup dependent, this is an example
set PYTHON_HOME=c:\Anaconda
set PYTHON_VERSION=38
cl.exe /LD .\distributions.c -DDLL_EXPORT \
-I%PYTHON_HOME%\lib\site-packages\numpy\_core\include \
-I%PYTHON_HOME%\include %PYTHON_HOME%\libs\python%PYTHON_VERSION%.lib
move distributions.dll ../../_examples/numba/
"""
import os
import numba as nb
from cffi import FFI
import numpy as np
from numpy.random import PCG64
ffi = FFI()
if os.path.exists('./distributions.dll'):
lib = ffi.dlopen('./distributions.dll')
elif os.path.exists('./libdistributions.so'):
lib = ffi.dlopen('./libdistributions.so')
else:
raise RuntimeError('Required DLL/so file was not found.')
ffi.cdef("""
double random_standard_normal(void *bitgen_state);
""")
x = PCG64()
xffi = x.cffi
bit_generator = xffi.bit_generator
random_standard_normal = lib.random_standard_normal
def normals(n, bit_generator):
out = np.empty(n)
for i in range(n):
out[i] = random_standard_normal(bit_generator)
return out
normalsj = nb.jit(normals, nopython=True)
# Numba requires a memory address for void *
# Can also get address from x.ctypes.bit_generator.value
bit_generator_address = int(ffi.cast('uintptr_t', bit_generator))
norm = normalsj(1000, bit_generator_address)
print(norm[:12])
| r"""
Building the required library in this example requires a source distribution
of NumPy or clone of the NumPy git repository since distributions.c is not
included in binary distributions.
On *nix, execute in numpy/random/src/distributions
export ${PYTHON_VERSION}=3.8 # Python version
export PYTHON_INCLUDE=#path to Python's include folder, usually \
${PYTHON_HOME}/include/python${PYTHON_VERSION}m
export NUMPY_INCLUDE=#path to numpy's include folder, usually \
${PYTHON_HOME}/lib/python${PYTHON_VERSION}/site-packages/numpy/_core/include
gcc -shared -o libdistributions.so -fPIC distributions.c \
-I${NUMPY_INCLUDE} -I${PYTHON_INCLUDE}
mv libdistributions.so ../../_examples/numba/
On Windows
rem PYTHON_HOME and PYTHON_VERSION are setup dependent, this is an example
set PYTHON_HOME=c:\Anaconda
set PYTHON_VERSION=38
cl.exe /LD .\distributions.c -DDLL_EXPORT \
-I%PYTHON_HOME%\lib\site-packages\numpy\_core\include \
-I%PYTHON_HOME%\include %PYTHON_HOME%\libs\python%PYTHON_VERSION%.lib
move distributions.dll ../../_examples/numba/
"""
import os
import numba as nb
from cffi import FFI
import numpy as np
from numpy.random import PCG64
ffi = FFI()
if os.path.exists('./distributions.dll'):
lib = ffi.dlopen('./distributions.dll')
elif os.path.exists('./libdistributions.so'):
lib | [
"# python-cffi/cffi:src/cffi/api.py\nFFI"
] | numpy/numpy | numpy/random/_examples/numba/extending_distributions.py |
from timeit import timeit
import numba as nb
import numpy as np
from numpy.random import PCG64
bit_gen = PCG64()
next_d = bit_gen.cffi.next_double
state_addr = bit_gen.cffi.state_address
def normals(n, state):
out = np.empty(n)
for i in range((n + 1) // 2):
x1 = 2.0 * next_d(state) - 1.0
x2 = 2.0 * next_d(state) - 1.0
r2 = x1 * x1 + x2 * x2
while r2 >= 1.0 or r2 == 0.0:
x1 = 2.0 * next_d(state) - 1.0
x2 = 2.0 * next_d(state) - 1.0
r2 = x1 * x1 + x2 * x2
f = np.sqrt(-2.0 * np.log(r2) / r2)
out[2 * i] = f * x1
if 2 * i + 1 < n:
out[2 * i + 1] = f * x2
return out
# Compile using Numba
normalsj = nb.jit(normals, nopython=True)
# Must use state address not state with numba
n = 10000
def numbacall():
return normalsj(n, state_addr)
rg = np.random.Generator(PCG64())
def numpycall():
return rg.normal(size=n)
# Check that the functions work
r1 = numbacall()
r2 = numpycall()
assert r1.shape == (n,)
assert r1.shape == r2.shape
t1 = timeit(numbacall, number=1000)
print(f'{t1:.2f} secs for {n} PCG64 (Numba/PCG64) gaussian randoms')
t2 = timeit(numpycall, number=1000)
print(f'{t2:.2f} secs for {n} PCG64 (NumPy/PCG64) gaussian randoms')
# example 2
next_u32 = bit_gen.ctypes.next_uint32
ctypes_state = bit_gen.ctypes.state
@nb.jit(nopython=True)
def bounded_uint(lb, ub, state):
mask = delta = ub - lb
mask |= mask >> 1
mask |= mask >> 2
mask |= mask >> 4
mask |= mask >> 8
mask |= mask >> 16
val = next_u32(state) & mask
while val > delta:
val = next_u32(state) & mask
return lb + val
print(bounded_uint(323, 2394691, ctypes_state.value))
@nb.jit(nopython=True)
def bounded_uints(lb, ub, n, state):
out = np.empty(n, dtype=np.uint32)
for i in range(n):
out[i] = bounded_uint(lb, ub, state)
bounded_uints(323, 2394691, 10000000, ctypes_state.value)
| from timeit import timeit
import numba as nb
import numpy as np
from numpy.random import PCG64
bit_gen = PCG64()
next_d = bit_gen.cffi.next_double
state_addr = bit_gen.cffi.state_address
def normals(n, state):
out = np.empty(n)
for i in range((n + 1) // 2):
x1 = 2.0 * next_d(state) - 1.0
x2 = 2.0 * next_d(state) - 1.0
r2 = x1 * x1 + x2 * x2
while r2 >= 1.0 or r2 == 0.0:
x1 = 2.0 * next_d(state) - 1.0
x2 = 2.0 * next_d(state) - 1.0
r2 = x1 * x1 + x2 * x2
f = np.sqrt(-2.0 * np.log(r2) / r2)
out[2 * i] = f * x1
if 2 * i + 1 < n:
out[2 * i + 1] = f * x2
return out
# Compile using Numba
normalsj = nb.jit(normals, nopython=True)
# Must use state address not state with numba
n = 10000
def numbacall():
return normalsj(n, state_addr)
rg = np.random.Generator(PCG64())
def numpycall():
return rg.normal(size=n)
# Check that the functions work
r1 = numbacall()
r2 = numpycall()
| [] | numpy/numpy | numpy/random/_examples/numba/extending.py |
import os
def parse_distributions_h(ffi, inc_dir):
"""
Parse distributions.h located in inc_dir for CFFI, filling in the ffi.cdef
Read the function declarations without the "#define ..." macros that will
be filled in when loading the library.
"""
with open(os.path.join(inc_dir, 'random', 'bitgen.h')) as fid:
s = []
for line in fid:
# massage the include file
if line.strip().startswith('#'):
continue
s.append(line)
ffi.cdef('\n'.join(s))
with open(os.path.join(inc_dir, 'random', 'distributions.h')) as fid:
s = []
in_skip = 0
ignoring = False
for line in fid:
# check for and remove extern "C" guards
if ignoring:
if line.strip().startswith('#endif'):
ignoring = False
continue
if line.strip().startswith('#ifdef __cplusplus'):
ignoring = True
# massage the include file
if line.strip().startswith('#'):
continue
# skip any inlined function definition
# which starts with 'static inline xxx(...) {'
# and ends with a closing '}'
if line.strip().startswith('static inline'):
in_skip += line.count('{')
continue
elif in_skip > 0:
in_skip += line.count('{')
in_skip -= line.count('}')
continue
# replace defines with their value or remove them
line = line.replace('DECLDIR', '')
line = line.replace('RAND_INT_TYPE', 'int64_t')
s.append(line)
ffi.cdef('\n'.join(s))
| import os
def parse_distributions_h(ffi, inc_dir):
"""
Parse distributions.h located in inc_dir for CFFI, filling in the ffi.cdef
Read the function declarations without the "#define ..." macros that will
be filled in when loading the library.
"""
with open(os.path.join(inc_dir, 'random', 'bitgen.h')) as fid:
s = []
for line in fid:
# massage the include file
if line.strip().startswith('#'):
continue
s.append(line)
ffi.cdef('\n'.join(s))
with open(os.path.join(inc_dir, 'random', 'distributions.h')) as fid:
s = []
in_skip = 0
ignoring = False
for line in fid:
# check for and remove extern "C" guards
if ignoring:
if line.strip().startswith('#endif'):
ignoring = False
continue
if line.strip().startswith('#ifdef __cplusplus'):
ignoring = True
# massage the include file
if line.strip().startswith('#'): | [] | numpy/numpy | numpy/random/_examples/cffi/parse.py |
"""
Use cffi to access any of the underlying C functions from distributions.h
"""
import os
import cffi
import numpy as np
from .parse import parse_distributions_h
ffi = cffi.FFI()
inc_dir = os.path.join(np.get_include(), 'numpy')
# Basic numpy types
ffi.cdef('''
typedef intptr_t npy_intp;
typedef unsigned char npy_bool;
''')
parse_distributions_h(ffi, inc_dir)
lib = ffi.dlopen(np.random._generator.__file__)
# Compare the distributions.h random_standard_normal_fill to
# Generator.standard_random
bit_gen = np.random.PCG64()
rng = np.random.Generator(bit_gen)
state = bit_gen.state
interface = rng.bit_generator.cffi
n = 100
vals_cffi = ffi.new('double[%d]' % n)
lib.random_standard_normal_fill(interface.bit_generator, n, vals_cffi)
# reset the state
bit_gen.state = state
vals = rng.standard_normal(n)
for i in range(n):
assert vals[i] == vals_cffi[i]
| """
Use cffi to access any of the underlying C functions from distributions.h
"""
import os
import cffi
import numpy as np
from .parse import parse_distributions_h
ffi = cffi.FFI()
inc_dir = os.path.join(np.get_include(), 'numpy')
# Basic numpy types
ffi.cdef('''
typedef intptr_t npy_intp;
typedef unsigned char npy_bool;
''')
parse_distributions_h(ffi, inc_dir)
lib = ffi.dlopen(np.random._generator.__file__)
# Compare the distributions.h random_standard_normal_fill to
# Generator.standard_random
bit_gen = np.random.PCG64()
rng = np.random.Generator(bit_gen)
state = bit_gen.state
interface = rng.bit_generator.cffi
n = 100
vals_cffi = ffi.new('double[%d]' % n)
lib.random_standard_normal_fill(interface.bit_generator, n, vals_cffi)
# reset the state
bit_gen.state = state
vals = rng.standard_normal(n)
for i in range(n):
assert vals[i] == vals_cffi[i]
| [] | numpy/numpy | numpy/random/_examples/cffi/extending.py |
"""
========================
Random Number Generation
========================
Use ``default_rng()`` to create a `Generator` and call its methods.
=============== =========================================================
Generator
--------------- ---------------------------------------------------------
Generator Class implementing all of the random number distributions
default_rng Default constructor for ``Generator``
=============== =========================================================
============================================= ===
BitGenerator Streams that work with Generator
--------------------------------------------- ---
MT19937
PCG64
PCG64DXSM
Philox
SFC64
============================================= ===
============================================= ===
Getting entropy to initialize a BitGenerator
--------------------------------------------- ---
SeedSequence
============================================= ===
Legacy
------
For backwards compatibility with previous versions of numpy before 1.17, the
various aliases to the global `RandomState` methods are left alone and do not
use the new `Generator` API.
==================== =========================================================
Utility functions
-------------------- ---------------------------------------------------------
random Uniformly distributed floats over ``[0, 1)``
bytes Uniformly distributed random bytes.
permutation Randomly permute a sequence / generate a random sequence.
shuffle Randomly permute a sequence in place.
choice Random sample from 1-D array.
==================== =========================================================
==================== =========================================================
Compatibility
functions - removed
in the new API
-------------------- ---------------------------------------------------------
rand Uniformly distributed values.
randn Normally distributed values.
ranf Uniformly distributed floating point numbers.
random_integers Uniformly distributed integers in a given range.
(deprecated, use ``integers(..., closed=True)`` instead)
random_sample Alias for `random_sample`
randint Uniformly distributed integers in a given range
seed Seed the legacy random number generator.
==================== =========================================================
==================== =========================================================
Univariate
distributions
-------------------- ---------------------------------------------------------
beta Beta distribution over ``[0, 1]``.
binomial Binomial distribution.
chisquare :math:`\\chi^2` distribution.
exponential Exponential distribution.
f F (Fisher-Snedecor) distribution.
gamma Gamma distribution.
geometric Geometric distribution.
gumbel Gumbel distribution.
hypergeometric Hypergeometric distribution.
laplace Laplace distribution.
logistic Logistic distribution.
lognormal Log-normal distribution.
logseries Logarithmic series distribution.
negative_binomial Negative binomial distribution.
noncentral_chisquare Non-central chi-square distribution.
noncentral_f Non-central F distribution.
normal Normal / Gaussian distribution.
pareto Pareto distribution.
poisson Poisson distribution.
power Power distribution.
rayleigh Rayleigh distribution.
triangular Triangular distribution.
uniform Uniform distribution.
vonmises Von Mises circular distribution.
wald Wald (inverse Gaussian) distribution.
weibull Weibull distribution.
zipf Zipf's distribution over ranked data.
==================== =========================================================
==================== ==========================================================
Multivariate
distributions
-------------------- ----------------------------------------------------------
dirichlet Multivariate generalization of Beta distribution.
multinomial Multivariate generalization of the binomial distribution.
multivariate_normal Multivariate generalization of the normal distribution.
==================== ==========================================================
==================== =========================================================
Standard
distributions
-------------------- ---------------------------------------------------------
standard_cauchy Standard Cauchy-Lorentz distribution.
standard_exponential Standard exponential distribution.
standard_gamma Standard Gamma distribution.
standard_normal Standard normal distribution.
standard_t Standard Student's t-distribution.
==================== =========================================================
==================== =========================================================
Internal functions
-------------------- ---------------------------------------------------------
get_state Get tuple representing internal state of generator.
set_state Set state of generator.
==================== =========================================================
"""
__all__ = [
'beta',
'binomial',
'bytes',
'chisquare',
'choice',
'dirichlet',
'exponential',
'f',
'gamma',
'geometric',
'get_state',
'gumbel',
'hypergeometric',
'laplace',
'logistic',
'lognormal',
'logseries',
'multinomial',
'multivariate_normal',
'negative_binomial',
'noncentral_chisquare',
'noncentral_f',
'normal',
'pareto',
'permutation',
'poisson',
'power',
'rand',
'randint',
'randn',
'random',
'random_integers',
'random_sample',
'ranf',
'rayleigh',
'sample',
'seed',
'set_state',
'shuffle',
'standard_cauchy',
'standard_exponential',
'standard_gamma',
'standard_normal',
'standard_t',
'triangular',
'uniform',
'vonmises',
'wald',
'weibull',
'zipf',
]
# add these for module-freeze analysis (like PyInstaller)
from . import _bounded_integers, _common, _pickle
from ._generator import Generator, default_rng
from ._mt19937 import MT19937
from ._pcg64 import PCG64, PCG64DXSM
from ._philox import Philox
from ._sfc64 import SFC64
from .bit_generator import BitGenerator, SeedSequence
from .mtrand import *
__all__ += ['Generator', 'RandomState', 'SeedSequence', 'MT19937',
'Philox', 'PCG64', 'PCG64DXSM', 'SFC64', 'default_rng',
'BitGenerator']
def __RandomState_ctor():
"""Return a RandomState instance.
This function exists solely to assist (un)pickling.
Note that the state of the RandomState returned here is irrelevant, as this
function's entire purpose is to return a newly allocated RandomState whose
state pickle can set. Consequently the RandomState returned by this function
is a freshly allocated copy with a seed=0.
See https://github.com/numpy/numpy/issues/4763 for a detailed discussion
"""
return RandomState(seed=0)
from numpy._pytesttester import PytestTester
test = PytestTester(__name__)
del PytestTester
| """
========================
Random Number Generation
========================
Use ``default_rng()`` to create a `Generator` and call its methods.
=============== =========================================================
Generator
--------------- ---------------------------------------------------------
Generator Class implementing all of the random number distributions
default_rng Default constructor for ``Generator``
=============== =========================================================
============================================= ===
BitGenerator Streams that work with Generator
--------------------------------------------- ---
MT19937
PCG64
PCG64DXSM
Philox
SFC64
============================================= ===
============================================= ===
Getting entropy to initialize a BitGenerator
--------------------------------------------- ---
SeedSequence
============================================= ===
Legacy
------
For backwards compatibility with previous versions of numpy before 1.17, the
various aliases to the global `RandomState` methods are left alone and do not
use the new `Generator` API.
==================== =========================================================
Utility functions
-------------------- ---------------------------------------------------------
random Uniformly distributed floats over ``[0, 1)``
bytes Uniformly distributed random bytes.
permutation Randomly permute a sequence / generate a random sequence.
shuffle Randomly permute a sequence in place.
choice Random sample from 1-D array.
==================== =========================================================
==================== =========================================================
Compatibility
functions - removed
in the new API
-------------------- ---------------------------------------------------------
rand Uniformly distributed values.
randn Normally distributed values.
ranf Uniformly distributed floating point numbers.
random_integers Uniformly distributed integers in a given range.
(deprecated, use ``integers(..., closed=True)`` instead | [
"# numpy/numpy:numpy/_pytesttester.py\nPytestTester"
] | numpy/numpy | numpy/random/__init__.py |
"""
Tests related to the ``symbol`` attribute of the ABCPolyBase class.
"""
import pytest
import numpy.polynomial as poly
from numpy._core import array
from numpy.testing import assert_, assert_equal, assert_raises
class TestInit:
"""
Test polynomial creation with symbol kwarg.
"""
c = [1, 2, 3]
def test_default_symbol(self):
p = poly.Polynomial(self.c)
assert_equal(p.symbol, 'x')
@pytest.mark.parametrize(('bad_input', 'exception'), (
('', ValueError),
('3', ValueError),
(None, TypeError),
(1, TypeError),
))
def test_symbol_bad_input(self, bad_input, exception):
with pytest.raises(exception):
p = poly.Polynomial(self.c, symbol=bad_input)
@pytest.mark.parametrize('symbol', (
'x',
'x_1',
'A',
'xyz',
'β',
))
def test_valid_symbols(self, symbol):
"""
Values for symbol that should pass input validation.
"""
p = poly.Polynomial(self.c, symbol=symbol)
assert_equal(p.symbol, symbol)
def test_property(self):
"""
'symbol' attribute is read only.
"""
p = poly.Polynomial(self.c, symbol='x')
with pytest.raises(AttributeError):
p.symbol = 'z'
def test_change_symbol(self):
p = poly.Polynomial(self.c, symbol='y')
# Create new polynomial from p with different symbol
pt = poly.Polynomial(p.coef, symbol='t')
assert_equal(pt.symbol, 't')
class TestUnaryOperators:
p = poly.Polynomial([1, 2, 3], symbol='z')
def test_neg(self):
n = -self.p
assert_equal(n.symbol, 'z')
def test_scalarmul(self):
out = self.p * 10
assert_equal(out.symbol, 'z')
def test_rscalarmul(self):
out = 10 * self.p
assert_equal(out.symbol, 'z')
def test_pow(self):
out = self.p ** 3
assert_equal(out.symbol, 'z')
@pytest.mark.parametrize(
'rhs',
(
poly.Polynomial([4, 5, 6], symbol='z'),
array([4, 5, 6]),
),
)
class TestBinaryOperatorsSameSymbol:
"""
Ensure symbol is preserved for numeric operations on polynomials with
the same symbol
"""
p = poly.Polynomial([1, 2, 3], symbol='z')
def test_add(self, rhs):
out = self.p + rhs
assert_equal(out.symbol, 'z')
def test_sub(self, rhs):
out = self.p - rhs
assert_equal(out.symbol, 'z')
def test_polymul(self, rhs):
out = self.p * rhs
assert_equal(out.symbol, 'z')
def test_divmod(self, rhs):
for out in divmod(self.p, rhs):
assert_equal(out.symbol, 'z')
def test_radd(self, rhs):
out = rhs + self.p
assert_equal(out.symbol, 'z')
def test_rsub(self, rhs):
out = rhs - self.p
assert_equal(out.symbol, 'z')
def test_rmul(self, rhs):
out = rhs * self.p
assert_equal(out.symbol, 'z')
def test_rdivmod(self, rhs):
for out in divmod(rhs, self.p):
assert_equal(out.symbol, 'z')
class TestBinaryOperatorsDifferentSymbol:
p = poly.Polynomial([1, 2, 3], symbol='x')
other = poly.Polynomial([4, 5, 6], symbol='y')
ops = (p.__add__, p.__sub__, p.__mul__, p.__floordiv__, p.__mod__)
@pytest.mark.parametrize('f', ops)
def test_binops_fails(self, f):
assert_raises(ValueError, f, self.other)
class TestEquality:
p = poly.Polynomial([1, 2, 3], symbol='x')
def test_eq(self):
other = poly.Polynomial([1, 2, 3], symbol='x')
assert_(self.p == other)
def test_neq(self):
other = poly.Polynomial([1, 2, 3], symbol='y')
assert_(not self.p == other)
class TestExtraMethods:
"""
Test other methods for manipulating/creating polynomial objects.
"""
p = poly.Polynomial([1, 2, 3, 0], symbol='z')
def test_copy(self):
other = self.p.copy()
assert_equal(other.symbol, 'z')
def test_trim(self):
other = self.p.trim()
assert_equal(other.symbol, 'z')
def test_truncate(self):
other = self.p.truncate(2)
assert_equal(other.symbol, 'z')
@pytest.mark.parametrize('kwarg', (
{'domain': [-10, 10]},
{'window': [-10, 10]},
{'kind': poly.Chebyshev},
))
def test_convert(self, kwarg):
other = self.p.convert(**kwarg)
assert_equal(other.symbol, 'z')
def test_integ(self):
other = self.p.integ()
assert_equal(other.symbol, 'z')
def test_deriv(self):
other = self.p.deriv()
assert_equal(other.symbol, 'z')
def test_composition():
p = poly.Polynomial([3, 2, 1], symbol="t")
q = poly.Polynomial([5, 1, 0, -1], symbol="λ_1")
r = p(q)
assert r.symbol == "λ_1"
#
# Class methods that result in new polynomial class instances
#
def test_fit():
x, y = (range(10),) * 2
p = poly.Polynomial.fit(x, y, deg=1, symbol='z')
assert_equal(p.symbol, 'z')
def test_froomroots():
roots = [-2, 2]
p = poly.Polynomial.fromroots(roots, symbol='z')
assert_equal(p.symbol, 'z')
def test_identity():
p = poly.Polynomial.identity(domain=[-1, 1], window=[5, 20], symbol='z')
assert_equal(p.symbol, 'z')
def test_basis():
p = poly.Polynomial.basis(3, symbol='z')
assert_equal(p.symbol, 'z')
| """
Tests related to the ``symbol`` attribute of the ABCPolyBase class.
"""
import pytest
import numpy.polynomial as poly
from numpy._core import array
from numpy.testing import assert_, assert_equal, assert_raises
class TestInit:
"""
Test polynomial creation with symbol kwarg.
"""
c = [1, 2, 3]
def test_default_symbol(self):
p = poly.Polynomial(self.c)
assert_equal(p.symbol, 'x')
@pytest.mark.parametrize(('bad_input', 'exception'), (
('', ValueError),
('3', ValueError),
(None, TypeError),
(1, TypeError),
))
def test_symbol_bad_input(self, bad_input, exception):
with pytest.raises(exception):
p = poly.Polynomial(self.c, symbol=bad_input)
@pytest.mark.parametrize('symbol', (
'x',
'x_1',
'A',
'xyz',
'β',
))
def test_valid_symbols(self, symbol):
"""
Values for symbol that should pass input validation.
"""
p = poly.Polynomial(self.c, symbol=symbol)
assert_equal(p.symbol, symbol)
def test_property(self):
| [
"# numpy/numpy:numpy/_core/records.py\narray",
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_",
"# numpy/numpy:numpy/lib/_polynomial_impl.py\npoly"
] | numpy/numpy | numpy/polynomial/tests/test_symbol.py |
from decimal import Decimal
# For testing polynomial printing with object arrays
from fractions import Fraction
from math import inf, nan
import pytest
import numpy.polynomial as poly
from numpy._core import arange, array, printoptions
from numpy.testing import assert_, assert_equal
class TestStrUnicodeSuperSubscripts:
@pytest.fixture(scope='class', autouse=True)
def use_unicode(self):
poly.set_default_printstyle('unicode')
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0·x + 3.0·x²"),
([-1, 0, 3, -1], "-1.0 + 0.0·x + 3.0·x² - 1.0·x³"),
(arange(12), ("0.0 + 1.0·x + 2.0·x² + 3.0·x³ + 4.0·x⁴ + 5.0·x⁵ + "
"6.0·x⁶ + 7.0·x⁷ +\n8.0·x⁸ + 9.0·x⁹ + 10.0·x¹⁰ + "
"11.0·x¹¹")),
))
def test_polynomial_str(self, inp, tgt):
p = poly.Polynomial(inp)
res = str(p)
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0·T₁(x) + 3.0·T₂(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0·T₁(x) + 3.0·T₂(x) - 1.0·T₃(x)"),
(arange(12), ("0.0 + 1.0·T₁(x) + 2.0·T₂(x) + 3.0·T₃(x) + 4.0·T₄(x) + "
"5.0·T₅(x) +\n6.0·T₆(x) + 7.0·T₇(x) + 8.0·T₈(x) + "
"9.0·T₉(x) + 10.0·T₁₀(x) + 11.0·T₁₁(x)")),
))
def test_chebyshev_str(self, inp, tgt):
res = str(poly.Chebyshev(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0·P₁(x) + 3.0·P₂(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0·P₁(x) + 3.0·P₂(x) - 1.0·P₃(x)"),
(arange(12), ("0.0 + 1.0·P₁(x) + 2.0·P₂(x) + 3.0·P₃(x) + 4.0·P₄(x) + "
"5.0·P₅(x) +\n6.0·P₆(x) + 7.0·P₇(x) + 8.0·P₈(x) + "
"9.0·P₉(x) + 10.0·P₁₀(x) + 11.0·P₁₁(x)")),
))
def test_legendre_str(self, inp, tgt):
res = str(poly.Legendre(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0·H₁(x) + 3.0·H₂(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0·H₁(x) + 3.0·H₂(x) - 1.0·H₃(x)"),
(arange(12), ("0.0 + 1.0·H₁(x) + 2.0·H₂(x) + 3.0·H₃(x) + 4.0·H₄(x) + "
"5.0·H₅(x) +\n6.0·H₆(x) + 7.0·H₇(x) + 8.0·H₈(x) + "
"9.0·H₉(x) + 10.0·H₁₀(x) + 11.0·H₁₁(x)")),
))
def test_hermite_str(self, inp, tgt):
res = str(poly.Hermite(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0·He₁(x) + 3.0·He₂(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0·He₁(x) + 3.0·He₂(x) - 1.0·He₃(x)"),
(arange(12), ("0.0 + 1.0·He₁(x) + 2.0·He₂(x) + 3.0·He₃(x) + "
"4.0·He₄(x) + 5.0·He₅(x) +\n6.0·He₆(x) + 7.0·He₇(x) + "
"8.0·He₈(x) + 9.0·He₉(x) + 10.0·He₁₀(x) +\n"
"11.0·He₁₁(x)")),
))
def test_hermiteE_str(self, inp, tgt):
res = str(poly.HermiteE(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0·L₁(x) + 3.0·L₂(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0·L₁(x) + 3.0·L₂(x) - 1.0·L₃(x)"),
(arange(12), ("0.0 + 1.0·L₁(x) + 2.0·L₂(x) + 3.0·L₃(x) + 4.0·L₄(x) + "
"5.0·L₅(x) +\n6.0·L₆(x) + 7.0·L₇(x) + 8.0·L₈(x) + "
"9.0·L₉(x) + 10.0·L₁₀(x) + 11.0·L₁₁(x)")),
))
def test_laguerre_str(self, inp, tgt):
res = str(poly.Laguerre(inp))
assert_equal(res, tgt)
def test_polynomial_str_domains(self):
res = str(poly.Polynomial([0, 1]))
tgt = '0.0 + 1.0·x'
assert_equal(res, tgt)
res = str(poly.Polynomial([0, 1], domain=[1, 2]))
tgt = '0.0 + 1.0·(-3.0 + 2.0x)'
assert_equal(res, tgt)
class TestStrAscii:
@pytest.fixture(scope='class', autouse=True)
def use_ascii(self):
poly.set_default_printstyle('ascii')
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0 x + 3.0 x**2"),
([-1, 0, 3, -1], "-1.0 + 0.0 x + 3.0 x**2 - 1.0 x**3"),
(arange(12), ("0.0 + 1.0 x + 2.0 x**2 + 3.0 x**3 + 4.0 x**4 + "
"5.0 x**5 + 6.0 x**6 +\n7.0 x**7 + 8.0 x**8 + "
"9.0 x**9 + 10.0 x**10 + 11.0 x**11")),
))
def test_polynomial_str(self, inp, tgt):
res = str(poly.Polynomial(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0 T_1(x) + 3.0 T_2(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0 T_1(x) + 3.0 T_2(x) - 1.0 T_3(x)"),
(arange(12), ("0.0 + 1.0 T_1(x) + 2.0 T_2(x) + 3.0 T_3(x) + "
"4.0 T_4(x) + 5.0 T_5(x) +\n6.0 T_6(x) + 7.0 T_7(x) + "
"8.0 T_8(x) + 9.0 T_9(x) + 10.0 T_10(x) +\n"
"11.0 T_11(x)")),
))
def test_chebyshev_str(self, inp, tgt):
res = str(poly.Chebyshev(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0 P_1(x) + 3.0 P_2(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0 P_1(x) + 3.0 P_2(x) - 1.0 P_3(x)"),
(arange(12), ("0.0 + 1.0 P_1(x) + 2.0 P_2(x) + 3.0 P_3(x) + "
"4.0 P_4(x) + 5.0 P_5(x) +\n6.0 P_6(x) + 7.0 P_7(x) + "
"8.0 P_8(x) + 9.0 P_9(x) + 10.0 P_10(x) +\n"
"11.0 P_11(x)")),
))
def test_legendre_str(self, inp, tgt):
res = str(poly.Legendre(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0 H_1(x) + 3.0 H_2(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0 H_1(x) + 3.0 H_2(x) - 1.0 H_3(x)"),
(arange(12), ("0.0 + 1.0 H_1(x) + 2.0 H_2(x) + 3.0 H_3(x) + "
"4.0 H_4(x) + 5.0 H_5(x) +\n6.0 H_6(x) + 7.0 H_7(x) + "
"8.0 H_8(x) + 9.0 H_9(x) + 10.0 H_10(x) +\n"
"11.0 H_11(x)")),
))
def test_hermite_str(self, inp, tgt):
res = str(poly.Hermite(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0 He_1(x) + 3.0 He_2(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0 He_1(x) + 3.0 He_2(x) - 1.0 He_3(x)"),
(arange(12), ("0.0 + 1.0 He_1(x) + 2.0 He_2(x) + 3.0 He_3(x) + "
"4.0 He_4(x) +\n5.0 He_5(x) + 6.0 He_6(x) + "
"7.0 He_7(x) + 8.0 He_8(x) + 9.0 He_9(x) +\n"
"10.0 He_10(x) + 11.0 He_11(x)")),
))
def test_hermiteE_str(self, inp, tgt):
res = str(poly.HermiteE(inp))
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0 L_1(x) + 3.0 L_2(x)"),
([-1, 0, 3, -1], "-1.0 + 0.0 L_1(x) + 3.0 L_2(x) - 1.0 L_3(x)"),
(arange(12), ("0.0 + 1.0 L_1(x) + 2.0 L_2(x) + 3.0 L_3(x) + "
"4.0 L_4(x) + 5.0 L_5(x) +\n6.0 L_6(x) + 7.0 L_7(x) + "
"8.0 L_8(x) + 9.0 L_9(x) + 10.0 L_10(x) +\n"
"11.0 L_11(x)")),
))
def test_laguerre_str(self, inp, tgt):
res = str(poly.Laguerre(inp))
assert_equal(res, tgt)
def test_polynomial_str_domains(self):
res = str(poly.Polynomial([0, 1]))
tgt = '0.0 + 1.0 x'
assert_equal(res, tgt)
res = str(poly.Polynomial([0, 1], domain=[1, 2]))
tgt = '0.0 + 1.0 (-3.0 + 2.0x)'
assert_equal(res, tgt)
class TestLinebreaking:
@pytest.fixture(scope='class', autouse=True)
def use_ascii(self):
poly.set_default_printstyle('ascii')
def test_single_line_one_less(self):
# With 'ascii' style, len(str(p)) is default linewidth - 1 (i.e. 74)
p = poly.Polynomial([12345678, 12345678, 12345678, 12345678, 123])
assert_equal(len(str(p)), 74)
assert_equal(str(p), (
'12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
'12345678.0 x**3 + 123.0 x**4'
))
def test_num_chars_is_linewidth(self):
# len(str(p)) == default linewidth == 75
p = poly.Polynomial([12345678, 12345678, 12345678, 12345678, 1234])
assert_equal(len(str(p)), 75)
assert_equal(str(p), (
'12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
'12345678.0 x**3 +\n1234.0 x**4'
))
def test_first_linebreak_multiline_one_less_than_linewidth(self):
# Multiline str where len(first_line) + len(next_term) == lw - 1 == 74
p = poly.Polynomial(
[12345678, 12345678, 12345678, 12345678, 1, 12345678]
)
assert_equal(len(str(p).split('\n')[0]), 74)
assert_equal(str(p), (
'12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
'12345678.0 x**3 + 1.0 x**4 +\n12345678.0 x**5'
))
def test_first_linebreak_multiline_on_linewidth(self):
# First line is one character longer than previous test
p = poly.Polynomial(
[12345678, 12345678, 12345678, 12345678.12, 1, 12345678]
)
assert_equal(str(p), (
'12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
'12345678.12 x**3 +\n1.0 x**4 + 12345678.0 x**5'
))
@pytest.mark.parametrize(('lw', 'tgt'), (
(75, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 + 40000.0 x**4 + '
'500000.0 x**5 +\n600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 + '
'900.0 x**9')),
(45, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 +\n40000.0 x**4 + '
'500000.0 x**5 +\n600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 +\n'
'900.0 x**9')),
(132, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 + 40000.0 x**4 + '
'500000.0 x**5 + 600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 + '
'900.0 x**9')),
))
def test_linewidth_printoption(self, lw, tgt):
p = poly.Polynomial(
[0, 10, 200, 3000, 40000, 500000, 600000, 70000, 8000, 900]
)
with printoptions(linewidth=lw):
assert_equal(str(p), tgt)
for line in str(p).split('\n'):
assert_(len(line) < lw)
@pytest.mark.thread_unsafe(reason="set_default_printstyle() is global state")
def test_set_default_printoptions():
p = poly.Polynomial([1, 2, 3])
c = poly.Chebyshev([1, 2, 3])
poly.set_default_printstyle('ascii')
assert_equal(str(p), "1.0 + 2.0 x + 3.0 x**2")
assert_equal(str(c), "1.0 + 2.0 T_1(x) + 3.0 T_2(x)")
poly.set_default_printstyle('unicode')
assert_equal(str(p), "1.0 + 2.0·x + 3.0·x²")
assert_equal(str(c), "1.0 + 2.0·T₁(x) + 3.0·T₂(x)")
with pytest.raises(ValueError):
poly.set_default_printstyle('invalid_input')
@pytest.mark.thread_unsafe(reason="set_default_printstyle() is global state")
def test_complex_coefficients():
"""Test both numpy and built-in complex."""
coefs = [0 + 1j, 1 + 1j, -2 + 2j, 3 + 0j]
# numpy complex
p1 = poly.Polynomial(coefs)
# Python complex
p2 = poly.Polynomial(array(coefs, dtype=object))
poly.set_default_printstyle('unicode')
assert_equal(str(p1), "1j + (1+1j)·x - (2-2j)·x² + (3+0j)·x³")
assert_equal(str(p2), "1j + (1+1j)·x + (-2+2j)·x² + (3+0j)·x³")
poly.set_default_printstyle('ascii')
assert_equal(str(p1), "1j + (1+1j) x - (2-2j) x**2 + (3+0j) x**3")
assert_equal(str(p2), "1j + (1+1j) x + (-2+2j) x**2 + (3+0j) x**3")
@pytest.mark.parametrize(('coefs', 'tgt'), (
(array([Fraction(1, 2), Fraction(3, 4)], dtype=object), (
"1/2 + 3/4·x"
)),
(array([1, 2, Fraction(5, 7)], dtype=object), (
"1 + 2·x + 5/7·x²"
)),
(array([Decimal('1.00'), Decimal('2.2'), 3], dtype=object), (
"1.00 + 2.2·x + 3·x²"
)),
))
def test_numeric_object_coefficients(coefs, tgt):
p = poly.Polynomial(coefs)
poly.set_default_printstyle('unicode')
assert_equal(str(p), tgt)
@pytest.mark.parametrize(('coefs', 'tgt'), (
(array([1, 2, 'f'], dtype=object), '1 + 2·x + f·x²'),
(array([1, 2, [3, 4]], dtype=object), '1 + 2·x + [3, 4]·x²'),
))
def test_nonnumeric_object_coefficients(coefs, tgt):
"""
Test coef fallback for object arrays of non-numeric coefficients.
"""
p = poly.Polynomial(coefs)
poly.set_default_printstyle('unicode')
assert_equal(str(p), tgt)
class TestFormat:
def test_format_unicode(self):
poly.set_default_printstyle('ascii')
p = poly.Polynomial([1, 2, 0, -1])
assert_equal(format(p, 'unicode'), "1.0 + 2.0·x + 0.0·x² - 1.0·x³")
def test_format_ascii(self):
poly.set_default_printstyle('unicode')
p = poly.Polynomial([1, 2, 0, -1])
assert_equal(
format(p, 'ascii'), "1.0 + 2.0 x + 0.0 x**2 - 1.0 x**3"
)
def test_empty_formatstr(self):
poly.set_default_printstyle('ascii')
p = poly.Polynomial([1, 2, 3])
assert_equal(format(p), "1.0 + 2.0 x + 3.0 x**2")
assert_equal(f"{p}", "1.0 + 2.0 x + 3.0 x**2")
def test_bad_formatstr(self):
p = poly.Polynomial([1, 2, 0, -1])
with pytest.raises(ValueError):
format(p, '.2f')
@pytest.mark.parametrize(('poly', 'tgt'), (
(poly.Polynomial, '1.0 + 2.0·z + 3.0·z²'),
(poly.Chebyshev, '1.0 + 2.0·T₁(z) + 3.0·T₂(z)'),
(poly.Hermite, '1.0 + 2.0·H₁(z) + 3.0·H₂(z)'),
(poly.HermiteE, '1.0 + 2.0·He₁(z) + 3.0·He₂(z)'),
(poly.Laguerre, '1.0 + 2.0·L₁(z) + 3.0·L₂(z)'),
(poly.Legendre, '1.0 + 2.0·P₁(z) + 3.0·P₂(z)'),
))
def test_symbol(poly, tgt):
p = poly([1, 2, 3], symbol='z')
assert_equal(f"{p:unicode}", tgt)
class TestRepr:
def test_polynomial_repr(self):
res = repr(poly.Polynomial([0, 1]))
tgt = (
"Polynomial([0., 1.], domain=[-1., 1.], window=[-1., 1.], "
"symbol='x')"
)
assert_equal(res, tgt)
def test_chebyshev_repr(self):
res = repr(poly.Chebyshev([0, 1]))
tgt = (
"Chebyshev([0., 1.], domain=[-1., 1.], window=[-1., 1.], "
"symbol='x')"
)
assert_equal(res, tgt)
def test_legendre_repr(self):
res = repr(poly.Legendre([0, 1]))
tgt = (
"Legendre([0., 1.], domain=[-1., 1.], window=[-1., 1.], "
"symbol='x')"
)
assert_equal(res, tgt)
def test_hermite_repr(self):
res = repr(poly.Hermite([0, 1]))
tgt = (
"Hermite([0., 1.], domain=[-1., 1.], window=[-1., 1.], "
"symbol='x')"
)
assert_equal(res, tgt)
def test_hermiteE_repr(self):
res = repr(poly.HermiteE([0, 1]))
tgt = (
"HermiteE([0., 1.], domain=[-1., 1.], window=[-1., 1.], "
"symbol='x')"
)
assert_equal(res, tgt)
def test_laguerre_repr(self):
res = repr(poly.Laguerre([0, 1]))
tgt = (
"Laguerre([0., 1.], domain=[0., 1.], window=[0., 1.], "
"symbol='x')"
)
assert_equal(res, tgt)
class TestLatexRepr:
"""Test the latex repr used by Jupyter"""
@staticmethod
def as_latex(obj):
# right now we ignore the formatting of scalars in our tests, since
# it makes them too verbose. Ideally, the formatting of scalars will
# be fixed such that tests below continue to pass
obj._repr_latex_scalar = lambda x, parens=False: str(x)
try:
return obj._repr_latex_()
finally:
del obj._repr_latex_scalar
def test_simple_polynomial(self):
# default input
p = poly.Polynomial([1, 2, 3])
assert_equal(self.as_latex(p),
r'$x \mapsto 1.0 + 2.0\,x + 3.0\,x^{2}$')
# translated input
p = poly.Polynomial([1, 2, 3], domain=[-2, 0])
assert_equal(self.as_latex(p),
r'$x \mapsto 1.0 + 2.0\,\left(1.0 + x\right) + 3.0\,\left(1.0 + x\right)^{2}$') # noqa: E501
# scaled input
p = poly.Polynomial([1, 2, 3], domain=[-0.5, 0.5])
assert_equal(self.as_latex(p),
r'$x \mapsto 1.0 + 2.0\,\left(2.0x\right) + 3.0\,\left(2.0x\right)^{2}$')
# affine input
p = poly.Polynomial([1, 2, 3], domain=[-1, 0])
assert_equal(self.as_latex(p),
r'$x \mapsto 1.0 + 2.0\,\left(1.0 + 2.0x\right) + 3.0\,\left(1.0 + 2.0x\right)^{2}$') # noqa: E501
def test_basis_func(self):
p = poly.Chebyshev([1, 2, 3])
assert_equal(self.as_latex(p),
r'$x \mapsto 1.0\,{T}_{0}(x) + 2.0\,{T}_{1}(x) + 3.0\,{T}_{2}(x)$')
# affine input - check no surplus parens are added
p = poly.Chebyshev([1, 2, 3], domain=[-1, 0])
assert_equal(self.as_latex(p),
r'$x \mapsto 1.0\,{T}_{0}(1.0 + 2.0x) + 2.0\,{T}_{1}(1.0 + 2.0x) + 3.0\,{T}_{2}(1.0 + 2.0x)$') # noqa: E501
def test_multichar_basis_func(self):
p = poly.HermiteE([1, 2, 3])
assert_equal(self.as_latex(p),
r'$x \mapsto 1.0\,{He}_{0}(x) + 2.0\,{He}_{1}(x) + 3.0\,{He}_{2}(x)$')
def test_symbol_basic(self):
# default input
p = poly.Polynomial([1, 2, 3], symbol='z')
assert_equal(self.as_latex(p),
r'$z \mapsto 1.0 + 2.0\,z + 3.0\,z^{2}$')
# translated input
p = poly.Polynomial([1, 2, 3], domain=[-2, 0], symbol='z')
assert_equal(
self.as_latex(p),
(
r'$z \mapsto 1.0 + 2.0\,\left(1.0 + z\right) + 3.0\,'
r'\left(1.0 + z\right)^{2}$'
),
)
# scaled input
p = poly.Polynomial([1, 2, 3], domain=[-0.5, 0.5], symbol='z')
assert_equal(
self.as_latex(p),
(
r'$z \mapsto 1.0 + 2.0\,\left(2.0z\right) + 3.0\,'
r'\left(2.0z\right)^{2}$'
),
)
# affine input
p = poly.Polynomial([1, 2, 3], domain=[-1, 0], symbol='z')
assert_equal(
self.as_latex(p),
(
r'$z \mapsto 1.0 + 2.0\,\left(1.0 + 2.0z\right) + 3.0\,'
r'\left(1.0 + 2.0z\right)^{2}$'
),
)
def test_numeric_object_coefficients(self):
coefs = array([Fraction(1, 2), Fraction(1)])
p = poly.Polynomial(coefs)
assert_equal(self.as_latex(p), '$x \\mapsto 1/2 + 1\\,x$')
SWITCH_TO_EXP = (
'1.0 + (1.0e-01) x + (1.0e-02) x**2',
'1.2 + (1.2e-01) x + (1.2e-02) x**2',
'1.23 + 0.12 x + (1.23e-02) x**2 + (1.23e-03) x**3',
'1.235 + 0.123 x + (1.235e-02) x**2 + (1.235e-03) x**3',
'1.2346 + 0.1235 x + 0.0123 x**2 + (1.2346e-03) x**3 + (1.2346e-04) x**4',
('1.23457 + 0.12346 x + 0.01235 x**2 + (1.23457e-03) x**3 + '
'(1.23457e-04) x**4'),
('1.234568 + 0.123457 x + 0.012346 x**2 + 0.001235 x**3 + '
'(1.234568e-04) x**4 + (1.234568e-05) x**5'),
('1.2345679 + 0.1234568 x + 0.0123457 x**2 + 0.0012346 x**3 + '
'(1.2345679e-04) x**4 + (1.2345679e-05) x**5')
)
class TestPrintOptions:
"""
Test the output is properly configured via printoptions.
The exponential notation is enabled automatically when the values
are too small or too large.
"""
@pytest.fixture(scope='class', autouse=True)
def use_ascii(self):
poly.set_default_printstyle('ascii')
def test_str(self):
p = poly.Polynomial([1 / 2, 1 / 7, 1 / 7 * 10**8, 1 / 7 * 10**9])
assert_equal(str(p), '0.5 + 0.14285714 x + 14285714.28571429 x**2 '
'+ (1.42857143e+08) x**3')
with printoptions(precision=3):
assert_equal(str(p), '0.5 + 0.143 x + 14285714.286 x**2 '
'+ (1.429e+08) x**3')
def test_latex(self):
p = poly.Polynomial([1 / 2, 1 / 7, 1 / 7 * 10**8, 1 / 7 * 10**9])
assert_equal(p._repr_latex_(),
r'$x \mapsto \text{0.5} + \text{0.14285714}\,x + '
r'\text{14285714.28571429}\,x^{2} + '
r'\text{(1.42857143e+08)}\,x^{3}$')
with printoptions(precision=3):
assert_equal(p._repr_latex_(),
r'$x \mapsto \text{0.5} + \text{0.143}\,x + '
r'\text{14285714.286}\,x^{2} + \text{(1.429e+08)}\,x^{3}$')
def test_fixed(self):
p = poly.Polynomial([1 / 2])
assert_equal(str(p), '0.5')
with printoptions(floatmode='fixed'):
assert_equal(str(p), '0.50000000')
with printoptions(floatmode='fixed', precision=4):
assert_equal(str(p), '0.5000')
def test_switch_to_exp(self):
for i, s in enumerate(SWITCH_TO_EXP):
with printoptions(precision=i):
p = poly.Polynomial([1.23456789 * 10**-i
for i in range(i // 2 + 3)])
assert str(p).replace('\n', ' ') == s
def test_non_finite(self):
p = poly.Polynomial([nan, inf])
assert str(p) == 'nan + inf x'
assert p._repr_latex_() == r'$x \mapsto \text{nan} + \text{inf}\,x$'
with printoptions(nanstr='NAN', infstr='INF'):
assert str(p) == 'NAN + INF x'
assert p._repr_latex_() == \
r'$x \mapsto \text{NAN} + \text{INF}\,x$'
| from decimal import Decimal
# For testing polynomial printing with object arrays
from fractions import Fraction
from math import inf, nan
import pytest
import numpy.polynomial as poly
from numpy._core import arange, array, printoptions
from numpy.testing import assert_, assert_equal
class TestStrUnicodeSuperSubscripts:
@pytest.fixture(scope='class', autouse=True)
def use_unicode(self):
poly.set_default_printstyle('unicode')
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3], "1.0 + 2.0·x + 3.0·x²"),
([-1, 0, 3, -1], "-1.0 + 0.0·x + 3.0·x² - 1.0·x³"),
(arange(12), ("0.0 + 1.0·x + 2.0·x² + 3.0·x³ + 4.0·x⁴ + 5.0·x⁵ + "
"6.0·x⁶ + 7.0·x⁷ +\n8.0·x⁸ + 9.0·x⁹ + 10.0·x¹⁰ + "
"11.0·x¹¹")),
))
def test_polynomial_str(self, inp, tgt):
p = poly.Polynomial(inp)
res = str(p)
assert_equal(res, tgt)
@pytest.mark.parametrize(('inp', 'tgt'), (
([1, 2, 3 | [
"# numpy/numpy:numpy/testing/_private/utils.py\nassert_",
"# numpy/numpy:numpy/lib/_polynomial_impl.py\npoly",
"# numpy/numpy:numpy/_core/arrayprint.py\nprintoptions",
"# numpy/numpy:numpy/_core/records.py\narray"
] | numpy/numpy | numpy/polynomial/tests/test_printing.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.