Dataset Viewer
Auto-converted to Parquet Duplicate
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
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
6