Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/tests/test_umath.py
from __future__ import division, absolute_import, print_function import sys import platform import warnings import fnmatch import itertools import numpy.core.umath as ncu from numpy.core import umath_tests as ncu_tests import numpy as np from numpy.testing import ( run_module_suite, assert_, assert_equal, assert_raises, assert_raises_regex, assert_array_equal, assert_almost_equal, assert_array_almost_equal, dec, assert_allclose, assert_no_warnings, suppress_warnings, _gen_alignment_data, ) def on_powerpc(): """ True if we are running on a Power PC platform.""" return platform.processor() == 'powerpc' or \ platform.machine().startswith('ppc') class _FilterInvalids(object): def setUp(self): self.olderr = np.seterr(invalid='ignore') def tearDown(self): np.seterr(**self.olderr) class TestConstants(object): def test_pi(self): assert_allclose(ncu.pi, 3.141592653589793, 1e-15) def test_e(self): assert_allclose(ncu.e, 2.718281828459045, 1e-15) def test_euler_gamma(self): assert_allclose(ncu.euler_gamma, 0.5772156649015329, 1e-15) class TestOut(object): def test_out_subok(self): for subok in (True, False): a = np.array(0.5) o = np.empty(()) r = np.add(a, 2, o, subok=subok) assert_(r is o) r = np.add(a, 2, out=o, subok=subok) assert_(r is o) r = np.add(a, 2, out=(o,), subok=subok) assert_(r is o) d = np.array(5.7) o1 = np.empty(()) o2 = np.empty((), dtype=np.int32) r1, r2 = np.frexp(d, o1, None, subok=subok) assert_(r1 is o1) r1, r2 = np.frexp(d, None, o2, subok=subok) assert_(r2 is o2) r1, r2 = np.frexp(d, o1, o2, subok=subok) assert_(r1 is o1) assert_(r2 is o2) r1, r2 = np.frexp(d, out=(o1, None), subok=subok) assert_(r1 is o1) r1, r2 = np.frexp(d, out=(None, o2), subok=subok) assert_(r2 is o2) r1, r2 = np.frexp(d, out=(o1, o2), subok=subok) assert_(r1 is o1) assert_(r2 is o2) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', DeprecationWarning) r1, r2 = np.frexp(d, out=o1, subok=subok) assert_(r1 is o1) assert_(w[0].category is DeprecationWarning) assert_raises(ValueError, np.add, a, 2, o, o, subok=subok) assert_raises(ValueError, np.add, a, 2, o, out=o, subok=subok) assert_raises(ValueError, np.add, a, 2, None, out=o, subok=subok) assert_raises(ValueError, np.add, a, 2, out=(o, o), subok=subok) assert_raises(ValueError, np.add, a, 2, out=(), subok=subok) assert_raises(TypeError, np.add, a, 2, [], subok=subok) assert_raises(TypeError, np.add, a, 2, out=[], subok=subok) assert_raises(TypeError, np.add, a, 2, out=([],), subok=subok) o.flags.writeable = False assert_raises(ValueError, np.add, a, 2, o, subok=subok) assert_raises(ValueError, np.add, a, 2, out=o, subok=subok) assert_raises(ValueError, np.add, a, 2, out=(o,), subok=subok) def test_out_wrap_subok(self): class ArrayWrap(np.ndarray): __array_priority__ = 10 def __new__(cls, arr): return np.asarray(arr).view(cls).copy() def __array_wrap__(self, arr, context): return arr.view(type(self)) for subok in (True, False): a = ArrayWrap([0.5]) r = np.add(a, 2, subok=subok) if subok: assert_(isinstance(r, ArrayWrap)) else: assert_(type(r) == np.ndarray) r = np.add(a, 2, None, subok=subok) if subok: assert_(isinstance(r, ArrayWrap)) else: assert_(type(r) == np.ndarray) r = np.add(a, 2, out=None, subok=subok) if subok: assert_(isinstance(r, ArrayWrap)) else: assert_(type(r) == np.ndarray) r = np.add(a, 2, out=(None,), subok=subok) if subok: assert_(isinstance(r, ArrayWrap)) else: assert_(type(r) == np.ndarray) d = ArrayWrap([5.7]) o1 = np.empty((1,)) o2 = np.empty((1,), dtype=np.int32) r1, r2 = np.frexp(d, o1, subok=subok) if subok: assert_(isinstance(r2, ArrayWrap)) else: assert_(type(r2) == np.ndarray) r1, r2 = np.frexp(d, o1, None, subok=subok) if subok: assert_(isinstance(r2, ArrayWrap)) else: assert_(type(r2) == np.ndarray) r1, r2 = np.frexp(d, None, o2, subok=subok) if subok: assert_(isinstance(r1, ArrayWrap)) else: assert_(type(r1) == np.ndarray) r1, r2 = np.frexp(d, out=(o1, None), subok=subok) if subok: assert_(isinstance(r2, ArrayWrap)) else: assert_(type(r2) == np.ndarray) r1, r2 = np.frexp(d, out=(None, o2), subok=subok) if subok: assert_(isinstance(r1, ArrayWrap)) else: assert_(type(r1) == np.ndarray) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', DeprecationWarning) r1, r2 = np.frexp(d, out=o1, subok=subok) if subok: assert_(isinstance(r2, ArrayWrap)) else: assert_(type(r2) == np.ndarray) assert_(w[0].category is DeprecationWarning) class TestComparisons(object): def test_ignore_object_identity_in_equal(self): # Check error raised when comparing identical objects whose comparison # is not a simple boolean, e.g., arrays that are compared elementwise. a = np.array([np.array([1, 2, 3]), None], dtype=object) assert_raises(ValueError, np.equal, a, a) # Check error raised when comparing identical non-comparable objects. class FunkyType(object): def __eq__(self, other): raise TypeError("I won't compare") a = np.array([FunkyType()]) assert_raises(TypeError, np.equal, a, a) # Check identity doesn't override comparison mismatch. a = np.array([np.nan], dtype=object) assert_equal(np.equal(a, a), [False]) def test_ignore_object_identity_in_not_equal(self): # Check error raised when comparing identical objects whose comparison # is not a simple boolean, e.g., arrays that are compared elementwise. a = np.array([np.array([1, 2, 3]), None], dtype=object) assert_raises(ValueError, np.not_equal, a, a) # Check error raised when comparing identical non-comparable objects. class FunkyType(object): def __ne__(self, other): raise TypeError("I won't compare") a = np.array([FunkyType()]) assert_raises(TypeError, np.not_equal, a, a) # Check identity doesn't override comparison mismatch. a = np.array([np.nan], dtype=object) assert_equal(np.not_equal(a, a), [True]) class TestAdd(object): def test_reduce_alignment(self): # gh-9876 # make sure arrays with weird strides work with the optimizations in # pairwise_sum_@TYPE@. On x86, the 'b' field will count as aligned at a # 4 byte offset, even though its itemsize is 8. a = np.zeros(2, dtype=[('a', np.int32), ('b', np.float64)]) a['a'] = -1 assert_equal(a['b'].sum(), 0) class TestDivision(object): def test_division_int(self): # int division should follow Python x = np.array([5, 10, 90, 100, -5, -10, -90, -100, -120]) if 5 / 10 == 0.5: assert_equal(x / 100, [0.05, 0.1, 0.9, 1, -0.05, -0.1, -0.9, -1, -1.2]) else: assert_equal(x / 100, [0, 0, 0, 1, -1, -1, -1, -1, -2]) assert_equal(x // 100, [0, 0, 0, 1, -1, -1, -1, -1, -2]) assert_equal(x % 100, [5, 10, 90, 0, 95, 90, 10, 0, 80]) def test_division_complex(self): # check that implementation is correct msg = "Complex division implementation check" x = np.array([1. + 1.*1j, 1. + .5*1j, 1. + 2.*1j], dtype=np.complex128) assert_almost_equal(x**2/x, x, err_msg=msg) # check overflow, underflow msg = "Complex division overflow/underflow check" x = np.array([1.e+110, 1.e-110], dtype=np.complex128) y = x**2/x assert_almost_equal(y/x, [1, 1], err_msg=msg) def test_zero_division_complex(self): with np.errstate(invalid="ignore", divide="ignore"): x = np.array([0.0], dtype=np.complex128) y = 1.0/x assert_(np.isinf(y)[0]) y = complex(np.inf, np.nan)/x assert_(np.isinf(y)[0]) y = complex(np.nan, np.inf)/x assert_(np.isinf(y)[0]) y = complex(np.inf, np.inf)/x assert_(np.isinf(y)[0]) y = 0.0/x assert_(np.isnan(y)[0]) def test_floor_division_complex(self): # check that implementation is correct msg = "Complex floor division implementation check" x = np.array([.9 + 1j, -.1 + 1j, .9 + .5*1j, .9 + 2.*1j], dtype=np.complex128) y = np.array([0., -1., 0., 0.], dtype=np.complex128) assert_equal(np.floor_divide(x**2, x), y, err_msg=msg) # check overflow, underflow msg = "Complex floor division overflow/underflow check" x = np.array([1.e+110, 1.e-110], dtype=np.complex128) y = np.floor_divide(x**2, x) assert_equal(y, [1.e+110, 0], err_msg=msg) def floor_divide_and_remainder(x, y): return (np.floor_divide(x, y), np.remainder(x, y)) def _signs(dt): if dt in np.typecodes['UnsignedInteger']: return (+1,) else: return (+1, -1) class TestRemainder(object): def test_remainder_basic(self): dt = np.typecodes['AllInteger'] + np.typecodes['Float'] for op in [floor_divide_and_remainder, np.divmod]: for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product(_signs(dt1), _signs(dt2)): fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (op.__name__, dt1, dt2, sg1, sg2) a = np.array(sg1*71, dtype=dt1) b = np.array(sg2*19, dtype=dt2) div, rem = op(a, b) assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg) def test_float_remainder_exact(self): # test that float results are exact for small integers. This also # holds for the same integers scaled by powers of two. nlst = list(range(-127, 0)) plst = list(range(1, 128)) dividend = nlst + [0] + plst divisor = nlst + plst arg = list(itertools.product(dividend, divisor)) tgt = list(divmod(*t) for t in arg) a, b = np.array(arg, dtype=int).T # convert exact integer results from Python to float so that # signed zero can be used, it is checked. tgtdiv, tgtrem = np.array(tgt, dtype=float).T tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv) tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem) for op in [floor_divide_and_remainder, np.divmod]: for dt in np.typecodes['Float']: msg = 'op: %s, dtype: %s' % (op.__name__, dt) fa = a.astype(dt) fb = b.astype(dt) div, rem = op(fa, fb) assert_equal(div, tgtdiv, err_msg=msg) assert_equal(rem, tgtrem, err_msg=msg) def test_float_remainder_roundoff(self): # gh-6127 dt = np.typecodes['Float'] for op in [floor_divide_and_remainder, np.divmod]: for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product((+1, -1), (+1, -1)): fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (op.__name__, dt1, dt2, sg1, sg2) a = np.array(sg1*78*6e-8, dtype=dt1) b = np.array(sg2*6e-8, dtype=dt2) div, rem = op(a, b) # Equal assertion should hold when fmod is used assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg) def test_float_remainder_corner_cases(self): # Check remainder magnitude. for dt in np.typecodes['Float']: b = np.array(1.0, dtype=dt) a = np.nextafter(np.array(0.0, dtype=dt), -b) rem = np.remainder(a, b) assert_(rem <= b, 'dt: %s' % dt) rem = np.remainder(-a, -b) assert_(rem >= -b, 'dt: %s' % dt) # Check nans, inf with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in remainder") for dt in np.typecodes['Float']: fone = np.array(1.0, dtype=dt) fzer = np.array(0.0, dtype=dt) finf = np.array(np.inf, dtype=dt) fnan = np.array(np.nan, dtype=dt) rem = np.remainder(fone, fzer) assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)) # MSVC 2008 returns NaN here, so disable the check. #rem = np.remainder(fone, finf) #assert_(rem == fone, 'dt: %s, rem: %s' % (dt, rem)) rem = np.remainder(fone, fnan) assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)) rem = np.remainder(finf, fone) assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)) class TestCbrt(object): def test_cbrt_scalar(self): assert_almost_equal((np.cbrt(np.float32(-2.5)**3)), -2.5) def test_cbrt(self): x = np.array([1., 2., -3., np.inf, -np.inf]) assert_almost_equal(np.cbrt(x**3), x) assert_(np.isnan(np.cbrt(np.nan))) assert_equal(np.cbrt(np.inf), np.inf) assert_equal(np.cbrt(-np.inf), -np.inf) class TestPower(object): def test_power_float(self): x = np.array([1., 2., 3.]) assert_equal(x**0, [1., 1., 1.]) assert_equal(x**1, x) assert_equal(x**2, [1., 4., 9.]) y = x.copy() y **= 2 assert_equal(y, [1., 4., 9.]) assert_almost_equal(x**(-1), [1., 0.5, 1./3]) assert_almost_equal(x**(0.5), [1., ncu.sqrt(2), ncu.sqrt(3)]) for out, inp, msg in _gen_alignment_data(dtype=np.float32, type='unary', max_size=11): exp = [ncu.sqrt(i) for i in inp] assert_almost_equal(inp**(0.5), exp, err_msg=msg) np.sqrt(inp, out=out) assert_equal(out, exp, err_msg=msg) for out, inp, msg in _gen_alignment_data(dtype=np.float64, type='unary', max_size=7): exp = [ncu.sqrt(i) for i in inp] assert_almost_equal(inp**(0.5), exp, err_msg=msg) np.sqrt(inp, out=out) assert_equal(out, exp, err_msg=msg) def test_power_complex(self): x = np.array([1+2j, 2+3j, 3+4j]) assert_equal(x**0, [1., 1., 1.]) assert_equal(x**1, x) assert_almost_equal(x**2, [-3+4j, -5+12j, -7+24j]) assert_almost_equal(x**3, [(1+2j)**3, (2+3j)**3, (3+4j)**3]) assert_almost_equal(x**4, [(1+2j)**4, (2+3j)**4, (3+4j)**4]) assert_almost_equal(x**(-1), [1/(1+2j), 1/(2+3j), 1/(3+4j)]) assert_almost_equal(x**(-2), [1/(1+2j)**2, 1/(2+3j)**2, 1/(3+4j)**2]) assert_almost_equal(x**(-3), [(-11+2j)/125, (-46-9j)/2197, (-117-44j)/15625]) assert_almost_equal(x**(0.5), [ncu.sqrt(1+2j), ncu.sqrt(2+3j), ncu.sqrt(3+4j)]) norm = 1./((x**14)[0]) assert_almost_equal(x**14 * norm, [i * norm for i in [-76443+16124j, 23161315+58317492j, 5583548873 + 2465133864j]]) # Ticket #836 def assert_complex_equal(x, y): assert_array_equal(x.real, y.real) assert_array_equal(x.imag, y.imag) for z in [complex(0, np.inf), complex(1, np.inf)]: z = np.array([z], dtype=np.complex_) with np.errstate(invalid="ignore"): assert_complex_equal(z**1, z) assert_complex_equal(z**2, z*z) assert_complex_equal(z**3, z*z*z) def test_power_zero(self): # ticket #1271 zero = np.array([0j]) one = np.array([1+0j]) cnan = np.array([complex(np.nan, np.nan)]) # FIXME cinf not tested. #cinf = np.array([complex(np.inf, 0)]) def assert_complex_equal(x, y): x, y = np.asarray(x), np.asarray(y) assert_array_equal(x.real, y.real) assert_array_equal(x.imag, y.imag) # positive powers for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]: assert_complex_equal(np.power(zero, p), zero) # zero power assert_complex_equal(np.power(zero, 0), one) with np.errstate(invalid="ignore"): assert_complex_equal(np.power(zero, 0+1j), cnan) # negative power for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]: assert_complex_equal(np.power(zero, -p), cnan) assert_complex_equal(np.power(zero, -1+0.2j), cnan) def test_fast_power(self): x = np.array([1, 2, 3], np.int16) res = x**2.0 assert_((x**2.00001).dtype is res.dtype) assert_array_equal(res, [1, 4, 9]) # check the inplace operation on the casted copy doesn't mess with x assert_(not np.may_share_memory(res, x)) assert_array_equal(x, [1, 2, 3]) # Check that the fast path ignores 1-element not 0-d arrays res = x ** np.array([[[2]]]) assert_equal(res.shape, (1, 1, 3)) def test_integer_power(self): a = np.array([15, 15], 'i8') b = np.power(a, a) assert_equal(b, [437893890380859375, 437893890380859375]) def test_integer_power_with_integer_zero_exponent(self): dtypes = np.typecodes['Integer'] for dt in dtypes: arr = np.arange(-10, 10, dtype=dt) assert_equal(np.power(arr, 0), np.ones_like(arr)) dtypes = np.typecodes['UnsignedInteger'] for dt in dtypes: arr = np.arange(10, dtype=dt) assert_equal(np.power(arr, 0), np.ones_like(arr)) def test_integer_power_of_1(self): dtypes = np.typecodes['AllInteger'] for dt in dtypes: arr = np.arange(10, dtype=dt) assert_equal(np.power(1, arr), np.ones_like(arr)) def test_integer_power_of_zero(self): dtypes = np.typecodes['AllInteger'] for dt in dtypes: arr = np.arange(1, 10, dtype=dt) assert_equal(np.power(0, arr), np.zeros_like(arr)) def test_integer_to_negative_power(self): dtypes = np.typecodes['Integer'] for dt in dtypes: a = np.array([0, 1, 2, 3], dtype=dt) b = np.array([0, 1, 2, -3], dtype=dt) one = np.array(1, dtype=dt) minusone = np.array(-1, dtype=dt) assert_raises(ValueError, np.power, a, b) assert_raises(ValueError, np.power, a, minusone) assert_raises(ValueError, np.power, one, b) assert_raises(ValueError, np.power, one, minusone) class TestFloat_power(object): def test_type_conversion(self): arg_type = '?bhilBHILefdgFDG' res_type = 'ddddddddddddgDDG' for dtin, dtout in zip(arg_type, res_type): msg = "dtin: %s, dtout: %s" % (dtin, dtout) arg = np.ones(1, dtype=dtin) res = np.float_power(arg, arg) assert_(res.dtype.name == np.dtype(dtout).name, msg) class TestLog2(object): def test_log2_values(self): x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for dt in ['f', 'd', 'g']: xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt) assert_almost_equal(np.log2(xf), yf) def test_log2_ints(self): # a good log2 implementation should provide this, # might fail on OS with bad libm for i in range(1, 65): v = np.log2(2.**i) assert_equal(v, float(i), err_msg='at exponent %d' % i) def test_log2_special(self): assert_equal(np.log2(1.), 0.) assert_equal(np.log2(np.inf), np.inf) assert_(np.isnan(np.log2(np.nan))) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', RuntimeWarning) assert_(np.isnan(np.log2(-1.))) assert_(np.isnan(np.log2(-np.inf))) assert_equal(np.log2(0.), -np.inf) assert_(w[0].category is RuntimeWarning) assert_(w[1].category is RuntimeWarning) assert_(w[2].category is RuntimeWarning) class TestExp2(object): def test_exp2_values(self): x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for dt in ['f', 'd', 'g']: xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt) assert_almost_equal(np.exp2(yf), xf) class TestLogAddExp2(_FilterInvalids): # Need test for intermediate precisions def test_logaddexp2_values(self): x = [1, 2, 3, 4, 5] y = [5, 4, 3, 2, 1] z = [6, 6, 6, 6, 6] for dt, dec_ in zip(['f', 'd', 'g'], [6, 15, 15]): xf = np.log2(np.array(x, dtype=dt)) yf = np.log2(np.array(y, dtype=dt)) zf = np.log2(np.array(z, dtype=dt)) assert_almost_equal(np.logaddexp2(xf, yf), zf, decimal=dec_) def test_logaddexp2_range(self): x = [1000000, -1000000, 1000200, -1000200] y = [1000200, -1000200, 1000000, -1000000] z = [1000200, -1000000, 1000200, -1000000] for dt in ['f', 'd', 'g']: logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) assert_almost_equal(np.logaddexp2(logxf, logyf), logzf) def test_inf(self): inf = np.inf x = [inf, -inf, inf, -inf, inf, 1, -inf, 1] y = [inf, inf, -inf, -inf, 1, inf, 1, -inf] z = [inf, inf, inf, -inf, inf, inf, 1, 1] with np.errstate(invalid='raise'): for dt in ['f', 'd', 'g']: logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) assert_equal(np.logaddexp2(logxf, logyf), logzf) def test_nan(self): assert_(np.isnan(np.logaddexp2(np.nan, np.inf))) assert_(np.isnan(np.logaddexp2(np.inf, np.nan))) assert_(np.isnan(np.logaddexp2(np.nan, 0))) assert_(np.isnan(np.logaddexp2(0, np.nan))) assert_(np.isnan(np.logaddexp2(np.nan, np.nan))) class TestLog(object): def test_log_values(self): x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for dt in ['f', 'd', 'g']: log2_ = 0.69314718055994530943 xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt)*log2_ assert_almost_equal(np.log(xf), yf) class TestExp(object): def test_exp_values(self): x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for dt in ['f', 'd', 'g']: log2_ = 0.69314718055994530943 xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt)*log2_ assert_almost_equal(np.exp(yf), xf) class TestLogAddExp(_FilterInvalids): def test_logaddexp_values(self): x = [1, 2, 3, 4, 5] y = [5, 4, 3, 2, 1] z = [6, 6, 6, 6, 6] for dt, dec_ in zip(['f', 'd', 'g'], [6, 15, 15]): xf = np.log(np.array(x, dtype=dt)) yf = np.log(np.array(y, dtype=dt)) zf = np.log(np.array(z, dtype=dt)) assert_almost_equal(np.logaddexp(xf, yf), zf, decimal=dec_) def test_logaddexp_range(self): x = [1000000, -1000000, 1000200, -1000200] y = [1000200, -1000200, 1000000, -1000000] z = [1000200, -1000000, 1000200, -1000000] for dt in ['f', 'd', 'g']: logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) assert_almost_equal(np.logaddexp(logxf, logyf), logzf) def test_inf(self): inf = np.inf x = [inf, -inf, inf, -inf, inf, 1, -inf, 1] y = [inf, inf, -inf, -inf, 1, inf, 1, -inf] z = [inf, inf, inf, -inf, inf, inf, 1, 1] with np.errstate(invalid='raise'): for dt in ['f', 'd', 'g']: logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) assert_equal(np.logaddexp(logxf, logyf), logzf) def test_nan(self): assert_(np.isnan(np.logaddexp(np.nan, np.inf))) assert_(np.isnan(np.logaddexp(np.inf, np.nan))) assert_(np.isnan(np.logaddexp(np.nan, 0))) assert_(np.isnan(np.logaddexp(0, np.nan))) assert_(np.isnan(np.logaddexp(np.nan, np.nan))) class TestLog1p(object): def test_log1p(self): assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2)) assert_almost_equal(ncu.log1p(1e-6), ncu.log(1+1e-6)) def test_special(self): with np.errstate(invalid="ignore", divide="ignore"): assert_equal(ncu.log1p(np.nan), np.nan) assert_equal(ncu.log1p(np.inf), np.inf) assert_equal(ncu.log1p(-1.), -np.inf) assert_equal(ncu.log1p(-2.), np.nan) assert_equal(ncu.log1p(-np.inf), np.nan) class TestExpm1(object): def test_expm1(self): assert_almost_equal(ncu.expm1(0.2), ncu.exp(0.2)-1) assert_almost_equal(ncu.expm1(1e-6), ncu.exp(1e-6)-1) def test_special(self): assert_equal(ncu.expm1(np.inf), np.inf) assert_equal(ncu.expm1(0.), 0.) assert_equal(ncu.expm1(-0.), -0.) assert_equal(ncu.expm1(np.inf), np.inf) assert_equal(ncu.expm1(-np.inf), -1.) class TestHypot(object): def test_simple(self): assert_almost_equal(ncu.hypot(1, 1), ncu.sqrt(2)) assert_almost_equal(ncu.hypot(0, 0), 0) def test_reduce(self): assert_almost_equal(ncu.hypot.reduce([3.0, 4.0]), 5.0) assert_almost_equal(ncu.hypot.reduce([3.0, 4.0, 0]), 5.0) assert_almost_equal(ncu.hypot.reduce([9.0, 12.0, 20.0]), 25.0) assert_equal(ncu.hypot.reduce([]), 0.0) def assert_hypot_isnan(x, y): with np.errstate(invalid='ignore'): assert_(np.isnan(ncu.hypot(x, y)), "hypot(%s, %s) is %s, not nan" % (x, y, ncu.hypot(x, y))) def assert_hypot_isinf(x, y): with np.errstate(invalid='ignore'): assert_(np.isinf(ncu.hypot(x, y)), "hypot(%s, %s) is %s, not inf" % (x, y, ncu.hypot(x, y))) class TestHypotSpecialValues(object): def test_nan_outputs(self): assert_hypot_isnan(np.nan, np.nan) assert_hypot_isnan(np.nan, 1) def test_nan_outputs2(self): assert_hypot_isinf(np.nan, np.inf) assert_hypot_isinf(np.inf, np.nan) assert_hypot_isinf(np.inf, 0) assert_hypot_isinf(0, np.inf) assert_hypot_isinf(np.inf, np.inf) assert_hypot_isinf(np.inf, 23.0) def test_no_fpe(self): assert_no_warnings(ncu.hypot, np.inf, 0) def assert_arctan2_isnan(x, y): assert_(np.isnan(ncu.arctan2(x, y)), "arctan(%s, %s) is %s, not nan" % (x, y, ncu.arctan2(x, y))) def assert_arctan2_ispinf(x, y): assert_((np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) > 0), "arctan(%s, %s) is %s, not +inf" % (x, y, ncu.arctan2(x, y))) def assert_arctan2_isninf(x, y): assert_((np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) < 0), "arctan(%s, %s) is %s, not -inf" % (x, y, ncu.arctan2(x, y))) def assert_arctan2_ispzero(x, y): assert_((ncu.arctan2(x, y) == 0 and not np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not +0" % (x, y, ncu.arctan2(x, y))) def assert_arctan2_isnzero(x, y): assert_((ncu.arctan2(x, y) == 0 and np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not -0" % (x, y, ncu.arctan2(x, y))) class TestArctan2SpecialValues(object): def test_one_one(self): # atan2(1, 1) returns pi/4. assert_almost_equal(ncu.arctan2(1, 1), 0.25 * np.pi) assert_almost_equal(ncu.arctan2(-1, 1), -0.25 * np.pi) assert_almost_equal(ncu.arctan2(1, -1), 0.75 * np.pi) def test_zero_nzero(self): # atan2(+-0, -0) returns +-pi. assert_almost_equal(ncu.arctan2(np.PZERO, np.NZERO), np.pi) assert_almost_equal(ncu.arctan2(np.NZERO, np.NZERO), -np.pi) def test_zero_pzero(self): # atan2(+-0, +0) returns +-0. assert_arctan2_ispzero(np.PZERO, np.PZERO) assert_arctan2_isnzero(np.NZERO, np.PZERO) def test_zero_negative(self): # atan2(+-0, x) returns +-pi for x < 0. assert_almost_equal(ncu.arctan2(np.PZERO, -1), np.pi) assert_almost_equal(ncu.arctan2(np.NZERO, -1), -np.pi) def test_zero_positive(self): # atan2(+-0, x) returns +-0 for x > 0. assert_arctan2_ispzero(np.PZERO, 1) assert_arctan2_isnzero(np.NZERO, 1) def test_positive_zero(self): # atan2(y, +-0) returns +pi/2 for y > 0. assert_almost_equal(ncu.arctan2(1, np.PZERO), 0.5 * np.pi) assert_almost_equal(ncu.arctan2(1, np.NZERO), 0.5 * np.pi) def test_negative_zero(self): # atan2(y, +-0) returns -pi/2 for y < 0. assert_almost_equal(ncu.arctan2(-1, np.PZERO), -0.5 * np.pi) assert_almost_equal(ncu.arctan2(-1, np.NZERO), -0.5 * np.pi) def test_any_ninf(self): # atan2(+-y, -infinity) returns +-pi for finite y > 0. assert_almost_equal(ncu.arctan2(1, np.NINF), np.pi) assert_almost_equal(ncu.arctan2(-1, np.NINF), -np.pi) def test_any_pinf(self): # atan2(+-y, +infinity) returns +-0 for finite y > 0. assert_arctan2_ispzero(1, np.inf) assert_arctan2_isnzero(-1, np.inf) def test_inf_any(self): # atan2(+-infinity, x) returns +-pi/2 for finite x. assert_almost_equal(ncu.arctan2( np.inf, 1), 0.5 * np.pi) assert_almost_equal(ncu.arctan2(-np.inf, 1), -0.5 * np.pi) def test_inf_ninf(self): # atan2(+-infinity, -infinity) returns +-3*pi/4. assert_almost_equal(ncu.arctan2( np.inf, -np.inf), 0.75 * np.pi) assert_almost_equal(ncu.arctan2(-np.inf, -np.inf), -0.75 * np.pi) def test_inf_pinf(self): # atan2(+-infinity, +infinity) returns +-pi/4. assert_almost_equal(ncu.arctan2( np.inf, np.inf), 0.25 * np.pi) assert_almost_equal(ncu.arctan2(-np.inf, np.inf), -0.25 * np.pi) def test_nan_any(self): # atan2(nan, x) returns nan for any x, including inf assert_arctan2_isnan(np.nan, np.inf) assert_arctan2_isnan(np.inf, np.nan) assert_arctan2_isnan(np.nan, np.nan) class TestLdexp(object): def _check_ldexp(self, tp): assert_almost_equal(ncu.ldexp(np.array(2., np.float32), np.array(3, tp)), 16.) assert_almost_equal(ncu.ldexp(np.array(2., np.float64), np.array(3, tp)), 16.) assert_almost_equal(ncu.ldexp(np.array(2., np.longdouble), np.array(3, tp)), 16.) def test_ldexp(self): # The default Python int type should work assert_almost_equal(ncu.ldexp(2., 3), 16.) # The following int types should all be accepted self._check_ldexp(np.int8) self._check_ldexp(np.int16) self._check_ldexp(np.int32) self._check_ldexp('i') self._check_ldexp('l') def test_ldexp_overflow(self): # silence warning emitted on overflow with np.errstate(over="ignore"): imax = np.iinfo(np.dtype('l')).max imin = np.iinfo(np.dtype('l')).min assert_equal(ncu.ldexp(2., imax), np.inf) assert_equal(ncu.ldexp(2., imin), 0) class TestMaximum(_FilterInvalids): def test_reduce(self): dflt = np.typecodes['AllFloat'] dint = np.typecodes['AllInteger'] seq1 = np.arange(11) seq2 = seq1[::-1] func = np.maximum.reduce for dt in dint: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 10) assert_equal(func(tmp2), 10) for dt in dflt: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 10) assert_equal(func(tmp2), 10) tmp1[::2] = np.nan tmp2[::2] = np.nan assert_equal(func(tmp1), np.nan) assert_equal(func(tmp2), np.nan) def test_reduce_complex(self): assert_equal(np.maximum.reduce([1, 2j]), 1) assert_equal(np.maximum.reduce([1+3j, 2j]), 1+3j) def test_float_nans(self): nan = np.nan arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([nan, nan, nan]) assert_equal(np.maximum(arg1, arg2), out) def test_object_nans(self): # Multiple checks to give this a chance to # fail if cmp is used instead of rich compare. # Failure cannot be guaranteed. for i in range(1): x = np.array(float('nan'), object) y = 1.0 z = np.array(float('nan'), object) assert_(np.maximum(x, y) == 1.0) assert_(np.maximum(z, y) == 1.0) def test_complex_nans(self): nan = np.nan for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]: arg1 = np.array([0, cnan, cnan], dtype=complex) arg2 = np.array([cnan, 0, cnan], dtype=complex) out = np.array([nan, nan, nan], dtype=complex) assert_equal(np.maximum(arg1, arg2), out) def test_object_array(self): arg1 = np.arange(5, dtype=object) arg2 = arg1 + 1 assert_equal(np.maximum(arg1, arg2), arg2) class TestMinimum(_FilterInvalids): def test_reduce(self): dflt = np.typecodes['AllFloat'] dint = np.typecodes['AllInteger'] seq1 = np.arange(11) seq2 = seq1[::-1] func = np.minimum.reduce for dt in dint: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 0) assert_equal(func(tmp2), 0) for dt in dflt: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 0) assert_equal(func(tmp2), 0) tmp1[::2] = np.nan tmp2[::2] = np.nan assert_equal(func(tmp1), np.nan) assert_equal(func(tmp2), np.nan) def test_reduce_complex(self): assert_equal(np.minimum.reduce([1, 2j]), 2j) assert_equal(np.minimum.reduce([1+3j, 2j]), 2j) def test_float_nans(self): nan = np.nan arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([nan, nan, nan]) assert_equal(np.minimum(arg1, arg2), out) def test_object_nans(self): # Multiple checks to give this a chance to # fail if cmp is used instead of rich compare. # Failure cannot be guaranteed. for i in range(1): x = np.array(float('nan'), object) y = 1.0 z = np.array(float('nan'), object) assert_(np.minimum(x, y) == 1.0) assert_(np.minimum(z, y) == 1.0) def test_complex_nans(self): nan = np.nan for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]: arg1 = np.array([0, cnan, cnan], dtype=complex) arg2 = np.array([cnan, 0, cnan], dtype=complex) out = np.array([nan, nan, nan], dtype=complex) assert_equal(np.minimum(arg1, arg2), out) def test_object_array(self): arg1 = np.arange(5, dtype=object) arg2 = arg1 + 1 assert_equal(np.minimum(arg1, arg2), arg1) class TestFmax(_FilterInvalids): def test_reduce(self): dflt = np.typecodes['AllFloat'] dint = np.typecodes['AllInteger'] seq1 = np.arange(11) seq2 = seq1[::-1] func = np.fmax.reduce for dt in dint: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 10) assert_equal(func(tmp2), 10) for dt in dflt: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 10) assert_equal(func(tmp2), 10) tmp1[::2] = np.nan tmp2[::2] = np.nan assert_equal(func(tmp1), 9) assert_equal(func(tmp2), 9) def test_reduce_complex(self): assert_equal(np.fmax.reduce([1, 2j]), 1) assert_equal(np.fmax.reduce([1+3j, 2j]), 1+3j) def test_float_nans(self): nan = np.nan arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([0, 0, nan]) assert_equal(np.fmax(arg1, arg2), out) def test_complex_nans(self): nan = np.nan for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]: arg1 = np.array([0, cnan, cnan], dtype=complex) arg2 = np.array([cnan, 0, cnan], dtype=complex) out = np.array([0, 0, nan], dtype=complex) assert_equal(np.fmax(arg1, arg2), out) class TestFmin(_FilterInvalids): def test_reduce(self): dflt = np.typecodes['AllFloat'] dint = np.typecodes['AllInteger'] seq1 = np.arange(11) seq2 = seq1[::-1] func = np.fmin.reduce for dt in dint: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 0) assert_equal(func(tmp2), 0) for dt in dflt: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 0) assert_equal(func(tmp2), 0) tmp1[::2] = np.nan tmp2[::2] = np.nan assert_equal(func(tmp1), 1) assert_equal(func(tmp2), 1) def test_reduce_complex(self): assert_equal(np.fmin.reduce([1, 2j]), 2j) assert_equal(np.fmin.reduce([1+3j, 2j]), 2j) def test_float_nans(self): nan = np.nan arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([0, 0, nan]) assert_equal(np.fmin(arg1, arg2), out) def test_complex_nans(self): nan = np.nan for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]: arg1 = np.array([0, cnan, cnan], dtype=complex) arg2 = np.array([cnan, 0, cnan], dtype=complex) out = np.array([0, 0, nan], dtype=complex) assert_equal(np.fmin(arg1, arg2), out) class TestBool(object): def test_exceptions(self): a = np.ones(1, dtype=np.bool_) assert_raises(TypeError, np.negative, a) assert_raises(TypeError, np.positive, a) assert_raises(TypeError, np.subtract, a, a) def test_truth_table_logical(self): # 2, 3 and 4 serves as true values input1 = [0, 0, 3, 2] input2 = [0, 4, 0, 2] typecodes = (np.typecodes['AllFloat'] + np.typecodes['AllInteger'] + '?') # boolean for dtype in map(np.dtype, typecodes): arg1 = np.asarray(input1, dtype=dtype) arg2 = np.asarray(input2, dtype=dtype) # OR out = [False, True, True, True] for func in (np.logical_or, np.maximum): assert_equal(func(arg1, arg2).astype(bool), out) # AND out = [False, False, False, True] for func in (np.logical_and, np.minimum): assert_equal(func(arg1, arg2).astype(bool), out) # XOR out = [False, True, True, False] for func in (np.logical_xor, np.not_equal): assert_equal(func(arg1, arg2).astype(bool), out) def test_truth_table_bitwise(self): arg1 = [False, False, True, True] arg2 = [False, True, False, True] out = [False, True, True, True] assert_equal(np.bitwise_or(arg1, arg2), out) out = [False, False, False, True] assert_equal(np.bitwise_and(arg1, arg2), out) out = [False, True, True, False] assert_equal(np.bitwise_xor(arg1, arg2), out) def test_reduce(self): none = np.array([0, 0, 0, 0], bool) some = np.array([1, 0, 1, 1], bool) every = np.array([1, 1, 1, 1], bool) empty = np.array([], bool) arrs = [none, some, every, empty] for arr in arrs: assert_equal(np.logical_and.reduce(arr), all(arr)) for arr in arrs: assert_equal(np.logical_or.reduce(arr), any(arr)) for arr in arrs: assert_equal(np.logical_xor.reduce(arr), arr.sum() % 2 == 1) class TestBitwiseUFuncs(object): bitwise_types = [np.dtype(c) for c in '?' + 'bBhHiIlLqQ' + 'O'] def test_values(self): for dt in self.bitwise_types: zeros = np.array([0], dtype=dt) ones = np.array([-1], dtype=dt) msg = "dt = '%s'" % dt.char assert_equal(np.bitwise_not(zeros), ones, err_msg=msg) assert_equal(np.bitwise_not(ones), zeros, err_msg=msg) assert_equal(np.bitwise_or(zeros, zeros), zeros, err_msg=msg) assert_equal(np.bitwise_or(zeros, ones), ones, err_msg=msg) assert_equal(np.bitwise_or(ones, zeros), ones, err_msg=msg) assert_equal(np.bitwise_or(ones, ones), ones, err_msg=msg) assert_equal(np.bitwise_xor(zeros, zeros), zeros, err_msg=msg) assert_equal(np.bitwise_xor(zeros, ones), ones, err_msg=msg) assert_equal(np.bitwise_xor(ones, zeros), ones, err_msg=msg) assert_equal(np.bitwise_xor(ones, ones), zeros, err_msg=msg) assert_equal(np.bitwise_and(zeros, zeros), zeros, err_msg=msg) assert_equal(np.bitwise_and(zeros, ones), zeros, err_msg=msg) assert_equal(np.bitwise_and(ones, zeros), zeros, err_msg=msg) assert_equal(np.bitwise_and(ones, ones), ones, err_msg=msg) def test_types(self): for dt in self.bitwise_types: zeros = np.array([0], dtype=dt) ones = np.array([-1], dtype=dt) msg = "dt = '%s'" % dt.char assert_(np.bitwise_not(zeros).dtype == dt, msg) assert_(np.bitwise_or(zeros, zeros).dtype == dt, msg) assert_(np.bitwise_xor(zeros, zeros).dtype == dt, msg) assert_(np.bitwise_and(zeros, zeros).dtype == dt, msg) def test_identity(self): assert_(np.bitwise_or.identity == 0, 'bitwise_or') assert_(np.bitwise_xor.identity == 0, 'bitwise_xor') assert_(np.bitwise_and.identity == -1, 'bitwise_and') def test_reduction(self): binary_funcs = (np.bitwise_or, np.bitwise_xor, np.bitwise_and) for dt in self.bitwise_types: zeros = np.array([0], dtype=dt) ones = np.array([-1], dtype=dt) for f in binary_funcs: msg = "dt: '%s', f: '%s'" % (dt, f) assert_equal(f.reduce(zeros), zeros, err_msg=msg) assert_equal(f.reduce(ones), ones, err_msg=msg) # Test empty reduction, no object dtype for dt in self.bitwise_types[:-1]: # No object array types empty = np.array([], dtype=dt) for f in binary_funcs: msg = "dt: '%s', f: '%s'" % (dt, f) tgt = np.array(f.identity, dtype=dt) res = f.reduce(empty) assert_equal(res, tgt, err_msg=msg) assert_(res.dtype == tgt.dtype, msg) # Empty object arrays use the identity. Note that the types may # differ, the actual type used is determined by the assign_identity # function and is not the same as the type returned by the identity # method. for f in binary_funcs: msg = "dt: '%s'" % (f,) empty = np.array([], dtype=object) tgt = f.identity res = f.reduce(empty) assert_equal(res, tgt, err_msg=msg) # Non-empty object arrays do not use the identity for f in binary_funcs: msg = "dt: '%s'" % (f,) btype = np.array([True], dtype=object) assert_(type(f.reduce(btype)) is bool, msg) class TestInt(object): def test_logical_not(self): x = np.ones(10, dtype=np.int16) o = np.ones(10 * 2, dtype=bool) tgt = o.copy() tgt[::2] = False os = o[::2] assert_array_equal(np.logical_not(x, out=os), False) assert_array_equal(o, tgt) class TestFloatingPoint(object): def test_floating_point(self): assert_equal(ncu.FLOATING_POINT_SUPPORT, 1) class TestDegrees(object): def test_degrees(self): assert_almost_equal(ncu.degrees(np.pi), 180.0) assert_almost_equal(ncu.degrees(-0.5*np.pi), -90.0) class TestRadians(object): def test_radians(self): assert_almost_equal(ncu.radians(180.0), np.pi) assert_almost_equal(ncu.radians(-90.0), -0.5*np.pi) class TestHeavside(object): def test_heaviside(self): x = np.array([[-30.0, -0.1, 0.0, 0.2], [7.5, np.nan, np.inf, -np.inf]]) expectedhalf = np.array([[0.0, 0.0, 0.5, 1.0], [1.0, np.nan, 1.0, 0.0]]) expected1 = expectedhalf.copy() expected1[0, 2] = 1 h = ncu.heaviside(x, 0.5) assert_equal(h, expectedhalf) h = ncu.heaviside(x, 1.0) assert_equal(h, expected1) x = x.astype(np.float32) h = ncu.heaviside(x, np.float32(0.5)) assert_equal(h, expectedhalf.astype(np.float32)) h = ncu.heaviside(x, np.float32(1.0)) assert_equal(h, expected1.astype(np.float32)) class TestSign(object): def test_sign(self): a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0]) out = np.zeros(a.shape) tgt = np.array([1., -1., np.nan, 0.0, 1.0, -1.0]) with np.errstate(invalid='ignore'): res = ncu.sign(a) assert_equal(res, tgt) res = ncu.sign(a, out) assert_equal(res, tgt) assert_equal(out, tgt) def test_sign_dtype_object(self): # In reference to github issue #6229 foo = np.array([-.1, 0, .1]) a = np.sign(foo.astype(object)) b = np.sign(foo) assert_array_equal(a, b) def test_sign_dtype_nan_object(self): # In reference to github issue #6229 def test_nan(): foo = np.array([np.nan]) a = np.sign(foo.astype(object)) assert_raises(TypeError, test_nan) class TestMinMax(object): def test_minmax_blocked(self): # simd tests on max/min, test all alignments, slow but important # for 2 * vz + 2 * (vs - 1) + 1 (unrolled once) for dt, sz in [(np.float32, 15), (np.float64, 7)]: for out, inp, msg in _gen_alignment_data(dtype=dt, type='unary', max_size=sz): for i in range(inp.size): inp[:] = np.arange(inp.size, dtype=dt) inp[i] = np.nan emsg = lambda: '%r\n%s' % (inp, msg) with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in reduce") assert_(np.isnan(inp.max()), msg=emsg) assert_(np.isnan(inp.min()), msg=emsg) inp[i] = 1e10 assert_equal(inp.max(), 1e10, err_msg=msg) inp[i] = -1e10 assert_equal(inp.min(), -1e10, err_msg=msg) def test_lower_align(self): # check data that is not aligned to element size # i.e doubles are aligned to 4 bytes on i386 d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) assert_equal(d.max(), d[0]) assert_equal(d.min(), d[0]) def test_reduce_warns(self): # gh 10370, 11029 Some compilers reorder the call to npy_getfloatstatus # and put it before the call to an intrisic function that causes # invalid status to be set. Also make sure warnings are emitted for n in (2, 4, 8, 16, 32): with suppress_warnings() as sup: sup.record(RuntimeWarning) for r in np.diagflat([np.nan] * n): assert_equal(np.min(r), np.nan) assert_equal(len(sup.log), n) class TestAbsoluteNegative(object): def test_abs_neg_blocked(self): # simd tests on abs, test all alignments for vz + 2 * (vs - 1) + 1 for dt, sz in [(np.float32, 11), (np.float64, 5)]: for out, inp, msg in _gen_alignment_data(dtype=dt, type='unary', max_size=sz): tgt = [ncu.absolute(i) for i in inp] np.absolute(inp, out=out) assert_equal(out, tgt, err_msg=msg) assert_((out >= 0).all()) tgt = [-1*(i) for i in inp] np.negative(inp, out=out) assert_equal(out, tgt, err_msg=msg) for v in [np.nan, -np.inf, np.inf]: for i in range(inp.size): d = np.arange(inp.size, dtype=dt) inp[:] = -d inp[i] = v d[i] = -v if v == -np.inf else v assert_array_equal(np.abs(inp), d, err_msg=msg) np.abs(inp, out=out) assert_array_equal(out, d, err_msg=msg) assert_array_equal(-inp, -1*inp, err_msg=msg) d = -1 * inp np.negative(inp, out=out) assert_array_equal(out, d, err_msg=msg) def test_lower_align(self): # check data that is not aligned to element size # i.e doubles are aligned to 4 bytes on i386 d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) assert_equal(np.abs(d), d) assert_equal(np.negative(d), -d) np.negative(d, out=d) np.negative(np.ones_like(d), out=d) np.abs(d, out=d) np.abs(np.ones_like(d), out=d) class TestPositive(object): def test_valid(self): valid_dtypes = [int, float, complex, object] for dtype in valid_dtypes: x = np.arange(5, dtype=dtype) result = np.positive(x) assert_equal(x, result, err_msg=str(dtype)) def test_invalid(self): with assert_raises(TypeError): np.positive(True) with assert_raises(TypeError): np.positive(np.datetime64('2000-01-01')) with assert_raises(TypeError): np.positive(np.array(['foo'], dtype=str)) with assert_raises(TypeError): np.positive(np.array(['bar'], dtype=object)) class TestSpecialMethods(object): def test_wrap(self): class with_wrap(object): def __array__(self): return np.zeros(1) def __array_wrap__(self, arr, context): r = with_wrap() r.arr = arr r.context = context return r a = with_wrap() x = ncu.minimum(a, a) assert_equal(x.arr, np.zeros(1)) func, args, i = x.context assert_(func is ncu.minimum) assert_equal(len(args), 2) assert_equal(args[0], a) assert_equal(args[1], a) assert_equal(i, 0) def test_wrap_with_iterable(self): # test fix for bug #1026: class with_wrap(np.ndarray): __array_priority__ = 10 def __new__(cls): return np.asarray(1).view(cls).copy() def __array_wrap__(self, arr, context): return arr.view(type(self)) a = with_wrap() x = ncu.multiply(a, (1, 2, 3)) assert_(isinstance(x, with_wrap)) assert_array_equal(x, np.array((1, 2, 3))) def test_priority_with_scalar(self): # test fix for bug #826: class A(np.ndarray): __array_priority__ = 10 def __new__(cls): return np.asarray(1.0, 'float64').view(cls).copy() a = A() x = np.float64(1)*a assert_(isinstance(x, A)) assert_array_equal(x, np.array(1)) def test_old_wrap(self): class with_wrap(object): def __array__(self): return np.zeros(1) def __array_wrap__(self, arr): r = with_wrap() r.arr = arr return r a = with_wrap() x = ncu.minimum(a, a) assert_equal(x.arr, np.zeros(1)) def test_priority(self): class A(object): def __array__(self): return np.zeros(1) def __array_wrap__(self, arr, context): r = type(self)() r.arr = arr r.context = context return r class B(A): __array_priority__ = 20. class C(A): __array_priority__ = 40. x = np.zeros(1) a = A() b = B() c = C() f = ncu.minimum assert_(type(f(x, x)) is np.ndarray) assert_(type(f(x, a)) is A) assert_(type(f(x, b)) is B) assert_(type(f(x, c)) is C) assert_(type(f(a, x)) is A) assert_(type(f(b, x)) is B) assert_(type(f(c, x)) is C) assert_(type(f(a, a)) is A) assert_(type(f(a, b)) is B) assert_(type(f(b, a)) is B) assert_(type(f(b, b)) is B) assert_(type(f(b, c)) is C) assert_(type(f(c, b)) is C) assert_(type(f(c, c)) is C) assert_(type(ncu.exp(a) is A)) assert_(type(ncu.exp(b) is B)) assert_(type(ncu.exp(c) is C)) def test_failing_wrap(self): class A(object): def __array__(self): return np.zeros(1) def __array_wrap__(self, arr, context): raise RuntimeError a = A() assert_raises(RuntimeError, ncu.maximum, a, a) def test_none_wrap(self): # Tests that issue #8507 is resolved. Previously, this would segfault class A(object): def __array__(self): return np.zeros(1) def __array_wrap__(self, arr, context=None): return None a = A() assert_equal(ncu.maximum(a, a), None) def test_default_prepare(self): class with_wrap(object): __array_priority__ = 10 def __array__(self): return np.zeros(1) def __array_wrap__(self, arr, context): return arr a = with_wrap() x = ncu.minimum(a, a) assert_equal(x, np.zeros(1)) assert_equal(type(x), np.ndarray) def test_prepare(self): class with_prepare(np.ndarray): __array_priority__ = 10 def __array_prepare__(self, arr, context): # make sure we can return a new return np.array(arr).view(type=with_prepare) a = np.array(1).view(type=with_prepare) x = np.add(a, a) assert_equal(x, np.array(2)) assert_equal(type(x), with_prepare) def test_prepare_out(self): class with_prepare(np.ndarray): __array_priority__ = 10 def __array_prepare__(self, arr, context): return np.array(arr).view(type=with_prepare) a = np.array([1]).view(type=with_prepare) x = np.add(a, a, a) # Returned array is new, because of the strange # __array_prepare__ above assert_(not np.shares_memory(x, a)) assert_equal(x, np.array([2])) assert_equal(type(x), with_prepare) def test_failing_prepare(self): class A(object): def __array__(self): return np.zeros(1) def __array_prepare__(self, arr, context=None): raise RuntimeError a = A() assert_raises(RuntimeError, ncu.maximum, a, a) def test_array_with_context(self): class A(object): def __array__(self, dtype=None, context=None): func, args, i = context self.func = func self.args = args self.i = i return np.zeros(1) class B(object): def __array__(self, dtype=None): return np.zeros(1, dtype) class C(object): def __array__(self): return np.zeros(1) a = A() ncu.maximum(np.zeros(1), a) assert_(a.func is ncu.maximum) assert_equal(a.args[0], 0) assert_(a.args[1] is a) assert_(a.i == 1) assert_equal(ncu.maximum(a, B()), 0) assert_equal(ncu.maximum(a, C()), 0) def test_ufunc_override(self): class A(object): def __array_ufunc__(self, func, method, *inputs, **kwargs): return self, func, method, inputs, kwargs a = A() b = np.matrix([1]) res0 = np.multiply(a, b) res1 = np.multiply(b, b, out=a) # self assert_equal(res0[0], a) assert_equal(res1[0], a) assert_equal(res0[1], np.multiply) assert_equal(res1[1], np.multiply) assert_equal(res0[2], '__call__') assert_equal(res1[2], '__call__') assert_equal(res0[3], (a, b)) assert_equal(res1[3], (b, b)) assert_equal(res0[4], {}) assert_equal(res1[4], {'out': (a,)}) def test_ufunc_override_mro(self): # Some multi arg functions for testing. def tres_mul(a, b, c): return a * b * c def quatro_mul(a, b, c, d): return a * b * c * d # Make these into ufuncs. three_mul_ufunc = np.frompyfunc(tres_mul, 3, 1) four_mul_ufunc = np.frompyfunc(quatro_mul, 4, 1) class A(object): def __array_ufunc__(self, func, method, *inputs, **kwargs): return "A" class ASub(A): def __array_ufunc__(self, func, method, *inputs, **kwargs): return "ASub" class B(object): def __array_ufunc__(self, func, method, *inputs, **kwargs): return "B" class C(object): def __array_ufunc__(self, func, method, *inputs, **kwargs): return NotImplemented class CSub(C): def __array_ufunc__(self, func, method, *inputs, **kwargs): return NotImplemented a = A() a_sub = ASub() b = B() c = C() c_sub = CSub() # Standard res = np.multiply(a, a_sub) assert_equal(res, "ASub") res = np.multiply(a_sub, b) assert_equal(res, "ASub") # With 1 NotImplemented res = np.multiply(c, a) assert_equal(res, "A") # Both NotImplemented. assert_raises(TypeError, np.multiply, c, c_sub) assert_raises(TypeError, np.multiply, c_sub, c) assert_raises(TypeError, np.multiply, 2, c) # Ternary testing. assert_equal(three_mul_ufunc(a, 1, 2), "A") assert_equal(three_mul_ufunc(1, a, 2), "A") assert_equal(three_mul_ufunc(1, 2, a), "A") assert_equal(three_mul_ufunc(a, a, 6), "A") assert_equal(three_mul_ufunc(a, 2, a), "A") assert_equal(three_mul_ufunc(a, 2, b), "A") assert_equal(three_mul_ufunc(a, 2, a_sub), "ASub") assert_equal(three_mul_ufunc(a, a_sub, 3), "ASub") assert_equal(three_mul_ufunc(c, a_sub, 3), "ASub") assert_equal(three_mul_ufunc(1, a_sub, c), "ASub") assert_equal(three_mul_ufunc(a, b, c), "A") assert_equal(three_mul_ufunc(a, b, c_sub), "A") assert_equal(three_mul_ufunc(1, 2, b), "B") assert_raises(TypeError, three_mul_ufunc, 1, 2, c) assert_raises(TypeError, three_mul_ufunc, c_sub, 2, c) assert_raises(TypeError, three_mul_ufunc, c_sub, 2, 3) # Quaternary testing. assert_equal(four_mul_ufunc(a, 1, 2, 3), "A") assert_equal(four_mul_ufunc(1, a, 2, 3), "A") assert_equal(four_mul_ufunc(1, 1, a, 3), "A") assert_equal(four_mul_ufunc(1, 1, 2, a), "A") assert_equal(four_mul_ufunc(a, b, 2, 3), "A") assert_equal(four_mul_ufunc(1, a, 2, b), "A") assert_equal(four_mul_ufunc(b, 1, a, 3), "B") assert_equal(four_mul_ufunc(a_sub, 1, 2, a), "ASub") assert_equal(four_mul_ufunc(a, 1, 2, a_sub), "ASub") assert_raises(TypeError, four_mul_ufunc, 1, 2, 3, c) assert_raises(TypeError, four_mul_ufunc, 1, 2, c_sub, c) assert_raises(TypeError, four_mul_ufunc, 1, c, c_sub, c) def test_ufunc_override_methods(self): class A(object): def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): return self, ufunc, method, inputs, kwargs # __call__ a = A() res = np.multiply.__call__(1, a, foo='bar', answer=42) assert_equal(res[0], a) assert_equal(res[1], np.multiply) assert_equal(res[2], '__call__') assert_equal(res[3], (1, a)) assert_equal(res[4], {'foo': 'bar', 'answer': 42}) # __call__, wrong args assert_raises(TypeError, np.multiply, a) assert_raises(TypeError, np.multiply, a, a, a, a) assert_raises(TypeError, np.multiply, a, a, sig='a', signature='a') # reduce, positional args res = np.multiply.reduce(a, 'axis0', 'dtype0', 'out0', 'keep0') assert_equal(res[0], a) assert_equal(res[1], np.multiply) assert_equal(res[2], 'reduce') assert_equal(res[3], (a,)) assert_equal(res[4], {'dtype':'dtype0', 'out': ('out0',), 'keepdims': 'keep0', 'axis': 'axis0'}) # reduce, kwargs res = np.multiply.reduce(a, axis='axis0', dtype='dtype0', out='out0', keepdims='keep0') assert_equal(res[0], a) assert_equal(res[1], np.multiply) assert_equal(res[2], 'reduce') assert_equal(res[3], (a,)) assert_equal(res[4], {'dtype':'dtype0', 'out': ('out0',), 'keepdims': 'keep0', 'axis': 'axis0'}) # reduce, output equal to None removed, but not other explicit ones, # even if they are at their default value. res = np.multiply.reduce(a, 0, None, None, False) assert_equal(res[4], {'axis': 0, 'dtype': None, 'keepdims': False}) res = np.multiply.reduce(a, out=None, axis=0, keepdims=True) assert_equal(res[4], {'axis': 0, 'keepdims': True}) res = np.multiply.reduce(a, None, out=(None,), dtype=None) assert_equal(res[4], {'axis': None, 'dtype': None}) # reduce, wrong args assert_raises(ValueError, np.multiply.reduce, a, out=()) assert_raises(ValueError, np.multiply.reduce, a, out=('out0', 'out1')) assert_raises(TypeError, np.multiply.reduce, a, 'axis0', axis='axis0') # accumulate, pos args res = np.multiply.accumulate(a, 'axis0', 'dtype0', 'out0') assert_equal(res[0], a) assert_equal(res[1], np.multiply) assert_equal(res[2], 'accumulate') assert_equal(res[3], (a,)) assert_equal(res[4], {'dtype':'dtype0', 'out': ('out0',), 'axis': 'axis0'}) # accumulate, kwargs res = np.multiply.accumulate(a, axis='axis0', dtype='dtype0', out='out0') assert_equal(res[0], a) assert_equal(res[1], np.multiply) assert_equal(res[2], 'accumulate') assert_equal(res[3], (a,)) assert_equal(res[4], {'dtype':'dtype0', 'out': ('out0',), 'axis': 'axis0'}) # accumulate, output equal to None removed. res = np.multiply.accumulate(a, 0, None, None) assert_equal(res[4], {'axis': 0, 'dtype': None}) res = np.multiply.accumulate(a, out=None, axis=0, dtype='dtype1') assert_equal(res[4], {'axis': 0, 'dtype': 'dtype1'}) res = np.multiply.accumulate(a, None, out=(None,), dtype=None) assert_equal(res[4], {'axis': None, 'dtype': None}) # accumulate, wrong args assert_raises(ValueError, np.multiply.accumulate, a, out=()) assert_raises(ValueError, np.multiply.accumulate, a, out=('out0', 'out1')) assert_raises(TypeError, np.multiply.accumulate, a, 'axis0', axis='axis0') # reduceat, pos args res = np.multiply.reduceat(a, [4, 2], 'axis0', 'dtype0', 'out0') assert_equal(res[0], a) assert_equal(res[1], np.multiply) assert_equal(res[2], 'reduceat') assert_equal(res[3], (a, [4, 2])) assert_equal(res[4], {'dtype':'dtype0', 'out': ('out0',), 'axis': 'axis0'}) # reduceat, kwargs res = np.multiply.reduceat(a, [4, 2], axis='axis0', dtype='dtype0', out='out0') assert_equal(res[0], a) assert_equal(res[1], np.multiply) assert_equal(res[2], 'reduceat') assert_equal(res[3], (a, [4, 2])) assert_equal(res[4], {'dtype':'dtype0', 'out': ('out0',), 'axis': 'axis0'}) # reduceat, output equal to None removed. res = np.multiply.reduceat(a, [4, 2], 0, None, None) assert_equal(res[4], {'axis': 0, 'dtype': None}) res = np.multiply.reduceat(a, [4, 2], axis=None, out=None, dtype='dt') assert_equal(res[4], {'axis': None, 'dtype': 'dt'}) res = np.multiply.reduceat(a, [4, 2], None, None, out=(None,)) assert_equal(res[4], {'axis': None, 'dtype': None}) # reduceat, wrong args assert_raises(ValueError, np.multiply.reduce, a, [4, 2], out=()) assert_raises(ValueError, np.multiply.reduce, a, [4, 2], out=('out0', 'out1')) assert_raises(TypeError, np.multiply.reduce, a, [4, 2], 'axis0', axis='axis0') # outer res = np.multiply.outer(a, 42) assert_equal(res[0], a) assert_equal(res[1], np.multiply) assert_equal(res[2], 'outer') assert_equal(res[3], (a, 42)) assert_equal(res[4], {}) # outer, wrong args assert_raises(TypeError, np.multiply.outer, a) assert_raises(TypeError, np.multiply.outer, a, a, a, a) assert_raises(TypeError, np.multiply.outer, a, a, sig='a', signature='a') # at res = np.multiply.at(a, [4, 2], 'b0') assert_equal(res[0], a) assert_equal(res[1], np.multiply) assert_equal(res[2], 'at') assert_equal(res[3], (a, [4, 2], 'b0')) # at, wrong args assert_raises(TypeError, np.multiply.at, a) assert_raises(TypeError, np.multiply.at, a, a, a, a) def test_ufunc_override_out(self): class A(object): def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): return kwargs class B(object): def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): return kwargs a = A() b = B() res0 = np.multiply(a, b, 'out_arg') res1 = np.multiply(a, b, out='out_arg') res2 = np.multiply(2, b, 'out_arg') res3 = np.multiply(3, b, out='out_arg') res4 = np.multiply(a, 4, 'out_arg') res5 = np.multiply(a, 5, out='out_arg') assert_equal(res0['out'][0], 'out_arg') assert_equal(res1['out'][0], 'out_arg') assert_equal(res2['out'][0], 'out_arg') assert_equal(res3['out'][0], 'out_arg') assert_equal(res4['out'][0], 'out_arg') assert_equal(res5['out'][0], 'out_arg') # ufuncs with multiple output modf and frexp. res6 = np.modf(a, 'out0', 'out1') res7 = np.frexp(a, 'out0', 'out1') assert_equal(res6['out'][0], 'out0') assert_equal(res6['out'][1], 'out1') assert_equal(res7['out'][0], 'out0') assert_equal(res7['out'][1], 'out1') # While we're at it, check that default output is never passed on. assert_(np.sin(a, None) == {}) assert_(np.sin(a, out=None) == {}) assert_(np.sin(a, out=(None,)) == {}) assert_(np.modf(a, None) == {}) assert_(np.modf(a, None, None) == {}) assert_(np.modf(a, out=(None, None)) == {}) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', DeprecationWarning) assert_(np.modf(a, out=None) == {}) assert_(w[0].category is DeprecationWarning) # don't give positional and output argument, or too many arguments. # wrong number of arguments in the tuple is an error too. assert_raises(TypeError, np.multiply, a, b, 'one', out='two') assert_raises(TypeError, np.multiply, a, b, 'one', 'two') assert_raises(ValueError, np.multiply, a, b, out=('one', 'two')) assert_raises(ValueError, np.multiply, a, out=()) assert_raises(TypeError, np.modf, a, 'one', out=('two', 'three')) assert_raises(TypeError, np.modf, a, 'one', 'two', 'three') assert_raises(ValueError, np.modf, a, out=('one', 'two', 'three')) assert_raises(ValueError, np.modf, a, out=('one',)) def test_ufunc_override_exception(self): class A(object): def __array_ufunc__(self, *a, **kwargs): raise ValueError("oops") a = A() assert_raises(ValueError, np.negative, 1, out=a) assert_raises(ValueError, np.negative, a) assert_raises(ValueError, np.divide, 1., a) def test_ufunc_override_not_implemented(self): class A(object): def __array_ufunc__(self, *args, **kwargs): return NotImplemented msg = ("operand type(s) all returned NotImplemented from " "__array_ufunc__(<ufunc 'negative'>, '__call__', <*>): 'A'") with assert_raises_regex(TypeError, fnmatch.translate(msg)): np.negative(A()) msg = ("operand type(s) all returned NotImplemented from " "__array_ufunc__(<ufunc 'add'>, '__call__', <*>, <object *>, " "out=(1,)): 'A', 'object', 'int'") with assert_raises_regex(TypeError, fnmatch.translate(msg)): np.add(A(), object(), out=1) def test_ufunc_override_disabled(self): class OptOut(object): __array_ufunc__ = None opt_out = OptOut() # ufuncs always raise msg = "operand 'OptOut' does not support ufuncs" with assert_raises_regex(TypeError, msg): np.add(opt_out, 1) with assert_raises_regex(TypeError, msg): np.add(1, opt_out) with assert_raises_regex(TypeError, msg): np.negative(opt_out) # opt-outs still hold even when other arguments have pathological # __array_ufunc__ implementations class GreedyArray(object): def __array_ufunc__(self, *args, **kwargs): return self greedy = GreedyArray() assert_(np.negative(greedy) is greedy) with assert_raises_regex(TypeError, msg): np.add(greedy, opt_out) with assert_raises_regex(TypeError, msg): np.add(greedy, 1, out=opt_out) def test_gufunc_override(self): # gufunc are just ufunc instances, but follow a different path, # so check __array_ufunc__ overrides them properly. class A(object): def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): return self, ufunc, method, inputs, kwargs inner1d = ncu_tests.inner1d a = A() res = inner1d(a, a) assert_equal(res[0], a) assert_equal(res[1], inner1d) assert_equal(res[2], '__call__') assert_equal(res[3], (a, a)) assert_equal(res[4], {}) res = inner1d(1, 1, out=a) assert_equal(res[0], a) assert_equal(res[1], inner1d) assert_equal(res[2], '__call__') assert_equal(res[3], (1, 1)) assert_equal(res[4], {'out': (a,)}) # wrong number of arguments in the tuple is an error too. assert_raises(TypeError, inner1d, a, out='two') assert_raises(TypeError, inner1d, a, a, 'one', out='two') assert_raises(TypeError, inner1d, a, a, 'one', 'two') assert_raises(ValueError, inner1d, a, a, out=('one', 'two')) assert_raises(ValueError, inner1d, a, a, out=()) def test_ufunc_override_with_super(self): # NOTE: this class is given as an example in doc/subclassing.py; # if you make any changes here, do update it there too. class A(np.ndarray): def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): args = [] in_no = [] for i, input_ in enumerate(inputs): if isinstance(input_, A): in_no.append(i) args.append(input_.view(np.ndarray)) else: args.append(input_) outputs = kwargs.pop('out', None) out_no = [] if outputs: out_args = [] for j, output in enumerate(outputs): if isinstance(output, A): out_no.append(j) out_args.append(output.view(np.ndarray)) else: out_args.append(output) kwargs['out'] = tuple(out_args) else: outputs = (None,) * ufunc.nout info = {} if in_no: info['inputs'] = in_no if out_no: info['outputs'] = out_no results = super(A, self).__array_ufunc__(ufunc, method, *args, **kwargs) if results is NotImplemented: return NotImplemented if method == 'at': if isinstance(inputs[0], A): inputs[0].info = info return if ufunc.nout == 1: results = (results,) results = tuple((np.asarray(result).view(A) if output is None else output) for result, output in zip(results, outputs)) if results and isinstance(results[0], A): results[0].info = info return results[0] if len(results) == 1 else results class B(object): def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): if any(isinstance(input_, A) for input_ in inputs): return "A!" else: return NotImplemented d = np.arange(5.) # 1 input, 1 output a = np.arange(5.).view(A) b = np.sin(a) check = np.sin(d) assert_(np.all(check == b)) assert_equal(b.info, {'inputs': [0]}) b = np.sin(d, out=(a,)) assert_(np.all(check == b)) assert_equal(b.info, {'outputs': [0]}) assert_(b is a) a = np.arange(5.).view(A) b = np.sin(a, out=a) assert_(np.all(check == b)) assert_equal(b.info, {'inputs': [0], 'outputs': [0]}) # 1 input, 2 outputs a = np.arange(5.).view(A) b1, b2 = np.modf(a) assert_equal(b1.info, {'inputs': [0]}) b1, b2 = np.modf(d, out=(None, a)) assert_(b2 is a) assert_equal(b1.info, {'outputs': [1]}) a = np.arange(5.).view(A) b = np.arange(5.).view(A) c1, c2 = np.modf(a, out=(a, b)) assert_(c1 is a) assert_(c2 is b) assert_equal(c1.info, {'inputs': [0], 'outputs': [0, 1]}) # 2 input, 1 output a = np.arange(5.).view(A) b = np.arange(5.).view(A) c = np.add(a, b, out=a) assert_(c is a) assert_equal(c.info, {'inputs': [0, 1], 'outputs': [0]}) # some tests with a non-ndarray subclass a = np.arange(5.) b = B() assert_(a.__array_ufunc__(np.add, '__call__', a, b) is NotImplemented) assert_(b.__array_ufunc__(np.add, '__call__', a, b) is NotImplemented) assert_raises(TypeError, np.add, a, b) a = a.view(A) assert_(a.__array_ufunc__(np.add, '__call__', a, b) is NotImplemented) assert_(b.__array_ufunc__(np.add, '__call__', a, b) == "A!") assert_(np.add(a, b) == "A!") # regression check for gh-9102 -- tests ufunc.reduce implicitly. d = np.array([[1, 2, 3], [1, 2, 3]]) a = d.view(A) c = a.any() check = d.any() assert_equal(c, check) assert_(c.info, {'inputs': [0]}) c = a.max() check = d.max() assert_equal(c, check) assert_(c.info, {'inputs': [0]}) b = np.array(0).view(A) c = a.max(out=b) assert_equal(c, check) assert_(c is b) assert_(c.info, {'inputs': [0], 'outputs': [0]}) check = a.max(axis=0) b = np.zeros_like(check).view(A) c = a.max(axis=0, out=b) assert_equal(c, check) assert_(c is b) assert_(c.info, {'inputs': [0], 'outputs': [0]}) # simple explicit tests of reduce, accumulate, reduceat check = np.add.reduce(d, axis=1) c = np.add.reduce(a, axis=1) assert_equal(c, check) assert_(c.info, {'inputs': [0]}) b = np.zeros_like(c) c = np.add.reduce(a, 1, None, b) assert_equal(c, check) assert_(c is b) assert_(c.info, {'inputs': [0], 'outputs': [0]}) check = np.add.accumulate(d, axis=0) c = np.add.accumulate(a, axis=0) assert_equal(c, check) assert_(c.info, {'inputs': [0]}) b = np.zeros_like(c) c = np.add.accumulate(a, 0, None, b) assert_equal(c, check) assert_(c is b) assert_(c.info, {'inputs': [0], 'outputs': [0]}) indices = [0, 2, 1] check = np.add.reduceat(d, indices, axis=1) c = np.add.reduceat(a, indices, axis=1) assert_equal(c, check) assert_(c.info, {'inputs': [0]}) b = np.zeros_like(c) c = np.add.reduceat(a, indices, 1, None, b) assert_equal(c, check) assert_(c is b) assert_(c.info, {'inputs': [0], 'outputs': [0]}) # and a few tests for at d = np.array([[1, 2, 3], [1, 2, 3]]) check = d.copy() a = d.copy().view(A) np.add.at(check, ([0, 1], [0, 2]), 1.) np.add.at(a, ([0, 1], [0, 2]), 1.) assert_equal(a, check) assert_(a.info, {'inputs': [0]}) b = np.array(1.).view(A) a = d.copy().view(A) np.add.at(a, ([0, 1], [0, 2]), b) assert_equal(a, check) assert_(a.info, {'inputs': [0, 2]}) class TestChoose(object): def test_mixed(self): c = np.array([True, True]) a = np.array([True, True]) assert_equal(np.choose(c, (a, 1)), np.array([1, 1])) def is_longdouble_finfo_bogus(): info = np.finfo(np.longcomplex) return not np.isfinite(np.log10(info.tiny/info.eps)) class TestComplexFunctions(object): funcs = [np.arcsin, np.arccos, np.arctan, np.arcsinh, np.arccosh, np.arctanh, np.sin, np.cos, np.tan, np.exp, np.exp2, np.log, np.sqrt, np.log10, np.log2, np.log1p] def test_it(self): for f in self.funcs: if f is np.arccosh: x = 1.5 else: x = .5 fr = f(x) fz = f(complex(x)) assert_almost_equal(fz.real, fr, err_msg='real part %s' % f) assert_almost_equal(fz.imag, 0., err_msg='imag part %s' % f) def test_precisions_consistent(self): z = 1 + 1j for f in self.funcs: fcf = f(np.csingle(z)) fcd = f(np.cdouble(z)) fcl = f(np.clongdouble(z)) assert_almost_equal(fcf, fcd, decimal=6, err_msg='fch-fcd %s' % f) assert_almost_equal(fcl, fcd, decimal=15, err_msg='fch-fcl %s' % f) def test_branch_cuts(self): # check branch cuts and continuity on them yield _check_branch_cut, np.log, -0.5, 1j, 1, -1, True yield _check_branch_cut, np.log2, -0.5, 1j, 1, -1, True yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1, True yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1, True yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1, True yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, 1j], 1, -1, True yield _check_branch_cut, np.arccos, [ -2, 2], [1j, 1j], 1, -1, True yield _check_branch_cut, np.arctan, [0-2j, 2j], [1, 1], -1, 1, True yield _check_branch_cut, np.arcsinh, [0-2j, 2j], [1, 1], -1, 1, True yield _check_branch_cut, np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True yield _check_branch_cut, np.arctanh, [ -2, 2], [1j, 1j], 1, -1, True # check against bogus branch cuts: assert continuity between quadrants yield _check_branch_cut, np.arcsin, [0-2j, 2j], [ 1, 1], 1, 1 yield _check_branch_cut, np.arccos, [0-2j, 2j], [ 1, 1], 1, 1 yield _check_branch_cut, np.arctan, [ -2, 2], [1j, 1j], 1, 1 yield _check_branch_cut, np.arcsinh, [ -2, 2, 0], [1j, 1j, 1], 1, 1 yield _check_branch_cut, np.arccosh, [0-2j, 2j, 2], [1, 1, 1j], 1, 1 yield _check_branch_cut, np.arctanh, [0-2j, 2j, 0], [1, 1, 1j], 1, 1 def test_branch_cuts_complex64(self): # check branch cuts and continuity on them yield _check_branch_cut, np.log, -0.5, 1j, 1, -1, True, np.complex64 yield _check_branch_cut, np.log2, -0.5, 1j, 1, -1, True, np.complex64 yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1, True, np.complex64 yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1, True, np.complex64 yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1, True, np.complex64 yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64 yield _check_branch_cut, np.arccos, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64 yield _check_branch_cut, np.arctan, [0-2j, 2j], [1, 1], -1, 1, True, np.complex64 yield _check_branch_cut, np.arcsinh, [0-2j, 2j], [1, 1], -1, 1, True, np.complex64 yield _check_branch_cut, np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True, np.complex64 yield _check_branch_cut, np.arctanh, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64 # check against bogus branch cuts: assert continuity between quadrants yield _check_branch_cut, np.arcsin, [0-2j, 2j], [ 1, 1], 1, 1, False, np.complex64 yield _check_branch_cut, np.arccos, [0-2j, 2j], [ 1, 1], 1, 1, False, np.complex64 yield _check_branch_cut, np.arctan, [ -2, 2], [1j, 1j], 1, 1, False, np.complex64 yield _check_branch_cut, np.arcsinh, [ -2, 2, 0], [1j, 1j, 1], 1, 1, False, np.complex64 yield _check_branch_cut, np.arccosh, [0-2j, 2j, 2], [1, 1, 1j], 1, 1, False, np.complex64 yield _check_branch_cut, np.arctanh, [0-2j, 2j, 0], [1, 1, 1j], 1, 1, False, np.complex64 def test_against_cmath(self): import cmath points = [-1-1j, -1+1j, +1-1j, +1+1j] name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan', 'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'} atol = 4*np.finfo(complex).eps for func in self.funcs: fname = func.__name__.split('.')[-1] cname = name_map.get(fname, fname) try: cfunc = getattr(cmath, cname) except AttributeError: continue for p in points: a = complex(func(np.complex_(p))) b = cfunc(p) assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s" % (fname, p, a, b)) def check_loss_of_precision(self, dtype): """Check loss of precision in complex arc* functions""" # Check against known-good functions info = np.finfo(dtype) real_dtype = dtype(0.).real.dtype eps = info.eps def check(x, rtol): x = x.astype(real_dtype) z = x.astype(dtype) d = np.absolute(np.arcsinh(x)/np.arcsinh(z).real - 1) assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(), 'arcsinh')) z = (1j*x).astype(dtype) d = np.absolute(np.arcsinh(x)/np.arcsin(z).imag - 1) assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(), 'arcsin')) z = x.astype(dtype) d = np.absolute(np.arctanh(x)/np.arctanh(z).real - 1) assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(), 'arctanh')) z = (1j*x).astype(dtype) d = np.absolute(np.arctanh(x)/np.arctan(z).imag - 1) assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(), 'arctan')) # The switchover was chosen as 1e-3; hence there can be up to # ~eps/1e-3 of relative cancellation error before it x_series = np.logspace(-20, -3.001, 200) x_basic = np.logspace(-2.999, 0, 10, endpoint=False) if dtype is np.longcomplex: # It's not guaranteed that the system-provided arc functions # are accurate down to a few epsilons. (Eg. on Linux 64-bit) # So, give more leeway for long complex tests here: check(x_series, 50*eps) else: check(x_series, 2.1*eps) check(x_basic, 2*eps/1e-3) # Check a few points z = np.array([1e-5*(1+1j)], dtype=dtype) p = 9.999999999333333333e-6 + 1.000000000066666666e-5j d = np.absolute(1-np.arctanh(z)/p) assert_(np.all(d < 1e-15)) p = 1.0000000000333333333e-5 + 9.999999999666666667e-6j d = np.absolute(1-np.arcsinh(z)/p) assert_(np.all(d < 1e-15)) p = 9.999999999333333333e-6j + 1.000000000066666666e-5 d = np.absolute(1-np.arctan(z)/p) assert_(np.all(d < 1e-15)) p = 1.0000000000333333333e-5j + 9.999999999666666667e-6 d = np.absolute(1-np.arcsin(z)/p) assert_(np.all(d < 1e-15)) # Check continuity across switchover points def check(func, z0, d=1): z0 = np.asarray(z0, dtype=dtype) zp = z0 + abs(z0) * d * eps * 2 zm = z0 - abs(z0) * d * eps * 2 assert_(np.all(zp != zm), (zp, zm)) # NB: the cancellation error at the switchover is at least eps good = (abs(func(zp) - func(zm)) < 2*eps) assert_(np.all(good), (func, z0[~good])) for func in (np.arcsinh, np.arcsinh, np.arcsin, np.arctanh, np.arctan): pts = [rp+1j*ip for rp in (-1e-3, 0, 1e-3) for ip in(-1e-3, 0, 1e-3) if rp != 0 or ip != 0] check(func, pts, 1) check(func, pts, 1j) check(func, pts, 1+1j) def test_loss_of_precision(self): for dtype in [np.complex64, np.complex_]: yield self.check_loss_of_precision, dtype @dec.knownfailureif(is_longdouble_finfo_bogus(), "Bogus long double finfo") def test_loss_of_precision_longcomplex(self): self.check_loss_of_precision(np.longcomplex) class TestAttributes(object): def test_attributes(self): add = ncu.add assert_equal(add.__name__, 'add') assert_(add.ntypes >= 18) # don't fail if types added assert_('ii->i' in add.types) assert_equal(add.nin, 2) assert_equal(add.nout, 1) assert_equal(add.identity, 0) def test_doc(self): # don't bother checking the long list of kwargs, which are likely to # change assert_(ncu.add.__doc__.startswith( "add(x1, x2, /, out=None, *, where=True")) assert_(ncu.frexp.__doc__.startswith( "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) class TestSubclass(object): def test_subclass_op(self): class simple(np.ndarray): def __new__(subtype, shape): self = np.ndarray.__new__(subtype, shape, dtype=object) self.fill(0) return self a = simple((3, 4)) assert_equal(a+a, a) def _check_branch_cut(f, x0, dx, re_sign=1, im_sign=-1, sig_zero_ok=False, dtype=complex): """ Check for a branch cut in a function. Assert that `x0` lies on a branch cut of function `f` and `f` is continuous from the direction `dx`. Parameters ---------- f : func Function to check x0 : array-like Point on branch cut dx : array-like Direction to check continuity in re_sign, im_sign : {1, -1} Change of sign of the real or imaginary part expected sig_zero_ok : bool Whether to check if the branch cut respects signed zero (if applicable) dtype : dtype Dtype to check (should be complex) """ x0 = np.atleast_1d(x0).astype(dtype) dx = np.atleast_1d(dx).astype(dtype) if np.dtype(dtype).char == 'F': scale = np.finfo(dtype).eps * 1e2 atol = np.float32(1e-2) else: scale = np.finfo(dtype).eps * 1e3 atol = 1e-4 y0 = f(x0) yp = f(x0 + dx*scale*np.absolute(x0)/np.absolute(dx)) ym = f(x0 - dx*scale*np.absolute(x0)/np.absolute(dx)) assert_(np.all(np.absolute(y0.real - yp.real) < atol), (y0, yp)) assert_(np.all(np.absolute(y0.imag - yp.imag) < atol), (y0, yp)) assert_(np.all(np.absolute(y0.real - ym.real*re_sign) < atol), (y0, ym)) assert_(np.all(np.absolute(y0.imag - ym.imag*im_sign) < atol), (y0, ym)) if sig_zero_ok: # check that signed zeros also work as a displacement jr = (x0.real == 0) & (dx.real != 0) ji = (x0.imag == 0) & (dx.imag != 0) if np.any(jr): x = x0[jr] x.real = np.NZERO ym = f(x) assert_(np.all(np.absolute(y0[jr].real - ym.real*re_sign) < atol), (y0[jr], ym)) assert_(np.all(np.absolute(y0[jr].imag - ym.imag*im_sign) < atol), (y0[jr], ym)) if np.any(ji): x = x0[ji] x.imag = np.NZERO ym = f(x) assert_(np.all(np.absolute(y0[ji].real - ym.real*re_sign) < atol), (y0[ji], ym)) assert_(np.all(np.absolute(y0[ji].imag - ym.imag*im_sign) < atol), (y0[ji], ym)) def test_copysign(): assert_(np.copysign(1, -1) == -1) with np.errstate(divide="ignore"): assert_(1 / np.copysign(0, -1) < 0) assert_(1 / np.copysign(0, 1) > 0) assert_(np.signbit(np.copysign(np.nan, -1))) assert_(not np.signbit(np.copysign(np.nan, 1))) def _test_nextafter(t): one = t(1) two = t(2) zero = t(0) eps = np.finfo(t).eps assert_(np.nextafter(one, two) - one == eps) assert_(np.nextafter(one, zero) - one < 0) assert_(np.isnan(np.nextafter(np.nan, one))) assert_(np.isnan(np.nextafter(one, np.nan))) assert_(np.nextafter(one, one) == one) def test_nextafter(): return _test_nextafter(np.float64) def test_nextafterf(): return _test_nextafter(np.float32) @dec.knownfailureif(sys.platform == 'win32', "Long double support buggy on win32, ticket 1664.") def test_nextafterl(): return _test_nextafter(np.longdouble) def test_nextafter_0(): for t, direction in itertools.product(np.sctypes['float'], (1, -1)): tiny = np.finfo(t).tiny assert_(0. < direction * np.nextafter(t(0), t(direction)) < tiny) assert_equal(np.nextafter(t(0), t(direction)) / t(2.1), direction * 0.0) def _test_spacing(t): one = t(1) eps = np.finfo(t).eps nan = t(np.nan) inf = t(np.inf) with np.errstate(invalid='ignore'): assert_(np.spacing(one) == eps) assert_(np.isnan(np.spacing(nan))) assert_(np.isnan(np.spacing(inf))) assert_(np.isnan(np.spacing(-inf))) assert_(np.spacing(t(1e30)) != 0) def test_spacing(): return _test_spacing(np.float64) def test_spacingf(): return _test_spacing(np.float32) @dec.knownfailureif(sys.platform == 'win32', "Long double support buggy on win32, ticket 1664.") def test_spacingl(): return _test_spacing(np.longdouble) def test_spacing_gfortran(): # Reference from this fortran file, built with gfortran 4.3.3 on linux # 32bits: # PROGRAM test_spacing # INTEGER, PARAMETER :: SGL = SELECTED_REAL_KIND(p=6, r=37) # INTEGER, PARAMETER :: DBL = SELECTED_REAL_KIND(p=13, r=200) # # WRITE(*,*) spacing(0.00001_DBL) # WRITE(*,*) spacing(1.0_DBL) # WRITE(*,*) spacing(1000._DBL) # WRITE(*,*) spacing(10500._DBL) # # WRITE(*,*) spacing(0.00001_SGL) # WRITE(*,*) spacing(1.0_SGL) # WRITE(*,*) spacing(1000._SGL) # WRITE(*,*) spacing(10500._SGL) # END PROGRAM ref = {np.float64: [1.69406589450860068E-021, 2.22044604925031308E-016, 1.13686837721616030E-013, 1.81898940354585648E-012], np.float32: [9.09494702E-13, 1.19209290E-07, 6.10351563E-05, 9.76562500E-04]} for dt, dec_ in zip([np.float32, np.float64], (10, 20)): x = np.array([1e-5, 1, 1000, 10500], dtype=dt) assert_array_almost_equal(np.spacing(x), ref[dt], decimal=dec_) def test_nextafter_vs_spacing(): # XXX: spacing does not handle long double yet for t in [np.float32, np.float64]: for _f in [1, 1e-5, 1000]: f = t(_f) f1 = t(_f + 1) assert_(np.nextafter(f, f1) - f == np.spacing(f)) def test_pos_nan(): """Check np.nan is a positive nan.""" assert_(np.signbit(np.nan) == 0) def test_reduceat(): """Test bug in reduceat when structured arrays are not copied.""" db = np.dtype([('name', 'S11'), ('time', np.int64), ('value', np.float32)]) a = np.empty([100], dtype=db) a['name'] = 'Simple' a['time'] = 10 a['value'] = 100 indx = [0, 7, 15, 25] h2 = [] val1 = indx[0] for val2 in indx[1:]: h2.append(np.add.reduce(a['value'][val1:val2])) val1 = val2 h2.append(np.add.reduce(a['value'][val1:])) h2 = np.array(h2) # test buffered -- this should work h1 = np.add.reduceat(a['value'], indx) assert_array_almost_equal(h1, h2) # This is when the error occurs. # test no buffer np.setbufsize(32) h1 = np.add.reduceat(a['value'], indx) np.setbufsize(np.UFUNC_BUFSIZE_DEFAULT) assert_array_almost_equal(h1, h2) def test_reduceat_empty(): """Reduceat should work with empty arrays""" indices = np.array([], 'i4') x = np.array([], 'f8') result = np.add.reduceat(x, indices) assert_equal(result.dtype, x.dtype) assert_equal(result.shape, (0,)) # Another case with a slightly different zero-sized shape x = np.ones((5, 2)) result = np.add.reduceat(x, [], axis=0) assert_equal(result.dtype, x.dtype) assert_equal(result.shape, (0, 2)) result = np.add.reduceat(x, [], axis=1) assert_equal(result.dtype, x.dtype) assert_equal(result.shape, (5, 0)) def test_complex_nan_comparisons(): nans = [complex(np.nan, 0), complex(0, np.nan), complex(np.nan, np.nan)] fins = [complex(1, 0), complex(-1, 0), complex(0, 1), complex(0, -1), complex(1, 1), complex(-1, -1), complex(0, 0)] with np.errstate(invalid='ignore'): for x in nans + fins: x = np.array([x]) for y in nans + fins: y = np.array([y]) if np.isfinite(x) and np.isfinite(y): continue assert_equal(x < y, False, err_msg="%r < %r" % (x, y)) assert_equal(x > y, False, err_msg="%r > %r" % (x, y)) assert_equal(x <= y, False, err_msg="%r <= %r" % (x, y)) assert_equal(x >= y, False, err_msg="%r >= %r" % (x, y)) assert_equal(x == y, False, err_msg="%r == %r" % (x, y)) def test_rint_big_int(): # np.rint bug for large integer values on Windows 32-bit and MKL # https://github.com/numpy/numpy/issues/6685 val = 4607998452777363968 # This is exactly representable in floating point assert_equal(val, int(float(val))) # Rint should not change the value assert_equal(val, np.rint(val)) def test_signaling_nan_exceptions(): with assert_no_warnings(): a = np.ndarray(shape=(), dtype='float32', buffer=b'\x00\xe0\xbf\xff') np.isnan(a) if __name__ == "__main__": run_module_suite()
99,647
36.057642
135
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/tests/test_arrayprint.py
# -*- coding: utf-8 -*- from __future__ import division, absolute_import, print_function import sys, gc import numpy as np from numpy.testing import ( run_module_suite, assert_, assert_equal, assert_raises, assert_warns, dec ) import textwrap class TestArrayRepr(object): def test_nan_inf(self): x = np.array([np.nan, np.inf]) assert_equal(repr(x), 'array([nan, inf])') def test_subclass(self): class sub(np.ndarray): pass # one dimensional x1d = np.array([1, 2]).view(sub) assert_equal(repr(x1d), 'sub([1, 2])') # two dimensional x2d = np.array([[1, 2], [3, 4]]).view(sub) assert_equal(repr(x2d), 'sub([[1, 2],\n' ' [3, 4]])') # two dimensional with flexible dtype xstruct = np.ones((2,2), dtype=[('a', '<i4')]).view(sub) assert_equal(repr(xstruct), "sub([[(1,), (1,)],\n" " [(1,), (1,)]], dtype=[('a', '<i4')])" ) @dec.knownfailureif(True, "See gh-10544") def test_object_subclass(self): class sub(np.ndarray): def __new__(cls, inp): obj = np.asarray(inp).view(cls) return obj def __getitem__(self, ind): ret = super(sub, self).__getitem__(ind) return sub(ret) # test that object + subclass is OK: x = sub([None, None]) assert_equal(repr(x), 'sub([None, None], dtype=object)') assert_equal(str(x), '[None None]') x = sub([None, sub([None, None])]) assert_equal(repr(x), 'sub([None, sub([None, None], dtype=object)], dtype=object)') assert_equal(str(x), '[None sub([None, None], dtype=object)]') def test_0d_object_subclass(self): # make sure that subclasses which return 0ds instead # of scalars don't cause infinite recursion in str class sub(np.ndarray): def __new__(cls, inp): obj = np.asarray(inp).view(cls) return obj def __getitem__(self, ind): ret = super(sub, self).__getitem__(ind) return sub(ret) x = sub(1) assert_equal(repr(x), 'sub(1)') assert_equal(str(x), '1') x = sub([1, 1]) assert_equal(repr(x), 'sub([1, 1])') assert_equal(str(x), '[1 1]') # check it works properly with object arrays too x = sub(None) assert_equal(repr(x), 'sub(None, dtype=object)') assert_equal(str(x), 'None') # plus recursive object arrays (even depth > 1) y = sub(None) x[()] = y y[()] = x assert_equal(repr(x), 'sub(sub(sub(..., dtype=object), dtype=object), dtype=object)') assert_equal(str(x), '...') # nested 0d-subclass-object x = sub(None) x[()] = sub(None) assert_equal(repr(x), 'sub(sub(None, dtype=object), dtype=object)') assert_equal(str(x), 'None') # gh-10663 class DuckCounter(np.ndarray): def __getitem__(self, item): result = super(DuckCounter, self).__getitem__(item) if not isinstance(result, DuckCounter): result = result[...].view(DuckCounter) return result def to_string(self): return {0: 'zero', 1: 'one', 2: 'two'}.get(self.item(), 'many') def __str__(self): if self.shape == (): return self.to_string() else: fmt = {'all': lambda x: x.to_string()} return np.array2string(self, formatter=fmt) dc = np.arange(5).view(DuckCounter) assert_equal(str(dc), "[zero one two many many]") assert_equal(str(dc[0]), "zero") def test_self_containing(self): arr0d = np.array(None) arr0d[()] = arr0d assert_equal(repr(arr0d), 'array(array(..., dtype=object), dtype=object)') arr1d = np.array([None, None]) arr1d[1] = arr1d assert_equal(repr(arr1d), 'array([None, array(..., dtype=object)], dtype=object)') first = np.array(None) second = np.array(None) first[()] = second second[()] = first assert_equal(repr(first), 'array(array(array(..., dtype=object), dtype=object), dtype=object)') def test_containing_list(self): # printing square brackets directly would be ambiguuous arr1d = np.array([None, None]) arr1d[0] = [1, 2] arr1d[1] = [3] assert_equal(repr(arr1d), 'array([list([1, 2]), list([3])], dtype=object)') def test_void_scalar_recursion(self): # gh-9345 repr(np.void(b'test')) # RecursionError ? def test_fieldless_structured(self): # gh-10366 no_fields = np.dtype([]) arr_no_fields = np.empty(4, dtype=no_fields) assert_equal(repr(arr_no_fields), 'array([(), (), (), ()], dtype=[])') class TestComplexArray(object): def test_str(self): rvals = [0, 1, -1, np.inf, -np.inf, np.nan] cvals = [complex(rp, ip) for rp in rvals for ip in rvals] dtypes = [np.complex64, np.cdouble, np.clongdouble] actual = [str(np.array([c], dt)) for c in cvals for dt in dtypes] wanted = [ '[0.+0.j]', '[0.+0.j]', '[0.+0.j]', '[0.+1.j]', '[0.+1.j]', '[0.+1.j]', '[0.-1.j]', '[0.-1.j]', '[0.-1.j]', '[0.+infj]', '[0.+infj]', '[0.+infj]', '[0.-infj]', '[0.-infj]', '[0.-infj]', '[0.+nanj]', '[0.+nanj]', '[0.+nanj]', '[1.+0.j]', '[1.+0.j]', '[1.+0.j]', '[1.+1.j]', '[1.+1.j]', '[1.+1.j]', '[1.-1.j]', '[1.-1.j]', '[1.-1.j]', '[1.+infj]', '[1.+infj]', '[1.+infj]', '[1.-infj]', '[1.-infj]', '[1.-infj]', '[1.+nanj]', '[1.+nanj]', '[1.+nanj]', '[-1.+0.j]', '[-1.+0.j]', '[-1.+0.j]', '[-1.+1.j]', '[-1.+1.j]', '[-1.+1.j]', '[-1.-1.j]', '[-1.-1.j]', '[-1.-1.j]', '[-1.+infj]', '[-1.+infj]', '[-1.+infj]', '[-1.-infj]', '[-1.-infj]', '[-1.-infj]', '[-1.+nanj]', '[-1.+nanj]', '[-1.+nanj]', '[inf+0.j]', '[inf+0.j]', '[inf+0.j]', '[inf+1.j]', '[inf+1.j]', '[inf+1.j]', '[inf-1.j]', '[inf-1.j]', '[inf-1.j]', '[inf+infj]', '[inf+infj]', '[inf+infj]', '[inf-infj]', '[inf-infj]', '[inf-infj]', '[inf+nanj]', '[inf+nanj]', '[inf+nanj]', '[-inf+0.j]', '[-inf+0.j]', '[-inf+0.j]', '[-inf+1.j]', '[-inf+1.j]', '[-inf+1.j]', '[-inf-1.j]', '[-inf-1.j]', '[-inf-1.j]', '[-inf+infj]', '[-inf+infj]', '[-inf+infj]', '[-inf-infj]', '[-inf-infj]', '[-inf-infj]', '[-inf+nanj]', '[-inf+nanj]', '[-inf+nanj]', '[nan+0.j]', '[nan+0.j]', '[nan+0.j]', '[nan+1.j]', '[nan+1.j]', '[nan+1.j]', '[nan-1.j]', '[nan-1.j]', '[nan-1.j]', '[nan+infj]', '[nan+infj]', '[nan+infj]', '[nan-infj]', '[nan-infj]', '[nan-infj]', '[nan+nanj]', '[nan+nanj]', '[nan+nanj]'] for res, val in zip(actual, wanted): assert_equal(res, val) class TestArray2String(object): def test_basic(self): """Basic test of array2string.""" a = np.arange(3) assert_(np.array2string(a) == '[0 1 2]') assert_(np.array2string(a, max_line_width=4, legacy='1.13') == '[0 1\n 2]') assert_(np.array2string(a, max_line_width=4) == '[0\n 1\n 2]') def test_format_function(self): """Test custom format function for each element in array.""" def _format_function(x): if np.abs(x) < 1: return '.' elif np.abs(x) < 2: return 'o' else: return 'O' x = np.arange(3) if sys.version_info[0] >= 3: x_hex = "[0x0 0x1 0x2]" x_oct = "[0o0 0o1 0o2]" else: x_hex = "[0x0L 0x1L 0x2L]" x_oct = "[0L 01L 02L]" assert_(np.array2string(x, formatter={'all':_format_function}) == "[. o O]") assert_(np.array2string(x, formatter={'int_kind':_format_function}) == "[. o O]") assert_(np.array2string(x, formatter={'all':lambda x: "%.4f" % x}) == "[0.0000 1.0000 2.0000]") assert_equal(np.array2string(x, formatter={'int':lambda x: hex(x)}), x_hex) assert_equal(np.array2string(x, formatter={'int':lambda x: oct(x)}), x_oct) x = np.arange(3.) assert_(np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) == "[0.00 1.00 2.00]") assert_(np.array2string(x, formatter={'float':lambda x: "%.2f" % x}) == "[0.00 1.00 2.00]") s = np.array(['abc', 'def']) assert_(np.array2string(s, formatter={'numpystr':lambda s: s*2}) == '[abcabc defdef]') # check for backcompat that using FloatFormat works and emits warning with assert_warns(DeprecationWarning): fmt = np.core.arrayprint.FloatFormat(x, 9, 'maxprec', False) assert_equal(np.array2string(x, formatter={'float_kind': fmt}), '[0. 1. 2.]') def test_structure_format(self): dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) x = np.array([('Sarah', (8.0, 7.0)), ('John', (6.0, 7.0))], dtype=dt) assert_equal(np.array2string(x), "[('Sarah', [8., 7.]) ('John', [6., 7.])]") np.set_printoptions(legacy='1.13') try: # for issue #5692 A = np.zeros(shape=10, dtype=[("A", "M8[s]")]) A[5:].fill(np.datetime64('NaT')) assert_equal( np.array2string(A), textwrap.dedent("""\ [('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) ('NaT',) ('NaT',) ('NaT',) ('NaT',) ('NaT',)]""") ) finally: np.set_printoptions(legacy=False) # same again, but with non-legacy behavior assert_equal( np.array2string(A), textwrap.dedent("""\ [('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) ( 'NaT',) ( 'NaT',) ( 'NaT',) ( 'NaT',) ( 'NaT',)]""") ) # and again, with timedeltas A = np.full(10, 123456, dtype=[("A", "m8[s]")]) A[5:].fill(np.datetime64('NaT')) assert_equal( np.array2string(A), textwrap.dedent("""\ [(123456,) (123456,) (123456,) (123456,) (123456,) ( 'NaT',) ( 'NaT',) ( 'NaT',) ( 'NaT',) ( 'NaT',)]""") ) # See #8160 struct_int = np.array([([1, -1],), ([123, 1],)], dtype=[('B', 'i4', 2)]) assert_equal(np.array2string(struct_int), "[([ 1, -1],) ([123, 1],)]") struct_2dint = np.array([([[0, 1], [2, 3]],), ([[12, 0], [0, 0]],)], dtype=[('B', 'i4', (2, 2))]) assert_equal(np.array2string(struct_2dint), "[([[ 0, 1], [ 2, 3]],) ([[12, 0], [ 0, 0]],)]") # See #8172 array_scalar = np.array( (1., 2.1234567890123456789, 3.), dtype=('f8,f8,f8')) assert_equal(np.array2string(array_scalar), "(1., 2.12345679, 3.)") def test_unstructured_void_repr(self): a = np.array([27, 91, 50, 75, 7, 65, 10, 8, 27, 91, 51, 49,109, 82,101,100], dtype='u1').view('V8') assert_equal(repr(a[0]), r"void(b'\x1B\x5B\x32\x4B\x07\x41\x0A\x08')") assert_equal(str(a[0]), r"b'\x1B\x5B\x32\x4B\x07\x41\x0A\x08'") assert_equal(repr(a), r"array([b'\x1B\x5B\x32\x4B\x07\x41\x0A\x08'," "\n" r" b'\x1B\x5B\x33\x31\x6D\x52\x65\x64'], dtype='|V8')") assert_equal(eval(repr(a), vars(np)), a) assert_equal(eval(repr(a[0]), vars(np)), a[0]) def test_edgeitems_kwarg(self): # previously the global print options would be taken over the kwarg arr = np.zeros(3, int) assert_equal( np.array2string(arr, edgeitems=1, threshold=0), "[0 ... 0]" ) def test_summarize_1d(self): A = np.arange(1001) strA = '[ 0 1 2 ... 998 999 1000]' assert_equal(str(A), strA) reprA = 'array([ 0, 1, 2, ..., 998, 999, 1000])' assert_equal(repr(A), reprA) def test_summarize_2d(self): A = np.arange(1002).reshape(2, 501) strA = '[[ 0 1 2 ... 498 499 500]\n' \ ' [ 501 502 503 ... 999 1000 1001]]' assert_equal(str(A), strA) reprA = 'array([[ 0, 1, 2, ..., 498, 499, 500],\n' \ ' [ 501, 502, 503, ..., 999, 1000, 1001]])' assert_equal(repr(A), reprA) def test_linewidth(self): a = np.full(6, 1) def make_str(a, width, **kw): return np.array2string(a, separator="", max_line_width=width, **kw) assert_equal(make_str(a, 8, legacy='1.13'), '[111111]') assert_equal(make_str(a, 7, legacy='1.13'), '[111111]') assert_equal(make_str(a, 5, legacy='1.13'), '[1111\n' ' 11]') assert_equal(make_str(a, 8), '[111111]') assert_equal(make_str(a, 7), '[11111\n' ' 1]') assert_equal(make_str(a, 5), '[111\n' ' 111]') b = a[None,None,:] assert_equal(make_str(b, 12, legacy='1.13'), '[[[111111]]]') assert_equal(make_str(b, 9, legacy='1.13'), '[[[111111]]]') assert_equal(make_str(b, 8, legacy='1.13'), '[[[11111\n' ' 1]]]') assert_equal(make_str(b, 12), '[[[111111]]]') assert_equal(make_str(b, 9), '[[[111\n' ' 111]]]') assert_equal(make_str(b, 8), '[[[11\n' ' 11\n' ' 11]]]') def test_wide_element(self): a = np.array(['xxxxx']) assert_equal( np.array2string(a, max_line_width=5), "['xxxxx']" ) assert_equal( np.array2string(a, max_line_width=5, legacy='1.13'), "[ 'xxxxx']" ) def test_refcount(self): # make sure we do not hold references to the array due to a recursive # closure (gh-10620) gc.disable() a = np.arange(2) r1 = sys.getrefcount(a) np.array2string(a) np.array2string(a) r2 = sys.getrefcount(a) gc.collect() gc.enable() assert_(r1 == r2) class TestPrintOptions(object): """Test getting and setting global print options.""" def setup(self): self.oldopts = np.get_printoptions() def teardown(self): np.set_printoptions(**self.oldopts) def test_basic(self): x = np.array([1.5, 0, 1.234567890]) assert_equal(repr(x), "array([1.5 , 0. , 1.23456789])") np.set_printoptions(precision=4) assert_equal(repr(x), "array([1.5 , 0. , 1.2346])") def test_precision_zero(self): np.set_printoptions(precision=0) for values, string in ( ([0.], "0."), ([.3], "0."), ([-.3], "-0."), ([.7], "1."), ([1.5], "2."), ([-1.5], "-2."), ([-15.34], "-15."), ([100.], "100."), ([.2, -1, 122.51], " 0., -1., 123."), ([0], "0"), ([-12], "-12"), ([complex(.3, -.7)], "0.-1.j")): x = np.array(values) assert_equal(repr(x), "array([%s])" % string) def test_formatter(self): x = np.arange(3) np.set_printoptions(formatter={'all':lambda x: str(x-1)}) assert_equal(repr(x), "array([-1, 0, 1])") def test_formatter_reset(self): x = np.arange(3) np.set_printoptions(formatter={'all':lambda x: str(x-1)}) assert_equal(repr(x), "array([-1, 0, 1])") np.set_printoptions(formatter={'int':None}) assert_equal(repr(x), "array([0, 1, 2])") np.set_printoptions(formatter={'all':lambda x: str(x-1)}) assert_equal(repr(x), "array([-1, 0, 1])") np.set_printoptions(formatter={'all':None}) assert_equal(repr(x), "array([0, 1, 2])") np.set_printoptions(formatter={'int':lambda x: str(x-1)}) assert_equal(repr(x), "array([-1, 0, 1])") np.set_printoptions(formatter={'int_kind':None}) assert_equal(repr(x), "array([0, 1, 2])") x = np.arange(3.) np.set_printoptions(formatter={'float':lambda x: str(x-1)}) assert_equal(repr(x), "array([-1.0, 0.0, 1.0])") np.set_printoptions(formatter={'float_kind':None}) assert_equal(repr(x), "array([0., 1., 2.])") def test_0d_arrays(self): unicode = type(u'') assert_equal(unicode(np.array(u'café', '<U4')), u'café') if sys.version_info[0] >= 3: assert_equal(repr(np.array('café', '<U4')), "array('café', dtype='<U4')") else: assert_equal(repr(np.array(u'café', '<U4')), "array(u'caf\\xe9', dtype='<U4')") assert_equal(str(np.array('test', np.str_)), 'test') a = np.zeros(1, dtype=[('a', '<i4', (3,))]) assert_equal(str(a[0]), '([0, 0, 0],)') assert_equal(repr(np.datetime64('2005-02-25')[...]), "array('2005-02-25', dtype='datetime64[D]')") assert_equal(repr(np.timedelta64('10', 'Y')[...]), "array(10, dtype='timedelta64[Y]')") # repr of 0d arrays is affected by printoptions x = np.array(1) np.set_printoptions(formatter={'all':lambda x: "test"}) assert_equal(repr(x), "array(test)") # str is unaffected assert_equal(str(x), "1") # check `style` arg raises assert_warns(DeprecationWarning, np.array2string, np.array(1.), style=repr) # but not in legacy mode np.array2string(np.array(1.), style=repr, legacy='1.13') # gh-10934 style was broken in legacy mode, check it works np.array2string(np.array(1.), legacy='1.13') def test_float_spacing(self): x = np.array([1., 2., 3.]) y = np.array([1., 2., -10.]) z = np.array([100., 2., -1.]) w = np.array([-100., 2., 1.]) assert_equal(repr(x), 'array([1., 2., 3.])') assert_equal(repr(y), 'array([ 1., 2., -10.])') assert_equal(repr(np.array(y[0])), 'array(1.)') assert_equal(repr(np.array(y[-1])), 'array(-10.)') assert_equal(repr(z), 'array([100., 2., -1.])') assert_equal(repr(w), 'array([-100., 2., 1.])') assert_equal(repr(np.array([np.nan, np.inf])), 'array([nan, inf])') assert_equal(repr(np.array([np.nan, -np.inf])), 'array([ nan, -inf])') x = np.array([np.inf, 100000, 1.1234]) y = np.array([np.inf, 100000, -1.1234]) z = np.array([np.inf, 1.1234, -1e120]) np.set_printoptions(precision=2) assert_equal(repr(x), 'array([ inf, 1.00e+05, 1.12e+00])') assert_equal(repr(y), 'array([ inf, 1.00e+05, -1.12e+00])') assert_equal(repr(z), 'array([ inf, 1.12e+000, -1.00e+120])') def test_bool_spacing(self): assert_equal(repr(np.array([True, True])), 'array([ True, True])') assert_equal(repr(np.array([True, False])), 'array([ True, False])') assert_equal(repr(np.array([True])), 'array([ True])') assert_equal(repr(np.array(True)), 'array(True)') assert_equal(repr(np.array(False)), 'array(False)') def test_sign_spacing(self): a = np.arange(4.) b = np.array([1.234e9]) c = np.array([1.0 + 1.0j, 1.123456789 + 1.123456789j], dtype='c16') assert_equal(repr(a), 'array([0., 1., 2., 3.])') assert_equal(repr(np.array(1.)), 'array(1.)') assert_equal(repr(b), 'array([1.234e+09])') assert_equal(repr(np.array([0.])), 'array([0.])') assert_equal(repr(c), "array([1. +1.j , 1.12345679+1.12345679j])") assert_equal(repr(np.array([0., -0.])), 'array([ 0., -0.])') np.set_printoptions(sign=' ') assert_equal(repr(a), 'array([ 0., 1., 2., 3.])') assert_equal(repr(np.array(1.)), 'array( 1.)') assert_equal(repr(b), 'array([ 1.234e+09])') assert_equal(repr(c), "array([ 1. +1.j , 1.12345679+1.12345679j])") assert_equal(repr(np.array([0., -0.])), 'array([ 0., -0.])') np.set_printoptions(sign='+') assert_equal(repr(a), 'array([+0., +1., +2., +3.])') assert_equal(repr(np.array(1.)), 'array(+1.)') assert_equal(repr(b), 'array([+1.234e+09])') assert_equal(repr(c), "array([+1. +1.j , +1.12345679+1.12345679j])") np.set_printoptions(legacy='1.13') assert_equal(repr(a), 'array([ 0., 1., 2., 3.])') assert_equal(repr(b), 'array([ 1.23400000e+09])') assert_equal(repr(-b), 'array([ -1.23400000e+09])') assert_equal(repr(np.array(1.)), 'array(1.0)') assert_equal(repr(np.array([0.])), 'array([ 0.])') assert_equal(repr(c), "array([ 1.00000000+1.j , 1.12345679+1.12345679j])") # gh-10383 assert_equal(str(np.array([-1., 10])), "[ -1. 10.]") assert_raises(TypeError, np.set_printoptions, wrongarg=True) def test_float_overflow_nowarn(self): # make sure internal computations in FloatingFormat don't # warn about overflow repr(np.array([1e4, 0.1], dtype='f2')) def test_sign_spacing_structured(self): a = np.ones(2, dtype='<f,<f') assert_equal(repr(a), "array([(1., 1.), (1., 1.)], dtype=[('f0', '<f4'), ('f1', '<f4')])") assert_equal(repr(a[0]), "(1., 1.)") def test_floatmode(self): x = np.array([0.6104, 0.922, 0.457, 0.0906, 0.3733, 0.007244, 0.5933, 0.947, 0.2383, 0.4226], dtype=np.float16) y = np.array([0.2918820979355541, 0.5064172631089138, 0.2848750619642916, 0.4342965294660567, 0.7326538397312751, 0.3459503329096204, 0.0862072768214508, 0.39112753029631175], dtype=np.float64) z = np.arange(6, dtype=np.float16)/10 c = np.array([1.0 + 1.0j, 1.123456789 + 1.123456789j], dtype='c16') # also make sure 1e23 is right (is between two fp numbers) w = np.array(['1e{}'.format(i) for i in range(25)], dtype=np.float64) # note: we construct w from the strings `1eXX` instead of doing # `10.**arange(24)` because it turns out the two are not equivalent in # python. On some architectures `1e23 != 10.**23`. wp = np.array([1.234e1, 1e2, 1e123]) # unique mode np.set_printoptions(floatmode='unique') assert_equal(repr(x), "array([0.6104 , 0.922 , 0.457 , 0.0906 , 0.3733 , 0.007244,\n" " 0.5933 , 0.947 , 0.2383 , 0.4226 ], dtype=float16)") assert_equal(repr(y), "array([0.2918820979355541 , 0.5064172631089138 , 0.2848750619642916 ,\n" " 0.4342965294660567 , 0.7326538397312751 , 0.3459503329096204 ,\n" " 0.0862072768214508 , 0.39112753029631175])") assert_equal(repr(z), "array([0. , 0.1, 0.2, 0.3, 0.4, 0.5], dtype=float16)") assert_equal(repr(w), "array([1.e+00, 1.e+01, 1.e+02, 1.e+03, 1.e+04, 1.e+05, 1.e+06, 1.e+07,\n" " 1.e+08, 1.e+09, 1.e+10, 1.e+11, 1.e+12, 1.e+13, 1.e+14, 1.e+15,\n" " 1.e+16, 1.e+17, 1.e+18, 1.e+19, 1.e+20, 1.e+21, 1.e+22, 1.e+23,\n" " 1.e+24])") assert_equal(repr(wp), "array([1.234e+001, 1.000e+002, 1.000e+123])") assert_equal(repr(c), "array([1. +1.j , 1.123456789+1.123456789j])") # maxprec mode, precision=8 np.set_printoptions(floatmode='maxprec', precision=8) assert_equal(repr(x), "array([0.6104 , 0.922 , 0.457 , 0.0906 , 0.3733 , 0.007244,\n" " 0.5933 , 0.947 , 0.2383 , 0.4226 ], dtype=float16)") assert_equal(repr(y), "array([0.2918821 , 0.50641726, 0.28487506, 0.43429653, 0.73265384,\n" " 0.34595033, 0.08620728, 0.39112753])") assert_equal(repr(z), "array([0. , 0.1, 0.2, 0.3, 0.4, 0.5], dtype=float16)") assert_equal(repr(w[::5]), "array([1.e+00, 1.e+05, 1.e+10, 1.e+15, 1.e+20])") assert_equal(repr(wp), "array([1.234e+001, 1.000e+002, 1.000e+123])") assert_equal(repr(c), "array([1. +1.j , 1.12345679+1.12345679j])") # fixed mode, precision=4 np.set_printoptions(floatmode='fixed', precision=4) assert_equal(repr(x), "array([0.6104, 0.9219, 0.4570, 0.0906, 0.3733, 0.0072, 0.5933, 0.9468,\n" " 0.2383, 0.4226], dtype=float16)") assert_equal(repr(y), "array([0.2919, 0.5064, 0.2849, 0.4343, 0.7327, 0.3460, 0.0862, 0.3911])") assert_equal(repr(z), "array([0.0000, 0.1000, 0.2000, 0.3000, 0.3999, 0.5000], dtype=float16)") assert_equal(repr(w[::5]), "array([1.0000e+00, 1.0000e+05, 1.0000e+10, 1.0000e+15, 1.0000e+20])") assert_equal(repr(wp), "array([1.2340e+001, 1.0000e+002, 1.0000e+123])") assert_equal(repr(np.zeros(3)), "array([0.0000, 0.0000, 0.0000])") assert_equal(repr(c), "array([1.0000+1.0000j, 1.1235+1.1235j])") # for larger precision, representation error becomes more apparent: np.set_printoptions(floatmode='fixed', precision=8) assert_equal(repr(z), "array([0.00000000, 0.09997559, 0.19995117, 0.30004883, 0.39990234,\n" " 0.50000000], dtype=float16)") # maxprec_equal mode, precision=8 np.set_printoptions(floatmode='maxprec_equal', precision=8) assert_equal(repr(x), "array([0.610352, 0.921875, 0.457031, 0.090576, 0.373291, 0.007244,\n" " 0.593262, 0.946777, 0.238281, 0.422607], dtype=float16)") assert_equal(repr(y), "array([0.29188210, 0.50641726, 0.28487506, 0.43429653, 0.73265384,\n" " 0.34595033, 0.08620728, 0.39112753])") assert_equal(repr(z), "array([0.0, 0.1, 0.2, 0.3, 0.4, 0.5], dtype=float16)") assert_equal(repr(w[::5]), "array([1.e+00, 1.e+05, 1.e+10, 1.e+15, 1.e+20])") assert_equal(repr(wp), "array([1.234e+001, 1.000e+002, 1.000e+123])") assert_equal(repr(c), "array([1.00000000+1.00000000j, 1.12345679+1.12345679j])") def test_legacy_mode_scalars(self): # in legacy mode, str of floats get truncated, and complex scalars # use * for non-finite imaginary part np.set_printoptions(legacy='1.13') assert_equal(str(np.float64(1.123456789123456789)), '1.12345678912') assert_equal(str(np.complex128(complex(1, np.nan))), '(1+nan*j)') np.set_printoptions(legacy=False) assert_equal(str(np.float64(1.123456789123456789)), '1.1234567891234568') assert_equal(str(np.complex128(complex(1, np.nan))), '(1+nanj)') def test_legacy_stray_comma(self): np.set_printoptions(legacy='1.13') assert_equal(str(np.arange(10000)), '[ 0 1 2 ..., 9997 9998 9999]') np.set_printoptions(legacy=False) assert_equal(str(np.arange(10000)), '[ 0 1 2 ... 9997 9998 9999]') def test_dtype_linewidth_wrapping(self): np.set_printoptions(linewidth=75) assert_equal(repr(np.arange(10,20., dtype='f4')), "array([10., 11., 12., 13., 14., 15., 16., 17., 18., 19.], dtype=float32)") assert_equal(repr(np.arange(10,23., dtype='f4')), textwrap.dedent("""\ array([10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22.], dtype=float32)""")) styp = '<U4' if sys.version_info[0] >= 3 else '|S4' assert_equal(repr(np.ones(3, dtype=styp)), "array(['1', '1', '1'], dtype='{}')".format(styp)) assert_equal(repr(np.ones(12, dtype=styp)), textwrap.dedent("""\ array(['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'], dtype='{}')""".format(styp))) def test_linewidth_repr(self): a = np.full(7, fill_value=2) np.set_printoptions(linewidth=17) assert_equal( repr(a), textwrap.dedent("""\ array([2, 2, 2, 2, 2, 2, 2])""") ) np.set_printoptions(linewidth=17, legacy='1.13') assert_equal( repr(a), textwrap.dedent("""\ array([2, 2, 2, 2, 2, 2, 2])""") ) a = np.full(8, fill_value=2) np.set_printoptions(linewidth=18, legacy=False) assert_equal( repr(a), textwrap.dedent("""\ array([2, 2, 2, 2, 2, 2, 2, 2])""") ) np.set_printoptions(linewidth=18, legacy='1.13') assert_equal( repr(a), textwrap.dedent("""\ array([2, 2, 2, 2, 2, 2, 2, 2])""") ) def test_linewidth_str(self): a = np.full(18, fill_value=2) np.set_printoptions(linewidth=18) assert_equal( str(a), textwrap.dedent("""\ [2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]""") ) np.set_printoptions(linewidth=18, legacy='1.13') assert_equal( str(a), textwrap.dedent("""\ [2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]""") ) def test_edgeitems(self): np.set_printoptions(edgeitems=1, threshold=1) a = np.arange(27).reshape((3, 3, 3)) assert_equal( repr(a), textwrap.dedent("""\ array([[[ 0, ..., 2], ..., [ 6, ..., 8]], ..., [[18, ..., 20], ..., [24, ..., 26]]])""") ) b = np.zeros((3, 3, 1, 1)) assert_equal( repr(b), textwrap.dedent("""\ array([[[[0.]], ..., [[0.]]], ..., [[[0.]], ..., [[0.]]]])""") ) # 1.13 had extra trailing spaces, and was missing newlines np.set_printoptions(legacy='1.13') assert_equal( repr(a), textwrap.dedent("""\ array([[[ 0, ..., 2], ..., [ 6, ..., 8]], ..., [[18, ..., 20], ..., [24, ..., 26]]])""") ) assert_equal( repr(b), textwrap.dedent("""\ array([[[[ 0.]], ..., [[ 0.]]], ..., [[[ 0.]], ..., [[ 0.]]]])""") ) def test_unicode_object_array(): import sys if sys.version_info[0] >= 3: expected = "array(['é'], dtype=object)" else: expected = "array([u'\\xe9'], dtype=object)" x = np.array([u'\xe9'], dtype=object) assert_equal(repr(x), expected) if __name__ == "__main__": run_module_suite()
32,679
37.674556
91
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/tests/test_abc.py
from __future__ import division, absolute_import, print_function from numpy.testing import assert_, run_module_suite import numbers import numpy as np from numpy.core.numerictypes import sctypes class TestABC(object): def test_abstract(self): assert_(issubclass(np.number, numbers.Number)) assert_(issubclass(np.inexact, numbers.Complex)) assert_(issubclass(np.complexfloating, numbers.Complex)) assert_(issubclass(np.floating, numbers.Real)) assert_(issubclass(np.integer, numbers.Integral)) assert_(issubclass(np.signedinteger, numbers.Integral)) assert_(issubclass(np.unsignedinteger, numbers.Integral)) def test_floats(self): for t in sctypes['float']: assert_(isinstance(t(), numbers.Real), "{0} is not instance of Real".format(t.__name__)) assert_(issubclass(t, numbers.Real), "{0} is not subclass of Real".format(t.__name__)) assert_(not isinstance(t(), numbers.Rational), "{0} is instance of Rational".format(t.__name__)) assert_(not issubclass(t, numbers.Rational), "{0} is subclass of Rational".format(t.__name__)) def test_complex(self): for t in sctypes['complex']: assert_(isinstance(t(), numbers.Complex), "{0} is not instance of Complex".format(t.__name__)) assert_(issubclass(t, numbers.Complex), "{0} is not subclass of Complex".format(t.__name__)) assert_(not isinstance(t(), numbers.Real), "{0} is instance of Real".format(t.__name__)) assert_(not issubclass(t, numbers.Real), "{0} is subclass of Real".format(t.__name__)) def test_int(self): for t in sctypes['int']: assert_(isinstance(t(), numbers.Integral), "{0} is not instance of Integral".format(t.__name__)) assert_(issubclass(t, numbers.Integral), "{0} is not subclass of Integral".format(t.__name__)) def test_uint(self): for t in sctypes['uint']: assert_(isinstance(t(), numbers.Integral), "{0} is not instance of Integral".format(t.__name__)) assert_(issubclass(t, numbers.Integral), "{0} is not subclass of Integral".format(t.__name__)) if __name__ == "__main__": run_module_suite()
2,472
39.540984
73
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/ufuncobject.h
#ifndef Py_UFUNCOBJECT_H #define Py_UFUNCOBJECT_H #include <numpy/npy_math.h> #include <numpy/npy_common.h> #ifdef __cplusplus extern "C" { #endif /* * The legacy generic inner loop for a standard element-wise or * generalized ufunc. */ typedef void (*PyUFuncGenericFunction) (char **args, npy_intp *dimensions, npy_intp *strides, void *innerloopdata); /* * The most generic one-dimensional inner loop for * a masked standard element-wise ufunc. "Masked" here means that it skips * doing calculations on any items for which the maskptr array has a true * value. */ typedef void (PyUFunc_MaskedStridedInnerLoopFunc)( char **dataptrs, npy_intp *strides, char *maskptr, npy_intp mask_stride, npy_intp count, NpyAuxData *innerloopdata); /* Forward declaration for the type resolver and loop selector typedefs */ struct _tagPyUFuncObject; /* * Given the operands for calling a ufunc, should determine the * calculation input and output data types and return an inner loop function. * This function should validate that the casting rule is being followed, * and fail if it is not. * * For backwards compatibility, the regular type resolution function does not * support auxiliary data with object semantics. The type resolution call * which returns a masked generic function returns a standard NpyAuxData * object, for which the NPY_AUXDATA_FREE and NPY_AUXDATA_CLONE macros * work. * * ufunc: The ufunc object. * casting: The 'casting' parameter provided to the ufunc. * operands: An array of length (ufunc->nin + ufunc->nout), * with the output parameters possibly NULL. * type_tup: Either NULL, or the type_tup passed to the ufunc. * out_dtypes: An array which should be populated with new * references to (ufunc->nin + ufunc->nout) new * dtypes, one for each input and output. These * dtypes should all be in native-endian format. * * Should return 0 on success, -1 on failure (with exception set), * or -2 if Py_NotImplemented should be returned. */ typedef int (PyUFunc_TypeResolutionFunc)( struct _tagPyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes); /* * Given an array of DTypes as returned by the PyUFunc_TypeResolutionFunc, * and an array of fixed strides (the array will contain NPY_MAX_INTP for * strides which are not necessarily fixed), returns an inner loop * with associated auxiliary data. * * For backwards compatibility, there is a variant of the inner loop * selection which returns an inner loop irrespective of the strides, * and with a void* static auxiliary data instead of an NpyAuxData * * dynamically allocatable auxiliary data. * * ufunc: The ufunc object. * dtypes: An array which has been populated with dtypes, * in most cases by the type resolution function * for the same ufunc. * fixed_strides: For each input/output, either the stride that * will be used every time the function is called * or NPY_MAX_INTP if the stride might change or * is not known ahead of time. The loop selection * function may use this stride to pick inner loops * which are optimized for contiguous or 0-stride * cases. * out_innerloop: Should be populated with the correct ufunc inner * loop for the given type. * out_innerloopdata: Should be populated with the void* data to * be passed into the out_innerloop function. * out_needs_api: If the inner loop needs to use the Python API, * should set the to 1, otherwise should leave * this untouched. */ typedef int (PyUFunc_LegacyInnerLoopSelectionFunc)( struct _tagPyUFuncObject *ufunc, PyArray_Descr **dtypes, PyUFuncGenericFunction *out_innerloop, void **out_innerloopdata, int *out_needs_api); typedef int (PyUFunc_MaskedInnerLoopSelectionFunc)( struct _tagPyUFuncObject *ufunc, PyArray_Descr **dtypes, PyArray_Descr *mask_dtype, npy_intp *fixed_strides, npy_intp fixed_mask_stride, PyUFunc_MaskedStridedInnerLoopFunc **out_innerloop, NpyAuxData **out_innerloopdata, int *out_needs_api); typedef struct _tagPyUFuncObject { PyObject_HEAD /* * nin: Number of inputs * nout: Number of outputs * nargs: Always nin + nout (Why is it stored?) */ int nin, nout, nargs; /* Identity for reduction, either PyUFunc_One or PyUFunc_Zero */ int identity; /* Array of one-dimensional core loops */ PyUFuncGenericFunction *functions; /* Array of funcdata that gets passed into the functions */ void **data; /* The number of elements in 'functions' and 'data' */ int ntypes; /* Used to be unused field 'check_return' */ int reserved1; /* The name of the ufunc */ const char *name; /* Array of type numbers, of size ('nargs' * 'ntypes') */ char *types; /* Documentation string */ const char *doc; void *ptr; PyObject *obj; PyObject *userloops; /* generalized ufunc parameters */ /* 0 for scalar ufunc; 1 for generalized ufunc */ int core_enabled; /* number of distinct dimension names in signature */ int core_num_dim_ix; /* * dimension indices of input/output argument k are stored in * core_dim_ixs[core_offsets[k]..core_offsets[k]+core_num_dims[k]-1] */ /* numbers of core dimensions of each argument */ int *core_num_dims; /* * dimension indices in a flatted form; indices * are in the range of [0,core_num_dim_ix) */ int *core_dim_ixs; /* * positions of 1st core dimensions of each * argument in core_dim_ixs */ int *core_offsets; /* signature string for printing purpose */ char *core_signature; /* * A function which resolves the types and fills an array * with the dtypes for the inputs and outputs. */ PyUFunc_TypeResolutionFunc *type_resolver; /* * A function which returns an inner loop written for * NumPy 1.6 and earlier ufuncs. This is for backwards * compatibility, and may be NULL if inner_loop_selector * is specified. */ PyUFunc_LegacyInnerLoopSelectionFunc *legacy_inner_loop_selector; /* * This was blocked off to be the "new" inner loop selector in 1.7, * but this was never implemented. (This is also why the above * selector is called the "legacy" selector.) */ void *reserved2; /* * A function which returns a masked inner loop for the ufunc. */ PyUFunc_MaskedInnerLoopSelectionFunc *masked_inner_loop_selector; /* * List of flags for each operand when ufunc is called by nditer object. * These flags will be used in addition to the default flags for each * operand set by nditer object. */ npy_uint32 *op_flags; /* * List of global flags used when ufunc is called by nditer object. * These flags will be used in addition to the default global flags * set by nditer object. */ npy_uint32 iter_flags; } PyUFuncObject; #include "arrayobject.h" #define UFUNC_ERR_IGNORE 0 #define UFUNC_ERR_WARN 1 #define UFUNC_ERR_RAISE 2 #define UFUNC_ERR_CALL 3 #define UFUNC_ERR_PRINT 4 #define UFUNC_ERR_LOG 5 /* Python side integer mask */ #define UFUNC_MASK_DIVIDEBYZERO 0x07 #define UFUNC_MASK_OVERFLOW 0x3f #define UFUNC_MASK_UNDERFLOW 0x1ff #define UFUNC_MASK_INVALID 0xfff #define UFUNC_SHIFT_DIVIDEBYZERO 0 #define UFUNC_SHIFT_OVERFLOW 3 #define UFUNC_SHIFT_UNDERFLOW 6 #define UFUNC_SHIFT_INVALID 9 #define UFUNC_OBJ_ISOBJECT 1 #define UFUNC_OBJ_NEEDS_API 2 /* Default user error mode */ #define UFUNC_ERR_DEFAULT \ (UFUNC_ERR_WARN << UFUNC_SHIFT_DIVIDEBYZERO) + \ (UFUNC_ERR_WARN << UFUNC_SHIFT_OVERFLOW) + \ (UFUNC_ERR_WARN << UFUNC_SHIFT_INVALID) #if NPY_ALLOW_THREADS #define NPY_LOOP_BEGIN_THREADS do {if (!(loop->obj & UFUNC_OBJ_NEEDS_API)) _save = PyEval_SaveThread();} while (0); #define NPY_LOOP_END_THREADS do {if (!(loop->obj & UFUNC_OBJ_NEEDS_API)) PyEval_RestoreThread(_save);} while (0); #else #define NPY_LOOP_BEGIN_THREADS #define NPY_LOOP_END_THREADS #endif /* * UFunc has unit of 0, and the order of operations can be reordered * This case allows reduction with multiple axes at once. */ #define PyUFunc_Zero 0 /* * UFunc has unit of 1, and the order of operations can be reordered * This case allows reduction with multiple axes at once. */ #define PyUFunc_One 1 /* * UFunc has unit of -1, and the order of operations can be reordered * This case allows reduction with multiple axes at once. Intended for * bitwise_and reduction. */ #define PyUFunc_MinusOne 2 /* * UFunc has no unit, and the order of operations cannot be reordered. * This case does not allow reduction with multiple axes at once. */ #define PyUFunc_None -1 /* * UFunc has no unit, and the order of operations can be reordered * This case allows reduction with multiple axes at once. */ #define PyUFunc_ReorderableNone -2 #define UFUNC_REDUCE 0 #define UFUNC_ACCUMULATE 1 #define UFUNC_REDUCEAT 2 #define UFUNC_OUTER 3 typedef struct { int nin; int nout; PyObject *callable; } PyUFunc_PyFuncData; /* A linked-list of function information for user-defined 1-d loops. */ typedef struct _loop1d_info { PyUFuncGenericFunction func; void *data; int *arg_types; struct _loop1d_info *next; int nargs; PyArray_Descr **arg_dtypes; } PyUFunc_Loop1d; #include "__ufunc_api.h" #define UFUNC_PYVALS_NAME "UFUNC_PYVALS" #define UFUNC_CHECK_ERROR(arg) \ do {if ((((arg)->obj & UFUNC_OBJ_NEEDS_API) && PyErr_Occurred()) || \ ((arg)->errormask && \ PyUFunc_checkfperr((arg)->errormask, \ (arg)->errobj, \ &(arg)->first))) \ goto fail;} while (0) /* keep in sync with ieee754.c.src */ #if defined(sun) || defined(__BSD__) || defined(__OpenBSD__) || \ (defined(__FreeBSD__) && (__FreeBSD_version < 502114)) || \ defined(__NetBSD__) || \ defined(__GLIBC__) || defined(__APPLE__) || \ defined(__CYGWIN__) || defined(__MINGW32__) || \ (defined(__FreeBSD__) && (__FreeBSD_version >= 502114)) || \ defined(_AIX) || \ defined(_MSC_VER) || \ defined(__osf__) && defined(__alpha) #else #define NO_FLOATING_POINT_SUPPORT #endif /* * THESE MACROS ARE DEPRECATED. * Use npy_set_floatstatus_* in the npymath library. */ #define UFUNC_FPE_DIVIDEBYZERO NPY_FPE_DIVIDEBYZERO #define UFUNC_FPE_OVERFLOW NPY_FPE_OVERFLOW #define UFUNC_FPE_UNDERFLOW NPY_FPE_UNDERFLOW #define UFUNC_FPE_INVALID NPY_FPE_INVALID #define UFUNC_CHECK_STATUS(ret) \ { \ ret = npy_clear_floatstatus(); \ } #define generate_divbyzero_error() npy_set_floatstatus_divbyzero() #define generate_overflow_error() npy_set_floatstatus_overflow() /* Make sure it gets defined if it isn't already */ #ifndef UFUNC_NOFPE /* Clear the floating point exception default of Borland C++ */ #if defined(__BORLANDC__) #define UFUNC_NOFPE _control87(MCW_EM, MCW_EM); #else #define UFUNC_NOFPE #endif #endif #ifdef __cplusplus } #endif #endif /* !Py_UFUNCOBJECT_H */
12,524
33.409341
115
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/noprefix.h
#ifndef NPY_NOPREFIX_H #define NPY_NOPREFIX_H /* * You can directly include noprefix.h as a backward * compatibility measure */ #ifndef NPY_NO_PREFIX #include "ndarrayobject.h" #include "npy_interrupt.h" #endif #define SIGSETJMP NPY_SIGSETJMP #define SIGLONGJMP NPY_SIGLONGJMP #define SIGJMP_BUF NPY_SIGJMP_BUF #define MAX_DIMS NPY_MAXDIMS #define longlong npy_longlong #define ulonglong npy_ulonglong #define Bool npy_bool #define longdouble npy_longdouble #define byte npy_byte #ifndef _BSD_SOURCE #define ushort npy_ushort #define uint npy_uint #define ulong npy_ulong #endif #define ubyte npy_ubyte #define ushort npy_ushort #define uint npy_uint #define ulong npy_ulong #define cfloat npy_cfloat #define cdouble npy_cdouble #define clongdouble npy_clongdouble #define Int8 npy_int8 #define UInt8 npy_uint8 #define Int16 npy_int16 #define UInt16 npy_uint16 #define Int32 npy_int32 #define UInt32 npy_uint32 #define Int64 npy_int64 #define UInt64 npy_uint64 #define Int128 npy_int128 #define UInt128 npy_uint128 #define Int256 npy_int256 #define UInt256 npy_uint256 #define Float16 npy_float16 #define Complex32 npy_complex32 #define Float32 npy_float32 #define Complex64 npy_complex64 #define Float64 npy_float64 #define Complex128 npy_complex128 #define Float80 npy_float80 #define Complex160 npy_complex160 #define Float96 npy_float96 #define Complex192 npy_complex192 #define Float128 npy_float128 #define Complex256 npy_complex256 #define intp npy_intp #define uintp npy_uintp #define datetime npy_datetime #define timedelta npy_timedelta #define SIZEOF_LONGLONG NPY_SIZEOF_LONGLONG #define SIZEOF_INTP NPY_SIZEOF_INTP #define SIZEOF_UINTP NPY_SIZEOF_UINTP #define SIZEOF_HALF NPY_SIZEOF_HALF #define SIZEOF_LONGDOUBLE NPY_SIZEOF_LONGDOUBLE #define SIZEOF_DATETIME NPY_SIZEOF_DATETIME #define SIZEOF_TIMEDELTA NPY_SIZEOF_TIMEDELTA #define LONGLONG_FMT NPY_LONGLONG_FMT #define ULONGLONG_FMT NPY_ULONGLONG_FMT #define LONGLONG_SUFFIX NPY_LONGLONG_SUFFIX #define ULONGLONG_SUFFIX NPY_ULONGLONG_SUFFIX #define MAX_INT8 127 #define MIN_INT8 -128 #define MAX_UINT8 255 #define MAX_INT16 32767 #define MIN_INT16 -32768 #define MAX_UINT16 65535 #define MAX_INT32 2147483647 #define MIN_INT32 (-MAX_INT32 - 1) #define MAX_UINT32 4294967295U #define MAX_INT64 LONGLONG_SUFFIX(9223372036854775807) #define MIN_INT64 (-MAX_INT64 - LONGLONG_SUFFIX(1)) #define MAX_UINT64 ULONGLONG_SUFFIX(18446744073709551615) #define MAX_INT128 LONGLONG_SUFFIX(85070591730234615865843651857942052864) #define MIN_INT128 (-MAX_INT128 - LONGLONG_SUFFIX(1)) #define MAX_UINT128 ULONGLONG_SUFFIX(170141183460469231731687303715884105728) #define MAX_INT256 LONGLONG_SUFFIX(57896044618658097711785492504343953926634992332820282019728792003956564819967) #define MIN_INT256 (-MAX_INT256 - LONGLONG_SUFFIX(1)) #define MAX_UINT256 ULONGLONG_SUFFIX(115792089237316195423570985008687907853269984665640564039457584007913129639935) #define MAX_BYTE NPY_MAX_BYTE #define MIN_BYTE NPY_MIN_BYTE #define MAX_UBYTE NPY_MAX_UBYTE #define MAX_SHORT NPY_MAX_SHORT #define MIN_SHORT NPY_MIN_SHORT #define MAX_USHORT NPY_MAX_USHORT #define MAX_INT NPY_MAX_INT #define MIN_INT NPY_MIN_INT #define MAX_UINT NPY_MAX_UINT #define MAX_LONG NPY_MAX_LONG #define MIN_LONG NPY_MIN_LONG #define MAX_ULONG NPY_MAX_ULONG #define MAX_LONGLONG NPY_MAX_LONGLONG #define MIN_LONGLONG NPY_MIN_LONGLONG #define MAX_ULONGLONG NPY_MAX_ULONGLONG #define MIN_DATETIME NPY_MIN_DATETIME #define MAX_DATETIME NPY_MAX_DATETIME #define MIN_TIMEDELTA NPY_MIN_TIMEDELTA #define MAX_TIMEDELTA NPY_MAX_TIMEDELTA #define BITSOF_BOOL NPY_BITSOF_BOOL #define BITSOF_CHAR NPY_BITSOF_CHAR #define BITSOF_SHORT NPY_BITSOF_SHORT #define BITSOF_INT NPY_BITSOF_INT #define BITSOF_LONG NPY_BITSOF_LONG #define BITSOF_LONGLONG NPY_BITSOF_LONGLONG #define BITSOF_HALF NPY_BITSOF_HALF #define BITSOF_FLOAT NPY_BITSOF_FLOAT #define BITSOF_DOUBLE NPY_BITSOF_DOUBLE #define BITSOF_LONGDOUBLE NPY_BITSOF_LONGDOUBLE #define BITSOF_DATETIME NPY_BITSOF_DATETIME #define BITSOF_TIMEDELTA NPY_BITSOF_TIMEDELTA #define _pya_malloc PyArray_malloc #define _pya_free PyArray_free #define _pya_realloc PyArray_realloc #define BEGIN_THREADS_DEF NPY_BEGIN_THREADS_DEF #define BEGIN_THREADS NPY_BEGIN_THREADS #define END_THREADS NPY_END_THREADS #define ALLOW_C_API_DEF NPY_ALLOW_C_API_DEF #define ALLOW_C_API NPY_ALLOW_C_API #define DISABLE_C_API NPY_DISABLE_C_API #define PY_FAIL NPY_FAIL #define PY_SUCCEED NPY_SUCCEED #ifndef TRUE #define TRUE NPY_TRUE #endif #ifndef FALSE #define FALSE NPY_FALSE #endif #define LONGDOUBLE_FMT NPY_LONGDOUBLE_FMT #define CONTIGUOUS NPY_CONTIGUOUS #define C_CONTIGUOUS NPY_C_CONTIGUOUS #define FORTRAN NPY_FORTRAN #define F_CONTIGUOUS NPY_F_CONTIGUOUS #define OWNDATA NPY_OWNDATA #define FORCECAST NPY_FORCECAST #define ENSURECOPY NPY_ENSURECOPY #define ENSUREARRAY NPY_ENSUREARRAY #define ELEMENTSTRIDES NPY_ELEMENTSTRIDES #define ALIGNED NPY_ALIGNED #define NOTSWAPPED NPY_NOTSWAPPED #define WRITEABLE NPY_WRITEABLE #define UPDATEIFCOPY NPY_UPDATEIFCOPY #define WRITEBACKIFCOPY NPY_ARRAY_WRITEBACKIFCOPY #define ARR_HAS_DESCR NPY_ARR_HAS_DESCR #define BEHAVED NPY_BEHAVED #define BEHAVED_NS NPY_BEHAVED_NS #define CARRAY NPY_CARRAY #define CARRAY_RO NPY_CARRAY_RO #define FARRAY NPY_FARRAY #define FARRAY_RO NPY_FARRAY_RO #define DEFAULT NPY_DEFAULT #define IN_ARRAY NPY_IN_ARRAY #define OUT_ARRAY NPY_OUT_ARRAY #define INOUT_ARRAY NPY_INOUT_ARRAY #define IN_FARRAY NPY_IN_FARRAY #define OUT_FARRAY NPY_OUT_FARRAY #define INOUT_FARRAY NPY_INOUT_FARRAY #define UPDATE_ALL NPY_UPDATE_ALL #define OWN_DATA NPY_OWNDATA #define BEHAVED_FLAGS NPY_BEHAVED #define BEHAVED_FLAGS_NS NPY_BEHAVED_NS #define CARRAY_FLAGS_RO NPY_CARRAY_RO #define CARRAY_FLAGS NPY_CARRAY #define FARRAY_FLAGS NPY_FARRAY #define FARRAY_FLAGS_RO NPY_FARRAY_RO #define DEFAULT_FLAGS NPY_DEFAULT #define UPDATE_ALL_FLAGS NPY_UPDATE_ALL_FLAGS #ifndef MIN #define MIN PyArray_MIN #endif #ifndef MAX #define MAX PyArray_MAX #endif #define MAX_INTP NPY_MAX_INTP #define MIN_INTP NPY_MIN_INTP #define MAX_UINTP NPY_MAX_UINTP #define INTP_FMT NPY_INTP_FMT #ifndef PYPY_VERSION #define REFCOUNT PyArray_REFCOUNT #define MAX_ELSIZE NPY_MAX_ELSIZE #endif #endif
6,786
30.86385
116
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/npy_os.h
#ifndef _NPY_OS_H_ #define _NPY_OS_H_ #if defined(linux) || defined(__linux) || defined(__linux__) #define NPY_OS_LINUX #elif defined(__FreeBSD__) || defined(__NetBSD__) || \ defined(__OpenBSD__) || defined(__DragonFly__) #define NPY_OS_BSD #ifdef __FreeBSD__ #define NPY_OS_FREEBSD #elif defined(__NetBSD__) #define NPY_OS_NETBSD #elif defined(__OpenBSD__) #define NPY_OS_OPENBSD #elif defined(__DragonFly__) #define NPY_OS_DRAGONFLY #endif #elif defined(sun) || defined(__sun) #define NPY_OS_SOLARIS #elif defined(__CYGWIN__) #define NPY_OS_CYGWIN #elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) #define NPY_OS_WIN32 #elif defined(__APPLE__) #define NPY_OS_DARWIN #else #define NPY_OS_UNKNOWN #endif #endif
817
25.387097
61
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h
#ifndef _NPY_1_7_DEPRECATED_API_H #define _NPY_1_7_DEPRECATED_API_H #ifndef NPY_DEPRECATED_INCLUDES #error "Should never include npy_*_*_deprecated_api directly." #endif #if defined(_WIN32) #define _WARN___STR2__(x) #x #define _WARN___STR1__(x) _WARN___STR2__(x) #define _WARN___LOC__ __FILE__ "(" _WARN___STR1__(__LINE__) ") : Warning Msg: " #pragma message(_WARN___LOC__"Using deprecated NumPy API, disable it by " \ "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION") #elif defined(__GNUC__) #warning "Using deprecated NumPy API, disable it by " \ "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" #endif /* TODO: How to do this warning message for other compilers? */ /* * This header exists to collect all dangerous/deprecated NumPy API * as of NumPy 1.7. * * This is an attempt to remove bad API, the proliferation of macros, * and namespace pollution currently produced by the NumPy headers. */ /* These array flags are deprecated as of NumPy 1.7 */ #define NPY_CONTIGUOUS NPY_ARRAY_C_CONTIGUOUS #define NPY_FORTRAN NPY_ARRAY_F_CONTIGUOUS /* * The consistent NPY_ARRAY_* names which don't pollute the NPY_* * namespace were added in NumPy 1.7. * * These versions of the carray flags are deprecated, but * probably should only be removed after two releases instead of one. */ #define NPY_C_CONTIGUOUS NPY_ARRAY_C_CONTIGUOUS #define NPY_F_CONTIGUOUS NPY_ARRAY_F_CONTIGUOUS #define NPY_OWNDATA NPY_ARRAY_OWNDATA #define NPY_FORCECAST NPY_ARRAY_FORCECAST #define NPY_ENSURECOPY NPY_ARRAY_ENSURECOPY #define NPY_ENSUREARRAY NPY_ARRAY_ENSUREARRAY #define NPY_ELEMENTSTRIDES NPY_ARRAY_ELEMENTSTRIDES #define NPY_ALIGNED NPY_ARRAY_ALIGNED #define NPY_NOTSWAPPED NPY_ARRAY_NOTSWAPPED #define NPY_WRITEABLE NPY_ARRAY_WRITEABLE #define NPY_UPDATEIFCOPY NPY_ARRAY_UPDATEIFCOPY #define NPY_BEHAVED NPY_ARRAY_BEHAVED #define NPY_BEHAVED_NS NPY_ARRAY_BEHAVED_NS #define NPY_CARRAY NPY_ARRAY_CARRAY #define NPY_CARRAY_RO NPY_ARRAY_CARRAY_RO #define NPY_FARRAY NPY_ARRAY_FARRAY #define NPY_FARRAY_RO NPY_ARRAY_FARRAY_RO #define NPY_DEFAULT NPY_ARRAY_DEFAULT #define NPY_IN_ARRAY NPY_ARRAY_IN_ARRAY #define NPY_OUT_ARRAY NPY_ARRAY_OUT_ARRAY #define NPY_INOUT_ARRAY NPY_ARRAY_INOUT_ARRAY #define NPY_IN_FARRAY NPY_ARRAY_IN_FARRAY #define NPY_OUT_FARRAY NPY_ARRAY_OUT_FARRAY #define NPY_INOUT_FARRAY NPY_ARRAY_INOUT_FARRAY #define NPY_UPDATE_ALL NPY_ARRAY_UPDATE_ALL /* This way of accessing the default type is deprecated as of NumPy 1.7 */ #define PyArray_DEFAULT NPY_DEFAULT_TYPE /* These DATETIME bits aren't used internally */ #if PY_VERSION_HEX >= 0x03000000 #define PyDataType_GetDatetimeMetaData(descr) \ ((descr->metadata == NULL) ? NULL : \ ((PyArray_DatetimeMetaData *)(PyCapsule_GetPointer( \ PyDict_GetItemString( \ descr->metadata, NPY_METADATA_DTSTR), NULL)))) #else #define PyDataType_GetDatetimeMetaData(descr) \ ((descr->metadata == NULL) ? NULL : \ ((PyArray_DatetimeMetaData *)(PyCObject_AsVoidPtr( \ PyDict_GetItemString(descr->metadata, NPY_METADATA_DTSTR))))) #endif /* * Deprecated as of NumPy 1.7, this kind of shortcut doesn't * belong in the public API. */ #define NPY_AO PyArrayObject /* * Deprecated as of NumPy 1.7, an all-lowercase macro doesn't * belong in the public API. */ #define fortran fortran_ /* * Deprecated as of NumPy 1.7, as it is a namespace-polluting * macro. */ #define FORTRAN_IF PyArray_FORTRAN_IF /* Deprecated as of NumPy 1.7, datetime64 uses c_metadata instead */ #define NPY_METADATA_DTSTR "__timeunit__" /* * Deprecated as of NumPy 1.7. * The reasoning: * - These are for datetime, but there's no datetime "namespace". * - They just turn NPY_STR_<x> into "<x>", which is just * making something simple be indirected. */ #define NPY_STR_Y "Y" #define NPY_STR_M "M" #define NPY_STR_W "W" #define NPY_STR_D "D" #define NPY_STR_h "h" #define NPY_STR_m "m" #define NPY_STR_s "s" #define NPY_STR_ms "ms" #define NPY_STR_us "us" #define NPY_STR_ns "ns" #define NPY_STR_ps "ps" #define NPY_STR_fs "fs" #define NPY_STR_as "as" /* * The macros in old_defines.h are Deprecated as of NumPy 1.7 and will be * removed in the next major release. */ #include "old_defines.h" #endif
4,604
34.152672
79
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/npy_cpu.h
/* * This set (target) cpu specific macros: * - Possible values: * NPY_CPU_X86 * NPY_CPU_AMD64 * NPY_CPU_PPC * NPY_CPU_PPC64 * NPY_CPU_PPC64LE * NPY_CPU_SPARC * NPY_CPU_S390 * NPY_CPU_IA64 * NPY_CPU_HPPA * NPY_CPU_ALPHA * NPY_CPU_ARMEL * NPY_CPU_ARMEB * NPY_CPU_SH_LE * NPY_CPU_SH_BE * NPY_CPU_ARCEL * NPY_CPU_ARCEB */ #ifndef _NPY_CPUARCH_H_ #define _NPY_CPUARCH_H_ #include "numpyconfig.h" #include <string.h> /* for memcpy */ #if defined( __i386__ ) || defined(i386) || defined(_M_IX86) /* * __i386__ is defined by gcc and Intel compiler on Linux, * _M_IX86 by VS compiler, * i386 by Sun compilers on opensolaris at least */ #define NPY_CPU_X86 #elif defined(__x86_64__) || defined(__amd64__) || defined(__x86_64) || defined(_M_AMD64) /* * both __x86_64__ and __amd64__ are defined by gcc * __x86_64 defined by sun compiler on opensolaris at least * _M_AMD64 defined by MS compiler */ #define NPY_CPU_AMD64 #elif defined(__ppc__) || defined(__powerpc__) || defined(_ARCH_PPC) /* * __ppc__ is defined by gcc, I remember having seen __powerpc__ once, * but can't find it ATM * _ARCH_PPC is used by at least gcc on AIX */ #define NPY_CPU_PPC #elif defined(__ppc64le__) #define NPY_CPU_PPC64LE #elif defined(__ppc64__) #define NPY_CPU_PPC64 #elif defined(__sparc__) || defined(__sparc) /* __sparc__ is defined by gcc and Forte (e.g. Sun) compilers */ #define NPY_CPU_SPARC #elif defined(__s390__) #define NPY_CPU_S390 #elif defined(__ia64) #define NPY_CPU_IA64 #elif defined(__hppa) #define NPY_CPU_HPPA #elif defined(__alpha__) #define NPY_CPU_ALPHA #elif defined(__arm__) && defined(__ARMEL__) #define NPY_CPU_ARMEL #elif defined(__arm__) && defined(__ARMEB__) #define NPY_CPU_ARMEB #elif defined(__sh__) && defined(__LITTLE_ENDIAN__) #define NPY_CPU_SH_LE #elif defined(__sh__) && defined(__BIG_ENDIAN__) #define NPY_CPU_SH_BE #elif defined(__MIPSEL__) #define NPY_CPU_MIPSEL #elif defined(__MIPSEB__) #define NPY_CPU_MIPSEB #elif defined(__or1k__) #define NPY_CPU_OR1K #elif defined(__aarch64__) #define NPY_CPU_AARCH64 #elif defined(__mc68000__) #define NPY_CPU_M68K #elif defined(__arc__) && defined(__LITTLE_ENDIAN__) #define NPY_CPU_ARCEL #elif defined(__arc__) && defined(__BIG_ENDIAN__) #define NPY_CPU_ARCEB #else #error Unknown CPU, please report this to numpy maintainers with \ information about your platform (OS, CPU and compiler) #endif #define NPY_COPY_PYOBJECT_PTR(dst, src) memcpy(dst, src, sizeof(PyObject *)) #if (defined(NPY_CPU_X86) || defined(NPY_CPU_AMD64)) #define NPY_CPU_HAVE_UNALIGNED_ACCESS 1 #else #define NPY_CPU_HAVE_UNALIGNED_ACCESS 0 #endif #endif
2,988
29.191919
89
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/arrayscalars.h
#ifndef _NPY_ARRAYSCALARS_H_ #define _NPY_ARRAYSCALARS_H_ #ifndef _MULTIARRAYMODULE typedef struct { PyObject_HEAD npy_bool obval; } PyBoolScalarObject; #endif typedef struct { PyObject_HEAD signed char obval; } PyByteScalarObject; typedef struct { PyObject_HEAD short obval; } PyShortScalarObject; typedef struct { PyObject_HEAD int obval; } PyIntScalarObject; typedef struct { PyObject_HEAD long obval; } PyLongScalarObject; typedef struct { PyObject_HEAD npy_longlong obval; } PyLongLongScalarObject; typedef struct { PyObject_HEAD unsigned char obval; } PyUByteScalarObject; typedef struct { PyObject_HEAD unsigned short obval; } PyUShortScalarObject; typedef struct { PyObject_HEAD unsigned int obval; } PyUIntScalarObject; typedef struct { PyObject_HEAD unsigned long obval; } PyULongScalarObject; typedef struct { PyObject_HEAD npy_ulonglong obval; } PyULongLongScalarObject; typedef struct { PyObject_HEAD npy_half obval; } PyHalfScalarObject; typedef struct { PyObject_HEAD float obval; } PyFloatScalarObject; typedef struct { PyObject_HEAD double obval; } PyDoubleScalarObject; typedef struct { PyObject_HEAD npy_longdouble obval; } PyLongDoubleScalarObject; typedef struct { PyObject_HEAD npy_cfloat obval; } PyCFloatScalarObject; typedef struct { PyObject_HEAD npy_cdouble obval; } PyCDoubleScalarObject; typedef struct { PyObject_HEAD npy_clongdouble obval; } PyCLongDoubleScalarObject; typedef struct { PyObject_HEAD PyObject * obval; } PyObjectScalarObject; typedef struct { PyObject_HEAD npy_datetime obval; PyArray_DatetimeMetaData obmeta; } PyDatetimeScalarObject; typedef struct { PyObject_HEAD npy_timedelta obval; PyArray_DatetimeMetaData obmeta; } PyTimedeltaScalarObject; typedef struct { PyObject_HEAD char obval; } PyScalarObject; #define PyStringScalarObject PyStringObject #define PyUnicodeScalarObject PyUnicodeObject typedef struct { PyObject_VAR_HEAD char *obval; PyArray_Descr *descr; int flags; PyObject *base; } PyVoidScalarObject; /* Macros Py<Cls><bitsize>ScalarObject Py<Cls><bitsize>ArrType_Type are defined in ndarrayobject.h */ #define PyArrayScalar_False ((PyObject *)(&(_PyArrayScalar_BoolValues[0]))) #define PyArrayScalar_True ((PyObject *)(&(_PyArrayScalar_BoolValues[1]))) #define PyArrayScalar_FromLong(i) \ ((PyObject *)(&(_PyArrayScalar_BoolValues[((i)!=0)]))) #define PyArrayScalar_RETURN_BOOL_FROM_LONG(i) \ return Py_INCREF(PyArrayScalar_FromLong(i)), \ PyArrayScalar_FromLong(i) #define PyArrayScalar_RETURN_FALSE \ return Py_INCREF(PyArrayScalar_False), \ PyArrayScalar_False #define PyArrayScalar_RETURN_TRUE \ return Py_INCREF(PyArrayScalar_True), \ PyArrayScalar_True #define PyArrayScalar_New(cls) \ Py##cls##ArrType_Type.tp_alloc(&Py##cls##ArrType_Type, 0) #define PyArrayScalar_VAL(obj, cls) \ ((Py##cls##ScalarObject *)obj)->obval #define PyArrayScalar_ASSIGN(obj, cls, val) \ PyArrayScalar_VAL(obj, cls) = val #endif
3,509
18.943182
75
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/ndarrayobject.h
/* * DON'T INCLUDE THIS DIRECTLY. */ #ifndef NPY_NDARRAYOBJECT_H #define NPY_NDARRAYOBJECT_H #ifdef __cplusplus #define CONFUSE_EMACS { #define CONFUSE_EMACS2 } extern "C" CONFUSE_EMACS #undef CONFUSE_EMACS #undef CONFUSE_EMACS2 /* ... otherwise a semi-smart identer (like emacs) tries to indent everything when you're typing */ #endif #include <Python.h> #include "ndarraytypes.h" /* Includes the "function" C-API -- these are all stored in a list of pointers --- one for each file The two lists are concatenated into one in multiarray. They are available as import_array() */ #include "__multiarray_api.h" /* C-API that requires previous API to be defined */ #define PyArray_DescrCheck(op) (((PyObject*)(op))->ob_type==&PyArrayDescr_Type) #define PyArray_Check(op) PyObject_TypeCheck(op, &PyArray_Type) #define PyArray_CheckExact(op) (((PyObject*)(op))->ob_type == &PyArray_Type) #define PyArray_HasArrayInterfaceType(op, type, context, out) \ ((((out)=PyArray_FromStructInterface(op)) != Py_NotImplemented) || \ (((out)=PyArray_FromInterface(op)) != Py_NotImplemented) || \ (((out)=PyArray_FromArrayAttr(op, type, context)) != \ Py_NotImplemented)) #define PyArray_HasArrayInterface(op, out) \ PyArray_HasArrayInterfaceType(op, NULL, NULL, out) #define PyArray_IsZeroDim(op) (PyArray_Check(op) && \ (PyArray_NDIM((PyArrayObject *)op) == 0)) #define PyArray_IsScalar(obj, cls) \ (PyObject_TypeCheck(obj, &Py##cls##ArrType_Type)) #define PyArray_CheckScalar(m) (PyArray_IsScalar(m, Generic) || \ PyArray_IsZeroDim(m)) #if PY_MAJOR_VERSION >= 3 #define PyArray_IsPythonNumber(obj) \ (PyFloat_Check(obj) || PyComplex_Check(obj) || \ PyLong_Check(obj) || PyBool_Check(obj)) #define PyArray_IsIntegerScalar(obj) (PyLong_Check(obj) \ || PyArray_IsScalar((obj), Integer)) #define PyArray_IsPythonScalar(obj) \ (PyArray_IsPythonNumber(obj) || PyBytes_Check(obj) || \ PyUnicode_Check(obj)) #else #define PyArray_IsPythonNumber(obj) \ (PyInt_Check(obj) || PyFloat_Check(obj) || PyComplex_Check(obj) || \ PyLong_Check(obj) || PyBool_Check(obj)) #define PyArray_IsIntegerScalar(obj) (PyInt_Check(obj) \ || PyLong_Check(obj) \ || PyArray_IsScalar((obj), Integer)) #define PyArray_IsPythonScalar(obj) \ (PyArray_IsPythonNumber(obj) || PyString_Check(obj) || \ PyUnicode_Check(obj)) #endif #define PyArray_IsAnyScalar(obj) \ (PyArray_IsScalar(obj, Generic) || PyArray_IsPythonScalar(obj)) #define PyArray_CheckAnyScalar(obj) (PyArray_IsPythonScalar(obj) || \ PyArray_CheckScalar(obj)) #define PyArray_GETCONTIGUOUS(m) (PyArray_ISCONTIGUOUS(m) ? \ Py_INCREF(m), (m) : \ (PyArrayObject *)(PyArray_Copy(m))) #define PyArray_SAMESHAPE(a1,a2) ((PyArray_NDIM(a1) == PyArray_NDIM(a2)) && \ PyArray_CompareLists(PyArray_DIMS(a1), \ PyArray_DIMS(a2), \ PyArray_NDIM(a1))) #define PyArray_SIZE(m) PyArray_MultiplyList(PyArray_DIMS(m), PyArray_NDIM(m)) #define PyArray_NBYTES(m) (PyArray_ITEMSIZE(m) * PyArray_SIZE(m)) #define PyArray_FROM_O(m) PyArray_FromAny(m, NULL, 0, 0, 0, NULL) #define PyArray_FROM_OF(m,flags) PyArray_CheckFromAny(m, NULL, 0, 0, flags, \ NULL) #define PyArray_FROM_OT(m,type) PyArray_FromAny(m, \ PyArray_DescrFromType(type), 0, 0, 0, NULL) #define PyArray_FROM_OTF(m, type, flags) \ PyArray_FromAny(m, PyArray_DescrFromType(type), 0, 0, \ (((flags) & NPY_ARRAY_ENSURECOPY) ? \ ((flags) | NPY_ARRAY_DEFAULT) : (flags)), NULL) #define PyArray_FROMANY(m, type, min, max, flags) \ PyArray_FromAny(m, PyArray_DescrFromType(type), min, max, \ (((flags) & NPY_ARRAY_ENSURECOPY) ? \ (flags) | NPY_ARRAY_DEFAULT : (flags)), NULL) #define PyArray_ZEROS(m, dims, type, is_f_order) \ PyArray_Zeros(m, dims, PyArray_DescrFromType(type), is_f_order) #define PyArray_EMPTY(m, dims, type, is_f_order) \ PyArray_Empty(m, dims, PyArray_DescrFromType(type), is_f_order) #define PyArray_FILLWBYTE(obj, val) memset(PyArray_DATA(obj), val, \ PyArray_NBYTES(obj)) #ifndef PYPY_VERSION #define PyArray_REFCOUNT(obj) (((PyObject *)(obj))->ob_refcnt) #define NPY_REFCOUNT PyArray_REFCOUNT #endif #define NPY_MAX_ELSIZE (2 * NPY_SIZEOF_LONGDOUBLE) #define PyArray_ContiguousFromAny(op, type, min_depth, max_depth) \ PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ max_depth, NPY_ARRAY_DEFAULT, NULL) #define PyArray_EquivArrTypes(a1, a2) \ PyArray_EquivTypes(PyArray_DESCR(a1), PyArray_DESCR(a2)) #define PyArray_EquivByteorders(b1, b2) \ (((b1) == (b2)) || (PyArray_ISNBO(b1) == PyArray_ISNBO(b2))) #define PyArray_SimpleNew(nd, dims, typenum) \ PyArray_New(&PyArray_Type, nd, dims, typenum, NULL, NULL, 0, 0, NULL) #define PyArray_SimpleNewFromData(nd, dims, typenum, data) \ PyArray_New(&PyArray_Type, nd, dims, typenum, NULL, \ data, 0, NPY_ARRAY_CARRAY, NULL) #define PyArray_SimpleNewFromDescr(nd, dims, descr) \ PyArray_NewFromDescr(&PyArray_Type, descr, nd, dims, \ NULL, NULL, 0, NULL) #define PyArray_ToScalar(data, arr) \ PyArray_Scalar(data, PyArray_DESCR(arr), (PyObject *)arr) /* These might be faster without the dereferencing of obj going on inside -- of course an optimizing compiler should inline the constants inside a for loop making it a moot point */ #define PyArray_GETPTR1(obj, i) ((void *)(PyArray_BYTES(obj) + \ (i)*PyArray_STRIDES(obj)[0])) #define PyArray_GETPTR2(obj, i, j) ((void *)(PyArray_BYTES(obj) + \ (i)*PyArray_STRIDES(obj)[0] + \ (j)*PyArray_STRIDES(obj)[1])) #define PyArray_GETPTR3(obj, i, j, k) ((void *)(PyArray_BYTES(obj) + \ (i)*PyArray_STRIDES(obj)[0] + \ (j)*PyArray_STRIDES(obj)[1] + \ (k)*PyArray_STRIDES(obj)[2])) #define PyArray_GETPTR4(obj, i, j, k, l) ((void *)(PyArray_BYTES(obj) + \ (i)*PyArray_STRIDES(obj)[0] + \ (j)*PyArray_STRIDES(obj)[1] + \ (k)*PyArray_STRIDES(obj)[2] + \ (l)*PyArray_STRIDES(obj)[3])) /* Move to arrayobject.c once PyArray_XDECREF_ERR is removed */ static NPY_INLINE void PyArray_DiscardWritebackIfCopy(PyArrayObject *arr) { PyArrayObject_fields *fa = (PyArrayObject_fields *)arr; if (fa && fa->base) { if ((fa->flags & NPY_ARRAY_UPDATEIFCOPY) || (fa->flags & NPY_ARRAY_WRITEBACKIFCOPY)) { PyArray_ENABLEFLAGS((PyArrayObject*)fa->base, NPY_ARRAY_WRITEABLE); Py_DECREF(fa->base); fa->base = NULL; PyArray_CLEARFLAGS(arr, NPY_ARRAY_WRITEBACKIFCOPY); PyArray_CLEARFLAGS(arr, NPY_ARRAY_UPDATEIFCOPY); } } } #define PyArray_DESCR_REPLACE(descr) do { \ PyArray_Descr *_new_; \ _new_ = PyArray_DescrNew(descr); \ Py_XDECREF(descr); \ descr = _new_; \ } while(0) /* Copy should always return contiguous array */ #define PyArray_Copy(obj) PyArray_NewCopy(obj, NPY_CORDER) #define PyArray_FromObject(op, type, min_depth, max_depth) \ PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ max_depth, NPY_ARRAY_BEHAVED | \ NPY_ARRAY_ENSUREARRAY, NULL) #define PyArray_ContiguousFromObject(op, type, min_depth, max_depth) \ PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ max_depth, NPY_ARRAY_DEFAULT | \ NPY_ARRAY_ENSUREARRAY, NULL) #define PyArray_CopyFromObject(op, type, min_depth, max_depth) \ PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ max_depth, NPY_ARRAY_ENSURECOPY | \ NPY_ARRAY_DEFAULT | \ NPY_ARRAY_ENSUREARRAY, NULL) #define PyArray_Cast(mp, type_num) \ PyArray_CastToType(mp, PyArray_DescrFromType(type_num), 0) #define PyArray_Take(ap, items, axis) \ PyArray_TakeFrom(ap, items, axis, NULL, NPY_RAISE) #define PyArray_Put(ap, items, values) \ PyArray_PutTo(ap, items, values, NPY_RAISE) /* Compatibility with old Numeric stuff -- don't use in new code */ #define PyArray_FromDimsAndData(nd, d, type, data) \ PyArray_FromDimsAndDataAndDescr(nd, d, PyArray_DescrFromType(type), \ data) /* Check to see if this key in the dictionary is the "title" entry of the tuple (i.e. a duplicate dictionary entry in the fields dict. */ static NPY_INLINE int NPY_TITLE_KEY_check(PyObject *key, PyObject *value) { PyObject *title; if (PyTuple_GET_SIZE(value) != 3) { return 0; } title = PyTuple_GET_ITEM(value, 2); if (key == title) { return 1; } #ifdef PYPY_VERSION /* * On PyPy, dictionary keys do not always preserve object identity. * Fall back to comparison by value. */ if (PyUnicode_Check(title) && PyUnicode_Check(key)) { return PyUnicode_Compare(title, key) == 0 ? 1 : 0; } #if PY_VERSION_HEX < 0x03000000 if (PyString_Check(title) && PyString_Check(key)) { return PyObject_Compare(title, key) == 0 ? 1 : 0; } #endif #endif return 0; } /* Macro, for backward compat with "if NPY_TITLE_KEY(key, value) { ..." */ #define NPY_TITLE_KEY(key, value) (NPY_TITLE_KEY_check((key), (value))) #define DEPRECATE(msg) PyErr_WarnEx(PyExc_DeprecationWarning,msg,1) #define DEPRECATE_FUTUREWARNING(msg) PyErr_WarnEx(PyExc_FutureWarning,msg,1) #if !defined(NPY_NO_DEPRECATED_API) || \ (NPY_NO_DEPRECATED_API < NPY_1_14_API_VERSION) static NPY_INLINE void PyArray_XDECREF_ERR(PyArrayObject *arr) { /* 2017-Nov-10 1.14 */ DEPRECATE("PyArray_XDECREF_ERR is deprecated, call " "PyArray_DiscardWritebackIfCopy then Py_XDECREF instead"); PyArray_DiscardWritebackIfCopy(arr); Py_XDECREF(arr); } #endif #ifdef __cplusplus } #endif #endif /* NPY_NDARRAYOBJECT_H */
11,718
39.133562
79
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/ndarraytypes.h
#ifndef NDARRAYTYPES_H #define NDARRAYTYPES_H #include "npy_common.h" #include "npy_endian.h" #include "npy_cpu.h" #include "utils.h" #define NPY_NO_EXPORT NPY_VISIBILITY_HIDDEN /* Only use thread if configured in config and python supports it */ #if defined WITH_THREAD && !NPY_NO_SMP #define NPY_ALLOW_THREADS 1 #else #define NPY_ALLOW_THREADS 0 #endif #ifndef __has_extension #define __has_extension(x) 0 #endif #if !defined(_NPY_NO_DEPRECATIONS) && \ ((defined(__GNUC__)&& __GNUC__ >= 6) || \ __has_extension(attribute_deprecated_with_message)) #define NPY_ATTR_DEPRECATE(text) __attribute__ ((deprecated (text))) #else #define NPY_ATTR_DEPRECATE(text) #endif /* * There are several places in the code where an array of dimensions * is allocated statically. This is the size of that static * allocation. * * The array creation itself could have arbitrary dimensions but all * the places where static allocation is used would need to be changed * to dynamic (including inside of several structures) */ #define NPY_MAXDIMS 32 #define NPY_MAXARGS 32 /* Used for Converter Functions "O&" code in ParseTuple */ #define NPY_FAIL 0 #define NPY_SUCCEED 1 /* * Binary compatibility version number. This number is increased * whenever the C-API is changed such that binary compatibility is * broken, i.e. whenever a recompile of extension modules is needed. */ #define NPY_VERSION NPY_ABI_VERSION /* * Minor API version. This number is increased whenever a change is * made to the C-API -- whether it breaks binary compatibility or not. * Some changes, such as adding a function pointer to the end of the * function table, can be made without breaking binary compatibility. * In this case, only the NPY_FEATURE_VERSION (*not* NPY_VERSION) * would be increased. Whenever binary compatibility is broken, both * NPY_VERSION and NPY_FEATURE_VERSION should be increased. */ #define NPY_FEATURE_VERSION NPY_API_VERSION enum NPY_TYPES { NPY_BOOL=0, NPY_BYTE, NPY_UBYTE, NPY_SHORT, NPY_USHORT, NPY_INT, NPY_UINT, NPY_LONG, NPY_ULONG, NPY_LONGLONG, NPY_ULONGLONG, NPY_FLOAT, NPY_DOUBLE, NPY_LONGDOUBLE, NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE, NPY_OBJECT=17, NPY_STRING, NPY_UNICODE, NPY_VOID, /* * New 1.6 types appended, may be integrated * into the above in 2.0. */ NPY_DATETIME, NPY_TIMEDELTA, NPY_HALF, NPY_NTYPES, NPY_NOTYPE, NPY_CHAR NPY_ATTR_DEPRECATE("Use NPY_STRING"), NPY_USERDEF=256, /* leave room for characters */ /* The number of types not including the new 1.6 types */ NPY_NTYPES_ABI_COMPATIBLE=21 }; #ifdef _MSC_VER #pragma deprecated(NPY_CHAR) #endif /* basetype array priority */ #define NPY_PRIORITY 0.0 /* default subtype priority */ #define NPY_SUBTYPE_PRIORITY 1.0 /* default scalar priority */ #define NPY_SCALAR_PRIORITY -1000000.0 /* How many floating point types are there (excluding half) */ #define NPY_NUM_FLOATTYPE 3 /* * These characters correspond to the array type and the struct * module */ enum NPY_TYPECHAR { NPY_BOOLLTR = '?', NPY_BYTELTR = 'b', NPY_UBYTELTR = 'B', NPY_SHORTLTR = 'h', NPY_USHORTLTR = 'H', NPY_INTLTR = 'i', NPY_UINTLTR = 'I', NPY_LONGLTR = 'l', NPY_ULONGLTR = 'L', NPY_LONGLONGLTR = 'q', NPY_ULONGLONGLTR = 'Q', NPY_HALFLTR = 'e', NPY_FLOATLTR = 'f', NPY_DOUBLELTR = 'd', NPY_LONGDOUBLELTR = 'g', NPY_CFLOATLTR = 'F', NPY_CDOUBLELTR = 'D', NPY_CLONGDOUBLELTR = 'G', NPY_OBJECTLTR = 'O', NPY_STRINGLTR = 'S', NPY_STRINGLTR2 = 'a', NPY_UNICODELTR = 'U', NPY_VOIDLTR = 'V', NPY_DATETIMELTR = 'M', NPY_TIMEDELTALTR = 'm', NPY_CHARLTR = 'c', /* * No Descriptor, just a define -- this let's * Python users specify an array of integers * large enough to hold a pointer on the * platform */ NPY_INTPLTR = 'p', NPY_UINTPLTR = 'P', /* * These are for dtype 'kinds', not dtype 'typecodes' * as the above are for. */ NPY_GENBOOLLTR ='b', NPY_SIGNEDLTR = 'i', NPY_UNSIGNEDLTR = 'u', NPY_FLOATINGLTR = 'f', NPY_COMPLEXLTR = 'c' }; typedef enum { NPY_QUICKSORT=0, NPY_HEAPSORT=1, NPY_MERGESORT=2 } NPY_SORTKIND; #define NPY_NSORTS (NPY_MERGESORT + 1) typedef enum { NPY_INTROSELECT=0 } NPY_SELECTKIND; #define NPY_NSELECTS (NPY_INTROSELECT + 1) typedef enum { NPY_SEARCHLEFT=0, NPY_SEARCHRIGHT=1 } NPY_SEARCHSIDE; #define NPY_NSEARCHSIDES (NPY_SEARCHRIGHT + 1) typedef enum { NPY_NOSCALAR=-1, NPY_BOOL_SCALAR, NPY_INTPOS_SCALAR, NPY_INTNEG_SCALAR, NPY_FLOAT_SCALAR, NPY_COMPLEX_SCALAR, NPY_OBJECT_SCALAR } NPY_SCALARKIND; #define NPY_NSCALARKINDS (NPY_OBJECT_SCALAR + 1) /* For specifying array memory layout or iteration order */ typedef enum { /* Fortran order if inputs are all Fortran, C otherwise */ NPY_ANYORDER=-1, /* C order */ NPY_CORDER=0, /* Fortran order */ NPY_FORTRANORDER=1, /* An order as close to the inputs as possible */ NPY_KEEPORDER=2 } NPY_ORDER; /* For specifying allowed casting in operations which support it */ typedef enum { /* Only allow identical types */ NPY_NO_CASTING=0, /* Allow identical and byte swapped types */ NPY_EQUIV_CASTING=1, /* Only allow safe casts */ NPY_SAFE_CASTING=2, /* Allow safe casts or casts within the same kind */ NPY_SAME_KIND_CASTING=3, /* Allow any casts */ NPY_UNSAFE_CASTING=4 } NPY_CASTING; typedef enum { NPY_CLIP=0, NPY_WRAP=1, NPY_RAISE=2 } NPY_CLIPMODE; /* The special not-a-time (NaT) value */ #define NPY_DATETIME_NAT NPY_MIN_INT64 /* * Upper bound on the length of a DATETIME ISO 8601 string * YEAR: 21 (64-bit year) * MONTH: 3 * DAY: 3 * HOURS: 3 * MINUTES: 3 * SECONDS: 3 * ATTOSECONDS: 1 + 3*6 * TIMEZONE: 5 * NULL TERMINATOR: 1 */ #define NPY_DATETIME_MAX_ISO8601_STRLEN (21+3*5+1+3*6+6+1) typedef enum { NPY_FR_Y = 0, /* Years */ NPY_FR_M = 1, /* Months */ NPY_FR_W = 2, /* Weeks */ /* Gap where 1.6 NPY_FR_B (value 3) was */ NPY_FR_D = 4, /* Days */ NPY_FR_h = 5, /* hours */ NPY_FR_m = 6, /* minutes */ NPY_FR_s = 7, /* seconds */ NPY_FR_ms = 8, /* milliseconds */ NPY_FR_us = 9, /* microseconds */ NPY_FR_ns = 10,/* nanoseconds */ NPY_FR_ps = 11,/* picoseconds */ NPY_FR_fs = 12,/* femtoseconds */ NPY_FR_as = 13,/* attoseconds */ NPY_FR_GENERIC = 14 /* Generic, unbound units, can convert to anything */ } NPY_DATETIMEUNIT; /* * NOTE: With the NPY_FR_B gap for 1.6 ABI compatibility, NPY_DATETIME_NUMUNITS * is technically one more than the actual number of units. */ #define NPY_DATETIME_NUMUNITS (NPY_FR_GENERIC + 1) #define NPY_DATETIME_DEFAULTUNIT NPY_FR_GENERIC /* * Business day conventions for mapping invalid business * days to valid business days. */ typedef enum { /* Go forward in time to the following business day. */ NPY_BUSDAY_FORWARD, NPY_BUSDAY_FOLLOWING = NPY_BUSDAY_FORWARD, /* Go backward in time to the preceding business day. */ NPY_BUSDAY_BACKWARD, NPY_BUSDAY_PRECEDING = NPY_BUSDAY_BACKWARD, /* * Go forward in time to the following business day, unless it * crosses a month boundary, in which case go backward */ NPY_BUSDAY_MODIFIEDFOLLOWING, /* * Go backward in time to the preceding business day, unless it * crosses a month boundary, in which case go forward. */ NPY_BUSDAY_MODIFIEDPRECEDING, /* Produce a NaT for non-business days. */ NPY_BUSDAY_NAT, /* Raise an exception for non-business days. */ NPY_BUSDAY_RAISE } NPY_BUSDAY_ROLL; /************************************************************ * NumPy Auxiliary Data for inner loops, sort functions, etc. ************************************************************/ /* * When creating an auxiliary data struct, this should always appear * as the first member, like this: * * typedef struct { * NpyAuxData base; * double constant; * } constant_multiplier_aux_data; */ typedef struct NpyAuxData_tag NpyAuxData; /* Function pointers for freeing or cloning auxiliary data */ typedef void (NpyAuxData_FreeFunc) (NpyAuxData *); typedef NpyAuxData *(NpyAuxData_CloneFunc) (NpyAuxData *); struct NpyAuxData_tag { NpyAuxData_FreeFunc *free; NpyAuxData_CloneFunc *clone; /* To allow for a bit of expansion without breaking the ABI */ void *reserved[2]; }; /* Macros to use for freeing and cloning auxiliary data */ #define NPY_AUXDATA_FREE(auxdata) \ do { \ if ((auxdata) != NULL) { \ (auxdata)->free(auxdata); \ } \ } while(0) #define NPY_AUXDATA_CLONE(auxdata) \ ((auxdata)->clone(auxdata)) #define NPY_ERR(str) fprintf(stderr, #str); fflush(stderr); #define NPY_ERR2(str) fprintf(stderr, str); fflush(stderr); #define NPY_STRINGIFY(x) #x #define NPY_TOSTRING(x) NPY_STRINGIFY(x) /* * Macros to define how array, and dimension/strides data is * allocated. */ /* Data buffer - PyDataMem_NEW/FREE/RENEW are in multiarraymodule.c */ #define NPY_USE_PYMEM 1 #if NPY_USE_PYMEM == 1 /* numpy sometimes calls PyArray_malloc() with the GIL released. On Python 3.3 and older, it was safe to call PyMem_Malloc() with the GIL released. On Python 3.4 and newer, it's better to use PyMem_RawMalloc() to be able to use tracemalloc. On Python 3.6, calling PyMem_Malloc() with the GIL released is now a fatal error in debug mode. */ # if PY_VERSION_HEX >= 0x03040000 # define PyArray_malloc PyMem_RawMalloc # define PyArray_free PyMem_RawFree # define PyArray_realloc PyMem_RawRealloc # else # define PyArray_malloc PyMem_Malloc # define PyArray_free PyMem_Free # define PyArray_realloc PyMem_Realloc # endif #else #define PyArray_malloc malloc #define PyArray_free free #define PyArray_realloc realloc #endif /* Dimensions and strides */ #define PyDimMem_NEW(size) \ ((npy_intp *)PyArray_malloc(size*sizeof(npy_intp))) #define PyDimMem_FREE(ptr) PyArray_free(ptr) #define PyDimMem_RENEW(ptr,size) \ ((npy_intp *)PyArray_realloc(ptr,size*sizeof(npy_intp))) /* forward declaration */ struct _PyArray_Descr; /* These must deal with unaligned and swapped data if necessary */ typedef PyObject * (PyArray_GetItemFunc) (void *, void *); typedef int (PyArray_SetItemFunc)(PyObject *, void *, void *); typedef void (PyArray_CopySwapNFunc)(void *, npy_intp, void *, npy_intp, npy_intp, int, void *); typedef void (PyArray_CopySwapFunc)(void *, void *, int, void *); typedef npy_bool (PyArray_NonzeroFunc)(void *, void *); /* * These assume aligned and notswapped data -- a buffer will be used * before or contiguous data will be obtained */ typedef int (PyArray_CompareFunc)(const void *, const void *, void *); typedef int (PyArray_ArgFunc)(void*, npy_intp, npy_intp*, void *); typedef void (PyArray_DotFunc)(void *, npy_intp, void *, npy_intp, void *, npy_intp, void *); typedef void (PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *); /* * XXX the ignore argument should be removed next time the API version * is bumped. It used to be the separator. */ typedef int (PyArray_ScanFunc)(FILE *fp, void *dptr, char *ignore, struct _PyArray_Descr *); typedef int (PyArray_FromStrFunc)(char *s, void *dptr, char **endptr, struct _PyArray_Descr *); typedef int (PyArray_FillFunc)(void *, npy_intp, void *); typedef int (PyArray_SortFunc)(void *, npy_intp, void *); typedef int (PyArray_ArgSortFunc)(void *, npy_intp *, npy_intp, void *); typedef int (PyArray_PartitionFunc)(void *, npy_intp, npy_intp, npy_intp *, npy_intp *, void *); typedef int (PyArray_ArgPartitionFunc)(void *, npy_intp *, npy_intp, npy_intp, npy_intp *, npy_intp *, void *); typedef int (PyArray_FillWithScalarFunc)(void *, npy_intp, void *, void *); typedef int (PyArray_ScalarKindFunc)(void *); typedef void (PyArray_FastClipFunc)(void *in, npy_intp n_in, void *min, void *max, void *out); typedef void (PyArray_FastPutmaskFunc)(void *in, void *mask, npy_intp n_in, void *values, npy_intp nv); typedef int (PyArray_FastTakeFunc)(void *dest, void *src, npy_intp *indarray, npy_intp nindarray, npy_intp n_outer, npy_intp m_middle, npy_intp nelem, NPY_CLIPMODE clipmode); typedef struct { npy_intp *ptr; int len; } PyArray_Dims; typedef struct { /* * Functions to cast to most other standard types * Can have some NULL entries. The types * DATETIME, TIMEDELTA, and HALF go into the castdict * even though they are built-in. */ PyArray_VectorUnaryFunc *cast[NPY_NTYPES_ABI_COMPATIBLE]; /* The next four functions *cannot* be NULL */ /* * Functions to get and set items with standard Python types * -- not array scalars */ PyArray_GetItemFunc *getitem; PyArray_SetItemFunc *setitem; /* * Copy and/or swap data. Memory areas may not overlap * Use memmove first if they might */ PyArray_CopySwapNFunc *copyswapn; PyArray_CopySwapFunc *copyswap; /* * Function to compare items * Can be NULL */ PyArray_CompareFunc *compare; /* * Function to select largest * Can be NULL */ PyArray_ArgFunc *argmax; /* * Function to compute dot product * Can be NULL */ PyArray_DotFunc *dotfunc; /* * Function to scan an ASCII file and * place a single value plus possible separator * Can be NULL */ PyArray_ScanFunc *scanfunc; /* * Function to read a single value from a string * and adjust the pointer; Can be NULL */ PyArray_FromStrFunc *fromstr; /* * Function to determine if data is zero or not * If NULL a default version is * used at Registration time. */ PyArray_NonzeroFunc *nonzero; /* * Used for arange. * Can be NULL. */ PyArray_FillFunc *fill; /* * Function to fill arrays with scalar values * Can be NULL */ PyArray_FillWithScalarFunc *fillwithscalar; /* * Sorting functions * Can be NULL */ PyArray_SortFunc *sort[NPY_NSORTS]; PyArray_ArgSortFunc *argsort[NPY_NSORTS]; /* * Dictionary of additional casting functions * PyArray_VectorUnaryFuncs * which can be populated to support casting * to other registered types. Can be NULL */ PyObject *castdict; /* * Functions useful for generalizing * the casting rules. * Can be NULL; */ PyArray_ScalarKindFunc *scalarkind; int **cancastscalarkindto; int *cancastto; PyArray_FastClipFunc *fastclip; PyArray_FastPutmaskFunc *fastputmask; PyArray_FastTakeFunc *fasttake; /* * Function to select smallest * Can be NULL */ PyArray_ArgFunc *argmin; } PyArray_ArrFuncs; /* The item must be reference counted when it is inserted or extracted. */ #define NPY_ITEM_REFCOUNT 0x01 /* Same as needing REFCOUNT */ #define NPY_ITEM_HASOBJECT 0x01 /* Convert to list for pickling */ #define NPY_LIST_PICKLE 0x02 /* The item is a POINTER */ #define NPY_ITEM_IS_POINTER 0x04 /* memory needs to be initialized for this data-type */ #define NPY_NEEDS_INIT 0x08 /* operations need Python C-API so don't give-up thread. */ #define NPY_NEEDS_PYAPI 0x10 /* Use f.getitem when extracting elements of this data-type */ #define NPY_USE_GETITEM 0x20 /* Use f.setitem when setting creating 0-d array from this data-type.*/ #define NPY_USE_SETITEM 0x40 /* A sticky flag specifically for structured arrays */ #define NPY_ALIGNED_STRUCT 0x80 /* *These are inherited for global data-type if any data-types in the * field have them */ #define NPY_FROM_FIELDS (NPY_NEEDS_INIT | NPY_LIST_PICKLE | \ NPY_ITEM_REFCOUNT | NPY_NEEDS_PYAPI) #define NPY_OBJECT_DTYPE_FLAGS (NPY_LIST_PICKLE | NPY_USE_GETITEM | \ NPY_ITEM_IS_POINTER | NPY_ITEM_REFCOUNT | \ NPY_NEEDS_INIT | NPY_NEEDS_PYAPI) #define PyDataType_FLAGCHK(dtype, flag) \ (((dtype)->flags & (flag)) == (flag)) #define PyDataType_REFCHK(dtype) \ PyDataType_FLAGCHK(dtype, NPY_ITEM_REFCOUNT) typedef struct _PyArray_Descr { PyObject_HEAD /* * the type object representing an * instance of this type -- should not * be two type_numbers with the same type * object. */ PyTypeObject *typeobj; /* kind for this type */ char kind; /* unique-character representing this type */ char type; /* * '>' (big), '<' (little), '|' * (not-applicable), or '=' (native). */ char byteorder; /* flags describing data type */ char flags; /* number representing this type */ int type_num; /* element size (itemsize) for this type */ int elsize; /* alignment needed for this type */ int alignment; /* * Non-NULL if this type is * is an array (C-contiguous) * of some other type */ struct _arr_descr *subarray; /* * The fields dictionary for this type * For statically defined descr this * is always Py_None */ PyObject *fields; /* * An ordered tuple of field names or NULL * if no fields are defined */ PyObject *names; /* * a table of functions specific for each * basic data descriptor */ PyArray_ArrFuncs *f; /* Metadata about this dtype */ PyObject *metadata; /* * Metadata specific to the C implementation * of the particular dtype. This was added * for NumPy 1.7.0. */ NpyAuxData *c_metadata; /* Cached hash value (-1 if not yet computed). * This was added for NumPy 2.0.0. */ npy_hash_t hash; } PyArray_Descr; typedef struct _arr_descr { PyArray_Descr *base; PyObject *shape; /* a tuple */ } PyArray_ArrayDescr; /* * The main array object structure. * * It has been recommended to use the inline functions defined below * (PyArray_DATA and friends) to access fields here for a number of * releases. Direct access to the members themselves is deprecated. * To ensure that your code does not use deprecated access, * #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION * (or NPY_1_8_API_VERSION or higher as required). */ /* This struct will be moved to a private header in a future release */ typedef struct tagPyArrayObject_fields { PyObject_HEAD /* Pointer to the raw data buffer */ char *data; /* The number of dimensions, also called 'ndim' */ int nd; /* The size in each dimension, also called 'shape' */ npy_intp *dimensions; /* * Number of bytes to jump to get to the * next element in each dimension */ npy_intp *strides; /* * This object is decref'd upon * deletion of array. Except in the * case of WRITEBACKIFCOPY which has * special handling. * * For views it points to the original * array, collapsed so no chains of * views occur. * * For creation from buffer object it * points to an object that should be * decref'd on deletion * * For WRITEBACKIFCOPY flag this is an * array to-be-updated upon calling * PyArray_ResolveWritebackIfCopy */ PyObject *base; /* Pointer to type structure */ PyArray_Descr *descr; /* Flags describing array -- see below */ int flags; /* For weak references */ PyObject *weakreflist; } PyArrayObject_fields; /* * To hide the implementation details, we only expose * the Python struct HEAD. */ #if !defined(NPY_NO_DEPRECATED_API) || \ (NPY_NO_DEPRECATED_API < NPY_1_7_API_VERSION) /* * Can't put this in npy_deprecated_api.h like the others. * PyArrayObject field access is deprecated as of NumPy 1.7. */ typedef PyArrayObject_fields PyArrayObject; #else typedef struct tagPyArrayObject { PyObject_HEAD } PyArrayObject; #endif #define NPY_SIZEOF_PYARRAYOBJECT (sizeof(PyArrayObject_fields)) /* Array Flags Object */ typedef struct PyArrayFlagsObject { PyObject_HEAD PyObject *arr; int flags; } PyArrayFlagsObject; /* Mirrors buffer object to ptr */ typedef struct { PyObject_HEAD PyObject *base; void *ptr; npy_intp len; int flags; } PyArray_Chunk; typedef struct { NPY_DATETIMEUNIT base; int num; } PyArray_DatetimeMetaData; typedef struct { NpyAuxData base; PyArray_DatetimeMetaData meta; } PyArray_DatetimeDTypeMetaData; /* * This structure contains an exploded view of a date-time value. * NaT is represented by year == NPY_DATETIME_NAT. */ typedef struct { npy_int64 year; npy_int32 month, day, hour, min, sec, us, ps, as; } npy_datetimestruct; /* This is not used internally. */ typedef struct { npy_int64 day; npy_int32 sec, us, ps, as; } npy_timedeltastruct; typedef int (PyArray_FinalizeFunc)(PyArrayObject *, PyObject *); /* * Means c-style contiguous (last index varies the fastest). The data * elements right after each other. * * This flag may be requested in constructor functions. * This flag may be tested for in PyArray_FLAGS(arr). */ #define NPY_ARRAY_C_CONTIGUOUS 0x0001 /* * Set if array is a contiguous Fortran array: the first index varies * the fastest in memory (strides array is reverse of C-contiguous * array) * * This flag may be requested in constructor functions. * This flag may be tested for in PyArray_FLAGS(arr). */ #define NPY_ARRAY_F_CONTIGUOUS 0x0002 /* * Note: all 0-d arrays are C_CONTIGUOUS and F_CONTIGUOUS. If a * 1-d array is C_CONTIGUOUS it is also F_CONTIGUOUS. Arrays with * more then one dimension can be C_CONTIGUOUS and F_CONTIGUOUS * at the same time if they have either zero or one element. * If NPY_RELAXED_STRIDES_CHECKING is set, a higher dimensional * array is always C_CONTIGUOUS and F_CONTIGUOUS if it has zero elements * and the array is contiguous if ndarray.squeeze() is contiguous. * I.e. dimensions for which `ndarray.shape[dimension] == 1` are * ignored. */ /* * If set, the array owns the data: it will be free'd when the array * is deleted. * * This flag may be tested for in PyArray_FLAGS(arr). */ #define NPY_ARRAY_OWNDATA 0x0004 /* * An array never has the next four set; they're only used as parameter * flags to the various FromAny functions * * This flag may be requested in constructor functions. */ /* Cause a cast to occur regardless of whether or not it is safe. */ #define NPY_ARRAY_FORCECAST 0x0010 /* * Always copy the array. Returned arrays are always CONTIGUOUS, * ALIGNED, and WRITEABLE. * * This flag may be requested in constructor functions. */ #define NPY_ARRAY_ENSURECOPY 0x0020 /* * Make sure the returned array is a base-class ndarray * * This flag may be requested in constructor functions. */ #define NPY_ARRAY_ENSUREARRAY 0x0040 /* * Make sure that the strides are in units of the element size Needed * for some operations with record-arrays. * * This flag may be requested in constructor functions. */ #define NPY_ARRAY_ELEMENTSTRIDES 0x0080 /* * Array data is aligned on the appropriate memory address for the type * stored according to how the compiler would align things (e.g., an * array of integers (4 bytes each) starts on a memory address that's * a multiple of 4) * * This flag may be requested in constructor functions. * This flag may be tested for in PyArray_FLAGS(arr). */ #define NPY_ARRAY_ALIGNED 0x0100 /* * Array data has the native endianness * * This flag may be requested in constructor functions. */ #define NPY_ARRAY_NOTSWAPPED 0x0200 /* * Array data is writeable * * This flag may be requested in constructor functions. * This flag may be tested for in PyArray_FLAGS(arr). */ #define NPY_ARRAY_WRITEABLE 0x0400 /* * If this flag is set, then base contains a pointer to an array of * the same size that should be updated with the current contents of * this array when PyArray_ResolveWritebackIfCopy is called. * * This flag may be requested in constructor functions. * This flag may be tested for in PyArray_FLAGS(arr). */ #define NPY_ARRAY_UPDATEIFCOPY 0x1000 /* Deprecated in 1.14 */ #define NPY_ARRAY_WRITEBACKIFCOPY 0x2000 /* * NOTE: there are also internal flags defined in multiarray/arrayobject.h, * which start at bit 31 and work down. */ #define NPY_ARRAY_BEHAVED (NPY_ARRAY_ALIGNED | \ NPY_ARRAY_WRITEABLE) #define NPY_ARRAY_BEHAVED_NS (NPY_ARRAY_ALIGNED | \ NPY_ARRAY_WRITEABLE | \ NPY_ARRAY_NOTSWAPPED) #define NPY_ARRAY_CARRAY (NPY_ARRAY_C_CONTIGUOUS | \ NPY_ARRAY_BEHAVED) #define NPY_ARRAY_CARRAY_RO (NPY_ARRAY_C_CONTIGUOUS | \ NPY_ARRAY_ALIGNED) #define NPY_ARRAY_FARRAY (NPY_ARRAY_F_CONTIGUOUS | \ NPY_ARRAY_BEHAVED) #define NPY_ARRAY_FARRAY_RO (NPY_ARRAY_F_CONTIGUOUS | \ NPY_ARRAY_ALIGNED) #define NPY_ARRAY_DEFAULT (NPY_ARRAY_CARRAY) #define NPY_ARRAY_IN_ARRAY (NPY_ARRAY_CARRAY_RO) #define NPY_ARRAY_OUT_ARRAY (NPY_ARRAY_CARRAY) #define NPY_ARRAY_INOUT_ARRAY (NPY_ARRAY_CARRAY | \ NPY_ARRAY_UPDATEIFCOPY) #define NPY_ARRAY_INOUT_ARRAY2 (NPY_ARRAY_CARRAY | \ NPY_ARRAY_WRITEBACKIFCOPY) #define NPY_ARRAY_IN_FARRAY (NPY_ARRAY_FARRAY_RO) #define NPY_ARRAY_OUT_FARRAY (NPY_ARRAY_FARRAY) #define NPY_ARRAY_INOUT_FARRAY (NPY_ARRAY_FARRAY | \ NPY_ARRAY_UPDATEIFCOPY) #define NPY_ARRAY_INOUT_FARRAY2 (NPY_ARRAY_FARRAY | \ NPY_ARRAY_WRITEBACKIFCOPY) #define NPY_ARRAY_UPDATE_ALL (NPY_ARRAY_C_CONTIGUOUS | \ NPY_ARRAY_F_CONTIGUOUS | \ NPY_ARRAY_ALIGNED) /* This flag is for the array interface, not PyArrayObject */ #define NPY_ARR_HAS_DESCR 0x0800 /* * Size of internal buffers used for alignment Make BUFSIZE a multiple * of sizeof(npy_cdouble) -- usually 16 so that ufunc buffers are aligned */ #define NPY_MIN_BUFSIZE ((int)sizeof(npy_cdouble)) #define NPY_MAX_BUFSIZE (((int)sizeof(npy_cdouble))*1000000) #define NPY_BUFSIZE 8192 /* buffer stress test size: */ /*#define NPY_BUFSIZE 17*/ #define PyArray_MAX(a,b) (((a)>(b))?(a):(b)) #define PyArray_MIN(a,b) (((a)<(b))?(a):(b)) #define PyArray_CLT(p,q) ((((p).real==(q).real) ? ((p).imag < (q).imag) : \ ((p).real < (q).real))) #define PyArray_CGT(p,q) ((((p).real==(q).real) ? ((p).imag > (q).imag) : \ ((p).real > (q).real))) #define PyArray_CLE(p,q) ((((p).real==(q).real) ? ((p).imag <= (q).imag) : \ ((p).real <= (q).real))) #define PyArray_CGE(p,q) ((((p).real==(q).real) ? ((p).imag >= (q).imag) : \ ((p).real >= (q).real))) #define PyArray_CEQ(p,q) (((p).real==(q).real) && ((p).imag == (q).imag)) #define PyArray_CNE(p,q) (((p).real!=(q).real) || ((p).imag != (q).imag)) /* * C API: consists of Macros and functions. The MACROS are defined * here. */ #define PyArray_ISCONTIGUOUS(m) PyArray_CHKFLAGS(m, NPY_ARRAY_C_CONTIGUOUS) #define PyArray_ISWRITEABLE(m) PyArray_CHKFLAGS(m, NPY_ARRAY_WRITEABLE) #define PyArray_ISALIGNED(m) PyArray_CHKFLAGS(m, NPY_ARRAY_ALIGNED) #define PyArray_IS_C_CONTIGUOUS(m) PyArray_CHKFLAGS(m, NPY_ARRAY_C_CONTIGUOUS) #define PyArray_IS_F_CONTIGUOUS(m) PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS) /* the variable is used in some places, so always define it */ #define NPY_BEGIN_THREADS_DEF PyThreadState *_save=NULL; #if NPY_ALLOW_THREADS #define NPY_BEGIN_ALLOW_THREADS Py_BEGIN_ALLOW_THREADS #define NPY_END_ALLOW_THREADS Py_END_ALLOW_THREADS #define NPY_BEGIN_THREADS do {_save = PyEval_SaveThread();} while (0); #define NPY_END_THREADS do { if (_save) \ { PyEval_RestoreThread(_save); _save = NULL;} } while (0); #define NPY_BEGIN_THREADS_THRESHOLDED(loop_size) do { if (loop_size > 500) \ { _save = PyEval_SaveThread();} } while (0); #define NPY_BEGIN_THREADS_DESCR(dtype) \ do {if (!(PyDataType_FLAGCHK(dtype, NPY_NEEDS_PYAPI))) \ NPY_BEGIN_THREADS;} while (0); #define NPY_END_THREADS_DESCR(dtype) \ do {if (!(PyDataType_FLAGCHK(dtype, NPY_NEEDS_PYAPI))) \ NPY_END_THREADS; } while (0); #define NPY_ALLOW_C_API_DEF PyGILState_STATE __save__; #define NPY_ALLOW_C_API do {__save__ = PyGILState_Ensure();} while (0); #define NPY_DISABLE_C_API do {PyGILState_Release(__save__);} while (0); #else #define NPY_BEGIN_ALLOW_THREADS #define NPY_END_ALLOW_THREADS #define NPY_BEGIN_THREADS #define NPY_END_THREADS #define NPY_BEGIN_THREADS_THRESHOLDED(loop_size) #define NPY_BEGIN_THREADS_DESCR(dtype) #define NPY_END_THREADS_DESCR(dtype) #define NPY_ALLOW_C_API_DEF #define NPY_ALLOW_C_API #define NPY_DISABLE_C_API #endif /********************************** * The nditer object, added in 1.6 **********************************/ /* The actual structure of the iterator is an internal detail */ typedef struct NpyIter_InternalOnly NpyIter; /* Iterator function pointers that may be specialized */ typedef int (NpyIter_IterNextFunc)(NpyIter *iter); typedef void (NpyIter_GetMultiIndexFunc)(NpyIter *iter, npy_intp *outcoords); /*** Global flags that may be passed to the iterator constructors ***/ /* Track an index representing C order */ #define NPY_ITER_C_INDEX 0x00000001 /* Track an index representing Fortran order */ #define NPY_ITER_F_INDEX 0x00000002 /* Track a multi-index */ #define NPY_ITER_MULTI_INDEX 0x00000004 /* User code external to the iterator does the 1-dimensional innermost loop */ #define NPY_ITER_EXTERNAL_LOOP 0x00000008 /* Convert all the operands to a common data type */ #define NPY_ITER_COMMON_DTYPE 0x00000010 /* Operands may hold references, requiring API access during iteration */ #define NPY_ITER_REFS_OK 0x00000020 /* Zero-sized operands should be permitted, iteration checks IterSize for 0 */ #define NPY_ITER_ZEROSIZE_OK 0x00000040 /* Permits reductions (size-0 stride with dimension size > 1) */ #define NPY_ITER_REDUCE_OK 0x00000080 /* Enables sub-range iteration */ #define NPY_ITER_RANGED 0x00000100 /* Enables buffering */ #define NPY_ITER_BUFFERED 0x00000200 /* When buffering is enabled, grows the inner loop if possible */ #define NPY_ITER_GROWINNER 0x00000400 /* Delay allocation of buffers until first Reset* call */ #define NPY_ITER_DELAY_BUFALLOC 0x00000800 /* When NPY_KEEPORDER is specified, disable reversing negative-stride axes */ #define NPY_ITER_DONT_NEGATE_STRIDES 0x00001000 /* * If output operands overlap with other operands (based on heuristics that * has false positives but no false negatives), make temporary copies to * eliminate overlap. */ #define NPY_ITER_COPY_IF_OVERLAP 0x00002000 /*** Per-operand flags that may be passed to the iterator constructors ***/ /* The operand will be read from and written to */ #define NPY_ITER_READWRITE 0x00010000 /* The operand will only be read from */ #define NPY_ITER_READONLY 0x00020000 /* The operand will only be written to */ #define NPY_ITER_WRITEONLY 0x00040000 /* The operand's data must be in native byte order */ #define NPY_ITER_NBO 0x00080000 /* The operand's data must be aligned */ #define NPY_ITER_ALIGNED 0x00100000 /* The operand's data must be contiguous (within the inner loop) */ #define NPY_ITER_CONTIG 0x00200000 /* The operand may be copied to satisfy requirements */ #define NPY_ITER_COPY 0x00400000 /* The operand may be copied with WRITEBACKIFCOPY to satisfy requirements */ #define NPY_ITER_UPDATEIFCOPY 0x00800000 /* Allocate the operand if it is NULL */ #define NPY_ITER_ALLOCATE 0x01000000 /* If an operand is allocated, don't use any subtype */ #define NPY_ITER_NO_SUBTYPE 0x02000000 /* This is a virtual array slot, operand is NULL but temporary data is there */ #define NPY_ITER_VIRTUAL 0x04000000 /* Require that the dimension match the iterator dimensions exactly */ #define NPY_ITER_NO_BROADCAST 0x08000000 /* A mask is being used on this array, affects buffer -> array copy */ #define NPY_ITER_WRITEMASKED 0x10000000 /* This array is the mask for all WRITEMASKED operands */ #define NPY_ITER_ARRAYMASK 0x20000000 /* Assume iterator order data access for COPY_IF_OVERLAP */ #define NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE 0x40000000 #define NPY_ITER_GLOBAL_FLAGS 0x0000ffff #define NPY_ITER_PER_OP_FLAGS 0xffff0000 /***************************** * Basic iterator object *****************************/ /* FWD declaration */ typedef struct PyArrayIterObject_tag PyArrayIterObject; /* * type of the function which translates a set of coordinates to a * pointer to the data */ typedef char* (*npy_iter_get_dataptr_t)(PyArrayIterObject* iter, npy_intp*); struct PyArrayIterObject_tag { PyObject_HEAD int nd_m1; /* number of dimensions - 1 */ npy_intp index, size; npy_intp coordinates[NPY_MAXDIMS];/* N-dimensional loop */ npy_intp dims_m1[NPY_MAXDIMS]; /* ao->dimensions - 1 */ npy_intp strides[NPY_MAXDIMS]; /* ao->strides or fake */ npy_intp backstrides[NPY_MAXDIMS];/* how far to jump back */ npy_intp factors[NPY_MAXDIMS]; /* shape factors */ PyArrayObject *ao; char *dataptr; /* pointer to current item*/ npy_bool contiguous; npy_intp bounds[NPY_MAXDIMS][2]; npy_intp limits[NPY_MAXDIMS][2]; npy_intp limits_sizes[NPY_MAXDIMS]; npy_iter_get_dataptr_t translate; } ; /* Iterator API */ #define PyArrayIter_Check(op) PyObject_TypeCheck(op, &PyArrayIter_Type) #define _PyAIT(it) ((PyArrayIterObject *)(it)) #define PyArray_ITER_RESET(it) do { \ _PyAIT(it)->index = 0; \ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao); \ memset(_PyAIT(it)->coordinates, 0, \ (_PyAIT(it)->nd_m1+1)*sizeof(npy_intp)); \ } while (0) #define _PyArray_ITER_NEXT1(it) do { \ (it)->dataptr += _PyAIT(it)->strides[0]; \ (it)->coordinates[0]++; \ } while (0) #define _PyArray_ITER_NEXT2(it) do { \ if ((it)->coordinates[1] < (it)->dims_m1[1]) { \ (it)->coordinates[1]++; \ (it)->dataptr += (it)->strides[1]; \ } \ else { \ (it)->coordinates[1] = 0; \ (it)->coordinates[0]++; \ (it)->dataptr += (it)->strides[0] - \ (it)->backstrides[1]; \ } \ } while (0) #define PyArray_ITER_NEXT(it) do { \ _PyAIT(it)->index++; \ if (_PyAIT(it)->nd_m1 == 0) { \ _PyArray_ITER_NEXT1(_PyAIT(it)); \ } \ else if (_PyAIT(it)->contiguous) \ _PyAIT(it)->dataptr += PyArray_DESCR(_PyAIT(it)->ao)->elsize; \ else if (_PyAIT(it)->nd_m1 == 1) { \ _PyArray_ITER_NEXT2(_PyAIT(it)); \ } \ else { \ int __npy_i; \ for (__npy_i=_PyAIT(it)->nd_m1; __npy_i >= 0; __npy_i--) { \ if (_PyAIT(it)->coordinates[__npy_i] < \ _PyAIT(it)->dims_m1[__npy_i]) { \ _PyAIT(it)->coordinates[__npy_i]++; \ _PyAIT(it)->dataptr += \ _PyAIT(it)->strides[__npy_i]; \ break; \ } \ else { \ _PyAIT(it)->coordinates[__npy_i] = 0; \ _PyAIT(it)->dataptr -= \ _PyAIT(it)->backstrides[__npy_i]; \ } \ } \ } \ } while (0) #define PyArray_ITER_GOTO(it, destination) do { \ int __npy_i; \ _PyAIT(it)->index = 0; \ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao); \ for (__npy_i = _PyAIT(it)->nd_m1; __npy_i>=0; __npy_i--) { \ if (destination[__npy_i] < 0) { \ destination[__npy_i] += \ _PyAIT(it)->dims_m1[__npy_i]+1; \ } \ _PyAIT(it)->dataptr += destination[__npy_i] * \ _PyAIT(it)->strides[__npy_i]; \ _PyAIT(it)->coordinates[__npy_i] = \ destination[__npy_i]; \ _PyAIT(it)->index += destination[__npy_i] * \ ( __npy_i==_PyAIT(it)->nd_m1 ? 1 : \ _PyAIT(it)->dims_m1[__npy_i+1]+1) ; \ } \ } while (0) #define PyArray_ITER_GOTO1D(it, ind) do { \ int __npy_i; \ npy_intp __npy_ind = (npy_intp) (ind); \ if (__npy_ind < 0) __npy_ind += _PyAIT(it)->size; \ _PyAIT(it)->index = __npy_ind; \ if (_PyAIT(it)->nd_m1 == 0) { \ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao) + \ __npy_ind * _PyAIT(it)->strides[0]; \ } \ else if (_PyAIT(it)->contiguous) \ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao) + \ __npy_ind * PyArray_DESCR(_PyAIT(it)->ao)->elsize; \ else { \ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao); \ for (__npy_i = 0; __npy_i<=_PyAIT(it)->nd_m1; \ __npy_i++) { \ _PyAIT(it)->dataptr += \ (__npy_ind / _PyAIT(it)->factors[__npy_i]) \ * _PyAIT(it)->strides[__npy_i]; \ __npy_ind %= _PyAIT(it)->factors[__npy_i]; \ } \ } \ } while (0) #define PyArray_ITER_DATA(it) ((void *)(_PyAIT(it)->dataptr)) #define PyArray_ITER_NOTDONE(it) (_PyAIT(it)->index < _PyAIT(it)->size) /* * Any object passed to PyArray_Broadcast must be binary compatible * with this structure. */ typedef struct { PyObject_HEAD int numiter; /* number of iters */ npy_intp size; /* broadcasted size */ npy_intp index; /* current index */ int nd; /* number of dims */ npy_intp dimensions[NPY_MAXDIMS]; /* dimensions */ PyArrayIterObject *iters[NPY_MAXARGS]; /* iterators */ } PyArrayMultiIterObject; #define _PyMIT(m) ((PyArrayMultiIterObject *)(m)) #define PyArray_MultiIter_RESET(multi) do { \ int __npy_mi; \ _PyMIT(multi)->index = 0; \ for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \ PyArray_ITER_RESET(_PyMIT(multi)->iters[__npy_mi]); \ } \ } while (0) #define PyArray_MultiIter_NEXT(multi) do { \ int __npy_mi; \ _PyMIT(multi)->index++; \ for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \ PyArray_ITER_NEXT(_PyMIT(multi)->iters[__npy_mi]); \ } \ } while (0) #define PyArray_MultiIter_GOTO(multi, dest) do { \ int __npy_mi; \ for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \ PyArray_ITER_GOTO(_PyMIT(multi)->iters[__npy_mi], dest); \ } \ _PyMIT(multi)->index = _PyMIT(multi)->iters[0]->index; \ } while (0) #define PyArray_MultiIter_GOTO1D(multi, ind) do { \ int __npy_mi; \ for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \ PyArray_ITER_GOTO1D(_PyMIT(multi)->iters[__npy_mi], ind); \ } \ _PyMIT(multi)->index = _PyMIT(multi)->iters[0]->index; \ } while (0) #define PyArray_MultiIter_DATA(multi, i) \ ((void *)(_PyMIT(multi)->iters[i]->dataptr)) #define PyArray_MultiIter_NEXTi(multi, i) \ PyArray_ITER_NEXT(_PyMIT(multi)->iters[i]) #define PyArray_MultiIter_NOTDONE(multi) \ (_PyMIT(multi)->index < _PyMIT(multi)->size) /* * Store the information needed for fancy-indexing over an array. The * fields are slightly unordered to keep consec, dataptr and subspace * where they were originally. */ typedef struct { PyObject_HEAD /* * Multi-iterator portion --- needs to be present in this * order to work with PyArray_Broadcast */ int numiter; /* number of index-array iterators */ npy_intp size; /* size of broadcasted result */ npy_intp index; /* current index */ int nd; /* number of dims */ npy_intp dimensions[NPY_MAXDIMS]; /* dimensions */ NpyIter *outer; /* index objects iterator */ void *unused[NPY_MAXDIMS - 2]; PyArrayObject *array; /* Flat iterator for the indexed array. For compatibility solely. */ PyArrayIterObject *ait; /* * Subspace array. For binary compatibility (was an iterator, * but only the check for NULL should be used). */ PyArrayObject *subspace; /* * if subspace iteration, then this is the array of axes in * the underlying array represented by the index objects */ int iteraxes[NPY_MAXDIMS]; npy_intp fancy_strides[NPY_MAXDIMS]; /* pointer when all fancy indices are 0 */ char *baseoffset; /* * after binding consec denotes at which axis the fancy axes * are inserted. */ int consec; char *dataptr; int nd_fancy; npy_intp fancy_dims[NPY_MAXDIMS]; /* Whether the iterator (any of the iterators) requires API */ int needs_api; /* * Extra op information. */ PyArrayObject *extra_op; PyArray_Descr *extra_op_dtype; /* desired dtype */ npy_uint32 *extra_op_flags; /* Iterator flags */ NpyIter *extra_op_iter; NpyIter_IterNextFunc *extra_op_next; char **extra_op_ptrs; /* * Information about the iteration state. */ NpyIter_IterNextFunc *outer_next; char **outer_ptrs; npy_intp *outer_strides; /* * Information about the subspace iterator. */ NpyIter *subspace_iter; NpyIter_IterNextFunc *subspace_next; char **subspace_ptrs; npy_intp *subspace_strides; /* Count for the external loop (which ever it is) for API iteration */ npy_intp iter_count; } PyArrayMapIterObject; enum { NPY_NEIGHBORHOOD_ITER_ZERO_PADDING, NPY_NEIGHBORHOOD_ITER_ONE_PADDING, NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING, NPY_NEIGHBORHOOD_ITER_CIRCULAR_PADDING, NPY_NEIGHBORHOOD_ITER_MIRROR_PADDING }; typedef struct { PyObject_HEAD /* * PyArrayIterObject part: keep this in this exact order */ int nd_m1; /* number of dimensions - 1 */ npy_intp index, size; npy_intp coordinates[NPY_MAXDIMS];/* N-dimensional loop */ npy_intp dims_m1[NPY_MAXDIMS]; /* ao->dimensions - 1 */ npy_intp strides[NPY_MAXDIMS]; /* ao->strides or fake */ npy_intp backstrides[NPY_MAXDIMS];/* how far to jump back */ npy_intp factors[NPY_MAXDIMS]; /* shape factors */ PyArrayObject *ao; char *dataptr; /* pointer to current item*/ npy_bool contiguous; npy_intp bounds[NPY_MAXDIMS][2]; npy_intp limits[NPY_MAXDIMS][2]; npy_intp limits_sizes[NPY_MAXDIMS]; npy_iter_get_dataptr_t translate; /* * New members */ npy_intp nd; /* Dimensions is the dimension of the array */ npy_intp dimensions[NPY_MAXDIMS]; /* * Neighborhood points coordinates are computed relatively to the * point pointed by _internal_iter */ PyArrayIterObject* _internal_iter; /* * To keep a reference to the representation of the constant value * for constant padding */ char* constant; int mode; } PyArrayNeighborhoodIterObject; /* * Neighborhood iterator API */ /* General: those work for any mode */ static NPY_INLINE int PyArrayNeighborhoodIter_Reset(PyArrayNeighborhoodIterObject* iter); static NPY_INLINE int PyArrayNeighborhoodIter_Next(PyArrayNeighborhoodIterObject* iter); #if 0 static NPY_INLINE int PyArrayNeighborhoodIter_Next2D(PyArrayNeighborhoodIterObject* iter); #endif /* * Include inline implementations - functions defined there are not * considered public API */ #define _NPY_INCLUDE_NEIGHBORHOOD_IMP #include "_neighborhood_iterator_imp.h" #undef _NPY_INCLUDE_NEIGHBORHOOD_IMP /* The default array type */ #define NPY_DEFAULT_TYPE NPY_DOUBLE /* * All sorts of useful ways to look into a PyArrayObject. It is recommended * to use PyArrayObject * objects instead of always casting from PyObject *, * for improved type checking. * * In many cases here the macro versions of the accessors are deprecated, * but can't be immediately changed to inline functions because the * preexisting macros accept PyObject * and do automatic casts. Inline * functions accepting PyArrayObject * provides for some compile-time * checking of correctness when working with these objects in C. */ #define PyArray_ISONESEGMENT(m) (PyArray_NDIM(m) == 0 || \ PyArray_CHKFLAGS(m, NPY_ARRAY_C_CONTIGUOUS) || \ PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS)) #define PyArray_ISFORTRAN(m) (PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS) && \ (!PyArray_CHKFLAGS(m, NPY_ARRAY_C_CONTIGUOUS))) #define PyArray_FORTRAN_IF(m) ((PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS) ? \ NPY_ARRAY_F_CONTIGUOUS : 0)) #if (defined(NPY_NO_DEPRECATED_API) && (NPY_1_7_API_VERSION <= NPY_NO_DEPRECATED_API)) /* * Changing access macros into functions, to allow for future hiding * of the internal memory layout. This later hiding will allow the 2.x series * to change the internal representation of arrays without affecting * ABI compatibility. */ static NPY_INLINE int PyArray_NDIM(const PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->nd; } static NPY_INLINE void * PyArray_DATA(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->data; } static NPY_INLINE char * PyArray_BYTES(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->data; } static NPY_INLINE npy_intp * PyArray_DIMS(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->dimensions; } static NPY_INLINE npy_intp * PyArray_STRIDES(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->strides; } static NPY_INLINE npy_intp PyArray_DIM(const PyArrayObject *arr, int idim) { return ((PyArrayObject_fields *)arr)->dimensions[idim]; } static NPY_INLINE npy_intp PyArray_STRIDE(const PyArrayObject *arr, int istride) { return ((PyArrayObject_fields *)arr)->strides[istride]; } static NPY_INLINE NPY_RETURNS_BORROWED_REF PyObject * PyArray_BASE(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->base; } static NPY_INLINE NPY_RETURNS_BORROWED_REF PyArray_Descr * PyArray_DESCR(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->descr; } static NPY_INLINE int PyArray_FLAGS(const PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->flags; } static NPY_INLINE npy_intp PyArray_ITEMSIZE(const PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->descr->elsize; } static NPY_INLINE int PyArray_TYPE(const PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->descr->type_num; } static NPY_INLINE int PyArray_CHKFLAGS(const PyArrayObject *arr, int flags) { return (PyArray_FLAGS(arr) & flags) == flags; } static NPY_INLINE PyObject * PyArray_GETITEM(const PyArrayObject *arr, const char *itemptr) { return ((PyArrayObject_fields *)arr)->descr->f->getitem( (void *)itemptr, (PyArrayObject *)arr); } static NPY_INLINE int PyArray_SETITEM(PyArrayObject *arr, char *itemptr, PyObject *v) { return ((PyArrayObject_fields *)arr)->descr->f->setitem( v, itemptr, arr); } #else /* These macros are deprecated as of NumPy 1.7. */ #define PyArray_NDIM(obj) (((PyArrayObject_fields *)(obj))->nd) #define PyArray_BYTES(obj) (((PyArrayObject_fields *)(obj))->data) #define PyArray_DATA(obj) ((void *)((PyArrayObject_fields *)(obj))->data) #define PyArray_DIMS(obj) (((PyArrayObject_fields *)(obj))->dimensions) #define PyArray_STRIDES(obj) (((PyArrayObject_fields *)(obj))->strides) #define PyArray_DIM(obj,n) (PyArray_DIMS(obj)[n]) #define PyArray_STRIDE(obj,n) (PyArray_STRIDES(obj)[n]) #define PyArray_BASE(obj) (((PyArrayObject_fields *)(obj))->base) #define PyArray_DESCR(obj) (((PyArrayObject_fields *)(obj))->descr) #define PyArray_FLAGS(obj) (((PyArrayObject_fields *)(obj))->flags) #define PyArray_CHKFLAGS(m, FLAGS) \ ((((PyArrayObject_fields *)(m))->flags & (FLAGS)) == (FLAGS)) #define PyArray_ITEMSIZE(obj) \ (((PyArrayObject_fields *)(obj))->descr->elsize) #define PyArray_TYPE(obj) \ (((PyArrayObject_fields *)(obj))->descr->type_num) #define PyArray_GETITEM(obj,itemptr) \ PyArray_DESCR(obj)->f->getitem((char *)(itemptr), \ (PyArrayObject *)(obj)) #define PyArray_SETITEM(obj,itemptr,v) \ PyArray_DESCR(obj)->f->setitem((PyObject *)(v), \ (char *)(itemptr), \ (PyArrayObject *)(obj)) #endif static NPY_INLINE PyArray_Descr * PyArray_DTYPE(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->descr; } static NPY_INLINE npy_intp * PyArray_SHAPE(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->dimensions; } /* * Enables the specified array flags. Does no checking, * assumes you know what you're doing. */ static NPY_INLINE void PyArray_ENABLEFLAGS(PyArrayObject *arr, int flags) { ((PyArrayObject_fields *)arr)->flags |= flags; } /* * Clears the specified array flags. Does no checking, * assumes you know what you're doing. */ static NPY_INLINE void PyArray_CLEARFLAGS(PyArrayObject *arr, int flags) { ((PyArrayObject_fields *)arr)->flags &= ~flags; } #define PyTypeNum_ISBOOL(type) ((type) == NPY_BOOL) #define PyTypeNum_ISUNSIGNED(type) (((type) == NPY_UBYTE) || \ ((type) == NPY_USHORT) || \ ((type) == NPY_UINT) || \ ((type) == NPY_ULONG) || \ ((type) == NPY_ULONGLONG)) #define PyTypeNum_ISSIGNED(type) (((type) == NPY_BYTE) || \ ((type) == NPY_SHORT) || \ ((type) == NPY_INT) || \ ((type) == NPY_LONG) || \ ((type) == NPY_LONGLONG)) #define PyTypeNum_ISINTEGER(type) (((type) >= NPY_BYTE) && \ ((type) <= NPY_ULONGLONG)) #define PyTypeNum_ISFLOAT(type) ((((type) >= NPY_FLOAT) && \ ((type) <= NPY_LONGDOUBLE)) || \ ((type) == NPY_HALF)) #define PyTypeNum_ISNUMBER(type) (((type) <= NPY_CLONGDOUBLE) || \ ((type) == NPY_HALF)) #define PyTypeNum_ISSTRING(type) (((type) == NPY_STRING) || \ ((type) == NPY_UNICODE)) #define PyTypeNum_ISCOMPLEX(type) (((type) >= NPY_CFLOAT) && \ ((type) <= NPY_CLONGDOUBLE)) #define PyTypeNum_ISPYTHON(type) (((type) == NPY_LONG) || \ ((type) == NPY_DOUBLE) || \ ((type) == NPY_CDOUBLE) || \ ((type) == NPY_BOOL) || \ ((type) == NPY_OBJECT )) #define PyTypeNum_ISFLEXIBLE(type) (((type) >=NPY_STRING) && \ ((type) <=NPY_VOID)) #define PyTypeNum_ISDATETIME(type) (((type) >=NPY_DATETIME) && \ ((type) <=NPY_TIMEDELTA)) #define PyTypeNum_ISUSERDEF(type) (((type) >= NPY_USERDEF) && \ ((type) < NPY_USERDEF+ \ NPY_NUMUSERTYPES)) #define PyTypeNum_ISEXTENDED(type) (PyTypeNum_ISFLEXIBLE(type) || \ PyTypeNum_ISUSERDEF(type)) #define PyTypeNum_ISOBJECT(type) ((type) == NPY_OBJECT) #define PyDataType_ISBOOL(obj) PyTypeNum_ISBOOL(_PyADt(obj)) #define PyDataType_ISUNSIGNED(obj) PyTypeNum_ISUNSIGNED(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISSIGNED(obj) PyTypeNum_ISSIGNED(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISINTEGER(obj) PyTypeNum_ISINTEGER(((PyArray_Descr*)(obj))->type_num ) #define PyDataType_ISFLOAT(obj) PyTypeNum_ISFLOAT(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISNUMBER(obj) PyTypeNum_ISNUMBER(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISSTRING(obj) PyTypeNum_ISSTRING(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISCOMPLEX(obj) PyTypeNum_ISCOMPLEX(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISPYTHON(obj) PyTypeNum_ISPYTHON(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISFLEXIBLE(obj) PyTypeNum_ISFLEXIBLE(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISDATETIME(obj) PyTypeNum_ISDATETIME(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISUSERDEF(obj) PyTypeNum_ISUSERDEF(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISEXTENDED(obj) PyTypeNum_ISEXTENDED(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISOBJECT(obj) PyTypeNum_ISOBJECT(((PyArray_Descr*)(obj))->type_num) #define PyDataType_HASFIELDS(obj) (((PyArray_Descr *)(obj))->names != NULL) #define PyDataType_HASSUBARRAY(dtype) ((dtype)->subarray != NULL) #define PyDataType_ISUNSIZED(dtype) ((dtype)->elsize == 0) #define PyDataType_MAKEUNSIZED(dtype) ((dtype)->elsize = 0) #define PyArray_ISBOOL(obj) PyTypeNum_ISBOOL(PyArray_TYPE(obj)) #define PyArray_ISUNSIGNED(obj) PyTypeNum_ISUNSIGNED(PyArray_TYPE(obj)) #define PyArray_ISSIGNED(obj) PyTypeNum_ISSIGNED(PyArray_TYPE(obj)) #define PyArray_ISINTEGER(obj) PyTypeNum_ISINTEGER(PyArray_TYPE(obj)) #define PyArray_ISFLOAT(obj) PyTypeNum_ISFLOAT(PyArray_TYPE(obj)) #define PyArray_ISNUMBER(obj) PyTypeNum_ISNUMBER(PyArray_TYPE(obj)) #define PyArray_ISSTRING(obj) PyTypeNum_ISSTRING(PyArray_TYPE(obj)) #define PyArray_ISCOMPLEX(obj) PyTypeNum_ISCOMPLEX(PyArray_TYPE(obj)) #define PyArray_ISPYTHON(obj) PyTypeNum_ISPYTHON(PyArray_TYPE(obj)) #define PyArray_ISFLEXIBLE(obj) PyTypeNum_ISFLEXIBLE(PyArray_TYPE(obj)) #define PyArray_ISDATETIME(obj) PyTypeNum_ISDATETIME(PyArray_TYPE(obj)) #define PyArray_ISUSERDEF(obj) PyTypeNum_ISUSERDEF(PyArray_TYPE(obj)) #define PyArray_ISEXTENDED(obj) PyTypeNum_ISEXTENDED(PyArray_TYPE(obj)) #define PyArray_ISOBJECT(obj) PyTypeNum_ISOBJECT(PyArray_TYPE(obj)) #define PyArray_HASFIELDS(obj) PyDataType_HASFIELDS(PyArray_DESCR(obj)) /* * FIXME: This should check for a flag on the data-type that * states whether or not it is variable length. Because the * ISFLEXIBLE check is hard-coded to the built-in data-types. */ #define PyArray_ISVARIABLE(obj) PyTypeNum_ISFLEXIBLE(PyArray_TYPE(obj)) #define PyArray_SAFEALIGNEDCOPY(obj) (PyArray_ISALIGNED(obj) && !PyArray_ISVARIABLE(obj)) #define NPY_LITTLE '<' #define NPY_BIG '>' #define NPY_NATIVE '=' #define NPY_SWAP 's' #define NPY_IGNORE '|' #if NPY_BYTE_ORDER == NPY_BIG_ENDIAN #define NPY_NATBYTE NPY_BIG #define NPY_OPPBYTE NPY_LITTLE #else #define NPY_NATBYTE NPY_LITTLE #define NPY_OPPBYTE NPY_BIG #endif #define PyArray_ISNBO(arg) ((arg) != NPY_OPPBYTE) #define PyArray_IsNativeByteOrder PyArray_ISNBO #define PyArray_ISNOTSWAPPED(m) PyArray_ISNBO(PyArray_DESCR(m)->byteorder) #define PyArray_ISBYTESWAPPED(m) (!PyArray_ISNOTSWAPPED(m)) #define PyArray_FLAGSWAP(m, flags) (PyArray_CHKFLAGS(m, flags) && \ PyArray_ISNOTSWAPPED(m)) #define PyArray_ISCARRAY(m) PyArray_FLAGSWAP(m, NPY_ARRAY_CARRAY) #define PyArray_ISCARRAY_RO(m) PyArray_FLAGSWAP(m, NPY_ARRAY_CARRAY_RO) #define PyArray_ISFARRAY(m) PyArray_FLAGSWAP(m, NPY_ARRAY_FARRAY) #define PyArray_ISFARRAY_RO(m) PyArray_FLAGSWAP(m, NPY_ARRAY_FARRAY_RO) #define PyArray_ISBEHAVED(m) PyArray_FLAGSWAP(m, NPY_ARRAY_BEHAVED) #define PyArray_ISBEHAVED_RO(m) PyArray_FLAGSWAP(m, NPY_ARRAY_ALIGNED) #define PyDataType_ISNOTSWAPPED(d) PyArray_ISNBO(((PyArray_Descr *)(d))->byteorder) #define PyDataType_ISBYTESWAPPED(d) (!PyDataType_ISNOTSWAPPED(d)) /************************************************************ * A struct used by PyArray_CreateSortedStridePerm, new in 1.7. ************************************************************/ typedef struct { npy_intp perm, stride; } npy_stride_sort_item; /************************************************************ * This is the form of the struct that's returned pointed by the * PyCObject attribute of an array __array_struct__. See * http://docs.scipy.org/doc/numpy/reference/arrays.interface.html for the full * documentation. ************************************************************/ typedef struct { int two; /* * contains the integer 2 as a sanity * check */ int nd; /* number of dimensions */ char typekind; /* * kind in array --- character code of * typestr */ int itemsize; /* size of each element */ int flags; /* * how should be data interpreted. Valid * flags are CONTIGUOUS (1), F_CONTIGUOUS (2), * ALIGNED (0x100), NOTSWAPPED (0x200), and * WRITEABLE (0x400). ARR_HAS_DESCR (0x800) * states that arrdescr field is present in * structure */ npy_intp *shape; /* * A length-nd array of shape * information */ npy_intp *strides; /* A length-nd array of stride information */ void *data; /* A pointer to the first element of the array */ PyObject *descr; /* * A list of fields or NULL (ignored if flags * does not have ARR_HAS_DESCR flag set) */ } PyArrayInterface; /* * This is a function for hooking into the PyDataMem_NEW/FREE/RENEW functions. * See the documentation for PyDataMem_SetEventHook. */ typedef void (PyDataMem_EventHookFunc)(void *inp, void *outp, size_t size, void *user_data); /* * Use the keyword NPY_DEPRECATED_INCLUDES to ensure that the header files * npy_*_*_deprecated_api.h are only included from here and nowhere else. */ #ifdef NPY_DEPRECATED_INCLUDES #error "Do not use the reserved keyword NPY_DEPRECATED_INCLUDES." #endif #define NPY_DEPRECATED_INCLUDES #if !defined(NPY_NO_DEPRECATED_API) || \ (NPY_NO_DEPRECATED_API < NPY_1_7_API_VERSION) #include "npy_1_7_deprecated_api.h" #endif /* * There is no file npy_1_8_deprecated_api.h since there are no additional * deprecated API features in NumPy 1.8. * * Note to maintainers: insert code like the following in future NumPy * versions. * * #if !defined(NPY_NO_DEPRECATED_API) || \ * (NPY_NO_DEPRECATED_API < NPY_1_9_API_VERSION) * #include "npy_1_9_deprecated_api.h" * #endif */ #undef NPY_DEPRECATED_INCLUDES #endif /* NPY_ARRAYTYPES_H */
64,303
34.081288
90
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/npy_endian.h
#ifndef _NPY_ENDIAN_H_ #define _NPY_ENDIAN_H_ /* * NPY_BYTE_ORDER is set to the same value as BYTE_ORDER set by glibc in * endian.h */ #if defined(NPY_HAVE_ENDIAN_H) || defined(NPY_HAVE_SYS_ENDIAN_H) /* Use endian.h if available */ #if defined(NPY_HAVE_ENDIAN_H) #include <endian.h> #elif defined(NPY_HAVE_SYS_ENDIAN_H) #include <sys/endian.h> #endif #if defined(BYTE_ORDER) && defined(BIG_ENDIAN) && defined(LITTLE_ENDIAN) #define NPY_BYTE_ORDER BYTE_ORDER #define NPY_LITTLE_ENDIAN LITTLE_ENDIAN #define NPY_BIG_ENDIAN BIG_ENDIAN #elif defined(_BYTE_ORDER) && defined(_BIG_ENDIAN) && defined(_LITTLE_ENDIAN) #define NPY_BYTE_ORDER _BYTE_ORDER #define NPY_LITTLE_ENDIAN _LITTLE_ENDIAN #define NPY_BIG_ENDIAN _BIG_ENDIAN #elif defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && defined(__LITTLE_ENDIAN) #define NPY_BYTE_ORDER __BYTE_ORDER #define NPY_LITTLE_ENDIAN __LITTLE_ENDIAN #define NPY_BIG_ENDIAN __BIG_ENDIAN #endif #endif #ifndef NPY_BYTE_ORDER /* Set endianness info using target CPU */ #include "npy_cpu.h" #define NPY_LITTLE_ENDIAN 1234 #define NPY_BIG_ENDIAN 4321 #if defined(NPY_CPU_X86) \ || defined(NPY_CPU_AMD64) \ || defined(NPY_CPU_IA64) \ || defined(NPY_CPU_ALPHA) \ || defined(NPY_CPU_ARMEL) \ || defined(NPY_CPU_AARCH64) \ || defined(NPY_CPU_SH_LE) \ || defined(NPY_CPU_MIPSEL) \ || defined(NPY_CPU_PPC64LE) \ || defined(NPY_CPU_ARCEL) #define NPY_BYTE_ORDER NPY_LITTLE_ENDIAN #elif defined(NPY_CPU_PPC) \ || defined(NPY_CPU_SPARC) \ || defined(NPY_CPU_S390) \ || defined(NPY_CPU_HPPA) \ || defined(NPY_CPU_PPC64) \ || defined(NPY_CPU_ARMEB) \ || defined(NPY_CPU_SH_BE) \ || defined(NPY_CPU_MIPSEB) \ || defined(NPY_CPU_OR1K) \ || defined(NPY_CPU_M68K) \ || defined(NPY_CPU_ARCEB) #define NPY_BYTE_ORDER NPY_BIG_ENDIAN #else #error Unknown CPU: can not set endianness #endif #endif #endif
2,288
32.173913
84
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/npy_math.h
#ifndef __NPY_MATH_C99_H_ #define __NPY_MATH_C99_H_ #ifdef __cplusplus extern "C" { #endif #include <math.h> #ifdef __SUNPRO_CC #include <sunmath.h> #endif #ifdef HAVE_NPY_CONFIG_H #include <npy_config.h> #endif #include <numpy/npy_common.h> /* By adding static inline specifiers to npy_math function definitions when appropriate, compiler is given the opportunity to optimize */ #if NPY_INLINE_MATH #define NPY_INPLACE NPY_INLINE static #else #define NPY_INPLACE #endif /* * NAN and INFINITY like macros (same behavior as glibc for NAN, same as C99 * for INFINITY) * * XXX: I should test whether INFINITY and NAN are available on the platform */ NPY_INLINE static float __npy_inff(void) { const union { npy_uint32 __i; float __f;} __bint = {0x7f800000UL}; return __bint.__f; } NPY_INLINE static float __npy_nanf(void) { const union { npy_uint32 __i; float __f;} __bint = {0x7fc00000UL}; return __bint.__f; } NPY_INLINE static float __npy_pzerof(void) { const union { npy_uint32 __i; float __f;} __bint = {0x00000000UL}; return __bint.__f; } NPY_INLINE static float __npy_nzerof(void) { const union { npy_uint32 __i; float __f;} __bint = {0x80000000UL}; return __bint.__f; } #define NPY_INFINITYF __npy_inff() #define NPY_NANF __npy_nanf() #define NPY_PZEROF __npy_pzerof() #define NPY_NZEROF __npy_nzerof() #define NPY_INFINITY ((npy_double)NPY_INFINITYF) #define NPY_NAN ((npy_double)NPY_NANF) #define NPY_PZERO ((npy_double)NPY_PZEROF) #define NPY_NZERO ((npy_double)NPY_NZEROF) #define NPY_INFINITYL ((npy_longdouble)NPY_INFINITYF) #define NPY_NANL ((npy_longdouble)NPY_NANF) #define NPY_PZEROL ((npy_longdouble)NPY_PZEROF) #define NPY_NZEROL ((npy_longdouble)NPY_NZEROF) /* * Useful constants */ #define NPY_E 2.718281828459045235360287471352662498 /* e */ #define NPY_LOG2E 1.442695040888963407359924681001892137 /* log_2 e */ #define NPY_LOG10E 0.434294481903251827651128918916605082 /* log_10 e */ #define NPY_LOGE2 0.693147180559945309417232121458176568 /* log_e 2 */ #define NPY_LOGE10 2.302585092994045684017991454684364208 /* log_e 10 */ #define NPY_PI 3.141592653589793238462643383279502884 /* pi */ #define NPY_PI_2 1.570796326794896619231321691639751442 /* pi/2 */ #define NPY_PI_4 0.785398163397448309615660845819875721 /* pi/4 */ #define NPY_1_PI 0.318309886183790671537767526745028724 /* 1/pi */ #define NPY_2_PI 0.636619772367581343075535053490057448 /* 2/pi */ #define NPY_EULER 0.577215664901532860606512090082402431 /* Euler constant */ #define NPY_SQRT2 1.414213562373095048801688724209698079 /* sqrt(2) */ #define NPY_SQRT1_2 0.707106781186547524400844362104849039 /* 1/sqrt(2) */ #define NPY_Ef 2.718281828459045235360287471352662498F /* e */ #define NPY_LOG2Ef 1.442695040888963407359924681001892137F /* log_2 e */ #define NPY_LOG10Ef 0.434294481903251827651128918916605082F /* log_10 e */ #define NPY_LOGE2f 0.693147180559945309417232121458176568F /* log_e 2 */ #define NPY_LOGE10f 2.302585092994045684017991454684364208F /* log_e 10 */ #define NPY_PIf 3.141592653589793238462643383279502884F /* pi */ #define NPY_PI_2f 1.570796326794896619231321691639751442F /* pi/2 */ #define NPY_PI_4f 0.785398163397448309615660845819875721F /* pi/4 */ #define NPY_1_PIf 0.318309886183790671537767526745028724F /* 1/pi */ #define NPY_2_PIf 0.636619772367581343075535053490057448F /* 2/pi */ #define NPY_EULERf 0.577215664901532860606512090082402431F /* Euler constant */ #define NPY_SQRT2f 1.414213562373095048801688724209698079F /* sqrt(2) */ #define NPY_SQRT1_2f 0.707106781186547524400844362104849039F /* 1/sqrt(2) */ #define NPY_El 2.718281828459045235360287471352662498L /* e */ #define NPY_LOG2El 1.442695040888963407359924681001892137L /* log_2 e */ #define NPY_LOG10El 0.434294481903251827651128918916605082L /* log_10 e */ #define NPY_LOGE2l 0.693147180559945309417232121458176568L /* log_e 2 */ #define NPY_LOGE10l 2.302585092994045684017991454684364208L /* log_e 10 */ #define NPY_PIl 3.141592653589793238462643383279502884L /* pi */ #define NPY_PI_2l 1.570796326794896619231321691639751442L /* pi/2 */ #define NPY_PI_4l 0.785398163397448309615660845819875721L /* pi/4 */ #define NPY_1_PIl 0.318309886183790671537767526745028724L /* 1/pi */ #define NPY_2_PIl 0.636619772367581343075535053490057448L /* 2/pi */ #define NPY_EULERl 0.577215664901532860606512090082402431L /* Euler constant */ #define NPY_SQRT2l 1.414213562373095048801688724209698079L /* sqrt(2) */ #define NPY_SQRT1_2l 0.707106781186547524400844362104849039L /* 1/sqrt(2) */ /* * C99 double math funcs */ NPY_INPLACE double npy_sin(double x); NPY_INPLACE double npy_cos(double x); NPY_INPLACE double npy_tan(double x); NPY_INPLACE double npy_sinh(double x); NPY_INPLACE double npy_cosh(double x); NPY_INPLACE double npy_tanh(double x); NPY_INPLACE double npy_asin(double x); NPY_INPLACE double npy_acos(double x); NPY_INPLACE double npy_atan(double x); NPY_INPLACE double npy_log(double x); NPY_INPLACE double npy_log10(double x); NPY_INPLACE double npy_exp(double x); NPY_INPLACE double npy_sqrt(double x); NPY_INPLACE double npy_cbrt(double x); NPY_INPLACE double npy_fabs(double x); NPY_INPLACE double npy_ceil(double x); NPY_INPLACE double npy_fmod(double x, double y); NPY_INPLACE double npy_floor(double x); NPY_INPLACE double npy_expm1(double x); NPY_INPLACE double npy_log1p(double x); NPY_INPLACE double npy_hypot(double x, double y); NPY_INPLACE double npy_acosh(double x); NPY_INPLACE double npy_asinh(double xx); NPY_INPLACE double npy_atanh(double x); NPY_INPLACE double npy_rint(double x); NPY_INPLACE double npy_trunc(double x); NPY_INPLACE double npy_exp2(double x); NPY_INPLACE double npy_log2(double x); NPY_INPLACE double npy_atan2(double x, double y); NPY_INPLACE double npy_pow(double x, double y); NPY_INPLACE double npy_modf(double x, double* y); NPY_INPLACE double npy_frexp(double x, int* y); NPY_INPLACE double npy_ldexp(double n, int y); NPY_INPLACE double npy_copysign(double x, double y); double npy_nextafter(double x, double y); double npy_spacing(double x); /* * IEEE 754 fpu handling. Those are guaranteed to be macros */ /* use builtins to avoid function calls in tight loops * only available if npy_config.h is available (= numpys own build) */ #if HAVE___BUILTIN_ISNAN #define npy_isnan(x) __builtin_isnan(x) #else #ifndef NPY_HAVE_DECL_ISNAN #define npy_isnan(x) ((x) != (x)) #else #if defined(_MSC_VER) && (_MSC_VER < 1900) #define npy_isnan(x) _isnan((x)) #else #define npy_isnan(x) isnan(x) #endif #endif #endif /* only available if npy_config.h is available (= numpys own build) */ #if HAVE___BUILTIN_ISFINITE #define npy_isfinite(x) __builtin_isfinite(x) #else #ifndef NPY_HAVE_DECL_ISFINITE #ifdef _MSC_VER #define npy_isfinite(x) _finite((x)) #else #define npy_isfinite(x) !npy_isnan((x) + (-x)) #endif #else #define npy_isfinite(x) isfinite((x)) #endif #endif /* only available if npy_config.h is available (= numpys own build) */ #if HAVE___BUILTIN_ISINF #define npy_isinf(x) __builtin_isinf(x) #else #ifndef NPY_HAVE_DECL_ISINF #define npy_isinf(x) (!npy_isfinite(x) && !npy_isnan(x)) #else #if defined(_MSC_VER) && (_MSC_VER < 1900) #define npy_isinf(x) (!_finite((x)) && !_isnan((x))) #else #define npy_isinf(x) isinf((x)) #endif #endif #endif #ifndef NPY_HAVE_DECL_SIGNBIT int _npy_signbit_f(float x); int _npy_signbit_d(double x); int _npy_signbit_ld(long double x); #define npy_signbit(x) \ (sizeof (x) == sizeof (long double) ? _npy_signbit_ld (x) \ : sizeof (x) == sizeof (double) ? _npy_signbit_d (x) \ : _npy_signbit_f (x)) #else #define npy_signbit(x) signbit((x)) #endif /* * float C99 math functions */ NPY_INPLACE float npy_sinf(float x); NPY_INPLACE float npy_cosf(float x); NPY_INPLACE float npy_tanf(float x); NPY_INPLACE float npy_sinhf(float x); NPY_INPLACE float npy_coshf(float x); NPY_INPLACE float npy_tanhf(float x); NPY_INPLACE float npy_fabsf(float x); NPY_INPLACE float npy_floorf(float x); NPY_INPLACE float npy_ceilf(float x); NPY_INPLACE float npy_rintf(float x); NPY_INPLACE float npy_truncf(float x); NPY_INPLACE float npy_sqrtf(float x); NPY_INPLACE float npy_cbrtf(float x); NPY_INPLACE float npy_log10f(float x); NPY_INPLACE float npy_logf(float x); NPY_INPLACE float npy_expf(float x); NPY_INPLACE float npy_expm1f(float x); NPY_INPLACE float npy_asinf(float x); NPY_INPLACE float npy_acosf(float x); NPY_INPLACE float npy_atanf(float x); NPY_INPLACE float npy_asinhf(float x); NPY_INPLACE float npy_acoshf(float x); NPY_INPLACE float npy_atanhf(float x); NPY_INPLACE float npy_log1pf(float x); NPY_INPLACE float npy_exp2f(float x); NPY_INPLACE float npy_log2f(float x); NPY_INPLACE float npy_atan2f(float x, float y); NPY_INPLACE float npy_hypotf(float x, float y); NPY_INPLACE float npy_powf(float x, float y); NPY_INPLACE float npy_fmodf(float x, float y); NPY_INPLACE float npy_modff(float x, float* y); NPY_INPLACE float npy_frexpf(float x, int* y); NPY_INPLACE float npy_ldexpf(float x, int y); NPY_INPLACE float npy_copysignf(float x, float y); float npy_nextafterf(float x, float y); float npy_spacingf(float x); /* * long double C99 math functions */ NPY_INPLACE npy_longdouble npy_sinl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_cosl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_tanl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_sinhl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_coshl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_tanhl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_fabsl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_floorl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_ceill(npy_longdouble x); NPY_INPLACE npy_longdouble npy_rintl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_truncl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_sqrtl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_cbrtl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_log10l(npy_longdouble x); NPY_INPLACE npy_longdouble npy_logl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_expl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_expm1l(npy_longdouble x); NPY_INPLACE npy_longdouble npy_asinl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_acosl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_atanl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_asinhl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_acoshl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_atanhl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_log1pl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_exp2l(npy_longdouble x); NPY_INPLACE npy_longdouble npy_log2l(npy_longdouble x); NPY_INPLACE npy_longdouble npy_atan2l(npy_longdouble x, npy_longdouble y); NPY_INPLACE npy_longdouble npy_hypotl(npy_longdouble x, npy_longdouble y); NPY_INPLACE npy_longdouble npy_powl(npy_longdouble x, npy_longdouble y); NPY_INPLACE npy_longdouble npy_fmodl(npy_longdouble x, npy_longdouble y); NPY_INPLACE npy_longdouble npy_modfl(npy_longdouble x, npy_longdouble* y); NPY_INPLACE npy_longdouble npy_frexpl(npy_longdouble x, int* y); NPY_INPLACE npy_longdouble npy_ldexpl(npy_longdouble x, int y); NPY_INPLACE npy_longdouble npy_copysignl(npy_longdouble x, npy_longdouble y); npy_longdouble npy_nextafterl(npy_longdouble x, npy_longdouble y); npy_longdouble npy_spacingl(npy_longdouble x); /* * Non standard functions */ NPY_INPLACE double npy_deg2rad(double x); NPY_INPLACE double npy_rad2deg(double x); NPY_INPLACE double npy_logaddexp(double x, double y); NPY_INPLACE double npy_logaddexp2(double x, double y); NPY_INPLACE double npy_divmod(double x, double y, double *modulus); NPY_INPLACE double npy_heaviside(double x, double h0); NPY_INPLACE float npy_deg2radf(float x); NPY_INPLACE float npy_rad2degf(float x); NPY_INPLACE float npy_logaddexpf(float x, float y); NPY_INPLACE float npy_logaddexp2f(float x, float y); NPY_INPLACE float npy_divmodf(float x, float y, float *modulus); NPY_INPLACE float npy_heavisidef(float x, float h0); NPY_INPLACE npy_longdouble npy_deg2radl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_rad2degl(npy_longdouble x); NPY_INPLACE npy_longdouble npy_logaddexpl(npy_longdouble x, npy_longdouble y); NPY_INPLACE npy_longdouble npy_logaddexp2l(npy_longdouble x, npy_longdouble y); NPY_INPLACE npy_longdouble npy_divmodl(npy_longdouble x, npy_longdouble y, npy_longdouble *modulus); NPY_INPLACE npy_longdouble npy_heavisidel(npy_longdouble x, npy_longdouble h0); #define npy_degrees npy_rad2deg #define npy_degreesf npy_rad2degf #define npy_degreesl npy_rad2degl #define npy_radians npy_deg2rad #define npy_radiansf npy_deg2radf #define npy_radiansl npy_deg2radl /* * Complex declarations */ /* * C99 specifies that complex numbers have the same representation as * an array of two elements, where the first element is the real part * and the second element is the imaginary part. */ #define __NPY_CPACK_IMP(x, y, type, ctype) \ union { \ ctype z; \ type a[2]; \ } z1;; \ \ z1.a[0] = (x); \ z1.a[1] = (y); \ \ return z1.z; static NPY_INLINE npy_cdouble npy_cpack(double x, double y) { __NPY_CPACK_IMP(x, y, double, npy_cdouble); } static NPY_INLINE npy_cfloat npy_cpackf(float x, float y) { __NPY_CPACK_IMP(x, y, float, npy_cfloat); } static NPY_INLINE npy_clongdouble npy_cpackl(npy_longdouble x, npy_longdouble y) { __NPY_CPACK_IMP(x, y, npy_longdouble, npy_clongdouble); } #undef __NPY_CPACK_IMP /* * Same remark as above, but in the other direction: extract first/second * member of complex number, assuming a C99-compatible representation * * Those are defineds as static inline, and such as a reasonable compiler would * most likely compile this to one or two instructions (on CISC at least) */ #define __NPY_CEXTRACT_IMP(z, index, type, ctype) \ union { \ ctype z; \ type a[2]; \ } __z_repr; \ __z_repr.z = z; \ \ return __z_repr.a[index]; static NPY_INLINE double npy_creal(npy_cdouble z) { __NPY_CEXTRACT_IMP(z, 0, double, npy_cdouble); } static NPY_INLINE double npy_cimag(npy_cdouble z) { __NPY_CEXTRACT_IMP(z, 1, double, npy_cdouble); } static NPY_INLINE float npy_crealf(npy_cfloat z) { __NPY_CEXTRACT_IMP(z, 0, float, npy_cfloat); } static NPY_INLINE float npy_cimagf(npy_cfloat z) { __NPY_CEXTRACT_IMP(z, 1, float, npy_cfloat); } static NPY_INLINE npy_longdouble npy_creall(npy_clongdouble z) { __NPY_CEXTRACT_IMP(z, 0, npy_longdouble, npy_clongdouble); } static NPY_INLINE npy_longdouble npy_cimagl(npy_clongdouble z) { __NPY_CEXTRACT_IMP(z, 1, npy_longdouble, npy_clongdouble); } #undef __NPY_CEXTRACT_IMP /* * Double precision complex functions */ double npy_cabs(npy_cdouble z); double npy_carg(npy_cdouble z); npy_cdouble npy_cexp(npy_cdouble z); npy_cdouble npy_clog(npy_cdouble z); npy_cdouble npy_cpow(npy_cdouble x, npy_cdouble y); npy_cdouble npy_csqrt(npy_cdouble z); npy_cdouble npy_ccos(npy_cdouble z); npy_cdouble npy_csin(npy_cdouble z); npy_cdouble npy_ctan(npy_cdouble z); npy_cdouble npy_ccosh(npy_cdouble z); npy_cdouble npy_csinh(npy_cdouble z); npy_cdouble npy_ctanh(npy_cdouble z); npy_cdouble npy_cacos(npy_cdouble z); npy_cdouble npy_casin(npy_cdouble z); npy_cdouble npy_catan(npy_cdouble z); npy_cdouble npy_cacosh(npy_cdouble z); npy_cdouble npy_casinh(npy_cdouble z); npy_cdouble npy_catanh(npy_cdouble z); /* * Single precision complex functions */ float npy_cabsf(npy_cfloat z); float npy_cargf(npy_cfloat z); npy_cfloat npy_cexpf(npy_cfloat z); npy_cfloat npy_clogf(npy_cfloat z); npy_cfloat npy_cpowf(npy_cfloat x, npy_cfloat y); npy_cfloat npy_csqrtf(npy_cfloat z); npy_cfloat npy_ccosf(npy_cfloat z); npy_cfloat npy_csinf(npy_cfloat z); npy_cfloat npy_ctanf(npy_cfloat z); npy_cfloat npy_ccoshf(npy_cfloat z); npy_cfloat npy_csinhf(npy_cfloat z); npy_cfloat npy_ctanhf(npy_cfloat z); npy_cfloat npy_cacosf(npy_cfloat z); npy_cfloat npy_casinf(npy_cfloat z); npy_cfloat npy_catanf(npy_cfloat z); npy_cfloat npy_cacoshf(npy_cfloat z); npy_cfloat npy_casinhf(npy_cfloat z); npy_cfloat npy_catanhf(npy_cfloat z); /* * Extended precision complex functions */ npy_longdouble npy_cabsl(npy_clongdouble z); npy_longdouble npy_cargl(npy_clongdouble z); npy_clongdouble npy_cexpl(npy_clongdouble z); npy_clongdouble npy_clogl(npy_clongdouble z); npy_clongdouble npy_cpowl(npy_clongdouble x, npy_clongdouble y); npy_clongdouble npy_csqrtl(npy_clongdouble z); npy_clongdouble npy_ccosl(npy_clongdouble z); npy_clongdouble npy_csinl(npy_clongdouble z); npy_clongdouble npy_ctanl(npy_clongdouble z); npy_clongdouble npy_ccoshl(npy_clongdouble z); npy_clongdouble npy_csinhl(npy_clongdouble z); npy_clongdouble npy_ctanhl(npy_clongdouble z); npy_clongdouble npy_cacosl(npy_clongdouble z); npy_clongdouble npy_casinl(npy_clongdouble z); npy_clongdouble npy_catanl(npy_clongdouble z); npy_clongdouble npy_cacoshl(npy_clongdouble z); npy_clongdouble npy_casinhl(npy_clongdouble z); npy_clongdouble npy_catanhl(npy_clongdouble z); /* * Functions that set the floating point error * status word. */ /* * platform-dependent code translates floating point * status to an integer sum of these values */ #define NPY_FPE_DIVIDEBYZERO 1 #define NPY_FPE_OVERFLOW 2 #define NPY_FPE_UNDERFLOW 4 #define NPY_FPE_INVALID 8 int npy_clear_floatstatus_barrier(char*); int npy_get_floatstatus_barrier(char*); /* * use caution with these - clang and gcc8.1 are known to reorder calls * to this form of the function which can defeat the check */ int npy_clear_floatstatus(void); int npy_get_floatstatus(void); void npy_set_floatstatus_divbyzero(void); void npy_set_floatstatus_overflow(void); void npy_set_floatstatus_underflow(void); void npy_set_floatstatus_invalid(void); #ifdef __cplusplus } #endif #if NPY_INLINE_MATH #include "npy_math_internal.h" #endif #endif
18,740
33.136612
82
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/old_defines.h
/* This header is deprecated as of NumPy 1.7 */ #ifndef OLD_DEFINES_H #define OLD_DEFINES_H #if defined(NPY_NO_DEPRECATED_API) && NPY_NO_DEPRECATED_API >= NPY_1_7_API_VERSION #error The header "old_defines.h" is deprecated as of NumPy 1.7. #endif #define NDARRAY_VERSION NPY_VERSION #define PyArray_MIN_BUFSIZE NPY_MIN_BUFSIZE #define PyArray_MAX_BUFSIZE NPY_MAX_BUFSIZE #define PyArray_BUFSIZE NPY_BUFSIZE #define PyArray_PRIORITY NPY_PRIORITY #define PyArray_SUBTYPE_PRIORITY NPY_PRIORITY #define PyArray_NUM_FLOATTYPE NPY_NUM_FLOATTYPE #define NPY_MAX PyArray_MAX #define NPY_MIN PyArray_MIN #define PyArray_TYPES NPY_TYPES #define PyArray_BOOL NPY_BOOL #define PyArray_BYTE NPY_BYTE #define PyArray_UBYTE NPY_UBYTE #define PyArray_SHORT NPY_SHORT #define PyArray_USHORT NPY_USHORT #define PyArray_INT NPY_INT #define PyArray_UINT NPY_UINT #define PyArray_LONG NPY_LONG #define PyArray_ULONG NPY_ULONG #define PyArray_LONGLONG NPY_LONGLONG #define PyArray_ULONGLONG NPY_ULONGLONG #define PyArray_HALF NPY_HALF #define PyArray_FLOAT NPY_FLOAT #define PyArray_DOUBLE NPY_DOUBLE #define PyArray_LONGDOUBLE NPY_LONGDOUBLE #define PyArray_CFLOAT NPY_CFLOAT #define PyArray_CDOUBLE NPY_CDOUBLE #define PyArray_CLONGDOUBLE NPY_CLONGDOUBLE #define PyArray_OBJECT NPY_OBJECT #define PyArray_STRING NPY_STRING #define PyArray_UNICODE NPY_UNICODE #define PyArray_VOID NPY_VOID #define PyArray_DATETIME NPY_DATETIME #define PyArray_TIMEDELTA NPY_TIMEDELTA #define PyArray_NTYPES NPY_NTYPES #define PyArray_NOTYPE NPY_NOTYPE #define PyArray_CHAR NPY_CHAR #define PyArray_USERDEF NPY_USERDEF #define PyArray_NUMUSERTYPES NPY_NUMUSERTYPES #define PyArray_INTP NPY_INTP #define PyArray_UINTP NPY_UINTP #define PyArray_INT8 NPY_INT8 #define PyArray_UINT8 NPY_UINT8 #define PyArray_INT16 NPY_INT16 #define PyArray_UINT16 NPY_UINT16 #define PyArray_INT32 NPY_INT32 #define PyArray_UINT32 NPY_UINT32 #ifdef NPY_INT64 #define PyArray_INT64 NPY_INT64 #define PyArray_UINT64 NPY_UINT64 #endif #ifdef NPY_INT128 #define PyArray_INT128 NPY_INT128 #define PyArray_UINT128 NPY_UINT128 #endif #ifdef NPY_FLOAT16 #define PyArray_FLOAT16 NPY_FLOAT16 #define PyArray_COMPLEX32 NPY_COMPLEX32 #endif #ifdef NPY_FLOAT80 #define PyArray_FLOAT80 NPY_FLOAT80 #define PyArray_COMPLEX160 NPY_COMPLEX160 #endif #ifdef NPY_FLOAT96 #define PyArray_FLOAT96 NPY_FLOAT96 #define PyArray_COMPLEX192 NPY_COMPLEX192 #endif #ifdef NPY_FLOAT128 #define PyArray_FLOAT128 NPY_FLOAT128 #define PyArray_COMPLEX256 NPY_COMPLEX256 #endif #define PyArray_FLOAT32 NPY_FLOAT32 #define PyArray_COMPLEX64 NPY_COMPLEX64 #define PyArray_FLOAT64 NPY_FLOAT64 #define PyArray_COMPLEX128 NPY_COMPLEX128 #define PyArray_TYPECHAR NPY_TYPECHAR #define PyArray_BOOLLTR NPY_BOOLLTR #define PyArray_BYTELTR NPY_BYTELTR #define PyArray_UBYTELTR NPY_UBYTELTR #define PyArray_SHORTLTR NPY_SHORTLTR #define PyArray_USHORTLTR NPY_USHORTLTR #define PyArray_INTLTR NPY_INTLTR #define PyArray_UINTLTR NPY_UINTLTR #define PyArray_LONGLTR NPY_LONGLTR #define PyArray_ULONGLTR NPY_ULONGLTR #define PyArray_LONGLONGLTR NPY_LONGLONGLTR #define PyArray_ULONGLONGLTR NPY_ULONGLONGLTR #define PyArray_HALFLTR NPY_HALFLTR #define PyArray_FLOATLTR NPY_FLOATLTR #define PyArray_DOUBLELTR NPY_DOUBLELTR #define PyArray_LONGDOUBLELTR NPY_LONGDOUBLELTR #define PyArray_CFLOATLTR NPY_CFLOATLTR #define PyArray_CDOUBLELTR NPY_CDOUBLELTR #define PyArray_CLONGDOUBLELTR NPY_CLONGDOUBLELTR #define PyArray_OBJECTLTR NPY_OBJECTLTR #define PyArray_STRINGLTR NPY_STRINGLTR #define PyArray_STRINGLTR2 NPY_STRINGLTR2 #define PyArray_UNICODELTR NPY_UNICODELTR #define PyArray_VOIDLTR NPY_VOIDLTR #define PyArray_DATETIMELTR NPY_DATETIMELTR #define PyArray_TIMEDELTALTR NPY_TIMEDELTALTR #define PyArray_CHARLTR NPY_CHARLTR #define PyArray_INTPLTR NPY_INTPLTR #define PyArray_UINTPLTR NPY_UINTPLTR #define PyArray_GENBOOLLTR NPY_GENBOOLLTR #define PyArray_SIGNEDLTR NPY_SIGNEDLTR #define PyArray_UNSIGNEDLTR NPY_UNSIGNEDLTR #define PyArray_FLOATINGLTR NPY_FLOATINGLTR #define PyArray_COMPLEXLTR NPY_COMPLEXLTR #define PyArray_QUICKSORT NPY_QUICKSORT #define PyArray_HEAPSORT NPY_HEAPSORT #define PyArray_MERGESORT NPY_MERGESORT #define PyArray_SORTKIND NPY_SORTKIND #define PyArray_NSORTS NPY_NSORTS #define PyArray_NOSCALAR NPY_NOSCALAR #define PyArray_BOOL_SCALAR NPY_BOOL_SCALAR #define PyArray_INTPOS_SCALAR NPY_INTPOS_SCALAR #define PyArray_INTNEG_SCALAR NPY_INTNEG_SCALAR #define PyArray_FLOAT_SCALAR NPY_FLOAT_SCALAR #define PyArray_COMPLEX_SCALAR NPY_COMPLEX_SCALAR #define PyArray_OBJECT_SCALAR NPY_OBJECT_SCALAR #define PyArray_SCALARKIND NPY_SCALARKIND #define PyArray_NSCALARKINDS NPY_NSCALARKINDS #define PyArray_ANYORDER NPY_ANYORDER #define PyArray_CORDER NPY_CORDER #define PyArray_FORTRANORDER NPY_FORTRANORDER #define PyArray_ORDER NPY_ORDER #define PyDescr_ISBOOL PyDataType_ISBOOL #define PyDescr_ISUNSIGNED PyDataType_ISUNSIGNED #define PyDescr_ISSIGNED PyDataType_ISSIGNED #define PyDescr_ISINTEGER PyDataType_ISINTEGER #define PyDescr_ISFLOAT PyDataType_ISFLOAT #define PyDescr_ISNUMBER PyDataType_ISNUMBER #define PyDescr_ISSTRING PyDataType_ISSTRING #define PyDescr_ISCOMPLEX PyDataType_ISCOMPLEX #define PyDescr_ISPYTHON PyDataType_ISPYTHON #define PyDescr_ISFLEXIBLE PyDataType_ISFLEXIBLE #define PyDescr_ISUSERDEF PyDataType_ISUSERDEF #define PyDescr_ISEXTENDED PyDataType_ISEXTENDED #define PyDescr_ISOBJECT PyDataType_ISOBJECT #define PyDescr_HASFIELDS PyDataType_HASFIELDS #define PyArray_LITTLE NPY_LITTLE #define PyArray_BIG NPY_BIG #define PyArray_NATIVE NPY_NATIVE #define PyArray_SWAP NPY_SWAP #define PyArray_IGNORE NPY_IGNORE #define PyArray_NATBYTE NPY_NATBYTE #define PyArray_OPPBYTE NPY_OPPBYTE #define PyArray_MAX_ELSIZE NPY_MAX_ELSIZE #define PyArray_USE_PYMEM NPY_USE_PYMEM #define PyArray_RemoveLargest PyArray_RemoveSmallest #define PyArray_UCS4 npy_ucs4 #endif
6,306
32.547872
82
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/utils.h
#ifndef __NUMPY_UTILS_HEADER__ #define __NUMPY_UTILS_HEADER__ #ifndef __COMP_NPY_UNUSED #if defined(__GNUC__) #define __COMP_NPY_UNUSED __attribute__ ((__unused__)) # elif defined(__ICC) #define __COMP_NPY_UNUSED __attribute__ ((__unused__)) #else #define __COMP_NPY_UNUSED #endif #endif /* Use this to tag a variable as not used. It will remove unused variable * warning on support platforms (see __COM_NPY_UNUSED) and mangle the variable * to avoid accidental use */ #define NPY_UNUSED(x) (__NPY_UNUSED_TAGGED ## x) __COMP_NPY_UNUSED #endif
628
30.45
78
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/npy_no_deprecated_api.h
/* * This include file is provided for inclusion in Cython *.pyd files where * one would like to define the NPY_NO_DEPRECATED_API macro. It can be * included by * * cdef extern from "npy_no_deprecated_api.h": pass * */ #ifndef NPY_NO_DEPRECATED_API /* put this check here since there may be multiple includes in C extensions. */ #if defined(NDARRAYTYPES_H) || defined(_NPY_DEPRECATED_API_H) || \ defined(OLD_DEFINES_H) #error "npy_no_deprecated_api.h" must be first among numpy includes. #else #define NPY_NO_DEPRECATED_API NPY_API_VERSION #endif #endif
567
27.4
79
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/arrayobject.h
#ifndef Py_ARRAYOBJECT_H #define Py_ARRAYOBJECT_H #include "ndarrayobject.h" #include "npy_interrupt.h" #ifdef NPY_NO_PREFIX #include "noprefix.h" #endif #endif
164
12.75
26
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/npy_3kcompat.h
/* * This is a convenience header file providing compatibility utilities * for supporting Python 2 and Python 3 in the same code base. * * If you want to use this for your own projects, it's recommended to make a * copy of it. Although the stuff below is unlikely to change, we don't provide * strong backwards compatibility guarantees at the moment. */ #ifndef _NPY_3KCOMPAT_H_ #define _NPY_3KCOMPAT_H_ #include <Python.h> #include <stdio.h> #if PY_VERSION_HEX >= 0x03000000 #ifndef NPY_PY3K #define NPY_PY3K 1 #endif #endif #include "numpy/npy_common.h" #include "numpy/ndarrayobject.h" #ifdef __cplusplus extern "C" { #endif /* * PyInt -> PyLong */ #if defined(NPY_PY3K) /* Return True only if the long fits in a C long */ static NPY_INLINE int PyInt_Check(PyObject *op) { int overflow = 0; if (!PyLong_Check(op)) { return 0; } PyLong_AsLongAndOverflow(op, &overflow); return (overflow == 0); } #define PyInt_FromLong PyLong_FromLong #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AsLong #define PyInt_AsSsize_t PyLong_AsSsize_t /* NOTE: * * Since the PyLong type is very different from the fixed-range PyInt, * we don't define PyInt_Type -> PyLong_Type. */ #endif /* NPY_PY3K */ /* Py3 changes PySlice_GetIndicesEx' first argument's type to PyObject* */ #ifdef NPY_PY3K # define NpySlice_GetIndicesEx PySlice_GetIndicesEx #else # define NpySlice_GetIndicesEx(op, nop, start, end, step, slicelength) \ PySlice_GetIndicesEx((PySliceObject *)op, nop, start, end, step, slicelength) #endif /* * PyString -> PyBytes */ #if defined(NPY_PY3K) #define PyString_Type PyBytes_Type #define PyString_Check PyBytes_Check #define PyStringObject PyBytesObject #define PyString_FromString PyBytes_FromString #define PyString_FromStringAndSize PyBytes_FromStringAndSize #define PyString_AS_STRING PyBytes_AS_STRING #define PyString_AsStringAndSize PyBytes_AsStringAndSize #define PyString_FromFormat PyBytes_FromFormat #define PyString_Concat PyBytes_Concat #define PyString_ConcatAndDel PyBytes_ConcatAndDel #define PyString_AsString PyBytes_AsString #define PyString_GET_SIZE PyBytes_GET_SIZE #define PyString_Size PyBytes_Size #define PyUString_Type PyUnicode_Type #define PyUString_Check PyUnicode_Check #define PyUStringObject PyUnicodeObject #define PyUString_FromString PyUnicode_FromString #define PyUString_FromStringAndSize PyUnicode_FromStringAndSize #define PyUString_FromFormat PyUnicode_FromFormat #define PyUString_Concat PyUnicode_Concat2 #define PyUString_ConcatAndDel PyUnicode_ConcatAndDel #define PyUString_GET_SIZE PyUnicode_GET_SIZE #define PyUString_Size PyUnicode_Size #define PyUString_InternFromString PyUnicode_InternFromString #define PyUString_Format PyUnicode_Format #define PyBaseString_Check(obj) (PyUnicode_Check(obj)) #else #define PyBytes_Type PyString_Type #define PyBytes_Check PyString_Check #define PyBytesObject PyStringObject #define PyBytes_FromString PyString_FromString #define PyBytes_FromStringAndSize PyString_FromStringAndSize #define PyBytes_AS_STRING PyString_AS_STRING #define PyBytes_AsStringAndSize PyString_AsStringAndSize #define PyBytes_FromFormat PyString_FromFormat #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #define PyBytes_AsString PyString_AsString #define PyBytes_GET_SIZE PyString_GET_SIZE #define PyBytes_Size PyString_Size #define PyUString_Type PyString_Type #define PyUString_Check PyString_Check #define PyUStringObject PyStringObject #define PyUString_FromString PyString_FromString #define PyUString_FromStringAndSize PyString_FromStringAndSize #define PyUString_FromFormat PyString_FromFormat #define PyUString_Concat PyString_Concat #define PyUString_ConcatAndDel PyString_ConcatAndDel #define PyUString_GET_SIZE PyString_GET_SIZE #define PyUString_Size PyString_Size #define PyUString_InternFromString PyString_InternFromString #define PyUString_Format PyString_Format #define PyBaseString_Check(obj) (PyBytes_Check(obj) || PyUnicode_Check(obj)) #endif /* NPY_PY3K */ static NPY_INLINE void PyUnicode_ConcatAndDel(PyObject **left, PyObject *right) { PyObject *newobj; newobj = PyUnicode_Concat(*left, right); Py_DECREF(*left); Py_DECREF(right); *left = newobj; } static NPY_INLINE void PyUnicode_Concat2(PyObject **left, PyObject *right) { PyObject *newobj; newobj = PyUnicode_Concat(*left, right); Py_DECREF(*left); *left = newobj; } /* * PyFile_* compatibility */ /* * Get a FILE* handle to the file represented by the Python object */ static NPY_INLINE FILE* npy_PyFile_Dup2(PyObject *file, char *mode, npy_off_t *orig_pos) { int fd, fd2, unbuf; PyObject *ret, *os, *io, *io_raw; npy_off_t pos; FILE *handle; /* For Python 2 PyFileObject, use PyFile_AsFile */ #if !defined(NPY_PY3K) if (PyFile_Check(file)) { return PyFile_AsFile(file); } #endif /* Flush first to ensure things end up in the file in the correct order */ ret = PyObject_CallMethod(file, "flush", ""); if (ret == NULL) { return NULL; } Py_DECREF(ret); fd = PyObject_AsFileDescriptor(file); if (fd == -1) { return NULL; } /* * The handle needs to be dup'd because we have to call fclose * at the end */ os = PyImport_ImportModule("os"); if (os == NULL) { return NULL; } ret = PyObject_CallMethod(os, "dup", "i", fd); Py_DECREF(os); if (ret == NULL) { return NULL; } fd2 = PyNumber_AsSsize_t(ret, NULL); Py_DECREF(ret); /* Convert to FILE* handle */ #ifdef _WIN32 handle = _fdopen(fd2, mode); #else handle = fdopen(fd2, mode); #endif if (handle == NULL) { PyErr_SetString(PyExc_IOError, "Getting a FILE* from a Python file object failed"); } /* Record the original raw file handle position */ *orig_pos = npy_ftell(handle); if (*orig_pos == -1) { /* The io module is needed to determine if buffering is used */ io = PyImport_ImportModule("io"); if (io == NULL) { fclose(handle); return NULL; } /* File object instances of RawIOBase are unbuffered */ io_raw = PyObject_GetAttrString(io, "RawIOBase"); Py_DECREF(io); if (io_raw == NULL) { fclose(handle); return NULL; } unbuf = PyObject_IsInstance(file, io_raw); Py_DECREF(io_raw); if (unbuf == 1) { /* Succeed if the IO is unbuffered */ return handle; } else { PyErr_SetString(PyExc_IOError, "obtaining file position failed"); fclose(handle); return NULL; } } /* Seek raw handle to the Python-side position */ ret = PyObject_CallMethod(file, "tell", ""); if (ret == NULL) { fclose(handle); return NULL; } pos = PyLong_AsLongLong(ret); Py_DECREF(ret); if (PyErr_Occurred()) { fclose(handle); return NULL; } if (npy_fseek(handle, pos, SEEK_SET) == -1) { PyErr_SetString(PyExc_IOError, "seeking file failed"); fclose(handle); return NULL; } return handle; } /* * Close the dup-ed file handle, and seek the Python one to the current position */ static NPY_INLINE int npy_PyFile_DupClose2(PyObject *file, FILE* handle, npy_off_t orig_pos) { int fd, unbuf; PyObject *ret, *io, *io_raw; npy_off_t position; /* For Python 2 PyFileObject, do nothing */ #if !defined(NPY_PY3K) if (PyFile_Check(file)) { return 0; } #endif position = npy_ftell(handle); /* Close the FILE* handle */ fclose(handle); /* * Restore original file handle position, in order to not confuse * Python-side data structures */ fd = PyObject_AsFileDescriptor(file); if (fd == -1) { return -1; } if (npy_lseek(fd, orig_pos, SEEK_SET) == -1) { /* The io module is needed to determine if buffering is used */ io = PyImport_ImportModule("io"); if (io == NULL) { return -1; } /* File object instances of RawIOBase are unbuffered */ io_raw = PyObject_GetAttrString(io, "RawIOBase"); Py_DECREF(io); if (io_raw == NULL) { return -1; } unbuf = PyObject_IsInstance(file, io_raw); Py_DECREF(io_raw); if (unbuf == 1) { /* Succeed if the IO is unbuffered */ return 0; } else { PyErr_SetString(PyExc_IOError, "seeking file failed"); return -1; } } if (position == -1) { PyErr_SetString(PyExc_IOError, "obtaining file position failed"); return -1; } /* Seek Python-side handle to the FILE* handle position */ ret = PyObject_CallMethod(file, "seek", NPY_OFF_T_PYFMT "i", position, 0); if (ret == NULL) { return -1; } Py_DECREF(ret); return 0; } static NPY_INLINE int npy_PyFile_Check(PyObject *file) { int fd; /* For Python 2, check if it is a PyFileObject */ #if !defined(NPY_PY3K) if (PyFile_Check(file)) { return 1; } #endif fd = PyObject_AsFileDescriptor(file); if (fd == -1) { PyErr_Clear(); return 0; } return 1; } static NPY_INLINE PyObject* npy_PyFile_OpenFile(PyObject *filename, const char *mode) { PyObject *open; open = PyDict_GetItemString(PyEval_GetBuiltins(), "open"); if (open == NULL) { return NULL; } return PyObject_CallFunction(open, "Os", filename, mode); } static NPY_INLINE int npy_PyFile_CloseFile(PyObject *file) { PyObject *ret; ret = PyObject_CallMethod(file, "close", NULL); if (ret == NULL) { return -1; } Py_DECREF(ret); return 0; } /* * PyObject_Cmp */ #if defined(NPY_PY3K) static NPY_INLINE int PyObject_Cmp(PyObject *i1, PyObject *i2, int *cmp) { int v; v = PyObject_RichCompareBool(i1, i2, Py_LT); if (v == 1) { *cmp = -1; return 1; } else if (v == -1) { return -1; } v = PyObject_RichCompareBool(i1, i2, Py_GT); if (v == 1) { *cmp = 1; return 1; } else if (v == -1) { return -1; } v = PyObject_RichCompareBool(i1, i2, Py_EQ); if (v == 1) { *cmp = 0; return 1; } else { *cmp = 0; return -1; } } #endif /* * PyCObject functions adapted to PyCapsules. * * The main job here is to get rid of the improved error handling * of PyCapsules. It's a shame... */ #if PY_VERSION_HEX >= 0x03000000 static NPY_INLINE PyObject * NpyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *)) { PyObject *ret = PyCapsule_New(ptr, NULL, dtor); if (ret == NULL) { PyErr_Clear(); } return ret; } static NPY_INLINE PyObject * NpyCapsule_FromVoidPtrAndDesc(void *ptr, void* context, void (*dtor)(PyObject *)) { PyObject *ret = NpyCapsule_FromVoidPtr(ptr, dtor); if (ret != NULL && PyCapsule_SetContext(ret, context) != 0) { PyErr_Clear(); Py_DECREF(ret); ret = NULL; } return ret; } static NPY_INLINE void * NpyCapsule_AsVoidPtr(PyObject *obj) { void *ret = PyCapsule_GetPointer(obj, NULL); if (ret == NULL) { PyErr_Clear(); } return ret; } static NPY_INLINE void * NpyCapsule_GetDesc(PyObject *obj) { return PyCapsule_GetContext(obj); } static NPY_INLINE int NpyCapsule_Check(PyObject *ptr) { return PyCapsule_CheckExact(ptr); } #else static NPY_INLINE PyObject * NpyCapsule_FromVoidPtr(void *ptr, void (*dtor)(void *)) { return PyCObject_FromVoidPtr(ptr, dtor); } static NPY_INLINE PyObject * NpyCapsule_FromVoidPtrAndDesc(void *ptr, void* context, void (*dtor)(void *, void *)) { return PyCObject_FromVoidPtrAndDesc(ptr, context, dtor); } static NPY_INLINE void * NpyCapsule_AsVoidPtr(PyObject *ptr) { return PyCObject_AsVoidPtr(ptr); } static NPY_INLINE void * NpyCapsule_GetDesc(PyObject *obj) { return PyCObject_GetDesc(obj); } static NPY_INLINE int NpyCapsule_Check(PyObject *ptr) { return PyCObject_Check(ptr); } #endif #ifdef __cplusplus } #endif #endif /* _NPY_3KCOMPAT_H_ */
12,315
23.485089
81
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/_numpyconfig.h
#define NPY_SIZEOF_SHORT SIZEOF_SHORT #define NPY_SIZEOF_INT SIZEOF_INT #define NPY_SIZEOF_LONG SIZEOF_LONG #define NPY_SIZEOF_FLOAT 4 #define NPY_SIZEOF_COMPLEX_FLOAT 8 #define NPY_SIZEOF_DOUBLE 8 #define NPY_SIZEOF_COMPLEX_DOUBLE 16 #define NPY_SIZEOF_LONGDOUBLE 16 #define NPY_SIZEOF_COMPLEX_LONGDOUBLE 32 #define NPY_SIZEOF_PY_INTPTR_T 8 #define NPY_SIZEOF_OFF_T 8 #define NPY_SIZEOF_PY_LONG_LONG 8 #define NPY_SIZEOF_LONGLONG 8 #define NPY_NO_SMP 0 #define NPY_HAVE_DECL_ISNAN #define NPY_HAVE_DECL_ISINF #define NPY_HAVE_DECL_ISFINITE #define NPY_HAVE_DECL_SIGNBIT #define NPY_USE_C99_COMPLEX 1 #define NPY_HAVE_COMPLEX_DOUBLE 1 #define NPY_HAVE_COMPLEX_FLOAT 1 #define NPY_HAVE_COMPLEX_LONG_DOUBLE 1 #define NPY_RELAXED_STRIDES_CHECKING 1 #define NPY_USE_C99_FORMATS 1 #define NPY_VISIBILITY_HIDDEN __attribute__((visibility("hidden"))) #define NPY_ABI_VERSION 0x01000009 #define NPY_API_VERSION 0x0000000C #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS 1 #endif
982
29.71875
67
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/npy_interrupt.h
/* Signal handling: This header file defines macros that allow your code to handle interrupts received during processing. Interrupts that could reasonably be handled: SIGINT, SIGABRT, SIGALRM, SIGSEGV ****Warning*************** Do not allow code that creates temporary memory or increases reference counts of Python objects to be interrupted unless you handle it differently. ************************** The mechanism for handling interrupts is conceptually simple: - replace the signal handler with our own home-grown version and store the old one. - run the code to be interrupted -- if an interrupt occurs the handler should basically just cause a return to the calling function for finish work. - restore the old signal handler Of course, every code that allows interrupts must account for returning via the interrupt and handle clean-up correctly. But, even still, the simple paradigm is complicated by at least three factors. 1) platform portability (i.e. Microsoft says not to use longjmp to return from signal handling. They have a __try and __except extension to C instead but what about mingw?). 2) how to handle threads: apparently whether signals are delivered to every thread of the process or the "invoking" thread is platform dependent. --- we don't handle threads for now. 3) do we need to worry about re-entrance. For now, assume the code will not call-back into itself. Ideas: 1) Start by implementing an approach that works on platforms that can use setjmp and longjmp functionality and does nothing on other platforms. 2) Ignore threads --- i.e. do not mix interrupt handling and threads 3) Add a default signal_handler function to the C-API but have the rest use macros. Simple Interface: In your C-extension: around a block of code you want to be interruptable with a SIGINT NPY_SIGINT_ON [code] NPY_SIGINT_OFF In order for this to work correctly, the [code] block must not allocate any memory or alter the reference count of any Python objects. In other words [code] must be interruptible so that continuation after NPY_SIGINT_OFF will only be "missing some computations" Interrupt handling does not work well with threads. */ /* Add signal handling macros Make the global variable and signal handler part of the C-API */ #ifndef NPY_INTERRUPT_H #define NPY_INTERRUPT_H #ifndef NPY_NO_SIGNAL #include <setjmp.h> #include <signal.h> #ifndef sigsetjmp #define NPY_SIGSETJMP(arg1, arg2) setjmp(arg1) #define NPY_SIGLONGJMP(arg1, arg2) longjmp(arg1, arg2) #define NPY_SIGJMP_BUF jmp_buf #else #define NPY_SIGSETJMP(arg1, arg2) sigsetjmp(arg1, arg2) #define NPY_SIGLONGJMP(arg1, arg2) siglongjmp(arg1, arg2) #define NPY_SIGJMP_BUF sigjmp_buf #endif # define NPY_SIGINT_ON { \ PyOS_sighandler_t _npy_sig_save; \ _npy_sig_save = PyOS_setsig(SIGINT, _PyArray_SigintHandler); \ if (NPY_SIGSETJMP(*((NPY_SIGJMP_BUF *)_PyArray_GetSigintBuf()), \ 1) == 0) { \ # define NPY_SIGINT_OFF } \ PyOS_setsig(SIGINT, _npy_sig_save); \ } #else /* NPY_NO_SIGNAL */ #define NPY_SIGINT_ON #define NPY_SIGINT_OFF #endif /* HAVE_SIGSETJMP */ #endif /* NPY_INTERRUPT_H */
3,439
28.152542
84
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/npy_common.h
#ifndef _NPY_COMMON_H_ #define _NPY_COMMON_H_ /* numpconfig.h is auto-generated */ #include "numpyconfig.h" #ifdef HAVE_NPY_CONFIG_H #include <npy_config.h> #endif /* need Python.h for npy_intp, npy_uintp */ #include <Python.h> /* * using static inline modifiers when defining npy_math functions * allows the compiler to make optimizations when possible */ #if NPY_INTERNAL_BUILD #ifndef NPY_INLINE_MATH #define NPY_INLINE_MATH 1 #endif #endif /* * gcc does not unroll even with -O3 * use with care, unrolling on modern cpus rarely speeds things up */ #ifdef HAVE_ATTRIBUTE_OPTIMIZE_UNROLL_LOOPS #define NPY_GCC_UNROLL_LOOPS \ __attribute__((optimize("unroll-loops"))) #else #define NPY_GCC_UNROLL_LOOPS #endif /* highest gcc optimization level, enabled autovectorizer */ #ifdef HAVE_ATTRIBUTE_OPTIMIZE_OPT_3 #define NPY_GCC_OPT_3 __attribute__((optimize("O3"))) #else #define NPY_GCC_OPT_3 #endif /* compile target attributes */ #if defined HAVE_ATTRIBUTE_TARGET_AVX && defined HAVE_LINK_AVX #define NPY_GCC_TARGET_AVX __attribute__((target("avx"))) #else #define NPY_GCC_TARGET_AVX #endif #if defined HAVE_ATTRIBUTE_TARGET_AVX2 && defined HAVE_LINK_AVX2 #define NPY_GCC_TARGET_AVX2 __attribute__((target("avx2"))) #else #define NPY_GCC_TARGET_AVX2 #endif /* * mark an argument (starting from 1) that must not be NULL and is not checked * DO NOT USE IF FUNCTION CHECKS FOR NULL!! the compiler will remove the check */ #ifdef HAVE_ATTRIBUTE_NONNULL #define NPY_GCC_NONNULL(n) __attribute__((nonnull(n))) #else #define NPY_GCC_NONNULL(n) #endif #if defined HAVE_XMMINTRIN_H && defined HAVE__MM_LOAD_PS #define NPY_HAVE_SSE_INTRINSICS #endif #if defined HAVE_EMMINTRIN_H && defined HAVE__MM_LOAD_PD #define NPY_HAVE_SSE2_INTRINSICS #endif /* * give a hint to the compiler which branch is more likely or unlikely * to occur, e.g. rare error cases: * * if (NPY_UNLIKELY(failure == 0)) * return NULL; * * the double !! is to cast the expression (e.g. NULL) to a boolean required by * the intrinsic */ #ifdef HAVE___BUILTIN_EXPECT #define NPY_LIKELY(x) __builtin_expect(!!(x), 1) #define NPY_UNLIKELY(x) __builtin_expect(!!(x), 0) #else #define NPY_LIKELY(x) (x) #define NPY_UNLIKELY(x) (x) #endif #ifdef HAVE___BUILTIN_PREFETCH /* unlike _mm_prefetch also works on non-x86 */ #define NPY_PREFETCH(x, rw, loc) __builtin_prefetch((x), (rw), (loc)) #else #ifdef HAVE__MM_PREFETCH /* _MM_HINT_ET[01] (rw = 1) unsupported, only available in gcc >= 4.9 */ #define NPY_PREFETCH(x, rw, loc) _mm_prefetch((x), loc == 0 ? _MM_HINT_NTA : \ (loc == 1 ? _MM_HINT_T2 : \ (loc == 2 ? _MM_HINT_T1 : \ (loc == 3 ? _MM_HINT_T0 : -1)))) #else #define NPY_PREFETCH(x, rw,loc) #endif #endif #ifdef HAVE___BUILTIN_CPU_SUPPORTS #ifdef HAVE_ATTRIBUTE_TARGET_AVX2 #define NPY_CPU_SUPPORTS_AVX2 __builtin_cpu_supports("avx2") #else #define NPY_CPU_SUPPORTS_AVX2 0 #endif #ifdef HAVE_ATTRIBUTE_TARGET_AVX #define NPY_CPU_SUPPORTS_AVX __builtin_cpu_supports("avx") #else #define NPY_CPU_SUPPORTS_AVX 0 #endif #else #define NPY_CPU_SUPPORTS_AVX 0 #define NPY_CPU_SUPPORTS_AVX2 0 #endif #if defined(_MSC_VER) #define NPY_INLINE __inline #elif defined(__GNUC__) #if defined(__STRICT_ANSI__) #define NPY_INLINE __inline__ #else #define NPY_INLINE inline #endif #else #define NPY_INLINE #endif #ifdef HAVE___THREAD #define NPY_TLS __thread #else #ifdef HAVE___DECLSPEC_THREAD_ #define NPY_TLS __declspec(thread) #else #define NPY_TLS #endif #endif #ifdef WITH_CPYCHECKER_RETURNS_BORROWED_REF_ATTRIBUTE #define NPY_RETURNS_BORROWED_REF \ __attribute__((cpychecker_returns_borrowed_ref)) #else #define NPY_RETURNS_BORROWED_REF #endif #ifdef WITH_CPYCHECKER_STEALS_REFERENCE_TO_ARG_ATTRIBUTE #define NPY_STEALS_REF_TO_ARG(n) \ __attribute__((cpychecker_steals_reference_to_arg(n))) #else #define NPY_STEALS_REF_TO_ARG(n) #endif /* 64 bit file position support, also on win-amd64. Ticket #1660 */ #if defined(_MSC_VER) && defined(_WIN64) && (_MSC_VER > 1400) || \ defined(__MINGW32__) || defined(__MINGW64__) #include <io.h> /* mingw based on 3.4.5 has lseek but not ftell/fseek */ #if defined(__MINGW32__) || defined(__MINGW64__) extern int __cdecl _fseeki64(FILE *, long long, int); extern long long __cdecl _ftelli64(FILE *); #endif #define npy_fseek _fseeki64 #define npy_ftell _ftelli64 #define npy_lseek _lseeki64 #define npy_off_t npy_int64 #if NPY_SIZEOF_INT == 8 #define NPY_OFF_T_PYFMT "i" #elif NPY_SIZEOF_LONG == 8 #define NPY_OFF_T_PYFMT "l" #elif NPY_SIZEOF_LONGLONG == 8 #define NPY_OFF_T_PYFMT "L" #else #error Unsupported size for type off_t #endif #else #ifdef HAVE_FSEEKO #define npy_fseek fseeko #else #define npy_fseek fseek #endif #ifdef HAVE_FTELLO #define npy_ftell ftello #else #define npy_ftell ftell #endif #include <sys/types.h> #define npy_lseek lseek #define npy_off_t off_t #if NPY_SIZEOF_OFF_T == NPY_SIZEOF_SHORT #define NPY_OFF_T_PYFMT "h" #elif NPY_SIZEOF_OFF_T == NPY_SIZEOF_INT #define NPY_OFF_T_PYFMT "i" #elif NPY_SIZEOF_OFF_T == NPY_SIZEOF_LONG #define NPY_OFF_T_PYFMT "l" #elif NPY_SIZEOF_OFF_T == NPY_SIZEOF_LONGLONG #define NPY_OFF_T_PYFMT "L" #else #error Unsupported size for type off_t #endif #endif /* enums for detected endianness */ enum { NPY_CPU_UNKNOWN_ENDIAN, NPY_CPU_LITTLE, NPY_CPU_BIG }; /* * This is to typedef npy_intp to the appropriate pointer size for this * platform. Py_intptr_t, Py_uintptr_t are defined in pyport.h. */ typedef Py_intptr_t npy_intp; typedef Py_uintptr_t npy_uintp; /* * Define sizes that were not defined in numpyconfig.h. */ #define NPY_SIZEOF_CHAR 1 #define NPY_SIZEOF_BYTE 1 #define NPY_SIZEOF_DATETIME 8 #define NPY_SIZEOF_TIMEDELTA 8 #define NPY_SIZEOF_INTP NPY_SIZEOF_PY_INTPTR_T #define NPY_SIZEOF_UINTP NPY_SIZEOF_PY_INTPTR_T #define NPY_SIZEOF_HALF 2 #define NPY_SIZEOF_CFLOAT NPY_SIZEOF_COMPLEX_FLOAT #define NPY_SIZEOF_CDOUBLE NPY_SIZEOF_COMPLEX_DOUBLE #define NPY_SIZEOF_CLONGDOUBLE NPY_SIZEOF_COMPLEX_LONGDOUBLE #ifdef constchar #undef constchar #endif #define NPY_SSIZE_T_PYFMT "n" #define constchar char /* NPY_INTP_FMT Note: * Unlike the other NPY_*_FMT macros which are used with * PyOS_snprintf, NPY_INTP_FMT is used with PyErr_Format and * PyString_Format. These functions use different formatting * codes which are portably specified according to the Python * documentation. See ticket #1795. */ #if NPY_SIZEOF_PY_INTPTR_T == NPY_SIZEOF_INT #define NPY_INTP NPY_INT #define NPY_UINTP NPY_UINT #define PyIntpArrType_Type PyIntArrType_Type #define PyUIntpArrType_Type PyUIntArrType_Type #define NPY_MAX_INTP NPY_MAX_INT #define NPY_MIN_INTP NPY_MIN_INT #define NPY_MAX_UINTP NPY_MAX_UINT #define NPY_INTP_FMT "d" #elif NPY_SIZEOF_PY_INTPTR_T == NPY_SIZEOF_LONG #define NPY_INTP NPY_LONG #define NPY_UINTP NPY_ULONG #define PyIntpArrType_Type PyLongArrType_Type #define PyUIntpArrType_Type PyULongArrType_Type #define NPY_MAX_INTP NPY_MAX_LONG #define NPY_MIN_INTP NPY_MIN_LONG #define NPY_MAX_UINTP NPY_MAX_ULONG #define NPY_INTP_FMT "ld" #elif defined(PY_LONG_LONG) && (NPY_SIZEOF_PY_INTPTR_T == NPY_SIZEOF_LONGLONG) #define NPY_INTP NPY_LONGLONG #define NPY_UINTP NPY_ULONGLONG #define PyIntpArrType_Type PyLongLongArrType_Type #define PyUIntpArrType_Type PyULongLongArrType_Type #define NPY_MAX_INTP NPY_MAX_LONGLONG #define NPY_MIN_INTP NPY_MIN_LONGLONG #define NPY_MAX_UINTP NPY_MAX_ULONGLONG #define NPY_INTP_FMT "lld" #endif /* * We can only use C99 formats for npy_int_p if it is the same as * intp_t, hence the condition on HAVE_UNITPTR_T */ #if (NPY_USE_C99_FORMATS) == 1 \ && (defined HAVE_UINTPTR_T) \ && (defined HAVE_INTTYPES_H) #include <inttypes.h> #undef NPY_INTP_FMT #define NPY_INTP_FMT PRIdPTR #endif /* * Some platforms don't define bool, long long, or long double. * Handle that here. */ #define NPY_BYTE_FMT "hhd" #define NPY_UBYTE_FMT "hhu" #define NPY_SHORT_FMT "hd" #define NPY_USHORT_FMT "hu" #define NPY_INT_FMT "d" #define NPY_UINT_FMT "u" #define NPY_LONG_FMT "ld" #define NPY_ULONG_FMT "lu" #define NPY_HALF_FMT "g" #define NPY_FLOAT_FMT "g" #define NPY_DOUBLE_FMT "g" #ifdef PY_LONG_LONG typedef PY_LONG_LONG npy_longlong; typedef unsigned PY_LONG_LONG npy_ulonglong; # ifdef _MSC_VER # define NPY_LONGLONG_FMT "I64d" # define NPY_ULONGLONG_FMT "I64u" # else # define NPY_LONGLONG_FMT "lld" # define NPY_ULONGLONG_FMT "llu" # endif # ifdef _MSC_VER # define NPY_LONGLONG_SUFFIX(x) (x##i64) # define NPY_ULONGLONG_SUFFIX(x) (x##Ui64) # else # define NPY_LONGLONG_SUFFIX(x) (x##LL) # define NPY_ULONGLONG_SUFFIX(x) (x##ULL) # endif #else typedef long npy_longlong; typedef unsigned long npy_ulonglong; # define NPY_LONGLONG_SUFFIX(x) (x##L) # define NPY_ULONGLONG_SUFFIX(x) (x##UL) #endif typedef unsigned char npy_bool; #define NPY_FALSE 0 #define NPY_TRUE 1 #if NPY_SIZEOF_LONGDOUBLE == NPY_SIZEOF_DOUBLE typedef double npy_longdouble; #define NPY_LONGDOUBLE_FMT "g" #else typedef long double npy_longdouble; #define NPY_LONGDOUBLE_FMT "Lg" #endif #ifndef Py_USING_UNICODE #error Must use Python with unicode enabled. #endif typedef signed char npy_byte; typedef unsigned char npy_ubyte; typedef unsigned short npy_ushort; typedef unsigned int npy_uint; typedef unsigned long npy_ulong; /* These are for completeness */ typedef char npy_char; typedef short npy_short; typedef int npy_int; typedef long npy_long; typedef float npy_float; typedef double npy_double; /* * Hash value compatibility. * As of Python 3.2 hash values are of type Py_hash_t. * Previous versions use C long. */ #if PY_VERSION_HEX < 0x03020000 typedef long npy_hash_t; #define NPY_SIZEOF_HASH_T NPY_SIZEOF_LONG #else typedef Py_hash_t npy_hash_t; #define NPY_SIZEOF_HASH_T NPY_SIZEOF_INTP #endif /* * Disabling C99 complex usage: a lot of C code in numpy/scipy rely on being * able to do .real/.imag. Will have to convert code first. */ #if 0 #if defined(NPY_USE_C99_COMPLEX) && defined(NPY_HAVE_COMPLEX_DOUBLE) typedef complex npy_cdouble; #else typedef struct { double real, imag; } npy_cdouble; #endif #if defined(NPY_USE_C99_COMPLEX) && defined(NPY_HAVE_COMPLEX_FLOAT) typedef complex float npy_cfloat; #else typedef struct { float real, imag; } npy_cfloat; #endif #if defined(NPY_USE_C99_COMPLEX) && defined(NPY_HAVE_COMPLEX_LONG_DOUBLE) typedef complex long double npy_clongdouble; #else typedef struct {npy_longdouble real, imag;} npy_clongdouble; #endif #endif #if NPY_SIZEOF_COMPLEX_DOUBLE != 2 * NPY_SIZEOF_DOUBLE #error npy_cdouble definition is not compatible with C99 complex definition ! \ Please contact NumPy maintainers and give detailed information about your \ compiler and platform #endif typedef struct { double real, imag; } npy_cdouble; #if NPY_SIZEOF_COMPLEX_FLOAT != 2 * NPY_SIZEOF_FLOAT #error npy_cfloat definition is not compatible with C99 complex definition ! \ Please contact NumPy maintainers and give detailed information about your \ compiler and platform #endif typedef struct { float real, imag; } npy_cfloat; #if NPY_SIZEOF_COMPLEX_LONGDOUBLE != 2 * NPY_SIZEOF_LONGDOUBLE #error npy_clongdouble definition is not compatible with C99 complex definition ! \ Please contact NumPy maintainers and give detailed information about your \ compiler and platform #endif typedef struct { npy_longdouble real, imag; } npy_clongdouble; /* * numarray-style bit-width typedefs */ #define NPY_MAX_INT8 127 #define NPY_MIN_INT8 -128 #define NPY_MAX_UINT8 255 #define NPY_MAX_INT16 32767 #define NPY_MIN_INT16 -32768 #define NPY_MAX_UINT16 65535 #define NPY_MAX_INT32 2147483647 #define NPY_MIN_INT32 (-NPY_MAX_INT32 - 1) #define NPY_MAX_UINT32 4294967295U #define NPY_MAX_INT64 NPY_LONGLONG_SUFFIX(9223372036854775807) #define NPY_MIN_INT64 (-NPY_MAX_INT64 - NPY_LONGLONG_SUFFIX(1)) #define NPY_MAX_UINT64 NPY_ULONGLONG_SUFFIX(18446744073709551615) #define NPY_MAX_INT128 NPY_LONGLONG_SUFFIX(85070591730234615865843651857942052864) #define NPY_MIN_INT128 (-NPY_MAX_INT128 - NPY_LONGLONG_SUFFIX(1)) #define NPY_MAX_UINT128 NPY_ULONGLONG_SUFFIX(170141183460469231731687303715884105728) #define NPY_MAX_INT256 NPY_LONGLONG_SUFFIX(57896044618658097711785492504343953926634992332820282019728792003956564819967) #define NPY_MIN_INT256 (-NPY_MAX_INT256 - NPY_LONGLONG_SUFFIX(1)) #define NPY_MAX_UINT256 NPY_ULONGLONG_SUFFIX(115792089237316195423570985008687907853269984665640564039457584007913129639935) #define NPY_MIN_DATETIME NPY_MIN_INT64 #define NPY_MAX_DATETIME NPY_MAX_INT64 #define NPY_MIN_TIMEDELTA NPY_MIN_INT64 #define NPY_MAX_TIMEDELTA NPY_MAX_INT64 /* Need to find the number of bits for each type and make definitions accordingly. C states that sizeof(char) == 1 by definition So, just using the sizeof keyword won't help. It also looks like Python itself uses sizeof(char) quite a bit, which by definition should be 1 all the time. Idea: Make Use of CHAR_BIT which should tell us how many BITS per CHARACTER */ /* Include platform definitions -- These are in the C89/90 standard */ #include <limits.h> #define NPY_MAX_BYTE SCHAR_MAX #define NPY_MIN_BYTE SCHAR_MIN #define NPY_MAX_UBYTE UCHAR_MAX #define NPY_MAX_SHORT SHRT_MAX #define NPY_MIN_SHORT SHRT_MIN #define NPY_MAX_USHORT USHRT_MAX #define NPY_MAX_INT INT_MAX #ifndef INT_MIN #define INT_MIN (-INT_MAX - 1) #endif #define NPY_MIN_INT INT_MIN #define NPY_MAX_UINT UINT_MAX #define NPY_MAX_LONG LONG_MAX #define NPY_MIN_LONG LONG_MIN #define NPY_MAX_ULONG ULONG_MAX #define NPY_BITSOF_BOOL (sizeof(npy_bool) * CHAR_BIT) #define NPY_BITSOF_CHAR CHAR_BIT #define NPY_BITSOF_BYTE (NPY_SIZEOF_BYTE * CHAR_BIT) #define NPY_BITSOF_SHORT (NPY_SIZEOF_SHORT * CHAR_BIT) #define NPY_BITSOF_INT (NPY_SIZEOF_INT * CHAR_BIT) #define NPY_BITSOF_LONG (NPY_SIZEOF_LONG * CHAR_BIT) #define NPY_BITSOF_LONGLONG (NPY_SIZEOF_LONGLONG * CHAR_BIT) #define NPY_BITSOF_INTP (NPY_SIZEOF_INTP * CHAR_BIT) #define NPY_BITSOF_HALF (NPY_SIZEOF_HALF * CHAR_BIT) #define NPY_BITSOF_FLOAT (NPY_SIZEOF_FLOAT * CHAR_BIT) #define NPY_BITSOF_DOUBLE (NPY_SIZEOF_DOUBLE * CHAR_BIT) #define NPY_BITSOF_LONGDOUBLE (NPY_SIZEOF_LONGDOUBLE * CHAR_BIT) #define NPY_BITSOF_CFLOAT (NPY_SIZEOF_CFLOAT * CHAR_BIT) #define NPY_BITSOF_CDOUBLE (NPY_SIZEOF_CDOUBLE * CHAR_BIT) #define NPY_BITSOF_CLONGDOUBLE (NPY_SIZEOF_CLONGDOUBLE * CHAR_BIT) #define NPY_BITSOF_DATETIME (NPY_SIZEOF_DATETIME * CHAR_BIT) #define NPY_BITSOF_TIMEDELTA (NPY_SIZEOF_TIMEDELTA * CHAR_BIT) #if NPY_BITSOF_LONG == 8 #define NPY_INT8 NPY_LONG #define NPY_UINT8 NPY_ULONG typedef long npy_int8; typedef unsigned long npy_uint8; #define PyInt8ScalarObject PyLongScalarObject #define PyInt8ArrType_Type PyLongArrType_Type #define PyUInt8ScalarObject PyULongScalarObject #define PyUInt8ArrType_Type PyULongArrType_Type #define NPY_INT8_FMT NPY_LONG_FMT #define NPY_UINT8_FMT NPY_ULONG_FMT #elif NPY_BITSOF_LONG == 16 #define NPY_INT16 NPY_LONG #define NPY_UINT16 NPY_ULONG typedef long npy_int16; typedef unsigned long npy_uint16; #define PyInt16ScalarObject PyLongScalarObject #define PyInt16ArrType_Type PyLongArrType_Type #define PyUInt16ScalarObject PyULongScalarObject #define PyUInt16ArrType_Type PyULongArrType_Type #define NPY_INT16_FMT NPY_LONG_FMT #define NPY_UINT16_FMT NPY_ULONG_FMT #elif NPY_BITSOF_LONG == 32 #define NPY_INT32 NPY_LONG #define NPY_UINT32 NPY_ULONG typedef long npy_int32; typedef unsigned long npy_uint32; typedef unsigned long npy_ucs4; #define PyInt32ScalarObject PyLongScalarObject #define PyInt32ArrType_Type PyLongArrType_Type #define PyUInt32ScalarObject PyULongScalarObject #define PyUInt32ArrType_Type PyULongArrType_Type #define NPY_INT32_FMT NPY_LONG_FMT #define NPY_UINT32_FMT NPY_ULONG_FMT #elif NPY_BITSOF_LONG == 64 #define NPY_INT64 NPY_LONG #define NPY_UINT64 NPY_ULONG typedef long npy_int64; typedef unsigned long npy_uint64; #define PyInt64ScalarObject PyLongScalarObject #define PyInt64ArrType_Type PyLongArrType_Type #define PyUInt64ScalarObject PyULongScalarObject #define PyUInt64ArrType_Type PyULongArrType_Type #define NPY_INT64_FMT NPY_LONG_FMT #define NPY_UINT64_FMT NPY_ULONG_FMT #define MyPyLong_FromInt64 PyLong_FromLong #define MyPyLong_AsInt64 PyLong_AsLong #elif NPY_BITSOF_LONG == 128 #define NPY_INT128 NPY_LONG #define NPY_UINT128 NPY_ULONG typedef long npy_int128; typedef unsigned long npy_uint128; #define PyInt128ScalarObject PyLongScalarObject #define PyInt128ArrType_Type PyLongArrType_Type #define PyUInt128ScalarObject PyULongScalarObject #define PyUInt128ArrType_Type PyULongArrType_Type #define NPY_INT128_FMT NPY_LONG_FMT #define NPY_UINT128_FMT NPY_ULONG_FMT #endif #if NPY_BITSOF_LONGLONG == 8 # ifndef NPY_INT8 # define NPY_INT8 NPY_LONGLONG # define NPY_UINT8 NPY_ULONGLONG typedef npy_longlong npy_int8; typedef npy_ulonglong npy_uint8; # define PyInt8ScalarObject PyLongLongScalarObject # define PyInt8ArrType_Type PyLongLongArrType_Type # define PyUInt8ScalarObject PyULongLongScalarObject # define PyUInt8ArrType_Type PyULongLongArrType_Type #define NPY_INT8_FMT NPY_LONGLONG_FMT #define NPY_UINT8_FMT NPY_ULONGLONG_FMT # endif # define NPY_MAX_LONGLONG NPY_MAX_INT8 # define NPY_MIN_LONGLONG NPY_MIN_INT8 # define NPY_MAX_ULONGLONG NPY_MAX_UINT8 #elif NPY_BITSOF_LONGLONG == 16 # ifndef NPY_INT16 # define NPY_INT16 NPY_LONGLONG # define NPY_UINT16 NPY_ULONGLONG typedef npy_longlong npy_int16; typedef npy_ulonglong npy_uint16; # define PyInt16ScalarObject PyLongLongScalarObject # define PyInt16ArrType_Type PyLongLongArrType_Type # define PyUInt16ScalarObject PyULongLongScalarObject # define PyUInt16ArrType_Type PyULongLongArrType_Type #define NPY_INT16_FMT NPY_LONGLONG_FMT #define NPY_UINT16_FMT NPY_ULONGLONG_FMT # endif # define NPY_MAX_LONGLONG NPY_MAX_INT16 # define NPY_MIN_LONGLONG NPY_MIN_INT16 # define NPY_MAX_ULONGLONG NPY_MAX_UINT16 #elif NPY_BITSOF_LONGLONG == 32 # ifndef NPY_INT32 # define NPY_INT32 NPY_LONGLONG # define NPY_UINT32 NPY_ULONGLONG typedef npy_longlong npy_int32; typedef npy_ulonglong npy_uint32; typedef npy_ulonglong npy_ucs4; # define PyInt32ScalarObject PyLongLongScalarObject # define PyInt32ArrType_Type PyLongLongArrType_Type # define PyUInt32ScalarObject PyULongLongScalarObject # define PyUInt32ArrType_Type PyULongLongArrType_Type #define NPY_INT32_FMT NPY_LONGLONG_FMT #define NPY_UINT32_FMT NPY_ULONGLONG_FMT # endif # define NPY_MAX_LONGLONG NPY_MAX_INT32 # define NPY_MIN_LONGLONG NPY_MIN_INT32 # define NPY_MAX_ULONGLONG NPY_MAX_UINT32 #elif NPY_BITSOF_LONGLONG == 64 # ifndef NPY_INT64 # define NPY_INT64 NPY_LONGLONG # define NPY_UINT64 NPY_ULONGLONG typedef npy_longlong npy_int64; typedef npy_ulonglong npy_uint64; # define PyInt64ScalarObject PyLongLongScalarObject # define PyInt64ArrType_Type PyLongLongArrType_Type # define PyUInt64ScalarObject PyULongLongScalarObject # define PyUInt64ArrType_Type PyULongLongArrType_Type #define NPY_INT64_FMT NPY_LONGLONG_FMT #define NPY_UINT64_FMT NPY_ULONGLONG_FMT # define MyPyLong_FromInt64 PyLong_FromLongLong # define MyPyLong_AsInt64 PyLong_AsLongLong # endif # define NPY_MAX_LONGLONG NPY_MAX_INT64 # define NPY_MIN_LONGLONG NPY_MIN_INT64 # define NPY_MAX_ULONGLONG NPY_MAX_UINT64 #elif NPY_BITSOF_LONGLONG == 128 # ifndef NPY_INT128 # define NPY_INT128 NPY_LONGLONG # define NPY_UINT128 NPY_ULONGLONG typedef npy_longlong npy_int128; typedef npy_ulonglong npy_uint128; # define PyInt128ScalarObject PyLongLongScalarObject # define PyInt128ArrType_Type PyLongLongArrType_Type # define PyUInt128ScalarObject PyULongLongScalarObject # define PyUInt128ArrType_Type PyULongLongArrType_Type #define NPY_INT128_FMT NPY_LONGLONG_FMT #define NPY_UINT128_FMT NPY_ULONGLONG_FMT # endif # define NPY_MAX_LONGLONG NPY_MAX_INT128 # define NPY_MIN_LONGLONG NPY_MIN_INT128 # define NPY_MAX_ULONGLONG NPY_MAX_UINT128 #elif NPY_BITSOF_LONGLONG == 256 # define NPY_INT256 NPY_LONGLONG # define NPY_UINT256 NPY_ULONGLONG typedef npy_longlong npy_int256; typedef npy_ulonglong npy_uint256; # define PyInt256ScalarObject PyLongLongScalarObject # define PyInt256ArrType_Type PyLongLongArrType_Type # define PyUInt256ScalarObject PyULongLongScalarObject # define PyUInt256ArrType_Type PyULongLongArrType_Type #define NPY_INT256_FMT NPY_LONGLONG_FMT #define NPY_UINT256_FMT NPY_ULONGLONG_FMT # define NPY_MAX_LONGLONG NPY_MAX_INT256 # define NPY_MIN_LONGLONG NPY_MIN_INT256 # define NPY_MAX_ULONGLONG NPY_MAX_UINT256 #endif #if NPY_BITSOF_INT == 8 #ifndef NPY_INT8 #define NPY_INT8 NPY_INT #define NPY_UINT8 NPY_UINT typedef int npy_int8; typedef unsigned int npy_uint8; # define PyInt8ScalarObject PyIntScalarObject # define PyInt8ArrType_Type PyIntArrType_Type # define PyUInt8ScalarObject PyUIntScalarObject # define PyUInt8ArrType_Type PyUIntArrType_Type #define NPY_INT8_FMT NPY_INT_FMT #define NPY_UINT8_FMT NPY_UINT_FMT #endif #elif NPY_BITSOF_INT == 16 #ifndef NPY_INT16 #define NPY_INT16 NPY_INT #define NPY_UINT16 NPY_UINT typedef int npy_int16; typedef unsigned int npy_uint16; # define PyInt16ScalarObject PyIntScalarObject # define PyInt16ArrType_Type PyIntArrType_Type # define PyUInt16ScalarObject PyIntUScalarObject # define PyUInt16ArrType_Type PyIntUArrType_Type #define NPY_INT16_FMT NPY_INT_FMT #define NPY_UINT16_FMT NPY_UINT_FMT #endif #elif NPY_BITSOF_INT == 32 #ifndef NPY_INT32 #define NPY_INT32 NPY_INT #define NPY_UINT32 NPY_UINT typedef int npy_int32; typedef unsigned int npy_uint32; typedef unsigned int npy_ucs4; # define PyInt32ScalarObject PyIntScalarObject # define PyInt32ArrType_Type PyIntArrType_Type # define PyUInt32ScalarObject PyUIntScalarObject # define PyUInt32ArrType_Type PyUIntArrType_Type #define NPY_INT32_FMT NPY_INT_FMT #define NPY_UINT32_FMT NPY_UINT_FMT #endif #elif NPY_BITSOF_INT == 64 #ifndef NPY_INT64 #define NPY_INT64 NPY_INT #define NPY_UINT64 NPY_UINT typedef int npy_int64; typedef unsigned int npy_uint64; # define PyInt64ScalarObject PyIntScalarObject # define PyInt64ArrType_Type PyIntArrType_Type # define PyUInt64ScalarObject PyUIntScalarObject # define PyUInt64ArrType_Type PyUIntArrType_Type #define NPY_INT64_FMT NPY_INT_FMT #define NPY_UINT64_FMT NPY_UINT_FMT # define MyPyLong_FromInt64 PyLong_FromLong # define MyPyLong_AsInt64 PyLong_AsLong #endif #elif NPY_BITSOF_INT == 128 #ifndef NPY_INT128 #define NPY_INT128 NPY_INT #define NPY_UINT128 NPY_UINT typedef int npy_int128; typedef unsigned int npy_uint128; # define PyInt128ScalarObject PyIntScalarObject # define PyInt128ArrType_Type PyIntArrType_Type # define PyUInt128ScalarObject PyUIntScalarObject # define PyUInt128ArrType_Type PyUIntArrType_Type #define NPY_INT128_FMT NPY_INT_FMT #define NPY_UINT128_FMT NPY_UINT_FMT #endif #endif #if NPY_BITSOF_SHORT == 8 #ifndef NPY_INT8 #define NPY_INT8 NPY_SHORT #define NPY_UINT8 NPY_USHORT typedef short npy_int8; typedef unsigned short npy_uint8; # define PyInt8ScalarObject PyShortScalarObject # define PyInt8ArrType_Type PyShortArrType_Type # define PyUInt8ScalarObject PyUShortScalarObject # define PyUInt8ArrType_Type PyUShortArrType_Type #define NPY_INT8_FMT NPY_SHORT_FMT #define NPY_UINT8_FMT NPY_USHORT_FMT #endif #elif NPY_BITSOF_SHORT == 16 #ifndef NPY_INT16 #define NPY_INT16 NPY_SHORT #define NPY_UINT16 NPY_USHORT typedef short npy_int16; typedef unsigned short npy_uint16; # define PyInt16ScalarObject PyShortScalarObject # define PyInt16ArrType_Type PyShortArrType_Type # define PyUInt16ScalarObject PyUShortScalarObject # define PyUInt16ArrType_Type PyUShortArrType_Type #define NPY_INT16_FMT NPY_SHORT_FMT #define NPY_UINT16_FMT NPY_USHORT_FMT #endif #elif NPY_BITSOF_SHORT == 32 #ifndef NPY_INT32 #define NPY_INT32 NPY_SHORT #define NPY_UINT32 NPY_USHORT typedef short npy_int32; typedef unsigned short npy_uint32; typedef unsigned short npy_ucs4; # define PyInt32ScalarObject PyShortScalarObject # define PyInt32ArrType_Type PyShortArrType_Type # define PyUInt32ScalarObject PyUShortScalarObject # define PyUInt32ArrType_Type PyUShortArrType_Type #define NPY_INT32_FMT NPY_SHORT_FMT #define NPY_UINT32_FMT NPY_USHORT_FMT #endif #elif NPY_BITSOF_SHORT == 64 #ifndef NPY_INT64 #define NPY_INT64 NPY_SHORT #define NPY_UINT64 NPY_USHORT typedef short npy_int64; typedef unsigned short npy_uint64; # define PyInt64ScalarObject PyShortScalarObject # define PyInt64ArrType_Type PyShortArrType_Type # define PyUInt64ScalarObject PyUShortScalarObject # define PyUInt64ArrType_Type PyUShortArrType_Type #define NPY_INT64_FMT NPY_SHORT_FMT #define NPY_UINT64_FMT NPY_USHORT_FMT # define MyPyLong_FromInt64 PyLong_FromLong # define MyPyLong_AsInt64 PyLong_AsLong #endif #elif NPY_BITSOF_SHORT == 128 #ifndef NPY_INT128 #define NPY_INT128 NPY_SHORT #define NPY_UINT128 NPY_USHORT typedef short npy_int128; typedef unsigned short npy_uint128; # define PyInt128ScalarObject PyShortScalarObject # define PyInt128ArrType_Type PyShortArrType_Type # define PyUInt128ScalarObject PyUShortScalarObject # define PyUInt128ArrType_Type PyUShortArrType_Type #define NPY_INT128_FMT NPY_SHORT_FMT #define NPY_UINT128_FMT NPY_USHORT_FMT #endif #endif #if NPY_BITSOF_CHAR == 8 #ifndef NPY_INT8 #define NPY_INT8 NPY_BYTE #define NPY_UINT8 NPY_UBYTE typedef signed char npy_int8; typedef unsigned char npy_uint8; # define PyInt8ScalarObject PyByteScalarObject # define PyInt8ArrType_Type PyByteArrType_Type # define PyUInt8ScalarObject PyUByteScalarObject # define PyUInt8ArrType_Type PyUByteArrType_Type #define NPY_INT8_FMT NPY_BYTE_FMT #define NPY_UINT8_FMT NPY_UBYTE_FMT #endif #elif NPY_BITSOF_CHAR == 16 #ifndef NPY_INT16 #define NPY_INT16 NPY_BYTE #define NPY_UINT16 NPY_UBYTE typedef signed char npy_int16; typedef unsigned char npy_uint16; # define PyInt16ScalarObject PyByteScalarObject # define PyInt16ArrType_Type PyByteArrType_Type # define PyUInt16ScalarObject PyUByteScalarObject # define PyUInt16ArrType_Type PyUByteArrType_Type #define NPY_INT16_FMT NPY_BYTE_FMT #define NPY_UINT16_FMT NPY_UBYTE_FMT #endif #elif NPY_BITSOF_CHAR == 32 #ifndef NPY_INT32 #define NPY_INT32 NPY_BYTE #define NPY_UINT32 NPY_UBYTE typedef signed char npy_int32; typedef unsigned char npy_uint32; typedef unsigned char npy_ucs4; # define PyInt32ScalarObject PyByteScalarObject # define PyInt32ArrType_Type PyByteArrType_Type # define PyUInt32ScalarObject PyUByteScalarObject # define PyUInt32ArrType_Type PyUByteArrType_Type #define NPY_INT32_FMT NPY_BYTE_FMT #define NPY_UINT32_FMT NPY_UBYTE_FMT #endif #elif NPY_BITSOF_CHAR == 64 #ifndef NPY_INT64 #define NPY_INT64 NPY_BYTE #define NPY_UINT64 NPY_UBYTE typedef signed char npy_int64; typedef unsigned char npy_uint64; # define PyInt64ScalarObject PyByteScalarObject # define PyInt64ArrType_Type PyByteArrType_Type # define PyUInt64ScalarObject PyUByteScalarObject # define PyUInt64ArrType_Type PyUByteArrType_Type #define NPY_INT64_FMT NPY_BYTE_FMT #define NPY_UINT64_FMT NPY_UBYTE_FMT # define MyPyLong_FromInt64 PyLong_FromLong # define MyPyLong_AsInt64 PyLong_AsLong #endif #elif NPY_BITSOF_CHAR == 128 #ifndef NPY_INT128 #define NPY_INT128 NPY_BYTE #define NPY_UINT128 NPY_UBYTE typedef signed char npy_int128; typedef unsigned char npy_uint128; # define PyInt128ScalarObject PyByteScalarObject # define PyInt128ArrType_Type PyByteArrType_Type # define PyUInt128ScalarObject PyUByteScalarObject # define PyUInt128ArrType_Type PyUByteArrType_Type #define NPY_INT128_FMT NPY_BYTE_FMT #define NPY_UINT128_FMT NPY_UBYTE_FMT #endif #endif #if NPY_BITSOF_DOUBLE == 32 #ifndef NPY_FLOAT32 #define NPY_FLOAT32 NPY_DOUBLE #define NPY_COMPLEX64 NPY_CDOUBLE typedef double npy_float32; typedef npy_cdouble npy_complex64; # define PyFloat32ScalarObject PyDoubleScalarObject # define PyComplex64ScalarObject PyCDoubleScalarObject # define PyFloat32ArrType_Type PyDoubleArrType_Type # define PyComplex64ArrType_Type PyCDoubleArrType_Type #define NPY_FLOAT32_FMT NPY_DOUBLE_FMT #define NPY_COMPLEX64_FMT NPY_CDOUBLE_FMT #endif #elif NPY_BITSOF_DOUBLE == 64 #ifndef NPY_FLOAT64 #define NPY_FLOAT64 NPY_DOUBLE #define NPY_COMPLEX128 NPY_CDOUBLE typedef double npy_float64; typedef npy_cdouble npy_complex128; # define PyFloat64ScalarObject PyDoubleScalarObject # define PyComplex128ScalarObject PyCDoubleScalarObject # define PyFloat64ArrType_Type PyDoubleArrType_Type # define PyComplex128ArrType_Type PyCDoubleArrType_Type #define NPY_FLOAT64_FMT NPY_DOUBLE_FMT #define NPY_COMPLEX128_FMT NPY_CDOUBLE_FMT #endif #elif NPY_BITSOF_DOUBLE == 80 #ifndef NPY_FLOAT80 #define NPY_FLOAT80 NPY_DOUBLE #define NPY_COMPLEX160 NPY_CDOUBLE typedef double npy_float80; typedef npy_cdouble npy_complex160; # define PyFloat80ScalarObject PyDoubleScalarObject # define PyComplex160ScalarObject PyCDoubleScalarObject # define PyFloat80ArrType_Type PyDoubleArrType_Type # define PyComplex160ArrType_Type PyCDoubleArrType_Type #define NPY_FLOAT80_FMT NPY_DOUBLE_FMT #define NPY_COMPLEX160_FMT NPY_CDOUBLE_FMT #endif #elif NPY_BITSOF_DOUBLE == 96 #ifndef NPY_FLOAT96 #define NPY_FLOAT96 NPY_DOUBLE #define NPY_COMPLEX192 NPY_CDOUBLE typedef double npy_float96; typedef npy_cdouble npy_complex192; # define PyFloat96ScalarObject PyDoubleScalarObject # define PyComplex192ScalarObject PyCDoubleScalarObject # define PyFloat96ArrType_Type PyDoubleArrType_Type # define PyComplex192ArrType_Type PyCDoubleArrType_Type #define NPY_FLOAT96_FMT NPY_DOUBLE_FMT #define NPY_COMPLEX192_FMT NPY_CDOUBLE_FMT #endif #elif NPY_BITSOF_DOUBLE == 128 #ifndef NPY_FLOAT128 #define NPY_FLOAT128 NPY_DOUBLE #define NPY_COMPLEX256 NPY_CDOUBLE typedef double npy_float128; typedef npy_cdouble npy_complex256; # define PyFloat128ScalarObject PyDoubleScalarObject # define PyComplex256ScalarObject PyCDoubleScalarObject # define PyFloat128ArrType_Type PyDoubleArrType_Type # define PyComplex256ArrType_Type PyCDoubleArrType_Type #define NPY_FLOAT128_FMT NPY_DOUBLE_FMT #define NPY_COMPLEX256_FMT NPY_CDOUBLE_FMT #endif #endif #if NPY_BITSOF_FLOAT == 32 #ifndef NPY_FLOAT32 #define NPY_FLOAT32 NPY_FLOAT #define NPY_COMPLEX64 NPY_CFLOAT typedef float npy_float32; typedef npy_cfloat npy_complex64; # define PyFloat32ScalarObject PyFloatScalarObject # define PyComplex64ScalarObject PyCFloatScalarObject # define PyFloat32ArrType_Type PyFloatArrType_Type # define PyComplex64ArrType_Type PyCFloatArrType_Type #define NPY_FLOAT32_FMT NPY_FLOAT_FMT #define NPY_COMPLEX64_FMT NPY_CFLOAT_FMT #endif #elif NPY_BITSOF_FLOAT == 64 #ifndef NPY_FLOAT64 #define NPY_FLOAT64 NPY_FLOAT #define NPY_COMPLEX128 NPY_CFLOAT typedef float npy_float64; typedef npy_cfloat npy_complex128; # define PyFloat64ScalarObject PyFloatScalarObject # define PyComplex128ScalarObject PyCFloatScalarObject # define PyFloat64ArrType_Type PyFloatArrType_Type # define PyComplex128ArrType_Type PyCFloatArrType_Type #define NPY_FLOAT64_FMT NPY_FLOAT_FMT #define NPY_COMPLEX128_FMT NPY_CFLOAT_FMT #endif #elif NPY_BITSOF_FLOAT == 80 #ifndef NPY_FLOAT80 #define NPY_FLOAT80 NPY_FLOAT #define NPY_COMPLEX160 NPY_CFLOAT typedef float npy_float80; typedef npy_cfloat npy_complex160; # define PyFloat80ScalarObject PyFloatScalarObject # define PyComplex160ScalarObject PyCFloatScalarObject # define PyFloat80ArrType_Type PyFloatArrType_Type # define PyComplex160ArrType_Type PyCFloatArrType_Type #define NPY_FLOAT80_FMT NPY_FLOAT_FMT #define NPY_COMPLEX160_FMT NPY_CFLOAT_FMT #endif #elif NPY_BITSOF_FLOAT == 96 #ifndef NPY_FLOAT96 #define NPY_FLOAT96 NPY_FLOAT #define NPY_COMPLEX192 NPY_CFLOAT typedef float npy_float96; typedef npy_cfloat npy_complex192; # define PyFloat96ScalarObject PyFloatScalarObject # define PyComplex192ScalarObject PyCFloatScalarObject # define PyFloat96ArrType_Type PyFloatArrType_Type # define PyComplex192ArrType_Type PyCFloatArrType_Type #define NPY_FLOAT96_FMT NPY_FLOAT_FMT #define NPY_COMPLEX192_FMT NPY_CFLOAT_FMT #endif #elif NPY_BITSOF_FLOAT == 128 #ifndef NPY_FLOAT128 #define NPY_FLOAT128 NPY_FLOAT #define NPY_COMPLEX256 NPY_CFLOAT typedef float npy_float128; typedef npy_cfloat npy_complex256; # define PyFloat128ScalarObject PyFloatScalarObject # define PyComplex256ScalarObject PyCFloatScalarObject # define PyFloat128ArrType_Type PyFloatArrType_Type # define PyComplex256ArrType_Type PyCFloatArrType_Type #define NPY_FLOAT128_FMT NPY_FLOAT_FMT #define NPY_COMPLEX256_FMT NPY_CFLOAT_FMT #endif #endif /* half/float16 isn't a floating-point type in C */ #define NPY_FLOAT16 NPY_HALF typedef npy_uint16 npy_half; typedef npy_half npy_float16; #if NPY_BITSOF_LONGDOUBLE == 32 #ifndef NPY_FLOAT32 #define NPY_FLOAT32 NPY_LONGDOUBLE #define NPY_COMPLEX64 NPY_CLONGDOUBLE typedef npy_longdouble npy_float32; typedef npy_clongdouble npy_complex64; # define PyFloat32ScalarObject PyLongDoubleScalarObject # define PyComplex64ScalarObject PyCLongDoubleScalarObject # define PyFloat32ArrType_Type PyLongDoubleArrType_Type # define PyComplex64ArrType_Type PyCLongDoubleArrType_Type #define NPY_FLOAT32_FMT NPY_LONGDOUBLE_FMT #define NPY_COMPLEX64_FMT NPY_CLONGDOUBLE_FMT #endif #elif NPY_BITSOF_LONGDOUBLE == 64 #ifndef NPY_FLOAT64 #define NPY_FLOAT64 NPY_LONGDOUBLE #define NPY_COMPLEX128 NPY_CLONGDOUBLE typedef npy_longdouble npy_float64; typedef npy_clongdouble npy_complex128; # define PyFloat64ScalarObject PyLongDoubleScalarObject # define PyComplex128ScalarObject PyCLongDoubleScalarObject # define PyFloat64ArrType_Type PyLongDoubleArrType_Type # define PyComplex128ArrType_Type PyCLongDoubleArrType_Type #define NPY_FLOAT64_FMT NPY_LONGDOUBLE_FMT #define NPY_COMPLEX128_FMT NPY_CLONGDOUBLE_FMT #endif #elif NPY_BITSOF_LONGDOUBLE == 80 #ifndef NPY_FLOAT80 #define NPY_FLOAT80 NPY_LONGDOUBLE #define NPY_COMPLEX160 NPY_CLONGDOUBLE typedef npy_longdouble npy_float80; typedef npy_clongdouble npy_complex160; # define PyFloat80ScalarObject PyLongDoubleScalarObject # define PyComplex160ScalarObject PyCLongDoubleScalarObject # define PyFloat80ArrType_Type PyLongDoubleArrType_Type # define PyComplex160ArrType_Type PyCLongDoubleArrType_Type #define NPY_FLOAT80_FMT NPY_LONGDOUBLE_FMT #define NPY_COMPLEX160_FMT NPY_CLONGDOUBLE_FMT #endif #elif NPY_BITSOF_LONGDOUBLE == 96 #ifndef NPY_FLOAT96 #define NPY_FLOAT96 NPY_LONGDOUBLE #define NPY_COMPLEX192 NPY_CLONGDOUBLE typedef npy_longdouble npy_float96; typedef npy_clongdouble npy_complex192; # define PyFloat96ScalarObject PyLongDoubleScalarObject # define PyComplex192ScalarObject PyCLongDoubleScalarObject # define PyFloat96ArrType_Type PyLongDoubleArrType_Type # define PyComplex192ArrType_Type PyCLongDoubleArrType_Type #define NPY_FLOAT96_FMT NPY_LONGDOUBLE_FMT #define NPY_COMPLEX192_FMT NPY_CLONGDOUBLE_FMT #endif #elif NPY_BITSOF_LONGDOUBLE == 128 #ifndef NPY_FLOAT128 #define NPY_FLOAT128 NPY_LONGDOUBLE #define NPY_COMPLEX256 NPY_CLONGDOUBLE typedef npy_longdouble npy_float128; typedef npy_clongdouble npy_complex256; # define PyFloat128ScalarObject PyLongDoubleScalarObject # define PyComplex256ScalarObject PyCLongDoubleScalarObject # define PyFloat128ArrType_Type PyLongDoubleArrType_Type # define PyComplex256ArrType_Type PyCLongDoubleArrType_Type #define NPY_FLOAT128_FMT NPY_LONGDOUBLE_FMT #define NPY_COMPLEX256_FMT NPY_CLONGDOUBLE_FMT #endif #elif NPY_BITSOF_LONGDOUBLE == 256 #define NPY_FLOAT256 NPY_LONGDOUBLE #define NPY_COMPLEX512 NPY_CLONGDOUBLE typedef npy_longdouble npy_float256; typedef npy_clongdouble npy_complex512; # define PyFloat256ScalarObject PyLongDoubleScalarObject # define PyComplex512ScalarObject PyCLongDoubleScalarObject # define PyFloat256ArrType_Type PyLongDoubleArrType_Type # define PyComplex512ArrType_Type PyCLongDoubleArrType_Type #define NPY_FLOAT256_FMT NPY_LONGDOUBLE_FMT #define NPY_COMPLEX512_FMT NPY_CLONGDOUBLE_FMT #endif /* datetime typedefs */ typedef npy_int64 npy_timedelta; typedef npy_int64 npy_datetime; #define NPY_DATETIME_FMT NPY_INT64_FMT #define NPY_TIMEDELTA_FMT NPY_INT64_FMT /* End of typedefs for numarray style bit-width names */ #endif
37,647
33.225455
124
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/halffloat.h
#ifndef __NPY_HALFFLOAT_H__ #define __NPY_HALFFLOAT_H__ #include <Python.h> #include <numpy/npy_math.h> #ifdef __cplusplus extern "C" { #endif /* * Half-precision routines */ /* Conversions */ float npy_half_to_float(npy_half h); double npy_half_to_double(npy_half h); npy_half npy_float_to_half(float f); npy_half npy_double_to_half(double d); /* Comparisons */ int npy_half_eq(npy_half h1, npy_half h2); int npy_half_ne(npy_half h1, npy_half h2); int npy_half_le(npy_half h1, npy_half h2); int npy_half_lt(npy_half h1, npy_half h2); int npy_half_ge(npy_half h1, npy_half h2); int npy_half_gt(npy_half h1, npy_half h2); /* faster *_nonan variants for when you know h1 and h2 are not NaN */ int npy_half_eq_nonan(npy_half h1, npy_half h2); int npy_half_lt_nonan(npy_half h1, npy_half h2); int npy_half_le_nonan(npy_half h1, npy_half h2); /* Miscellaneous functions */ int npy_half_iszero(npy_half h); int npy_half_isnan(npy_half h); int npy_half_isinf(npy_half h); int npy_half_isfinite(npy_half h); int npy_half_signbit(npy_half h); npy_half npy_half_copysign(npy_half x, npy_half y); npy_half npy_half_spacing(npy_half h); npy_half npy_half_nextafter(npy_half x, npy_half y); npy_half npy_half_divmod(npy_half x, npy_half y, npy_half *modulus); /* * Half-precision constants */ #define NPY_HALF_ZERO (0x0000u) #define NPY_HALF_PZERO (0x0000u) #define NPY_HALF_NZERO (0x8000u) #define NPY_HALF_ONE (0x3c00u) #define NPY_HALF_NEGONE (0xbc00u) #define NPY_HALF_PINF (0x7c00u) #define NPY_HALF_NINF (0xfc00u) #define NPY_HALF_NAN (0x7e00u) #define NPY_MAX_HALF (0x7bffu) /* * Bit-level conversions */ npy_uint16 npy_floatbits_to_halfbits(npy_uint32 f); npy_uint16 npy_doublebits_to_halfbits(npy_uint64 d); npy_uint32 npy_halfbits_to_floatbits(npy_uint16 h); npy_uint64 npy_halfbits_to_doublebits(npy_uint16 h); #ifdef __cplusplus } #endif #endif
1,878
25.464789
69
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/oldnumeric.h
#include "arrayobject.h" #ifndef PYPY_VERSION #ifndef REFCOUNT # define REFCOUNT NPY_REFCOUNT # define MAX_ELSIZE 16 #endif #endif #define PyArray_UNSIGNED_TYPES #define PyArray_SBYTE NPY_BYTE #define PyArray_CopyArray PyArray_CopyInto #define _PyArray_multiply_list PyArray_MultiplyIntList #define PyArray_ISSPACESAVER(m) NPY_FALSE #define PyScalarArray_Check PyArray_CheckScalar #define CONTIGUOUS NPY_CONTIGUOUS #define OWN_DIMENSIONS 0 #define OWN_STRIDES 0 #define OWN_DATA NPY_OWNDATA #define SAVESPACE 0 #define SAVESPACEBIT 0 #undef import_array #define import_array() { if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); } }
708
26.269231
147
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/_neighborhood_iterator_imp.h
#ifndef _NPY_INCLUDE_NEIGHBORHOOD_IMP #error You should not include this header directly #endif /* * Private API (here for inline) */ static NPY_INLINE int _PyArrayNeighborhoodIter_IncrCoord(PyArrayNeighborhoodIterObject* iter); /* * Update to next item of the iterator * * Note: this simply increment the coordinates vector, last dimension * incremented first , i.e, for dimension 3 * ... * -1, -1, -1 * -1, -1, 0 * -1, -1, 1 * .... * -1, 0, -1 * -1, 0, 0 * .... * 0, -1, -1 * 0, -1, 0 * .... */ #define _UPDATE_COORD_ITER(c) \ wb = iter->coordinates[c] < iter->bounds[c][1]; \ if (wb) { \ iter->coordinates[c] += 1; \ return 0; \ } \ else { \ iter->coordinates[c] = iter->bounds[c][0]; \ } static NPY_INLINE int _PyArrayNeighborhoodIter_IncrCoord(PyArrayNeighborhoodIterObject* iter) { npy_intp i, wb; for (i = iter->nd - 1; i >= 0; --i) { _UPDATE_COORD_ITER(i) } return 0; } /* * Version optimized for 2d arrays, manual loop unrolling */ static NPY_INLINE int _PyArrayNeighborhoodIter_IncrCoord2D(PyArrayNeighborhoodIterObject* iter) { npy_intp wb; _UPDATE_COORD_ITER(1) _UPDATE_COORD_ITER(0) return 0; } #undef _UPDATE_COORD_ITER /* * Advance to the next neighbour */ static NPY_INLINE int PyArrayNeighborhoodIter_Next(PyArrayNeighborhoodIterObject* iter) { _PyArrayNeighborhoodIter_IncrCoord (iter); iter->dataptr = iter->translate((PyArrayIterObject*)iter, iter->coordinates); return 0; } /* * Reset functions */ static NPY_INLINE int PyArrayNeighborhoodIter_Reset(PyArrayNeighborhoodIterObject* iter) { npy_intp i; for (i = 0; i < iter->nd; ++i) { iter->coordinates[i] = iter->bounds[i][0]; } iter->dataptr = iter->translate((PyArrayIterObject*)iter, iter->coordinates); return 0; }
1,861
19.461538
81
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/numpyconfig.h
#ifndef _NPY_NUMPYCONFIG_H_ #define _NPY_NUMPYCONFIG_H_ #include "_numpyconfig.h" /* * On Mac OS X, because there is only one configuration stage for all the archs * in universal builds, any macro which depends on the arch needs to be * hardcoded */ #ifdef __APPLE__ #undef NPY_SIZEOF_LONG #undef NPY_SIZEOF_PY_INTPTR_T #ifdef __LP64__ #define NPY_SIZEOF_LONG 8 #define NPY_SIZEOF_PY_INTPTR_T 8 #else #define NPY_SIZEOF_LONG 4 #define NPY_SIZEOF_PY_INTPTR_T 4 #endif #endif /** * To help with the NPY_NO_DEPRECATED_API macro, we include API version * numbers for specific versions of NumPy. To exclude all API that was * deprecated as of 1.7, add the following before #including any NumPy * headers: * #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION */ #define NPY_1_7_API_VERSION 0x00000007 #define NPY_1_8_API_VERSION 0x00000008 #define NPY_1_9_API_VERSION 0x00000008 #define NPY_1_10_API_VERSION 0x00000008 #define NPY_1_11_API_VERSION 0x00000008 #define NPY_1_12_API_VERSION 0x00000008 #define NPY_1_13_API_VERSION 0x00000008 #define NPY_1_14_API_VERSION 0x00000008 #endif
1,167
27.487805
79
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/__multiarray_api.h
#if defined(_MULTIARRAYMODULE) || defined(WITH_CPYCHECKER_STEALS_REFERENCE_TO_ARG_ATTRIBUTE) typedef struct { PyObject_HEAD npy_bool obval; } PyBoolScalarObject; extern NPY_NO_EXPORT PyTypeObject PyArrayMapIter_Type; extern NPY_NO_EXPORT PyTypeObject PyArrayNeighborhoodIter_Type; extern NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[2]; NPY_NO_EXPORT unsigned int PyArray_GetNDArrayCVersion \ (void); extern NPY_NO_EXPORT PyTypeObject PyBigArray_Type; extern NPY_NO_EXPORT PyTypeObject PyArray_Type; extern NPY_NO_EXPORT PyTypeObject PyArrayDescr_Type; extern NPY_NO_EXPORT PyTypeObject PyArrayFlags_Type; extern NPY_NO_EXPORT PyTypeObject PyArrayIter_Type; extern NPY_NO_EXPORT PyTypeObject PyArrayMultiIter_Type; extern NPY_NO_EXPORT int NPY_NUMUSERTYPES; extern NPY_NO_EXPORT PyTypeObject PyBoolArrType_Type; extern NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[2]; extern NPY_NO_EXPORT PyTypeObject PyGenericArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyNumberArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyIntegerArrType_Type; extern NPY_NO_EXPORT PyTypeObject PySignedIntegerArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyUnsignedIntegerArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyInexactArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyFloatingArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyComplexFloatingArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyFlexibleArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyCharacterArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyByteArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyShortArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyIntArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyLongArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyLongLongArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyUByteArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyUShortArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyUIntArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyULongArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyULongLongArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyFloatArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyDoubleArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyLongDoubleArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyCFloatArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyCDoubleArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyCLongDoubleArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyObjectArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyStringArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyUnicodeArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyVoidArrType_Type; NPY_NO_EXPORT int PyArray_SetNumericOps \ (PyObject *); NPY_NO_EXPORT PyObject * PyArray_GetNumericOps \ (void); NPY_NO_EXPORT int PyArray_INCREF \ (PyArrayObject *); NPY_NO_EXPORT int PyArray_XDECREF \ (PyArrayObject *); NPY_NO_EXPORT void PyArray_SetStringFunction \ (PyObject *, int); NPY_NO_EXPORT PyArray_Descr * PyArray_DescrFromType \ (int); NPY_NO_EXPORT PyObject * PyArray_TypeObjectFromType \ (int); NPY_NO_EXPORT char * PyArray_Zero \ (PyArrayObject *); NPY_NO_EXPORT char * PyArray_One \ (PyArrayObject *); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) NPY_GCC_NONNULL(2) PyObject * PyArray_CastToType \ (PyArrayObject *, PyArray_Descr *, int); NPY_NO_EXPORT int PyArray_CastTo \ (PyArrayObject *, PyArrayObject *); NPY_NO_EXPORT int PyArray_CastAnyTo \ (PyArrayObject *, PyArrayObject *); NPY_NO_EXPORT int PyArray_CanCastSafely \ (int, int); NPY_NO_EXPORT npy_bool PyArray_CanCastTo \ (PyArray_Descr *, PyArray_Descr *); NPY_NO_EXPORT int PyArray_ObjectType \ (PyObject *, int); NPY_NO_EXPORT PyArray_Descr * PyArray_DescrFromObject \ (PyObject *, PyArray_Descr *); NPY_NO_EXPORT PyArrayObject ** PyArray_ConvertToCommonType \ (PyObject *, int *); NPY_NO_EXPORT PyArray_Descr * PyArray_DescrFromScalar \ (PyObject *); NPY_NO_EXPORT PyArray_Descr * PyArray_DescrFromTypeObject \ (PyObject *); NPY_NO_EXPORT npy_intp PyArray_Size \ (PyObject *); NPY_NO_EXPORT PyObject * PyArray_Scalar \ (void *, PyArray_Descr *, PyObject *); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_FromScalar \ (PyObject *, PyArray_Descr *); NPY_NO_EXPORT void PyArray_ScalarAsCtype \ (PyObject *, void *); NPY_NO_EXPORT int PyArray_CastScalarToCtype \ (PyObject *, void *, PyArray_Descr *); NPY_NO_EXPORT int PyArray_CastScalarDirect \ (PyObject *, PyArray_Descr *, void *, int); NPY_NO_EXPORT PyObject * PyArray_ScalarFromObject \ (PyObject *); NPY_NO_EXPORT PyArray_VectorUnaryFunc * PyArray_GetCastFunc \ (PyArray_Descr *, int); NPY_NO_EXPORT PyObject * PyArray_FromDims \ (int, int *, int); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(3) PyObject * PyArray_FromDimsAndDataAndDescr \ (int, int *, PyArray_Descr *, char *); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_FromAny \ (PyObject *, PyArray_Descr *, int, int, int, PyObject *); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(1) PyObject * PyArray_EnsureArray \ (PyObject *); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(1) PyObject * PyArray_EnsureAnyArray \ (PyObject *); NPY_NO_EXPORT PyObject * PyArray_FromFile \ (FILE *, PyArray_Descr *, npy_intp, char *); NPY_NO_EXPORT PyObject * PyArray_FromString \ (char *, npy_intp, PyArray_Descr *, npy_intp, char *); NPY_NO_EXPORT PyObject * PyArray_FromBuffer \ (PyObject *, PyArray_Descr *, npy_intp, npy_intp); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_FromIter \ (PyObject *, PyArray_Descr *, npy_intp); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(1) PyObject * PyArray_Return \ (PyArrayObject *); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) NPY_GCC_NONNULL(2) PyObject * PyArray_GetField \ (PyArrayObject *, PyArray_Descr *, int); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) NPY_GCC_NONNULL(2) int PyArray_SetField \ (PyArrayObject *, PyArray_Descr *, int, PyObject *); NPY_NO_EXPORT PyObject * PyArray_Byteswap \ (PyArrayObject *, npy_bool); NPY_NO_EXPORT PyObject * PyArray_Resize \ (PyArrayObject *, PyArray_Dims *, int, NPY_ORDER); NPY_NO_EXPORT int PyArray_MoveInto \ (PyArrayObject *, PyArrayObject *); NPY_NO_EXPORT int PyArray_CopyInto \ (PyArrayObject *, PyArrayObject *); NPY_NO_EXPORT int PyArray_CopyAnyInto \ (PyArrayObject *, PyArrayObject *); NPY_NO_EXPORT int PyArray_CopyObject \ (PyArrayObject *, PyObject *); NPY_NO_EXPORT NPY_GCC_NONNULL(1) PyObject * PyArray_NewCopy \ (PyArrayObject *, NPY_ORDER); NPY_NO_EXPORT PyObject * PyArray_ToList \ (PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_ToString \ (PyArrayObject *, NPY_ORDER); NPY_NO_EXPORT int PyArray_ToFile \ (PyArrayObject *, FILE *, char *, char *); NPY_NO_EXPORT int PyArray_Dump \ (PyObject *, PyObject *, int); NPY_NO_EXPORT PyObject * PyArray_Dumps \ (PyObject *, int); NPY_NO_EXPORT int PyArray_ValidType \ (int); NPY_NO_EXPORT void PyArray_UpdateFlags \ (PyArrayObject *, int); NPY_NO_EXPORT NPY_GCC_NONNULL(1) PyObject * PyArray_New \ (PyTypeObject *, int, npy_intp *, int, npy_intp *, void *, int, int, PyObject *); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) NPY_GCC_NONNULL(1) NPY_GCC_NONNULL(2) PyObject * PyArray_NewFromDescr \ (PyTypeObject *, PyArray_Descr *, int, npy_intp *, npy_intp *, void *, int, PyObject *); NPY_NO_EXPORT PyArray_Descr * PyArray_DescrNew \ (PyArray_Descr *); NPY_NO_EXPORT PyArray_Descr * PyArray_DescrNewFromType \ (int); NPY_NO_EXPORT double PyArray_GetPriority \ (PyObject *, double); NPY_NO_EXPORT PyObject * PyArray_IterNew \ (PyObject *); NPY_NO_EXPORT PyObject * PyArray_MultiIterNew \ (int, ...); NPY_NO_EXPORT int PyArray_PyIntAsInt \ (PyObject *); NPY_NO_EXPORT npy_intp PyArray_PyIntAsIntp \ (PyObject *); NPY_NO_EXPORT int PyArray_Broadcast \ (PyArrayMultiIterObject *); NPY_NO_EXPORT void PyArray_FillObjectArray \ (PyArrayObject *, PyObject *); NPY_NO_EXPORT int PyArray_FillWithScalar \ (PyArrayObject *, PyObject *); NPY_NO_EXPORT npy_bool PyArray_CheckStrides \ (int, int, npy_intp, npy_intp, npy_intp *, npy_intp *); NPY_NO_EXPORT PyArray_Descr * PyArray_DescrNewByteorder \ (PyArray_Descr *, char); NPY_NO_EXPORT PyObject * PyArray_IterAllButAxis \ (PyObject *, int *); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_CheckFromAny \ (PyObject *, PyArray_Descr *, int, int, int, PyObject *); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_FromArray \ (PyArrayObject *, PyArray_Descr *, int); NPY_NO_EXPORT PyObject * PyArray_FromInterface \ (PyObject *); NPY_NO_EXPORT PyObject * PyArray_FromStructInterface \ (PyObject *); NPY_NO_EXPORT PyObject * PyArray_FromArrayAttr \ (PyObject *, PyArray_Descr *, PyObject *); NPY_NO_EXPORT NPY_SCALARKIND PyArray_ScalarKind \ (int, PyArrayObject **); NPY_NO_EXPORT int PyArray_CanCoerceScalar \ (int, int, NPY_SCALARKIND); NPY_NO_EXPORT PyObject * PyArray_NewFlagsObject \ (PyObject *); NPY_NO_EXPORT npy_bool PyArray_CanCastScalar \ (PyTypeObject *, PyTypeObject *); NPY_NO_EXPORT int PyArray_CompareUCS4 \ (npy_ucs4 *, npy_ucs4 *, size_t); NPY_NO_EXPORT int PyArray_RemoveSmallest \ (PyArrayMultiIterObject *); NPY_NO_EXPORT int PyArray_ElementStrides \ (PyObject *); NPY_NO_EXPORT void PyArray_Item_INCREF \ (char *, PyArray_Descr *); NPY_NO_EXPORT void PyArray_Item_XDECREF \ (char *, PyArray_Descr *); NPY_NO_EXPORT PyObject * PyArray_FieldNames \ (PyObject *); NPY_NO_EXPORT PyObject * PyArray_Transpose \ (PyArrayObject *, PyArray_Dims *); NPY_NO_EXPORT PyObject * PyArray_TakeFrom \ (PyArrayObject *, PyObject *, int, PyArrayObject *, NPY_CLIPMODE); NPY_NO_EXPORT PyObject * PyArray_PutTo \ (PyArrayObject *, PyObject*, PyObject *, NPY_CLIPMODE); NPY_NO_EXPORT PyObject * PyArray_PutMask \ (PyArrayObject *, PyObject*, PyObject*); NPY_NO_EXPORT PyObject * PyArray_Repeat \ (PyArrayObject *, PyObject *, int); NPY_NO_EXPORT PyObject * PyArray_Choose \ (PyArrayObject *, PyObject *, PyArrayObject *, NPY_CLIPMODE); NPY_NO_EXPORT int PyArray_Sort \ (PyArrayObject *, int, NPY_SORTKIND); NPY_NO_EXPORT PyObject * PyArray_ArgSort \ (PyArrayObject *, int, NPY_SORTKIND); NPY_NO_EXPORT PyObject * PyArray_SearchSorted \ (PyArrayObject *, PyObject *, NPY_SEARCHSIDE, PyObject *); NPY_NO_EXPORT PyObject * PyArray_ArgMax \ (PyArrayObject *, int, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_ArgMin \ (PyArrayObject *, int, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_Reshape \ (PyArrayObject *, PyObject *); NPY_NO_EXPORT PyObject * PyArray_Newshape \ (PyArrayObject *, PyArray_Dims *, NPY_ORDER); NPY_NO_EXPORT PyObject * PyArray_Squeeze \ (PyArrayObject *); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) PyObject * PyArray_View \ (PyArrayObject *, PyArray_Descr *, PyTypeObject *); NPY_NO_EXPORT PyObject * PyArray_SwapAxes \ (PyArrayObject *, int, int); NPY_NO_EXPORT PyObject * PyArray_Max \ (PyArrayObject *, int, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_Min \ (PyArrayObject *, int, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_Ptp \ (PyArrayObject *, int, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_Mean \ (PyArrayObject *, int, int, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_Trace \ (PyArrayObject *, int, int, int, int, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_Diagonal \ (PyArrayObject *, int, int, int); NPY_NO_EXPORT PyObject * PyArray_Clip \ (PyArrayObject *, PyObject *, PyObject *, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_Conjugate \ (PyArrayObject *, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_Nonzero \ (PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_Std \ (PyArrayObject *, int, int, PyArrayObject *, int); NPY_NO_EXPORT PyObject * PyArray_Sum \ (PyArrayObject *, int, int, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_CumSum \ (PyArrayObject *, int, int, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_Prod \ (PyArrayObject *, int, int, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_CumProd \ (PyArrayObject *, int, int, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_All \ (PyArrayObject *, int, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_Any \ (PyArrayObject *, int, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_Compress \ (PyArrayObject *, PyObject *, int, PyArrayObject *); NPY_NO_EXPORT PyObject * PyArray_Flatten \ (PyArrayObject *, NPY_ORDER); NPY_NO_EXPORT PyObject * PyArray_Ravel \ (PyArrayObject *, NPY_ORDER); NPY_NO_EXPORT npy_intp PyArray_MultiplyList \ (npy_intp *, int); NPY_NO_EXPORT int PyArray_MultiplyIntList \ (int *, int); NPY_NO_EXPORT void * PyArray_GetPtr \ (PyArrayObject *, npy_intp*); NPY_NO_EXPORT int PyArray_CompareLists \ (npy_intp *, npy_intp *, int); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(5) int PyArray_AsCArray \ (PyObject **, void *, npy_intp *, int, PyArray_Descr*); NPY_NO_EXPORT int PyArray_As1D \ (PyObject **, char **, int *, int); NPY_NO_EXPORT int PyArray_As2D \ (PyObject **, char ***, int *, int *, int); NPY_NO_EXPORT int PyArray_Free \ (PyObject *, void *); NPY_NO_EXPORT int PyArray_Converter \ (PyObject *, PyObject **); NPY_NO_EXPORT int PyArray_IntpFromSequence \ (PyObject *, npy_intp *, int); NPY_NO_EXPORT PyObject * PyArray_Concatenate \ (PyObject *, int); NPY_NO_EXPORT PyObject * PyArray_InnerProduct \ (PyObject *, PyObject *); NPY_NO_EXPORT PyObject * PyArray_MatrixProduct \ (PyObject *, PyObject *); NPY_NO_EXPORT PyObject * PyArray_CopyAndTranspose \ (PyObject *); NPY_NO_EXPORT PyObject * PyArray_Correlate \ (PyObject *, PyObject *, int); NPY_NO_EXPORT int PyArray_TypestrConvert \ (int, int); NPY_NO_EXPORT int PyArray_DescrConverter \ (PyObject *, PyArray_Descr **); NPY_NO_EXPORT int PyArray_DescrConverter2 \ (PyObject *, PyArray_Descr **); NPY_NO_EXPORT int PyArray_IntpConverter \ (PyObject *, PyArray_Dims *); NPY_NO_EXPORT int PyArray_BufferConverter \ (PyObject *, PyArray_Chunk *); NPY_NO_EXPORT int PyArray_AxisConverter \ (PyObject *, int *); NPY_NO_EXPORT int PyArray_BoolConverter \ (PyObject *, npy_bool *); NPY_NO_EXPORT int PyArray_ByteorderConverter \ (PyObject *, char *); NPY_NO_EXPORT int PyArray_OrderConverter \ (PyObject *, NPY_ORDER *); NPY_NO_EXPORT unsigned char PyArray_EquivTypes \ (PyArray_Descr *, PyArray_Descr *); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(3) PyObject * PyArray_Zeros \ (int, npy_intp *, PyArray_Descr *, int); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(3) PyObject * PyArray_Empty \ (int, npy_intp *, PyArray_Descr *, int); NPY_NO_EXPORT PyObject * PyArray_Where \ (PyObject *, PyObject *, PyObject *); NPY_NO_EXPORT PyObject * PyArray_Arange \ (double, double, double, int); NPY_NO_EXPORT PyObject * PyArray_ArangeObj \ (PyObject *, PyObject *, PyObject *, PyArray_Descr *); NPY_NO_EXPORT int PyArray_SortkindConverter \ (PyObject *, NPY_SORTKIND *); NPY_NO_EXPORT PyObject * PyArray_LexSort \ (PyObject *, int); NPY_NO_EXPORT PyObject * PyArray_Round \ (PyArrayObject *, int, PyArrayObject *); NPY_NO_EXPORT unsigned char PyArray_EquivTypenums \ (int, int); NPY_NO_EXPORT int PyArray_RegisterDataType \ (PyArray_Descr *); NPY_NO_EXPORT int PyArray_RegisterCastFunc \ (PyArray_Descr *, int, PyArray_VectorUnaryFunc *); NPY_NO_EXPORT int PyArray_RegisterCanCast \ (PyArray_Descr *, int, NPY_SCALARKIND); NPY_NO_EXPORT void PyArray_InitArrFuncs \ (PyArray_ArrFuncs *); NPY_NO_EXPORT PyObject * PyArray_IntTupleFromIntp \ (int, npy_intp *); NPY_NO_EXPORT int PyArray_TypeNumFromName \ (char *); NPY_NO_EXPORT int PyArray_ClipmodeConverter \ (PyObject *, NPY_CLIPMODE *); NPY_NO_EXPORT int PyArray_OutputConverter \ (PyObject *, PyArrayObject **); NPY_NO_EXPORT PyObject * PyArray_BroadcastToShape \ (PyObject *, npy_intp *, int); NPY_NO_EXPORT void _PyArray_SigintHandler \ (int); NPY_NO_EXPORT void* _PyArray_GetSigintBuf \ (void); NPY_NO_EXPORT int PyArray_DescrAlignConverter \ (PyObject *, PyArray_Descr **); NPY_NO_EXPORT int PyArray_DescrAlignConverter2 \ (PyObject *, PyArray_Descr **); NPY_NO_EXPORT int PyArray_SearchsideConverter \ (PyObject *, void *); NPY_NO_EXPORT PyObject * PyArray_CheckAxis \ (PyArrayObject *, int *, int); NPY_NO_EXPORT npy_intp PyArray_OverflowMultiplyList \ (npy_intp *, int); NPY_NO_EXPORT int PyArray_CompareString \ (char *, char *, size_t); NPY_NO_EXPORT PyObject * PyArray_MultiIterFromObjects \ (PyObject **, int, int, ...); NPY_NO_EXPORT int PyArray_GetEndianness \ (void); NPY_NO_EXPORT unsigned int PyArray_GetNDArrayCFeatureVersion \ (void); NPY_NO_EXPORT PyObject * PyArray_Correlate2 \ (PyObject *, PyObject *, int); NPY_NO_EXPORT PyObject* PyArray_NeighborhoodIterNew \ (PyArrayIterObject *, npy_intp *, int, PyArrayObject*); extern NPY_NO_EXPORT PyTypeObject PyTimeIntegerArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyDatetimeArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyTimedeltaArrType_Type; extern NPY_NO_EXPORT PyTypeObject PyHalfArrType_Type; extern NPY_NO_EXPORT PyTypeObject NpyIter_Type; NPY_NO_EXPORT void PyArray_SetDatetimeParseFunction \ (PyObject *); NPY_NO_EXPORT void PyArray_DatetimeToDatetimeStruct \ (npy_datetime, NPY_DATETIMEUNIT, npy_datetimestruct *); NPY_NO_EXPORT void PyArray_TimedeltaToTimedeltaStruct \ (npy_timedelta, NPY_DATETIMEUNIT, npy_timedeltastruct *); NPY_NO_EXPORT npy_datetime PyArray_DatetimeStructToDatetime \ (NPY_DATETIMEUNIT, npy_datetimestruct *); NPY_NO_EXPORT npy_datetime PyArray_TimedeltaStructToTimedelta \ (NPY_DATETIMEUNIT, npy_timedeltastruct *); NPY_NO_EXPORT NpyIter * NpyIter_New \ (PyArrayObject *, npy_uint32, NPY_ORDER, NPY_CASTING, PyArray_Descr*); NPY_NO_EXPORT NpyIter * NpyIter_MultiNew \ (int, PyArrayObject **, npy_uint32, NPY_ORDER, NPY_CASTING, npy_uint32 *, PyArray_Descr **); NPY_NO_EXPORT NpyIter * NpyIter_AdvancedNew \ (int, PyArrayObject **, npy_uint32, NPY_ORDER, NPY_CASTING, npy_uint32 *, PyArray_Descr **, int, int **, npy_intp *, npy_intp); NPY_NO_EXPORT NpyIter * NpyIter_Copy \ (NpyIter *); NPY_NO_EXPORT int NpyIter_Deallocate \ (NpyIter *); NPY_NO_EXPORT npy_bool NpyIter_HasDelayedBufAlloc \ (NpyIter *); NPY_NO_EXPORT npy_bool NpyIter_HasExternalLoop \ (NpyIter *); NPY_NO_EXPORT int NpyIter_EnableExternalLoop \ (NpyIter *); NPY_NO_EXPORT npy_intp * NpyIter_GetInnerStrideArray \ (NpyIter *); NPY_NO_EXPORT npy_intp * NpyIter_GetInnerLoopSizePtr \ (NpyIter *); NPY_NO_EXPORT int NpyIter_Reset \ (NpyIter *, char **); NPY_NO_EXPORT int NpyIter_ResetBasePointers \ (NpyIter *, char **, char **); NPY_NO_EXPORT int NpyIter_ResetToIterIndexRange \ (NpyIter *, npy_intp, npy_intp, char **); NPY_NO_EXPORT int NpyIter_GetNDim \ (NpyIter *); NPY_NO_EXPORT int NpyIter_GetNOp \ (NpyIter *); NPY_NO_EXPORT NpyIter_IterNextFunc * NpyIter_GetIterNext \ (NpyIter *, char **); NPY_NO_EXPORT npy_intp NpyIter_GetIterSize \ (NpyIter *); NPY_NO_EXPORT void NpyIter_GetIterIndexRange \ (NpyIter *, npy_intp *, npy_intp *); NPY_NO_EXPORT npy_intp NpyIter_GetIterIndex \ (NpyIter *); NPY_NO_EXPORT int NpyIter_GotoIterIndex \ (NpyIter *, npy_intp); NPY_NO_EXPORT npy_bool NpyIter_HasMultiIndex \ (NpyIter *); NPY_NO_EXPORT int NpyIter_GetShape \ (NpyIter *, npy_intp *); NPY_NO_EXPORT NpyIter_GetMultiIndexFunc * NpyIter_GetGetMultiIndex \ (NpyIter *, char **); NPY_NO_EXPORT int NpyIter_GotoMultiIndex \ (NpyIter *, npy_intp *); NPY_NO_EXPORT int NpyIter_RemoveMultiIndex \ (NpyIter *); NPY_NO_EXPORT npy_bool NpyIter_HasIndex \ (NpyIter *); NPY_NO_EXPORT npy_bool NpyIter_IsBuffered \ (NpyIter *); NPY_NO_EXPORT npy_bool NpyIter_IsGrowInner \ (NpyIter *); NPY_NO_EXPORT npy_intp NpyIter_GetBufferSize \ (NpyIter *); NPY_NO_EXPORT npy_intp * NpyIter_GetIndexPtr \ (NpyIter *); NPY_NO_EXPORT int NpyIter_GotoIndex \ (NpyIter *, npy_intp); NPY_NO_EXPORT char ** NpyIter_GetDataPtrArray \ (NpyIter *); NPY_NO_EXPORT PyArray_Descr ** NpyIter_GetDescrArray \ (NpyIter *); NPY_NO_EXPORT PyArrayObject ** NpyIter_GetOperandArray \ (NpyIter *); NPY_NO_EXPORT PyArrayObject * NpyIter_GetIterView \ (NpyIter *, npy_intp); NPY_NO_EXPORT void NpyIter_GetReadFlags \ (NpyIter *, char *); NPY_NO_EXPORT void NpyIter_GetWriteFlags \ (NpyIter *, char *); NPY_NO_EXPORT void NpyIter_DebugPrint \ (NpyIter *); NPY_NO_EXPORT npy_bool NpyIter_IterationNeedsAPI \ (NpyIter *); NPY_NO_EXPORT void NpyIter_GetInnerFixedStrideArray \ (NpyIter *, npy_intp *); NPY_NO_EXPORT int NpyIter_RemoveAxis \ (NpyIter *, int); NPY_NO_EXPORT npy_intp * NpyIter_GetAxisStrideArray \ (NpyIter *, int); NPY_NO_EXPORT npy_bool NpyIter_RequiresBuffering \ (NpyIter *); NPY_NO_EXPORT char ** NpyIter_GetInitialDataPtrArray \ (NpyIter *); NPY_NO_EXPORT int NpyIter_CreateCompatibleStrides \ (NpyIter *, npy_intp, npy_intp *); NPY_NO_EXPORT int PyArray_CastingConverter \ (PyObject *, NPY_CASTING *); NPY_NO_EXPORT npy_intp PyArray_CountNonzero \ (PyArrayObject *); NPY_NO_EXPORT PyArray_Descr * PyArray_PromoteTypes \ (PyArray_Descr *, PyArray_Descr *); NPY_NO_EXPORT PyArray_Descr * PyArray_MinScalarType \ (PyArrayObject *); NPY_NO_EXPORT PyArray_Descr * PyArray_ResultType \ (npy_intp, PyArrayObject **, npy_intp, PyArray_Descr **); NPY_NO_EXPORT npy_bool PyArray_CanCastArrayTo \ (PyArrayObject *, PyArray_Descr *, NPY_CASTING); NPY_NO_EXPORT npy_bool PyArray_CanCastTypeTo \ (PyArray_Descr *, PyArray_Descr *, NPY_CASTING); NPY_NO_EXPORT PyArrayObject * PyArray_EinsteinSum \ (char *, npy_intp, PyArrayObject **, PyArray_Descr *, NPY_ORDER, NPY_CASTING, PyArrayObject *); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(3) NPY_GCC_NONNULL(1) PyObject * PyArray_NewLikeArray \ (PyArrayObject *, NPY_ORDER, PyArray_Descr *, int); NPY_NO_EXPORT int PyArray_GetArrayParamsFromObject \ (PyObject *, PyArray_Descr *, npy_bool, PyArray_Descr **, int *, npy_intp *, PyArrayObject **, PyObject *); NPY_NO_EXPORT int PyArray_ConvertClipmodeSequence \ (PyObject *, NPY_CLIPMODE *, int); NPY_NO_EXPORT PyObject * PyArray_MatrixProduct2 \ (PyObject *, PyObject *, PyArrayObject*); NPY_NO_EXPORT npy_bool NpyIter_IsFirstVisit \ (NpyIter *, int); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) int PyArray_SetBaseObject \ (PyArrayObject *, PyObject *); NPY_NO_EXPORT void PyArray_CreateSortedStridePerm \ (int, npy_intp *, npy_stride_sort_item *); NPY_NO_EXPORT void PyArray_RemoveAxesInPlace \ (PyArrayObject *, npy_bool *); NPY_NO_EXPORT void PyArray_DebugPrint \ (PyArrayObject *); NPY_NO_EXPORT int PyArray_FailUnlessWriteable \ (PyArrayObject *, const char *); NPY_NO_EXPORT NPY_STEALS_REF_TO_ARG(2) int PyArray_SetUpdateIfCopyBase \ (PyArrayObject *, PyArrayObject *); NPY_NO_EXPORT void * PyDataMem_NEW \ (size_t); NPY_NO_EXPORT void PyDataMem_FREE \ (void *); NPY_NO_EXPORT void * PyDataMem_RENEW \ (void *, size_t); NPY_NO_EXPORT PyDataMem_EventHookFunc * PyDataMem_SetEventHook \ (PyDataMem_EventHookFunc *, void *, void **); extern NPY_NO_EXPORT NPY_CASTING NPY_DEFAULT_ASSIGN_CASTING; NPY_NO_EXPORT void PyArray_MapIterSwapAxes \ (PyArrayMapIterObject *, PyArrayObject **, int); NPY_NO_EXPORT PyObject * PyArray_MapIterArray \ (PyArrayObject *, PyObject *); NPY_NO_EXPORT void PyArray_MapIterNext \ (PyArrayMapIterObject *); NPY_NO_EXPORT int PyArray_Partition \ (PyArrayObject *, PyArrayObject *, int, NPY_SELECTKIND); NPY_NO_EXPORT PyObject * PyArray_ArgPartition \ (PyArrayObject *, PyArrayObject *, int, NPY_SELECTKIND); NPY_NO_EXPORT int PyArray_SelectkindConverter \ (PyObject *, NPY_SELECTKIND *); NPY_NO_EXPORT void * PyDataMem_NEW_ZEROED \ (size_t, size_t); NPY_NO_EXPORT NPY_GCC_NONNULL(1) int PyArray_CheckAnyScalarExact \ (PyObject *); NPY_NO_EXPORT PyObject * PyArray_MapIterArrayCopyIfOverlap \ (PyArrayObject *, PyObject *, int, PyArrayObject *); NPY_NO_EXPORT int PyArray_ResolveWritebackIfCopy \ (PyArrayObject *); NPY_NO_EXPORT int PyArray_SetWritebackIfCopyBase \ (PyArrayObject *, PyArrayObject *); #else #if defined(PY_ARRAY_UNIQUE_SYMBOL) #define PyArray_API PY_ARRAY_UNIQUE_SYMBOL #endif #if defined(NO_IMPORT) || defined(NO_IMPORT_ARRAY) extern void **PyArray_API; #else #if defined(PY_ARRAY_UNIQUE_SYMBOL) void **PyArray_API; #else static void **PyArray_API=NULL; #endif #endif #define PyArray_GetNDArrayCVersion \ (*(unsigned int (*)(void)) \ PyArray_API[0]) #define PyBigArray_Type (*(PyTypeObject *)PyArray_API[1]) #define PyArray_Type (*(PyTypeObject *)PyArray_API[2]) #define PyArrayDescr_Type (*(PyTypeObject *)PyArray_API[3]) #define PyArrayFlags_Type (*(PyTypeObject *)PyArray_API[4]) #define PyArrayIter_Type (*(PyTypeObject *)PyArray_API[5]) #define PyArrayMultiIter_Type (*(PyTypeObject *)PyArray_API[6]) #define NPY_NUMUSERTYPES (*(int *)PyArray_API[7]) #define PyBoolArrType_Type (*(PyTypeObject *)PyArray_API[8]) #define _PyArrayScalar_BoolValues ((PyBoolScalarObject *)PyArray_API[9]) #define PyGenericArrType_Type (*(PyTypeObject *)PyArray_API[10]) #define PyNumberArrType_Type (*(PyTypeObject *)PyArray_API[11]) #define PyIntegerArrType_Type (*(PyTypeObject *)PyArray_API[12]) #define PySignedIntegerArrType_Type (*(PyTypeObject *)PyArray_API[13]) #define PyUnsignedIntegerArrType_Type (*(PyTypeObject *)PyArray_API[14]) #define PyInexactArrType_Type (*(PyTypeObject *)PyArray_API[15]) #define PyFloatingArrType_Type (*(PyTypeObject *)PyArray_API[16]) #define PyComplexFloatingArrType_Type (*(PyTypeObject *)PyArray_API[17]) #define PyFlexibleArrType_Type (*(PyTypeObject *)PyArray_API[18]) #define PyCharacterArrType_Type (*(PyTypeObject *)PyArray_API[19]) #define PyByteArrType_Type (*(PyTypeObject *)PyArray_API[20]) #define PyShortArrType_Type (*(PyTypeObject *)PyArray_API[21]) #define PyIntArrType_Type (*(PyTypeObject *)PyArray_API[22]) #define PyLongArrType_Type (*(PyTypeObject *)PyArray_API[23]) #define PyLongLongArrType_Type (*(PyTypeObject *)PyArray_API[24]) #define PyUByteArrType_Type (*(PyTypeObject *)PyArray_API[25]) #define PyUShortArrType_Type (*(PyTypeObject *)PyArray_API[26]) #define PyUIntArrType_Type (*(PyTypeObject *)PyArray_API[27]) #define PyULongArrType_Type (*(PyTypeObject *)PyArray_API[28]) #define PyULongLongArrType_Type (*(PyTypeObject *)PyArray_API[29]) #define PyFloatArrType_Type (*(PyTypeObject *)PyArray_API[30]) #define PyDoubleArrType_Type (*(PyTypeObject *)PyArray_API[31]) #define PyLongDoubleArrType_Type (*(PyTypeObject *)PyArray_API[32]) #define PyCFloatArrType_Type (*(PyTypeObject *)PyArray_API[33]) #define PyCDoubleArrType_Type (*(PyTypeObject *)PyArray_API[34]) #define PyCLongDoubleArrType_Type (*(PyTypeObject *)PyArray_API[35]) #define PyObjectArrType_Type (*(PyTypeObject *)PyArray_API[36]) #define PyStringArrType_Type (*(PyTypeObject *)PyArray_API[37]) #define PyUnicodeArrType_Type (*(PyTypeObject *)PyArray_API[38]) #define PyVoidArrType_Type (*(PyTypeObject *)PyArray_API[39]) #define PyArray_SetNumericOps \ (*(int (*)(PyObject *)) \ PyArray_API[40]) #define PyArray_GetNumericOps \ (*(PyObject * (*)(void)) \ PyArray_API[41]) #define PyArray_INCREF \ (*(int (*)(PyArrayObject *)) \ PyArray_API[42]) #define PyArray_XDECREF \ (*(int (*)(PyArrayObject *)) \ PyArray_API[43]) #define PyArray_SetStringFunction \ (*(void (*)(PyObject *, int)) \ PyArray_API[44]) #define PyArray_DescrFromType \ (*(PyArray_Descr * (*)(int)) \ PyArray_API[45]) #define PyArray_TypeObjectFromType \ (*(PyObject * (*)(int)) \ PyArray_API[46]) #define PyArray_Zero \ (*(char * (*)(PyArrayObject *)) \ PyArray_API[47]) #define PyArray_One \ (*(char * (*)(PyArrayObject *)) \ PyArray_API[48]) #define PyArray_CastToType \ (*(PyObject * (*)(PyArrayObject *, PyArray_Descr *, int)) \ PyArray_API[49]) #define PyArray_CastTo \ (*(int (*)(PyArrayObject *, PyArrayObject *)) \ PyArray_API[50]) #define PyArray_CastAnyTo \ (*(int (*)(PyArrayObject *, PyArrayObject *)) \ PyArray_API[51]) #define PyArray_CanCastSafely \ (*(int (*)(int, int)) \ PyArray_API[52]) #define PyArray_CanCastTo \ (*(npy_bool (*)(PyArray_Descr *, PyArray_Descr *)) \ PyArray_API[53]) #define PyArray_ObjectType \ (*(int (*)(PyObject *, int)) \ PyArray_API[54]) #define PyArray_DescrFromObject \ (*(PyArray_Descr * (*)(PyObject *, PyArray_Descr *)) \ PyArray_API[55]) #define PyArray_ConvertToCommonType \ (*(PyArrayObject ** (*)(PyObject *, int *)) \ PyArray_API[56]) #define PyArray_DescrFromScalar \ (*(PyArray_Descr * (*)(PyObject *)) \ PyArray_API[57]) #define PyArray_DescrFromTypeObject \ (*(PyArray_Descr * (*)(PyObject *)) \ PyArray_API[58]) #define PyArray_Size \ (*(npy_intp (*)(PyObject *)) \ PyArray_API[59]) #define PyArray_Scalar \ (*(PyObject * (*)(void *, PyArray_Descr *, PyObject *)) \ PyArray_API[60]) #define PyArray_FromScalar \ (*(PyObject * (*)(PyObject *, PyArray_Descr *)) \ PyArray_API[61]) #define PyArray_ScalarAsCtype \ (*(void (*)(PyObject *, void *)) \ PyArray_API[62]) #define PyArray_CastScalarToCtype \ (*(int (*)(PyObject *, void *, PyArray_Descr *)) \ PyArray_API[63]) #define PyArray_CastScalarDirect \ (*(int (*)(PyObject *, PyArray_Descr *, void *, int)) \ PyArray_API[64]) #define PyArray_ScalarFromObject \ (*(PyObject * (*)(PyObject *)) \ PyArray_API[65]) #define PyArray_GetCastFunc \ (*(PyArray_VectorUnaryFunc * (*)(PyArray_Descr *, int)) \ PyArray_API[66]) #define PyArray_FromDims \ (*(PyObject * (*)(int, int *, int)) \ PyArray_API[67]) #define PyArray_FromDimsAndDataAndDescr \ (*(PyObject * (*)(int, int *, PyArray_Descr *, char *)) \ PyArray_API[68]) #define PyArray_FromAny \ (*(PyObject * (*)(PyObject *, PyArray_Descr *, int, int, int, PyObject *)) \ PyArray_API[69]) #define PyArray_EnsureArray \ (*(PyObject * (*)(PyObject *)) \ PyArray_API[70]) #define PyArray_EnsureAnyArray \ (*(PyObject * (*)(PyObject *)) \ PyArray_API[71]) #define PyArray_FromFile \ (*(PyObject * (*)(FILE *, PyArray_Descr *, npy_intp, char *)) \ PyArray_API[72]) #define PyArray_FromString \ (*(PyObject * (*)(char *, npy_intp, PyArray_Descr *, npy_intp, char *)) \ PyArray_API[73]) #define PyArray_FromBuffer \ (*(PyObject * (*)(PyObject *, PyArray_Descr *, npy_intp, npy_intp)) \ PyArray_API[74]) #define PyArray_FromIter \ (*(PyObject * (*)(PyObject *, PyArray_Descr *, npy_intp)) \ PyArray_API[75]) #define PyArray_Return \ (*(PyObject * (*)(PyArrayObject *)) \ PyArray_API[76]) #define PyArray_GetField \ (*(PyObject * (*)(PyArrayObject *, PyArray_Descr *, int)) \ PyArray_API[77]) #define PyArray_SetField \ (*(int (*)(PyArrayObject *, PyArray_Descr *, int, PyObject *)) \ PyArray_API[78]) #define PyArray_Byteswap \ (*(PyObject * (*)(PyArrayObject *, npy_bool)) \ PyArray_API[79]) #define PyArray_Resize \ (*(PyObject * (*)(PyArrayObject *, PyArray_Dims *, int, NPY_ORDER)) \ PyArray_API[80]) #define PyArray_MoveInto \ (*(int (*)(PyArrayObject *, PyArrayObject *)) \ PyArray_API[81]) #define PyArray_CopyInto \ (*(int (*)(PyArrayObject *, PyArrayObject *)) \ PyArray_API[82]) #define PyArray_CopyAnyInto \ (*(int (*)(PyArrayObject *, PyArrayObject *)) \ PyArray_API[83]) #define PyArray_CopyObject \ (*(int (*)(PyArrayObject *, PyObject *)) \ PyArray_API[84]) #define PyArray_NewCopy \ (*(PyObject * (*)(PyArrayObject *, NPY_ORDER)) \ PyArray_API[85]) #define PyArray_ToList \ (*(PyObject * (*)(PyArrayObject *)) \ PyArray_API[86]) #define PyArray_ToString \ (*(PyObject * (*)(PyArrayObject *, NPY_ORDER)) \ PyArray_API[87]) #define PyArray_ToFile \ (*(int (*)(PyArrayObject *, FILE *, char *, char *)) \ PyArray_API[88]) #define PyArray_Dump \ (*(int (*)(PyObject *, PyObject *, int)) \ PyArray_API[89]) #define PyArray_Dumps \ (*(PyObject * (*)(PyObject *, int)) \ PyArray_API[90]) #define PyArray_ValidType \ (*(int (*)(int)) \ PyArray_API[91]) #define PyArray_UpdateFlags \ (*(void (*)(PyArrayObject *, int)) \ PyArray_API[92]) #define PyArray_New \ (*(PyObject * (*)(PyTypeObject *, int, npy_intp *, int, npy_intp *, void *, int, int, PyObject *)) \ PyArray_API[93]) #define PyArray_NewFromDescr \ (*(PyObject * (*)(PyTypeObject *, PyArray_Descr *, int, npy_intp *, npy_intp *, void *, int, PyObject *)) \ PyArray_API[94]) #define PyArray_DescrNew \ (*(PyArray_Descr * (*)(PyArray_Descr *)) \ PyArray_API[95]) #define PyArray_DescrNewFromType \ (*(PyArray_Descr * (*)(int)) \ PyArray_API[96]) #define PyArray_GetPriority \ (*(double (*)(PyObject *, double)) \ PyArray_API[97]) #define PyArray_IterNew \ (*(PyObject * (*)(PyObject *)) \ PyArray_API[98]) #define PyArray_MultiIterNew \ (*(PyObject * (*)(int, ...)) \ PyArray_API[99]) #define PyArray_PyIntAsInt \ (*(int (*)(PyObject *)) \ PyArray_API[100]) #define PyArray_PyIntAsIntp \ (*(npy_intp (*)(PyObject *)) \ PyArray_API[101]) #define PyArray_Broadcast \ (*(int (*)(PyArrayMultiIterObject *)) \ PyArray_API[102]) #define PyArray_FillObjectArray \ (*(void (*)(PyArrayObject *, PyObject *)) \ PyArray_API[103]) #define PyArray_FillWithScalar \ (*(int (*)(PyArrayObject *, PyObject *)) \ PyArray_API[104]) #define PyArray_CheckStrides \ (*(npy_bool (*)(int, int, npy_intp, npy_intp, npy_intp *, npy_intp *)) \ PyArray_API[105]) #define PyArray_DescrNewByteorder \ (*(PyArray_Descr * (*)(PyArray_Descr *, char)) \ PyArray_API[106]) #define PyArray_IterAllButAxis \ (*(PyObject * (*)(PyObject *, int *)) \ PyArray_API[107]) #define PyArray_CheckFromAny \ (*(PyObject * (*)(PyObject *, PyArray_Descr *, int, int, int, PyObject *)) \ PyArray_API[108]) #define PyArray_FromArray \ (*(PyObject * (*)(PyArrayObject *, PyArray_Descr *, int)) \ PyArray_API[109]) #define PyArray_FromInterface \ (*(PyObject * (*)(PyObject *)) \ PyArray_API[110]) #define PyArray_FromStructInterface \ (*(PyObject * (*)(PyObject *)) \ PyArray_API[111]) #define PyArray_FromArrayAttr \ (*(PyObject * (*)(PyObject *, PyArray_Descr *, PyObject *)) \ PyArray_API[112]) #define PyArray_ScalarKind \ (*(NPY_SCALARKIND (*)(int, PyArrayObject **)) \ PyArray_API[113]) #define PyArray_CanCoerceScalar \ (*(int (*)(int, int, NPY_SCALARKIND)) \ PyArray_API[114]) #define PyArray_NewFlagsObject \ (*(PyObject * (*)(PyObject *)) \ PyArray_API[115]) #define PyArray_CanCastScalar \ (*(npy_bool (*)(PyTypeObject *, PyTypeObject *)) \ PyArray_API[116]) #define PyArray_CompareUCS4 \ (*(int (*)(npy_ucs4 *, npy_ucs4 *, size_t)) \ PyArray_API[117]) #define PyArray_RemoveSmallest \ (*(int (*)(PyArrayMultiIterObject *)) \ PyArray_API[118]) #define PyArray_ElementStrides \ (*(int (*)(PyObject *)) \ PyArray_API[119]) #define PyArray_Item_INCREF \ (*(void (*)(char *, PyArray_Descr *)) \ PyArray_API[120]) #define PyArray_Item_XDECREF \ (*(void (*)(char *, PyArray_Descr *)) \ PyArray_API[121]) #define PyArray_FieldNames \ (*(PyObject * (*)(PyObject *)) \ PyArray_API[122]) #define PyArray_Transpose \ (*(PyObject * (*)(PyArrayObject *, PyArray_Dims *)) \ PyArray_API[123]) #define PyArray_TakeFrom \ (*(PyObject * (*)(PyArrayObject *, PyObject *, int, PyArrayObject *, NPY_CLIPMODE)) \ PyArray_API[124]) #define PyArray_PutTo \ (*(PyObject * (*)(PyArrayObject *, PyObject*, PyObject *, NPY_CLIPMODE)) \ PyArray_API[125]) #define PyArray_PutMask \ (*(PyObject * (*)(PyArrayObject *, PyObject*, PyObject*)) \ PyArray_API[126]) #define PyArray_Repeat \ (*(PyObject * (*)(PyArrayObject *, PyObject *, int)) \ PyArray_API[127]) #define PyArray_Choose \ (*(PyObject * (*)(PyArrayObject *, PyObject *, PyArrayObject *, NPY_CLIPMODE)) \ PyArray_API[128]) #define PyArray_Sort \ (*(int (*)(PyArrayObject *, int, NPY_SORTKIND)) \ PyArray_API[129]) #define PyArray_ArgSort \ (*(PyObject * (*)(PyArrayObject *, int, NPY_SORTKIND)) \ PyArray_API[130]) #define PyArray_SearchSorted \ (*(PyObject * (*)(PyArrayObject *, PyObject *, NPY_SEARCHSIDE, PyObject *)) \ PyArray_API[131]) #define PyArray_ArgMax \ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \ PyArray_API[132]) #define PyArray_ArgMin \ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \ PyArray_API[133]) #define PyArray_Reshape \ (*(PyObject * (*)(PyArrayObject *, PyObject *)) \ PyArray_API[134]) #define PyArray_Newshape \ (*(PyObject * (*)(PyArrayObject *, PyArray_Dims *, NPY_ORDER)) \ PyArray_API[135]) #define PyArray_Squeeze \ (*(PyObject * (*)(PyArrayObject *)) \ PyArray_API[136]) #define PyArray_View \ (*(PyObject * (*)(PyArrayObject *, PyArray_Descr *, PyTypeObject *)) \ PyArray_API[137]) #define PyArray_SwapAxes \ (*(PyObject * (*)(PyArrayObject *, int, int)) \ PyArray_API[138]) #define PyArray_Max \ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \ PyArray_API[139]) #define PyArray_Min \ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \ PyArray_API[140]) #define PyArray_Ptp \ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \ PyArray_API[141]) #define PyArray_Mean \ (*(PyObject * (*)(PyArrayObject *, int, int, PyArrayObject *)) \ PyArray_API[142]) #define PyArray_Trace \ (*(PyObject * (*)(PyArrayObject *, int, int, int, int, PyArrayObject *)) \ PyArray_API[143]) #define PyArray_Diagonal \ (*(PyObject * (*)(PyArrayObject *, int, int, int)) \ PyArray_API[144]) #define PyArray_Clip \ (*(PyObject * (*)(PyArrayObject *, PyObject *, PyObject *, PyArrayObject *)) \ PyArray_API[145]) #define PyArray_Conjugate \ (*(PyObject * (*)(PyArrayObject *, PyArrayObject *)) \ PyArray_API[146]) #define PyArray_Nonzero \ (*(PyObject * (*)(PyArrayObject *)) \ PyArray_API[147]) #define PyArray_Std \ (*(PyObject * (*)(PyArrayObject *, int, int, PyArrayObject *, int)) \ PyArray_API[148]) #define PyArray_Sum \ (*(PyObject * (*)(PyArrayObject *, int, int, PyArrayObject *)) \ PyArray_API[149]) #define PyArray_CumSum \ (*(PyObject * (*)(PyArrayObject *, int, int, PyArrayObject *)) \ PyArray_API[150]) #define PyArray_Prod \ (*(PyObject * (*)(PyArrayObject *, int, int, PyArrayObject *)) \ PyArray_API[151]) #define PyArray_CumProd \ (*(PyObject * (*)(PyArrayObject *, int, int, PyArrayObject *)) \ PyArray_API[152]) #define PyArray_All \ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \ PyArray_API[153]) #define PyArray_Any \ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \ PyArray_API[154]) #define PyArray_Compress \ (*(PyObject * (*)(PyArrayObject *, PyObject *, int, PyArrayObject *)) \ PyArray_API[155]) #define PyArray_Flatten \ (*(PyObject * (*)(PyArrayObject *, NPY_ORDER)) \ PyArray_API[156]) #define PyArray_Ravel \ (*(PyObject * (*)(PyArrayObject *, NPY_ORDER)) \ PyArray_API[157]) #define PyArray_MultiplyList \ (*(npy_intp (*)(npy_intp *, int)) \ PyArray_API[158]) #define PyArray_MultiplyIntList \ (*(int (*)(int *, int)) \ PyArray_API[159]) #define PyArray_GetPtr \ (*(void * (*)(PyArrayObject *, npy_intp*)) \ PyArray_API[160]) #define PyArray_CompareLists \ (*(int (*)(npy_intp *, npy_intp *, int)) \ PyArray_API[161]) #define PyArray_AsCArray \ (*(int (*)(PyObject **, void *, npy_intp *, int, PyArray_Descr*)) \ PyArray_API[162]) #define PyArray_As1D \ (*(int (*)(PyObject **, char **, int *, int)) \ PyArray_API[163]) #define PyArray_As2D \ (*(int (*)(PyObject **, char ***, int *, int *, int)) \ PyArray_API[164]) #define PyArray_Free \ (*(int (*)(PyObject *, void *)) \ PyArray_API[165]) #define PyArray_Converter \ (*(int (*)(PyObject *, PyObject **)) \ PyArray_API[166]) #define PyArray_IntpFromSequence \ (*(int (*)(PyObject *, npy_intp *, int)) \ PyArray_API[167]) #define PyArray_Concatenate \ (*(PyObject * (*)(PyObject *, int)) \ PyArray_API[168]) #define PyArray_InnerProduct \ (*(PyObject * (*)(PyObject *, PyObject *)) \ PyArray_API[169]) #define PyArray_MatrixProduct \ (*(PyObject * (*)(PyObject *, PyObject *)) \ PyArray_API[170]) #define PyArray_CopyAndTranspose \ (*(PyObject * (*)(PyObject *)) \ PyArray_API[171]) #define PyArray_Correlate \ (*(PyObject * (*)(PyObject *, PyObject *, int)) \ PyArray_API[172]) #define PyArray_TypestrConvert \ (*(int (*)(int, int)) \ PyArray_API[173]) #define PyArray_DescrConverter \ (*(int (*)(PyObject *, PyArray_Descr **)) \ PyArray_API[174]) #define PyArray_DescrConverter2 \ (*(int (*)(PyObject *, PyArray_Descr **)) \ PyArray_API[175]) #define PyArray_IntpConverter \ (*(int (*)(PyObject *, PyArray_Dims *)) \ PyArray_API[176]) #define PyArray_BufferConverter \ (*(int (*)(PyObject *, PyArray_Chunk *)) \ PyArray_API[177]) #define PyArray_AxisConverter \ (*(int (*)(PyObject *, int *)) \ PyArray_API[178]) #define PyArray_BoolConverter \ (*(int (*)(PyObject *, npy_bool *)) \ PyArray_API[179]) #define PyArray_ByteorderConverter \ (*(int (*)(PyObject *, char *)) \ PyArray_API[180]) #define PyArray_OrderConverter \ (*(int (*)(PyObject *, NPY_ORDER *)) \ PyArray_API[181]) #define PyArray_EquivTypes \ (*(unsigned char (*)(PyArray_Descr *, PyArray_Descr *)) \ PyArray_API[182]) #define PyArray_Zeros \ (*(PyObject * (*)(int, npy_intp *, PyArray_Descr *, int)) \ PyArray_API[183]) #define PyArray_Empty \ (*(PyObject * (*)(int, npy_intp *, PyArray_Descr *, int)) \ PyArray_API[184]) #define PyArray_Where \ (*(PyObject * (*)(PyObject *, PyObject *, PyObject *)) \ PyArray_API[185]) #define PyArray_Arange \ (*(PyObject * (*)(double, double, double, int)) \ PyArray_API[186]) #define PyArray_ArangeObj \ (*(PyObject * (*)(PyObject *, PyObject *, PyObject *, PyArray_Descr *)) \ PyArray_API[187]) #define PyArray_SortkindConverter \ (*(int (*)(PyObject *, NPY_SORTKIND *)) \ PyArray_API[188]) #define PyArray_LexSort \ (*(PyObject * (*)(PyObject *, int)) \ PyArray_API[189]) #define PyArray_Round \ (*(PyObject * (*)(PyArrayObject *, int, PyArrayObject *)) \ PyArray_API[190]) #define PyArray_EquivTypenums \ (*(unsigned char (*)(int, int)) \ PyArray_API[191]) #define PyArray_RegisterDataType \ (*(int (*)(PyArray_Descr *)) \ PyArray_API[192]) #define PyArray_RegisterCastFunc \ (*(int (*)(PyArray_Descr *, int, PyArray_VectorUnaryFunc *)) \ PyArray_API[193]) #define PyArray_RegisterCanCast \ (*(int (*)(PyArray_Descr *, int, NPY_SCALARKIND)) \ PyArray_API[194]) #define PyArray_InitArrFuncs \ (*(void (*)(PyArray_ArrFuncs *)) \ PyArray_API[195]) #define PyArray_IntTupleFromIntp \ (*(PyObject * (*)(int, npy_intp *)) \ PyArray_API[196]) #define PyArray_TypeNumFromName \ (*(int (*)(char *)) \ PyArray_API[197]) #define PyArray_ClipmodeConverter \ (*(int (*)(PyObject *, NPY_CLIPMODE *)) \ PyArray_API[198]) #define PyArray_OutputConverter \ (*(int (*)(PyObject *, PyArrayObject **)) \ PyArray_API[199]) #define PyArray_BroadcastToShape \ (*(PyObject * (*)(PyObject *, npy_intp *, int)) \ PyArray_API[200]) #define _PyArray_SigintHandler \ (*(void (*)(int)) \ PyArray_API[201]) #define _PyArray_GetSigintBuf \ (*(void* (*)(void)) \ PyArray_API[202]) #define PyArray_DescrAlignConverter \ (*(int (*)(PyObject *, PyArray_Descr **)) \ PyArray_API[203]) #define PyArray_DescrAlignConverter2 \ (*(int (*)(PyObject *, PyArray_Descr **)) \ PyArray_API[204]) #define PyArray_SearchsideConverter \ (*(int (*)(PyObject *, void *)) \ PyArray_API[205]) #define PyArray_CheckAxis \ (*(PyObject * (*)(PyArrayObject *, int *, int)) \ PyArray_API[206]) #define PyArray_OverflowMultiplyList \ (*(npy_intp (*)(npy_intp *, int)) \ PyArray_API[207]) #define PyArray_CompareString \ (*(int (*)(char *, char *, size_t)) \ PyArray_API[208]) #define PyArray_MultiIterFromObjects \ (*(PyObject * (*)(PyObject **, int, int, ...)) \ PyArray_API[209]) #define PyArray_GetEndianness \ (*(int (*)(void)) \ PyArray_API[210]) #define PyArray_GetNDArrayCFeatureVersion \ (*(unsigned int (*)(void)) \ PyArray_API[211]) #define PyArray_Correlate2 \ (*(PyObject * (*)(PyObject *, PyObject *, int)) \ PyArray_API[212]) #define PyArray_NeighborhoodIterNew \ (*(PyObject* (*)(PyArrayIterObject *, npy_intp *, int, PyArrayObject*)) \ PyArray_API[213]) #define PyTimeIntegerArrType_Type (*(PyTypeObject *)PyArray_API[214]) #define PyDatetimeArrType_Type (*(PyTypeObject *)PyArray_API[215]) #define PyTimedeltaArrType_Type (*(PyTypeObject *)PyArray_API[216]) #define PyHalfArrType_Type (*(PyTypeObject *)PyArray_API[217]) #define NpyIter_Type (*(PyTypeObject *)PyArray_API[218]) #define PyArray_SetDatetimeParseFunction \ (*(void (*)(PyObject *)) \ PyArray_API[219]) #define PyArray_DatetimeToDatetimeStruct \ (*(void (*)(npy_datetime, NPY_DATETIMEUNIT, npy_datetimestruct *)) \ PyArray_API[220]) #define PyArray_TimedeltaToTimedeltaStruct \ (*(void (*)(npy_timedelta, NPY_DATETIMEUNIT, npy_timedeltastruct *)) \ PyArray_API[221]) #define PyArray_DatetimeStructToDatetime \ (*(npy_datetime (*)(NPY_DATETIMEUNIT, npy_datetimestruct *)) \ PyArray_API[222]) #define PyArray_TimedeltaStructToTimedelta \ (*(npy_datetime (*)(NPY_DATETIMEUNIT, npy_timedeltastruct *)) \ PyArray_API[223]) #define NpyIter_New \ (*(NpyIter * (*)(PyArrayObject *, npy_uint32, NPY_ORDER, NPY_CASTING, PyArray_Descr*)) \ PyArray_API[224]) #define NpyIter_MultiNew \ (*(NpyIter * (*)(int, PyArrayObject **, npy_uint32, NPY_ORDER, NPY_CASTING, npy_uint32 *, PyArray_Descr **)) \ PyArray_API[225]) #define NpyIter_AdvancedNew \ (*(NpyIter * (*)(int, PyArrayObject **, npy_uint32, NPY_ORDER, NPY_CASTING, npy_uint32 *, PyArray_Descr **, int, int **, npy_intp *, npy_intp)) \ PyArray_API[226]) #define NpyIter_Copy \ (*(NpyIter * (*)(NpyIter *)) \ PyArray_API[227]) #define NpyIter_Deallocate \ (*(int (*)(NpyIter *)) \ PyArray_API[228]) #define NpyIter_HasDelayedBufAlloc \ (*(npy_bool (*)(NpyIter *)) \ PyArray_API[229]) #define NpyIter_HasExternalLoop \ (*(npy_bool (*)(NpyIter *)) \ PyArray_API[230]) #define NpyIter_EnableExternalLoop \ (*(int (*)(NpyIter *)) \ PyArray_API[231]) #define NpyIter_GetInnerStrideArray \ (*(npy_intp * (*)(NpyIter *)) \ PyArray_API[232]) #define NpyIter_GetInnerLoopSizePtr \ (*(npy_intp * (*)(NpyIter *)) \ PyArray_API[233]) #define NpyIter_Reset \ (*(int (*)(NpyIter *, char **)) \ PyArray_API[234]) #define NpyIter_ResetBasePointers \ (*(int (*)(NpyIter *, char **, char **)) \ PyArray_API[235]) #define NpyIter_ResetToIterIndexRange \ (*(int (*)(NpyIter *, npy_intp, npy_intp, char **)) \ PyArray_API[236]) #define NpyIter_GetNDim \ (*(int (*)(NpyIter *)) \ PyArray_API[237]) #define NpyIter_GetNOp \ (*(int (*)(NpyIter *)) \ PyArray_API[238]) #define NpyIter_GetIterNext \ (*(NpyIter_IterNextFunc * (*)(NpyIter *, char **)) \ PyArray_API[239]) #define NpyIter_GetIterSize \ (*(npy_intp (*)(NpyIter *)) \ PyArray_API[240]) #define NpyIter_GetIterIndexRange \ (*(void (*)(NpyIter *, npy_intp *, npy_intp *)) \ PyArray_API[241]) #define NpyIter_GetIterIndex \ (*(npy_intp (*)(NpyIter *)) \ PyArray_API[242]) #define NpyIter_GotoIterIndex \ (*(int (*)(NpyIter *, npy_intp)) \ PyArray_API[243]) #define NpyIter_HasMultiIndex \ (*(npy_bool (*)(NpyIter *)) \ PyArray_API[244]) #define NpyIter_GetShape \ (*(int (*)(NpyIter *, npy_intp *)) \ PyArray_API[245]) #define NpyIter_GetGetMultiIndex \ (*(NpyIter_GetMultiIndexFunc * (*)(NpyIter *, char **)) \ PyArray_API[246]) #define NpyIter_GotoMultiIndex \ (*(int (*)(NpyIter *, npy_intp *)) \ PyArray_API[247]) #define NpyIter_RemoveMultiIndex \ (*(int (*)(NpyIter *)) \ PyArray_API[248]) #define NpyIter_HasIndex \ (*(npy_bool (*)(NpyIter *)) \ PyArray_API[249]) #define NpyIter_IsBuffered \ (*(npy_bool (*)(NpyIter *)) \ PyArray_API[250]) #define NpyIter_IsGrowInner \ (*(npy_bool (*)(NpyIter *)) \ PyArray_API[251]) #define NpyIter_GetBufferSize \ (*(npy_intp (*)(NpyIter *)) \ PyArray_API[252]) #define NpyIter_GetIndexPtr \ (*(npy_intp * (*)(NpyIter *)) \ PyArray_API[253]) #define NpyIter_GotoIndex \ (*(int (*)(NpyIter *, npy_intp)) \ PyArray_API[254]) #define NpyIter_GetDataPtrArray \ (*(char ** (*)(NpyIter *)) \ PyArray_API[255]) #define NpyIter_GetDescrArray \ (*(PyArray_Descr ** (*)(NpyIter *)) \ PyArray_API[256]) #define NpyIter_GetOperandArray \ (*(PyArrayObject ** (*)(NpyIter *)) \ PyArray_API[257]) #define NpyIter_GetIterView \ (*(PyArrayObject * (*)(NpyIter *, npy_intp)) \ PyArray_API[258]) #define NpyIter_GetReadFlags \ (*(void (*)(NpyIter *, char *)) \ PyArray_API[259]) #define NpyIter_GetWriteFlags \ (*(void (*)(NpyIter *, char *)) \ PyArray_API[260]) #define NpyIter_DebugPrint \ (*(void (*)(NpyIter *)) \ PyArray_API[261]) #define NpyIter_IterationNeedsAPI \ (*(npy_bool (*)(NpyIter *)) \ PyArray_API[262]) #define NpyIter_GetInnerFixedStrideArray \ (*(void (*)(NpyIter *, npy_intp *)) \ PyArray_API[263]) #define NpyIter_RemoveAxis \ (*(int (*)(NpyIter *, int)) \ PyArray_API[264]) #define NpyIter_GetAxisStrideArray \ (*(npy_intp * (*)(NpyIter *, int)) \ PyArray_API[265]) #define NpyIter_RequiresBuffering \ (*(npy_bool (*)(NpyIter *)) \ PyArray_API[266]) #define NpyIter_GetInitialDataPtrArray \ (*(char ** (*)(NpyIter *)) \ PyArray_API[267]) #define NpyIter_CreateCompatibleStrides \ (*(int (*)(NpyIter *, npy_intp, npy_intp *)) \ PyArray_API[268]) #define PyArray_CastingConverter \ (*(int (*)(PyObject *, NPY_CASTING *)) \ PyArray_API[269]) #define PyArray_CountNonzero \ (*(npy_intp (*)(PyArrayObject *)) \ PyArray_API[270]) #define PyArray_PromoteTypes \ (*(PyArray_Descr * (*)(PyArray_Descr *, PyArray_Descr *)) \ PyArray_API[271]) #define PyArray_MinScalarType \ (*(PyArray_Descr * (*)(PyArrayObject *)) \ PyArray_API[272]) #define PyArray_ResultType \ (*(PyArray_Descr * (*)(npy_intp, PyArrayObject **, npy_intp, PyArray_Descr **)) \ PyArray_API[273]) #define PyArray_CanCastArrayTo \ (*(npy_bool (*)(PyArrayObject *, PyArray_Descr *, NPY_CASTING)) \ PyArray_API[274]) #define PyArray_CanCastTypeTo \ (*(npy_bool (*)(PyArray_Descr *, PyArray_Descr *, NPY_CASTING)) \ PyArray_API[275]) #define PyArray_EinsteinSum \ (*(PyArrayObject * (*)(char *, npy_intp, PyArrayObject **, PyArray_Descr *, NPY_ORDER, NPY_CASTING, PyArrayObject *)) \ PyArray_API[276]) #define PyArray_NewLikeArray \ (*(PyObject * (*)(PyArrayObject *, NPY_ORDER, PyArray_Descr *, int)) \ PyArray_API[277]) #define PyArray_GetArrayParamsFromObject \ (*(int (*)(PyObject *, PyArray_Descr *, npy_bool, PyArray_Descr **, int *, npy_intp *, PyArrayObject **, PyObject *)) \ PyArray_API[278]) #define PyArray_ConvertClipmodeSequence \ (*(int (*)(PyObject *, NPY_CLIPMODE *, int)) \ PyArray_API[279]) #define PyArray_MatrixProduct2 \ (*(PyObject * (*)(PyObject *, PyObject *, PyArrayObject*)) \ PyArray_API[280]) #define NpyIter_IsFirstVisit \ (*(npy_bool (*)(NpyIter *, int)) \ PyArray_API[281]) #define PyArray_SetBaseObject \ (*(int (*)(PyArrayObject *, PyObject *)) \ PyArray_API[282]) #define PyArray_CreateSortedStridePerm \ (*(void (*)(int, npy_intp *, npy_stride_sort_item *)) \ PyArray_API[283]) #define PyArray_RemoveAxesInPlace \ (*(void (*)(PyArrayObject *, npy_bool *)) \ PyArray_API[284]) #define PyArray_DebugPrint \ (*(void (*)(PyArrayObject *)) \ PyArray_API[285]) #define PyArray_FailUnlessWriteable \ (*(int (*)(PyArrayObject *, const char *)) \ PyArray_API[286]) #define PyArray_SetUpdateIfCopyBase \ (*(int (*)(PyArrayObject *, PyArrayObject *)) \ PyArray_API[287]) #define PyDataMem_NEW \ (*(void * (*)(size_t)) \ PyArray_API[288]) #define PyDataMem_FREE \ (*(void (*)(void *)) \ PyArray_API[289]) #define PyDataMem_RENEW \ (*(void * (*)(void *, size_t)) \ PyArray_API[290]) #define PyDataMem_SetEventHook \ (*(PyDataMem_EventHookFunc * (*)(PyDataMem_EventHookFunc *, void *, void **)) \ PyArray_API[291]) #define NPY_DEFAULT_ASSIGN_CASTING (*(NPY_CASTING *)PyArray_API[292]) #define PyArray_MapIterSwapAxes \ (*(void (*)(PyArrayMapIterObject *, PyArrayObject **, int)) \ PyArray_API[293]) #define PyArray_MapIterArray \ (*(PyObject * (*)(PyArrayObject *, PyObject *)) \ PyArray_API[294]) #define PyArray_MapIterNext \ (*(void (*)(PyArrayMapIterObject *)) \ PyArray_API[295]) #define PyArray_Partition \ (*(int (*)(PyArrayObject *, PyArrayObject *, int, NPY_SELECTKIND)) \ PyArray_API[296]) #define PyArray_ArgPartition \ (*(PyObject * (*)(PyArrayObject *, PyArrayObject *, int, NPY_SELECTKIND)) \ PyArray_API[297]) #define PyArray_SelectkindConverter \ (*(int (*)(PyObject *, NPY_SELECTKIND *)) \ PyArray_API[298]) #define PyDataMem_NEW_ZEROED \ (*(void * (*)(size_t, size_t)) \ PyArray_API[299]) #define PyArray_CheckAnyScalarExact \ (*(int (*)(PyObject *)) \ PyArray_API[300]) #define PyArray_MapIterArrayCopyIfOverlap \ (*(PyObject * (*)(PyArrayObject *, PyObject *, int, PyArrayObject *)) \ PyArray_API[301]) #define PyArray_ResolveWritebackIfCopy \ (*(int (*)(PyArrayObject *)) \ PyArray_API[302]) #define PyArray_SetWritebackIfCopyBase \ (*(int (*)(PyArrayObject *, PyArrayObject *)) \ PyArray_API[303]) #if !defined(NO_IMPORT_ARRAY) && !defined(NO_IMPORT) static int _import_array(void) { int st; PyObject *numpy = PyImport_ImportModule("numpy.core.multiarray"); PyObject *c_api = NULL; if (numpy == NULL) { PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return -1; } c_api = PyObject_GetAttrString(numpy, "_ARRAY_API"); Py_DECREF(numpy); if (c_api == NULL) { PyErr_SetString(PyExc_AttributeError, "_ARRAY_API not found"); return -1; } #if PY_VERSION_HEX >= 0x03000000 if (!PyCapsule_CheckExact(c_api)) { PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is not PyCapsule object"); Py_DECREF(c_api); return -1; } PyArray_API = (void **)PyCapsule_GetPointer(c_api, NULL); #else if (!PyCObject_Check(c_api)) { PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is not PyCObject object"); Py_DECREF(c_api); return -1; } PyArray_API = (void **)PyCObject_AsVoidPtr(c_api); #endif Py_DECREF(c_api); if (PyArray_API == NULL) { PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is NULL pointer"); return -1; } /* Perform runtime check of C API version */ if (NPY_VERSION != PyArray_GetNDArrayCVersion()) { PyErr_Format(PyExc_RuntimeError, "module compiled against "\ "ABI version 0x%x but this version of numpy is 0x%x", \ (int) NPY_VERSION, (int) PyArray_GetNDArrayCVersion()); return -1; } if (NPY_FEATURE_VERSION > PyArray_GetNDArrayCFeatureVersion()) { PyErr_Format(PyExc_RuntimeError, "module compiled against "\ "API version 0x%x but this version of numpy is 0x%x", \ (int) NPY_FEATURE_VERSION, (int) PyArray_GetNDArrayCFeatureVersion()); return -1; } /* * Perform runtime check of endianness and check it matches the one set by * the headers (npy_endian.h) as a safeguard */ st = PyArray_GetEndianness(); if (st == NPY_CPU_UNKNOWN_ENDIAN) { PyErr_Format(PyExc_RuntimeError, "FATAL: module compiled as unknown endian"); return -1; } #if NPY_BYTE_ORDER == NPY_BIG_ENDIAN if (st != NPY_CPU_BIG) { PyErr_Format(PyExc_RuntimeError, "FATAL: module compiled as "\ "big endian, but detected different endianness at runtime"); return -1; } #elif NPY_BYTE_ORDER == NPY_LITTLE_ENDIAN if (st != NPY_CPU_LITTLE) { PyErr_Format(PyExc_RuntimeError, "FATAL: module compiled as "\ "little endian, but detected different endianness at runtime"); return -1; } #endif return 0; } #if PY_VERSION_HEX >= 0x03000000 #define NUMPY_IMPORT_ARRAY_RETVAL NULL #else #define NUMPY_IMPORT_ARRAY_RETVAL #endif #define import_array() {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return NUMPY_IMPORT_ARRAY_RETVAL; } } #define import_array1(ret) {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return ret; } } #define import_array2(msg, ret) {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, msg); return ret; } } #endif #endif
61,035
38.226221
180
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/core/include/numpy/__ufunc_api.h
#ifdef _UMATHMODULE extern NPY_NO_EXPORT PyTypeObject PyUFunc_Type; extern NPY_NO_EXPORT PyTypeObject PyUFunc_Type; NPY_NO_EXPORT PyObject * PyUFunc_FromFuncAndData \ (PyUFuncGenericFunction *, void **, char *, int, int, int, int, const char *, const char *, int); NPY_NO_EXPORT int PyUFunc_RegisterLoopForType \ (PyUFuncObject *, int, PyUFuncGenericFunction, int *, void *); NPY_NO_EXPORT int PyUFunc_GenericFunction \ (PyUFuncObject *, PyObject *, PyObject *, PyArrayObject **); NPY_NO_EXPORT void PyUFunc_f_f_As_d_d \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_d_d \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_f_f \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_g_g \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_F_F_As_D_D \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_F_F \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_D_D \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_G_G \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_O_O \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_ff_f_As_dd_d \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_ff_f \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_dd_d \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_gg_g \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_FF_F_As_DD_D \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_DD_D \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_FF_F \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_GG_G \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_OO_O \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_O_O_method \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_OO_O_method \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_On_Om \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT int PyUFunc_GetPyValues \ (char *, int *, int *, PyObject **); NPY_NO_EXPORT int PyUFunc_checkfperr \ (int, PyObject *, int *); NPY_NO_EXPORT void PyUFunc_clearfperr \ (void); NPY_NO_EXPORT int PyUFunc_getfperr \ (void); NPY_NO_EXPORT int PyUFunc_handlefperr \ (int, PyObject *, int, int *); NPY_NO_EXPORT int PyUFunc_ReplaceLoopBySignature \ (PyUFuncObject *, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *); NPY_NO_EXPORT PyObject * PyUFunc_FromFuncAndDataAndSignature \ (PyUFuncGenericFunction *, void **, char *, int, int, int, int, const char *, const char *, int, const char *); NPY_NO_EXPORT int PyUFunc_SetUsesArraysAsData \ (void **, size_t); NPY_NO_EXPORT void PyUFunc_e_e \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_e_e_As_f_f \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_e_e_As_d_d \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_ee_e \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_ee_e_As_ff_f \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT void PyUFunc_ee_e_As_dd_d \ (char **, npy_intp *, npy_intp *, void *); NPY_NO_EXPORT int PyUFunc_DefaultTypeResolver \ (PyUFuncObject *, NPY_CASTING, PyArrayObject **, PyObject *, PyArray_Descr **); NPY_NO_EXPORT int PyUFunc_ValidateCasting \ (PyUFuncObject *, NPY_CASTING, PyArrayObject **, PyArray_Descr **); NPY_NO_EXPORT int PyUFunc_RegisterLoopForDescr \ (PyUFuncObject *, PyArray_Descr *, PyUFuncGenericFunction, PyArray_Descr **, void *); #else #if defined(PY_UFUNC_UNIQUE_SYMBOL) #define PyUFunc_API PY_UFUNC_UNIQUE_SYMBOL #endif #if defined(NO_IMPORT) || defined(NO_IMPORT_UFUNC) extern void **PyUFunc_API; #else #if defined(PY_UFUNC_UNIQUE_SYMBOL) void **PyUFunc_API; #else static void **PyUFunc_API=NULL; #endif #endif #define PyUFunc_Type (*(PyTypeObject *)PyUFunc_API[0]) #define PyUFunc_FromFuncAndData \ (*(PyObject * (*)(PyUFuncGenericFunction *, void **, char *, int, int, int, int, const char *, const char *, int)) \ PyUFunc_API[1]) #define PyUFunc_RegisterLoopForType \ (*(int (*)(PyUFuncObject *, int, PyUFuncGenericFunction, int *, void *)) \ PyUFunc_API[2]) #define PyUFunc_GenericFunction \ (*(int (*)(PyUFuncObject *, PyObject *, PyObject *, PyArrayObject **)) \ PyUFunc_API[3]) #define PyUFunc_f_f_As_d_d \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[4]) #define PyUFunc_d_d \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[5]) #define PyUFunc_f_f \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[6]) #define PyUFunc_g_g \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[7]) #define PyUFunc_F_F_As_D_D \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[8]) #define PyUFunc_F_F \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[9]) #define PyUFunc_D_D \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[10]) #define PyUFunc_G_G \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[11]) #define PyUFunc_O_O \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[12]) #define PyUFunc_ff_f_As_dd_d \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[13]) #define PyUFunc_ff_f \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[14]) #define PyUFunc_dd_d \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[15]) #define PyUFunc_gg_g \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[16]) #define PyUFunc_FF_F_As_DD_D \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[17]) #define PyUFunc_DD_D \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[18]) #define PyUFunc_FF_F \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[19]) #define PyUFunc_GG_G \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[20]) #define PyUFunc_OO_O \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[21]) #define PyUFunc_O_O_method \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[22]) #define PyUFunc_OO_O_method \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[23]) #define PyUFunc_On_Om \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[24]) #define PyUFunc_GetPyValues \ (*(int (*)(char *, int *, int *, PyObject **)) \ PyUFunc_API[25]) #define PyUFunc_checkfperr \ (*(int (*)(int, PyObject *, int *)) \ PyUFunc_API[26]) #define PyUFunc_clearfperr \ (*(void (*)(void)) \ PyUFunc_API[27]) #define PyUFunc_getfperr \ (*(int (*)(void)) \ PyUFunc_API[28]) #define PyUFunc_handlefperr \ (*(int (*)(int, PyObject *, int, int *)) \ PyUFunc_API[29]) #define PyUFunc_ReplaceLoopBySignature \ (*(int (*)(PyUFuncObject *, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *)) \ PyUFunc_API[30]) #define PyUFunc_FromFuncAndDataAndSignature \ (*(PyObject * (*)(PyUFuncGenericFunction *, void **, char *, int, int, int, int, const char *, const char *, int, const char *)) \ PyUFunc_API[31]) #define PyUFunc_SetUsesArraysAsData \ (*(int (*)(void **, size_t)) \ PyUFunc_API[32]) #define PyUFunc_e_e \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[33]) #define PyUFunc_e_e_As_f_f \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[34]) #define PyUFunc_e_e_As_d_d \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[35]) #define PyUFunc_ee_e \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[36]) #define PyUFunc_ee_e_As_ff_f \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[37]) #define PyUFunc_ee_e_As_dd_d \ (*(void (*)(char **, npy_intp *, npy_intp *, void *)) \ PyUFunc_API[38]) #define PyUFunc_DefaultTypeResolver \ (*(int (*)(PyUFuncObject *, NPY_CASTING, PyArrayObject **, PyObject *, PyArray_Descr **)) \ PyUFunc_API[39]) #define PyUFunc_ValidateCasting \ (*(int (*)(PyUFuncObject *, NPY_CASTING, PyArrayObject **, PyArray_Descr **)) \ PyUFunc_API[40]) #define PyUFunc_RegisterLoopForDescr \ (*(int (*)(PyUFuncObject *, PyArray_Descr *, PyUFuncGenericFunction, PyArray_Descr **, void *)) \ PyUFunc_API[41]) static NPY_INLINE int _import_umath(void) { PyObject *numpy = PyImport_ImportModule("numpy.core.umath"); PyObject *c_api = NULL; if (numpy == NULL) { PyErr_SetString(PyExc_ImportError, "numpy.core.umath failed to import"); return -1; } c_api = PyObject_GetAttrString(numpy, "_UFUNC_API"); Py_DECREF(numpy); if (c_api == NULL) { PyErr_SetString(PyExc_AttributeError, "_UFUNC_API not found"); return -1; } #if PY_VERSION_HEX >= 0x03000000 if (!PyCapsule_CheckExact(c_api)) { PyErr_SetString(PyExc_RuntimeError, "_UFUNC_API is not PyCapsule object"); Py_DECREF(c_api); return -1; } PyUFunc_API = (void **)PyCapsule_GetPointer(c_api, NULL); #else if (!PyCObject_Check(c_api)) { PyErr_SetString(PyExc_RuntimeError, "_UFUNC_API is not PyCObject object"); Py_DECREF(c_api); return -1; } PyUFunc_API = (void **)PyCObject_AsVoidPtr(c_api); #endif Py_DECREF(c_api); if (PyUFunc_API == NULL) { PyErr_SetString(PyExc_RuntimeError, "_UFUNC_API is NULL pointer"); return -1; } return 0; } #if PY_VERSION_HEX >= 0x03000000 #define NUMPY_IMPORT_UMATH_RETVAL NULL #else #define NUMPY_IMPORT_UMATH_RETVAL #endif #define import_umath() \ do {\ UFUNC_NOFPE\ if (_import_umath() < 0) {\ PyErr_Print();\ PyErr_SetString(PyExc_ImportError,\ "numpy.core.umath failed to import");\ return NUMPY_IMPORT_UMATH_RETVAL;\ }\ } while(0) #define import_umath1(ret) \ do {\ UFUNC_NOFPE\ if (_import_umath() < 0) {\ PyErr_Print();\ PyErr_SetString(PyExc_ImportError,\ "numpy.core.umath failed to import");\ return ret;\ }\ } while(0) #define import_umath2(ret, msg) \ do {\ UFUNC_NOFPE\ if (_import_umath() < 0) {\ PyErr_Print();\ PyErr_SetString(PyExc_ImportError, msg);\ return ret;\ }\ } while(0) #define import_ufunc() \ do {\ UFUNC_NOFPE\ if (_import_umath() < 0) {\ PyErr_Print();\ PyErr_SetString(PyExc_ImportError,\ "numpy.core.umath failed to import");\ }\ } while(0) #endif
11,657
35.317757
138
h
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/ccompiler.py
from __future__ import division, absolute_import, print_function import os import re import sys import types import shlex import time from copy import copy from distutils import ccompiler from distutils.ccompiler import * from distutils.errors import DistutilsExecError, DistutilsModuleError, \ DistutilsPlatformError, CompileError from distutils.sysconfig import customize_compiler from distutils.version import LooseVersion from numpy.distutils import log from numpy.distutils.compat import get_exception from numpy.distutils.exec_command import exec_command from numpy.distutils.misc_util import cyg2win32, is_sequence, mingw32, \ quote_args, get_num_build_jobs, \ _commandline_dep_string # globals for parallel build management try: import threading except ImportError: import dummy_threading as threading _job_semaphore = None _global_lock = threading.Lock() _processing_files = set() def _needs_build(obj, cc_args, extra_postargs, pp_opts): """ Check if an objects needs to be rebuild based on its dependencies Parameters ---------- obj : str object file Returns ------- bool """ # defined in unixcompiler.py dep_file = obj + '.d' if not os.path.exists(dep_file): return True # dep_file is a makefile containing 'object: dependencies' # formated like posix shell (spaces escaped, \ line continuations) # the last line contains the compiler commandline arguments as some # projects may compile an extension multiple times with different # arguments with open(dep_file, "r") as f: lines = f.readlines() cmdline =_commandline_dep_string(cc_args, extra_postargs, pp_opts) last_cmdline = lines[-1] if last_cmdline != cmdline: return True contents = ''.join(lines[:-1]) deps = [x for x in shlex.split(contents, posix=True) if x != "\n" and not x.endswith(":")] try: t_obj = os.stat(obj).st_mtime # check if any of the dependencies is newer than the object # the dependencies includes the source used to create the object for f in deps: if os.stat(f).st_mtime > t_obj: return True except OSError: # no object counts as newer (shouldn't happen if dep_file exists) return True return False def replace_method(klass, method_name, func): if sys.version_info[0] < 3: m = types.MethodType(func, None, klass) else: # Py3k does not have unbound method anymore, MethodType does not work m = lambda self, *args, **kw: func(self, *args, **kw) setattr(klass, method_name, m) ###################################################################### ## Method that subclasses may redefine. But don't call this method, ## it i private to CCompiler class and may return unexpected ## results if used elsewhere. So, you have been warned.. def CCompiler_find_executables(self): """ Does nothing here, but is called by the get_version method and can be overridden by subclasses. In particular it is redefined in the `FCompiler` class where more documentation can be found. """ pass replace_method(CCompiler, 'find_executables', CCompiler_find_executables) # Using customized CCompiler.spawn. def CCompiler_spawn(self, cmd, display=None): """ Execute a command in a sub-process. Parameters ---------- cmd : str The command to execute. display : str or sequence of str, optional The text to add to the log file kept by `numpy.distutils`. If not given, `display` is equal to `cmd`. Returns ------- None Raises ------ DistutilsExecError If the command failed, i.e. the exit status was not 0. """ if display is None: display = cmd if is_sequence(display): display = ' '.join(list(display)) log.info(display) s, o = exec_command(cmd) if s: if is_sequence(cmd): cmd = ' '.join(list(cmd)) try: print(o) except UnicodeError: # When installing through pip, `o` can contain non-ascii chars pass if re.search('Too many open files', o): msg = '\nTry rerunning setup command until build succeeds.' else: msg = '' raise DistutilsExecError('Command "%s" failed with exit status %d%s' % (cmd, s, msg)) replace_method(CCompiler, 'spawn', CCompiler_spawn) def CCompiler_object_filenames(self, source_filenames, strip_dir=0, output_dir=''): """ Return the name of the object files for the given source files. Parameters ---------- source_filenames : list of str The list of paths to source files. Paths can be either relative or absolute, this is handled transparently. strip_dir : bool, optional Whether to strip the directory from the returned paths. If True, the file name prepended by `output_dir` is returned. Default is False. output_dir : str, optional If given, this path is prepended to the returned paths to the object files. Returns ------- obj_names : list of str The list of paths to the object files corresponding to the source files in `source_filenames`. """ if output_dir is None: output_dir = '' obj_names = [] for src_name in source_filenames: base, ext = os.path.splitext(os.path.normpath(src_name)) base = os.path.splitdrive(base)[1] # Chop off the drive base = base[os.path.isabs(base):] # If abs, chop off leading / if base.startswith('..'): # Resolve starting relative path components, middle ones # (if any) have been handled by os.path.normpath above. i = base.rfind('..')+2 d = base[:i] d = os.path.basename(os.path.abspath(d)) base = d + base[i:] if ext not in self.src_extensions: raise UnknownFileError("unknown file type '%s' (from '%s')" % (ext, src_name)) if strip_dir: base = os.path.basename(base) obj_name = os.path.join(output_dir, base + self.obj_extension) obj_names.append(obj_name) return obj_names replace_method(CCompiler, 'object_filenames', CCompiler_object_filenames) def CCompiler_compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None): """ Compile one or more source files. Please refer to the Python distutils API reference for more details. Parameters ---------- sources : list of str A list of filenames output_dir : str, optional Path to the output directory. macros : list of tuples A list of macro definitions. include_dirs : list of str, optional The directories to add to the default include file search path for this compilation only. debug : bool, optional Whether or not to output debug symbols in or alongside the object file(s). extra_preargs, extra_postargs : ? Extra pre- and post-arguments. depends : list of str, optional A list of file names that all targets depend on. Returns ------- objects : list of str A list of object file names, one per source file `sources`. Raises ------ CompileError If compilation fails. """ # This method is effective only with Python >=2.3 distutils. # Any changes here should be applied also to fcompiler.compile # method to support pre Python 2.3 distutils. global _job_semaphore jobs = get_num_build_jobs() # setup semaphore to not exceed number of compile jobs when parallelized at # extension level (python >= 3.5) with _global_lock: if _job_semaphore is None: _job_semaphore = threading.Semaphore(jobs) if not sources: return [] # FIXME:RELATIVE_IMPORT if sys.version_info[0] < 3: from .fcompiler import FCompiler, is_f_file, has_f90_header else: from numpy.distutils.fcompiler import (FCompiler, is_f_file, has_f90_header) if isinstance(self, FCompiler): display = [] for fc in ['f77', 'f90', 'fix']: fcomp = getattr(self, 'compiler_'+fc) if fcomp is None: continue display.append("Fortran %s compiler: %s" % (fc, ' '.join(fcomp))) display = '\n'.join(display) else: ccomp = self.compiler_so display = "C compiler: %s\n" % (' '.join(ccomp),) log.info(display) macros, objects, extra_postargs, pp_opts, build = \ self._setup_compile(output_dir, macros, include_dirs, sources, depends, extra_postargs) cc_args = self._get_cc_args(pp_opts, debug, extra_preargs) display = "compile options: '%s'" % (' '.join(cc_args)) if extra_postargs: display += "\nextra options: '%s'" % (' '.join(extra_postargs)) log.info(display) def single_compile(args): obj, (src, ext) = args if not _needs_build(obj, cc_args, extra_postargs, pp_opts): return # check if we are currently already processing the same object # happens when using the same source in multiple extensions while True: # need explicit lock as there is no atomic check and add with GIL with _global_lock: # file not being worked on, start working if obj not in _processing_files: _processing_files.add(obj) break # wait for the processing to end time.sleep(0.1) try: # retrieve slot from our #job semaphore and build with _job_semaphore: self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) finally: # register being done processing with _global_lock: _processing_files.remove(obj) if isinstance(self, FCompiler): objects_to_build = list(build.keys()) f77_objects, other_objects = [], [] for obj in objects: if obj in objects_to_build: src, ext = build[obj] if self.compiler_type=='absoft': obj = cyg2win32(obj) src = cyg2win32(src) if is_f_file(src) and not has_f90_header(src): f77_objects.append((obj, (src, ext))) else: other_objects.append((obj, (src, ext))) # f77 objects can be built in parallel build_items = f77_objects # build f90 modules serial, module files are generated during # compilation and may be used by files later in the list so the # ordering is important for o in other_objects: single_compile(o) else: build_items = build.items() if len(build) > 1 and jobs > 1: # build parallel import multiprocessing.pool pool = multiprocessing.pool.ThreadPool(jobs) pool.map(single_compile, build_items) pool.close() else: # build serial for o in build_items: single_compile(o) # Return *all* object filenames, not just the ones we just built. return objects replace_method(CCompiler, 'compile', CCompiler_compile) def CCompiler_customize_cmd(self, cmd, ignore=()): """ Customize compiler using distutils command. Parameters ---------- cmd : class instance An instance inheriting from `distutils.cmd.Command`. ignore : sequence of str, optional List of `CCompiler` commands (without ``'set_'``) that should not be altered. Strings that are checked for are: ``('include_dirs', 'define', 'undef', 'libraries', 'library_dirs', 'rpath', 'link_objects')``. Returns ------- None """ log.info('customize %s using %s' % (self.__class__.__name__, cmd.__class__.__name__)) def allow(attr): return getattr(cmd, attr, None) is not None and attr not in ignore if allow('include_dirs'): self.set_include_dirs(cmd.include_dirs) if allow('define'): for (name, value) in cmd.define: self.define_macro(name, value) if allow('undef'): for macro in cmd.undef: self.undefine_macro(macro) if allow('libraries'): self.set_libraries(self.libraries + cmd.libraries) if allow('library_dirs'): self.set_library_dirs(self.library_dirs + cmd.library_dirs) if allow('rpath'): self.set_runtime_library_dirs(cmd.rpath) if allow('link_objects'): self.set_link_objects(cmd.link_objects) replace_method(CCompiler, 'customize_cmd', CCompiler_customize_cmd) def _compiler_to_string(compiler): props = [] mx = 0 keys = list(compiler.executables.keys()) for key in ['version', 'libraries', 'library_dirs', 'object_switch', 'compile_switch', 'include_dirs', 'define', 'undef', 'rpath', 'link_objects']: if key not in keys: keys.append(key) for key in keys: if hasattr(compiler, key): v = getattr(compiler, key) mx = max(mx, len(key)) props.append((key, repr(v))) lines = [] format = '%-' + repr(mx+1) + 's = %s' for prop in props: lines.append(format % prop) return '\n'.join(lines) def CCompiler_show_customization(self): """ Print the compiler customizations to stdout. Parameters ---------- None Returns ------- None Notes ----- Printing is only done if the distutils log threshold is < 2. """ if 0: for attrname in ['include_dirs', 'define', 'undef', 'libraries', 'library_dirs', 'rpath', 'link_objects']: attr = getattr(self, attrname, None) if not attr: continue log.info("compiler '%s' is set to %s" % (attrname, attr)) try: self.get_version() except Exception: pass if log._global_log.threshold<2: print('*'*80) print(self.__class__) print(_compiler_to_string(self)) print('*'*80) replace_method(CCompiler, 'show_customization', CCompiler_show_customization) def CCompiler_customize(self, dist, need_cxx=0): """ Do any platform-specific customization of a compiler instance. This method calls `distutils.sysconfig.customize_compiler` for platform-specific customization, as well as optionally remove a flag to suppress spurious warnings in case C++ code is being compiled. Parameters ---------- dist : object This parameter is not used for anything. need_cxx : bool, optional Whether or not C++ has to be compiled. If so (True), the ``"-Wstrict-prototypes"`` option is removed to prevent spurious warnings. Default is False. Returns ------- None Notes ----- All the default options used by distutils can be extracted with:: from distutils import sysconfig sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'BASECFLAGS', 'CCSHARED', 'LDSHARED', 'SO') """ # See FCompiler.customize for suggested usage. log.info('customize %s' % (self.__class__.__name__)) customize_compiler(self) if need_cxx: # In general, distutils uses -Wstrict-prototypes, but this option is # not valid for C++ code, only for C. Remove it if it's there to # avoid a spurious warning on every compilation. try: self.compiler_so.remove('-Wstrict-prototypes') except (AttributeError, ValueError): pass if hasattr(self, 'compiler') and 'cc' in self.compiler[0]: if not self.compiler_cxx: if self.compiler[0].startswith('gcc'): a, b = 'gcc', 'g++' else: a, b = 'cc', 'c++' self.compiler_cxx = [self.compiler[0].replace(a, b)]\ + self.compiler[1:] else: if hasattr(self, 'compiler'): log.warn("#### %s #######" % (self.compiler,)) if not hasattr(self, 'compiler_cxx'): log.warn('Missing compiler_cxx fix for ' + self.__class__.__name__) # check if compiler supports gcc style automatic dependencies # run on every extension so skip for known good compilers if hasattr(self, 'compiler') and ('gcc' in self.compiler[0] or 'g++' in self.compiler[0] or 'clang' in self.compiler[0]): self._auto_depends = True elif os.name == 'posix': import tempfile import shutil tmpdir = tempfile.mkdtemp() try: fn = os.path.join(tmpdir, "file.c") with open(fn, "w") as f: f.write("int a;\n") self.compile([fn], output_dir=tmpdir, extra_preargs=['-MMD', '-MF', fn + '.d']) self._auto_depends = True except CompileError: self._auto_depends = False finally: shutil.rmtree(tmpdir) return replace_method(CCompiler, 'customize', CCompiler_customize) def simple_version_match(pat=r'[-.\d]+', ignore='', start=''): """ Simple matching of version numbers, for use in CCompiler and FCompiler. Parameters ---------- pat : str, optional A regular expression matching version numbers. Default is ``r'[-.\\d]+'``. ignore : str, optional A regular expression matching patterns to skip. Default is ``''``, in which case nothing is skipped. start : str, optional A regular expression matching the start of where to start looking for version numbers. Default is ``''``, in which case searching is started at the beginning of the version string given to `matcher`. Returns ------- matcher : callable A function that is appropriate to use as the ``.version_match`` attribute of a `CCompiler` class. `matcher` takes a single parameter, a version string. """ def matcher(self, version_string): # version string may appear in the second line, so getting rid # of new lines: version_string = version_string.replace('\n', ' ') pos = 0 if start: m = re.match(start, version_string) if not m: return None pos = m.end() while True: m = re.search(pat, version_string[pos:]) if not m: return None if ignore and re.match(ignore, m.group(0)): pos = m.end() continue break return m.group(0) return matcher def CCompiler_get_version(self, force=False, ok_status=[0]): """ Return compiler version, or None if compiler is not available. Parameters ---------- force : bool, optional If True, force a new determination of the version, even if the compiler already has a version attribute. Default is False. ok_status : list of int, optional The list of status values returned by the version look-up process for which a version string is returned. If the status value is not in `ok_status`, None is returned. Default is ``[0]``. Returns ------- version : str or None Version string, in the format of `distutils.version.LooseVersion`. """ if not force and hasattr(self, 'version'): return self.version self.find_executables() try: version_cmd = self.version_cmd except AttributeError: return None if not version_cmd or not version_cmd[0]: return None try: matcher = self.version_match except AttributeError: try: pat = self.version_pattern except AttributeError: return None def matcher(version_string): m = re.match(pat, version_string) if not m: return None version = m.group('version') return version status, output = exec_command(version_cmd, use_tee=0) version = None if status in ok_status: version = matcher(output) if version: version = LooseVersion(version) self.version = version return version replace_method(CCompiler, 'get_version', CCompiler_get_version) def CCompiler_cxx_compiler(self): """ Return the C++ compiler. Parameters ---------- None Returns ------- cxx : class instance The C++ compiler, as a `CCompiler` instance. """ if self.compiler_type in ('msvc', 'intelw', 'intelemw'): return self cxx = copy(self) cxx.compiler_so = [cxx.compiler_cxx[0]] + cxx.compiler_so[1:] if sys.platform.startswith('aix') and 'ld_so_aix' in cxx.linker_so[0]: # AIX needs the ld_so_aix script included with Python cxx.linker_so = [cxx.linker_so[0], cxx.compiler_cxx[0]] \ + cxx.linker_so[2:] else: cxx.linker_so = [cxx.compiler_cxx[0]] + cxx.linker_so[1:] return cxx replace_method(CCompiler, 'cxx_compiler', CCompiler_cxx_compiler) compiler_class['intel'] = ('intelccompiler', 'IntelCCompiler', "Intel C Compiler for 32-bit applications") compiler_class['intele'] = ('intelccompiler', 'IntelItaniumCCompiler', "Intel C Itanium Compiler for Itanium-based applications") compiler_class['intelem'] = ('intelccompiler', 'IntelEM64TCCompiler', "Intel C Compiler for 64-bit applications") compiler_class['intelw'] = ('intelccompiler', 'IntelCCompilerW', "Intel C Compiler for 32-bit applications on Windows") compiler_class['intelemw'] = ('intelccompiler', 'IntelEM64TCCompilerW', "Intel C Compiler for 64-bit applications on Windows") compiler_class['pathcc'] = ('pathccompiler', 'PathScaleCCompiler', "PathScale Compiler for SiCortex-based applications") ccompiler._default_compilers += (('linux.*', 'intel'), ('linux.*', 'intele'), ('linux.*', 'intelem'), ('linux.*', 'pathcc'), ('nt', 'intelw'), ('nt', 'intelemw')) if sys.platform == 'win32': compiler_class['mingw32'] = ('mingw32ccompiler', 'Mingw32CCompiler', "Mingw32 port of GNU C Compiler for Win32"\ "(for MSC built Python)") if mingw32(): # On windows platforms, we want to default to mingw32 (gcc) # because msvc can't build blitz stuff. log.info('Setting mingw32 as default compiler for nt.') ccompiler._default_compilers = (('nt', 'mingw32'),) \ + ccompiler._default_compilers _distutils_new_compiler = new_compiler def new_compiler (plat=None, compiler=None, verbose=0, dry_run=0, force=0): # Try first C compilers from numpy.distutils. if plat is None: plat = os.name try: if compiler is None: compiler = get_default_compiler(plat) (module_name, class_name, long_description) = compiler_class[compiler] except KeyError: msg = "don't know how to compile C/C++ code on platform '%s'" % plat if compiler is not None: msg = msg + " with '%s' compiler" % compiler raise DistutilsPlatformError(msg) module_name = "numpy.distutils." + module_name try: __import__ (module_name) except ImportError: msg = str(get_exception()) log.info('%s in numpy.distutils; trying from distutils', str(msg)) module_name = module_name[6:] try: __import__(module_name) except ImportError: msg = str(get_exception()) raise DistutilsModuleError("can't compile C/C++ code: unable to load module '%s'" % \ module_name) try: module = sys.modules[module_name] klass = vars(module)[class_name] except KeyError: raise DistutilsModuleError(("can't compile C/C++ code: unable to find class '%s' " + "in module '%s'") % (class_name, module_name)) compiler = klass(None, dry_run, force) log.debug('new_compiler returns %s' % (klass)) return compiler ccompiler.new_compiler = new_compiler _distutils_gen_lib_options = gen_lib_options def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries): library_dirs = quote_args(library_dirs) runtime_library_dirs = quote_args(runtime_library_dirs) r = _distutils_gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries) lib_opts = [] for i in r: if is_sequence(i): lib_opts.extend(list(i)) else: lib_opts.append(i) return lib_opts ccompiler.gen_lib_options = gen_lib_options # Also fix up the various compiler modules, which do # from distutils.ccompiler import gen_lib_options # Don't bother with mwerks, as we don't support Classic Mac. for _cc in ['msvc9', 'msvc', '_msvc', 'bcpp', 'cygwinc', 'emxc', 'unixc']: _m = sys.modules.get('distutils.' + _cc + 'compiler') if _m is not None: setattr(_m, 'gen_lib_options', gen_lib_options) _distutils_gen_preprocess_options = gen_preprocess_options def gen_preprocess_options (macros, include_dirs): include_dirs = quote_args(include_dirs) return _distutils_gen_preprocess_options(macros, include_dirs) ccompiler.gen_preprocess_options = gen_preprocess_options ##Fix distutils.util.split_quoted: # NOTE: I removed this fix in revision 4481 (see ticket #619), but it appears # that removing this fix causes f2py problems on Windows XP (see ticket #723). # Specifically, on WinXP when gfortran is installed in a directory path, which # contains spaces, then f2py is unable to find it. import string _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace) _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'") _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"') _has_white_re = re.compile(r'\s') def split_quoted(s): s = s.strip() words = [] pos = 0 while s: m = _wordchars_re.match(s, pos) end = m.end() if end == len(s): words.append(s[:end]) break if s[end] in string.whitespace: # unescaped, unquoted whitespace: now words.append(s[:end]) # we definitely have a word delimiter s = s[end:].lstrip() pos = 0 elif s[end] == '\\': # preserve whatever is being escaped; # will become part of the current word s = s[:end] + s[end+1:] pos = end+1 else: if s[end] == "'": # slurp singly-quoted string m = _squote_re.match(s, end) elif s[end] == '"': # slurp doubly-quoted string m = _dquote_re.match(s, end) else: raise RuntimeError("this can't happen (bad char '%c')" % s[end]) if m is None: raise ValueError("bad string (mismatched %s quotes?)" % s[end]) (beg, end) = m.span() if _has_white_re.search(s[beg+1:end-1]): s = s[:beg] + s[beg+1:end-1] + s[end:] pos = m.end() - 2 else: # Keeping quotes when a quoted word does not contain # white-space. XXX: send a patch to distutils pos = m.end() if pos >= len(s): words.append(s) break return words ccompiler.split_quoted = split_quoted ##Fix distutils.util.split_quoted:
28,547
33.519952
97
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/core.py
from __future__ import division, absolute_import, print_function import sys from distutils.core import * if 'setuptools' in sys.modules: have_setuptools = True from setuptools import setup as old_setup # easy_install imports math, it may be picked up from cwd from setuptools.command import easy_install try: # very old versions of setuptools don't have this from setuptools.command import bdist_egg except ImportError: have_setuptools = False else: from distutils.core import setup as old_setup have_setuptools = False import warnings import distutils.core import distutils.dist from numpy.distutils.extension import Extension from numpy.distutils.numpy_distribution import NumpyDistribution from numpy.distutils.command import config, config_compiler, \ build, build_py, build_ext, build_clib, build_src, build_scripts, \ sdist, install_data, install_headers, install, bdist_rpm, \ install_clib from numpy.distutils.misc_util import get_data_files, is_sequence, is_string numpy_cmdclass = {'build': build.build, 'build_src': build_src.build_src, 'build_scripts': build_scripts.build_scripts, 'config_cc': config_compiler.config_cc, 'config_fc': config_compiler.config_fc, 'config': config.config, 'build_ext': build_ext.build_ext, 'build_py': build_py.build_py, 'build_clib': build_clib.build_clib, 'sdist': sdist.sdist, 'install_data': install_data.install_data, 'install_headers': install_headers.install_headers, 'install_clib': install_clib.install_clib, 'install': install.install, 'bdist_rpm': bdist_rpm.bdist_rpm, } if have_setuptools: # Use our own versions of develop and egg_info to ensure that build_src is # handled appropriately. from numpy.distutils.command import develop, egg_info numpy_cmdclass['bdist_egg'] = bdist_egg.bdist_egg numpy_cmdclass['develop'] = develop.develop numpy_cmdclass['easy_install'] = easy_install.easy_install numpy_cmdclass['egg_info'] = egg_info.egg_info def _dict_append(d, **kws): for k, v in kws.items(): if k not in d: d[k] = v continue dv = d[k] if isinstance(dv, tuple): d[k] = dv + tuple(v) elif isinstance(dv, list): d[k] = dv + list(v) elif isinstance(dv, dict): _dict_append(dv, **v) elif is_string(dv): d[k] = dv + v else: raise TypeError(repr(type(dv))) def _command_line_ok(_cache=[]): """ Return True if command line does not contain any help or display requests. """ if _cache: return _cache[0] ok = True display_opts = ['--'+n for n in Distribution.display_option_names] for o in Distribution.display_options: if o[1]: display_opts.append('-'+o[1]) for arg in sys.argv: if arg.startswith('--help') or arg=='-h' or arg in display_opts: ok = False break _cache.append(ok) return ok def get_distribution(always=False): dist = distutils.core._setup_distribution # XXX Hack to get numpy installable with easy_install. # The problem is easy_install runs it's own setup(), which # sets up distutils.core._setup_distribution. However, # when our setup() runs, that gets overwritten and lost. # We can't use isinstance, as the DistributionWithoutHelpCommands # class is local to a function in setuptools.command.easy_install if dist is not None and \ 'DistributionWithoutHelpCommands' in repr(dist): dist = None if always and dist is None: dist = NumpyDistribution() return dist def setup(**attr): cmdclass = numpy_cmdclass.copy() new_attr = attr.copy() if 'cmdclass' in new_attr: cmdclass.update(new_attr['cmdclass']) new_attr['cmdclass'] = cmdclass if 'configuration' in new_attr: # To avoid calling configuration if there are any errors # or help request in command in the line. configuration = new_attr.pop('configuration') old_dist = distutils.core._setup_distribution old_stop = distutils.core._setup_stop_after distutils.core._setup_distribution = None distutils.core._setup_stop_after = "commandline" try: dist = setup(**new_attr) finally: distutils.core._setup_distribution = old_dist distutils.core._setup_stop_after = old_stop if dist.help or not _command_line_ok(): # probably displayed help, skip running any commands return dist # create setup dictionary and append to new_attr config = configuration() if hasattr(config, 'todict'): config = config.todict() _dict_append(new_attr, **config) # Move extension source libraries to libraries libraries = [] for ext in new_attr.get('ext_modules', []): new_libraries = [] for item in ext.libraries: if is_sequence(item): lib_name, build_info = item _check_append_ext_library(libraries, lib_name, build_info) new_libraries.append(lib_name) elif is_string(item): new_libraries.append(item) else: raise TypeError("invalid description of extension module " "library %r" % (item,)) ext.libraries = new_libraries if libraries: if 'libraries' not in new_attr: new_attr['libraries'] = [] for item in libraries: _check_append_library(new_attr['libraries'], item) # sources in ext_modules or libraries may contain header files if ('ext_modules' in new_attr or 'libraries' in new_attr) \ and 'headers' not in new_attr: new_attr['headers'] = [] # Use our custom NumpyDistribution class instead of distutils' one new_attr['distclass'] = NumpyDistribution return old_setup(**new_attr) def _check_append_library(libraries, item): for libitem in libraries: if is_sequence(libitem): if is_sequence(item): if item[0]==libitem[0]: if item[1] is libitem[1]: return warnings.warn("[0] libraries list contains %r with" " different build_info" % (item[0],), stacklevel=2) break else: if item==libitem[0]: warnings.warn("[1] libraries list contains %r with" " no build_info" % (item[0],), stacklevel=2) break else: if is_sequence(item): if item[0]==libitem: warnings.warn("[2] libraries list contains %r with" " no build_info" % (item[0],), stacklevel=2) break else: if item==libitem: return libraries.append(item) def _check_append_ext_library(libraries, lib_name, build_info): for item in libraries: if is_sequence(item): if item[0]==lib_name: if item[1] is build_info: return warnings.warn("[3] libraries list contains %r with" " different build_info" % (lib_name,), stacklevel=2) break elif item==lib_name: warnings.warn("[4] libraries list contains %r with" " no build_info" % (lib_name,), stacklevel=2) break libraries.append((lib_name, build_info))
8,183
36.888889
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/environment.py
from __future__ import division, absolute_import, print_function import os from distutils.dist import Distribution __metaclass__ = type class EnvironmentConfig(object): def __init__(self, distutils_section='ALL', **kw): self._distutils_section = distutils_section self._conf_keys = kw self._conf = None self._hook_handler = None def dump_variable(self, name): conf_desc = self._conf_keys[name] hook, envvar, confvar, convert = conf_desc if not convert: convert = lambda x : x print('%s.%s:' % (self._distutils_section, name)) v = self._hook_handler(name, hook) print(' hook : %s' % (convert(v),)) if envvar: v = os.environ.get(envvar, None) print(' environ: %s' % (convert(v),)) if confvar and self._conf: v = self._conf.get(confvar, (None, None))[1] print(' config : %s' % (convert(v),)) def dump_variables(self): for name in self._conf_keys: self.dump_variable(name) def __getattr__(self, name): try: conf_desc = self._conf_keys[name] except KeyError: raise AttributeError(name) return self._get_var(name, conf_desc) def get(self, name, default=None): try: conf_desc = self._conf_keys[name] except KeyError: return default var = self._get_var(name, conf_desc) if var is None: var = default return var def _get_var(self, name, conf_desc): hook, envvar, confvar, convert = conf_desc var = self._hook_handler(name, hook) if envvar is not None: var = os.environ.get(envvar, var) if confvar is not None and self._conf: var = self._conf.get(confvar, (None, var))[1] if convert is not None: var = convert(var) return var def clone(self, hook_handler): ec = self.__class__(distutils_section=self._distutils_section, **self._conf_keys) ec._hook_handler = hook_handler return ec def use_distribution(self, dist): if isinstance(dist, Distribution): self._conf = dist.get_option_dict(self._distutils_section) else: self._conf = dist
2,346
31.150685
70
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/cpuinfo.py
#!/usr/bin/env python """ cpuinfo Copyright 2002 Pearu Peterson all rights reserved, Pearu Peterson <[email protected]> Permission to use, modify, and distribute this software is given under the terms of the NumPy (BSD style) license. See LICENSE.txt that came with this distribution for specifics. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. Pearu Peterson """ from __future__ import division, absolute_import, print_function __all__ = ['cpu'] import sys, re, types import os if sys.version_info[0] >= 3: from subprocess import getstatusoutput else: from commands import getstatusoutput import warnings import platform from numpy.distutils.compat import get_exception def getoutput(cmd, successful_status=(0,), stacklevel=1): try: status, output = getstatusoutput(cmd) except EnvironmentError: e = get_exception() warnings.warn(str(e), UserWarning, stacklevel=stacklevel) return False, "" if os.WIFEXITED(status) and os.WEXITSTATUS(status) in successful_status: return True, output return False, output def command_info(successful_status=(0,), stacklevel=1, **kw): info = {} for key in kw: ok, output = getoutput(kw[key], successful_status=successful_status, stacklevel=stacklevel+1) if ok: info[key] = output.strip() return info def command_by_line(cmd, successful_status=(0,), stacklevel=1): ok, output = getoutput(cmd, successful_status=successful_status, stacklevel=stacklevel+1) if not ok: return for line in output.splitlines(): yield line.strip() def key_value_from_command(cmd, sep, successful_status=(0,), stacklevel=1): d = {} for line in command_by_line(cmd, successful_status=successful_status, stacklevel=stacklevel+1): l = [s.strip() for s in line.split(sep, 1)] if len(l) == 2: d[l[0]] = l[1] return d class CPUInfoBase(object): """Holds CPU information and provides methods for requiring the availability of various CPU features. """ def _try_call(self, func): try: return func() except Exception: pass def __getattr__(self, name): if not name.startswith('_'): if hasattr(self, '_'+name): attr = getattr(self, '_'+name) if isinstance(attr, types.MethodType): return lambda func=self._try_call,attr=attr : func(attr) else: return lambda : None raise AttributeError(name) def _getNCPUs(self): return 1 def __get_nbits(self): abits = platform.architecture()[0] nbits = re.compile(r'(\d+)bit').search(abits).group(1) return nbits def _is_32bit(self): return self.__get_nbits() == '32' def _is_64bit(self): return self.__get_nbits() == '64' class LinuxCPUInfo(CPUInfoBase): info = None def __init__(self): if self.info is not None: return info = [ {} ] ok, output = getoutput('uname -m') if ok: info[0]['uname_m'] = output.strip() try: fo = open('/proc/cpuinfo') except EnvironmentError: e = get_exception() warnings.warn(str(e), UserWarning, stacklevel=2) else: for line in fo: name_value = [s.strip() for s in line.split(':', 1)] if len(name_value) != 2: continue name, value = name_value if not info or name in info[-1]: # next processor info.append({}) info[-1][name] = value fo.close() self.__class__.info = info def _not_impl(self): pass # Athlon def _is_AMD(self): return self.info[0]['vendor_id']=='AuthenticAMD' def _is_AthlonK6_2(self): return self._is_AMD() and self.info[0]['model'] == '2' def _is_AthlonK6_3(self): return self._is_AMD() and self.info[0]['model'] == '3' def _is_AthlonK6(self): return re.match(r'.*?AMD-K6', self.info[0]['model name']) is not None def _is_AthlonK7(self): return re.match(r'.*?AMD-K7', self.info[0]['model name']) is not None def _is_AthlonMP(self): return re.match(r'.*?Athlon\(tm\) MP\b', self.info[0]['model name']) is not None def _is_AMD64(self): return self.is_AMD() and self.info[0]['family'] == '15' def _is_Athlon64(self): return re.match(r'.*?Athlon\(tm\) 64\b', self.info[0]['model name']) is not None def _is_AthlonHX(self): return re.match(r'.*?Athlon HX\b', self.info[0]['model name']) is not None def _is_Opteron(self): return re.match(r'.*?Opteron\b', self.info[0]['model name']) is not None def _is_Hammer(self): return re.match(r'.*?Hammer\b', self.info[0]['model name']) is not None # Alpha def _is_Alpha(self): return self.info[0]['cpu']=='Alpha' def _is_EV4(self): return self.is_Alpha() and self.info[0]['cpu model'] == 'EV4' def _is_EV5(self): return self.is_Alpha() and self.info[0]['cpu model'] == 'EV5' def _is_EV56(self): return self.is_Alpha() and self.info[0]['cpu model'] == 'EV56' def _is_PCA56(self): return self.is_Alpha() and self.info[0]['cpu model'] == 'PCA56' # Intel #XXX _is_i386 = _not_impl def _is_Intel(self): return self.info[0]['vendor_id']=='GenuineIntel' def _is_i486(self): return self.info[0]['cpu']=='i486' def _is_i586(self): return self.is_Intel() and self.info[0]['cpu family'] == '5' def _is_i686(self): return self.is_Intel() and self.info[0]['cpu family'] == '6' def _is_Celeron(self): return re.match(r'.*?Celeron', self.info[0]['model name']) is not None def _is_Pentium(self): return re.match(r'.*?Pentium', self.info[0]['model name']) is not None def _is_PentiumII(self): return re.match(r'.*?Pentium.*?II\b', self.info[0]['model name']) is not None def _is_PentiumPro(self): return re.match(r'.*?PentiumPro\b', self.info[0]['model name']) is not None def _is_PentiumMMX(self): return re.match(r'.*?Pentium.*?MMX\b', self.info[0]['model name']) is not None def _is_PentiumIII(self): return re.match(r'.*?Pentium.*?III\b', self.info[0]['model name']) is not None def _is_PentiumIV(self): return re.match(r'.*?Pentium.*?(IV|4)\b', self.info[0]['model name']) is not None def _is_PentiumM(self): return re.match(r'.*?Pentium.*?M\b', self.info[0]['model name']) is not None def _is_Prescott(self): return self.is_PentiumIV() and self.has_sse3() def _is_Nocona(self): return self.is_Intel() \ and (self.info[0]['cpu family'] == '6' \ or self.info[0]['cpu family'] == '15' ) \ and (self.has_sse3() and not self.has_ssse3())\ and re.match(r'.*?\blm\b', self.info[0]['flags']) is not None def _is_Core2(self): return self.is_64bit() and self.is_Intel() and \ re.match(r'.*?Core\(TM\)2\b', \ self.info[0]['model name']) is not None def _is_Itanium(self): return re.match(r'.*?Itanium\b', self.info[0]['family']) is not None def _is_XEON(self): return re.match(r'.*?XEON\b', self.info[0]['model name'], re.IGNORECASE) is not None _is_Xeon = _is_XEON # Varia def _is_singleCPU(self): return len(self.info) == 1 def _getNCPUs(self): return len(self.info) def _has_fdiv_bug(self): return self.info[0]['fdiv_bug']=='yes' def _has_f00f_bug(self): return self.info[0]['f00f_bug']=='yes' def _has_mmx(self): return re.match(r'.*?\bmmx\b', self.info[0]['flags']) is not None def _has_sse(self): return re.match(r'.*?\bsse\b', self.info[0]['flags']) is not None def _has_sse2(self): return re.match(r'.*?\bsse2\b', self.info[0]['flags']) is not None def _has_sse3(self): return re.match(r'.*?\bpni\b', self.info[0]['flags']) is not None def _has_ssse3(self): return re.match(r'.*?\bssse3\b', self.info[0]['flags']) is not None def _has_3dnow(self): return re.match(r'.*?\b3dnow\b', self.info[0]['flags']) is not None def _has_3dnowext(self): return re.match(r'.*?\b3dnowext\b', self.info[0]['flags']) is not None class IRIXCPUInfo(CPUInfoBase): info = None def __init__(self): if self.info is not None: return info = key_value_from_command('sysconf', sep=' ', successful_status=(0, 1)) self.__class__.info = info def _not_impl(self): pass def _is_singleCPU(self): return self.info.get('NUM_PROCESSORS') == '1' def _getNCPUs(self): return int(self.info.get('NUM_PROCESSORS', 1)) def __cputype(self, n): return self.info.get('PROCESSORS').split()[0].lower() == 'r%s' % (n) def _is_r2000(self): return self.__cputype(2000) def _is_r3000(self): return self.__cputype(3000) def _is_r3900(self): return self.__cputype(3900) def _is_r4000(self): return self.__cputype(4000) def _is_r4100(self): return self.__cputype(4100) def _is_r4300(self): return self.__cputype(4300) def _is_r4400(self): return self.__cputype(4400) def _is_r4600(self): return self.__cputype(4600) def _is_r4650(self): return self.__cputype(4650) def _is_r5000(self): return self.__cputype(5000) def _is_r6000(self): return self.__cputype(6000) def _is_r8000(self): return self.__cputype(8000) def _is_r10000(self): return self.__cputype(10000) def _is_r12000(self): return self.__cputype(12000) def _is_rorion(self): return self.__cputype('orion') def get_ip(self): try: return self.info.get('MACHINE') except Exception: pass def __machine(self, n): return self.info.get('MACHINE').lower() == 'ip%s' % (n) def _is_IP19(self): return self.__machine(19) def _is_IP20(self): return self.__machine(20) def _is_IP21(self): return self.__machine(21) def _is_IP22(self): return self.__machine(22) def _is_IP22_4k(self): return self.__machine(22) and self._is_r4000() def _is_IP22_5k(self): return self.__machine(22) and self._is_r5000() def _is_IP24(self): return self.__machine(24) def _is_IP25(self): return self.__machine(25) def _is_IP26(self): return self.__machine(26) def _is_IP27(self): return self.__machine(27) def _is_IP28(self): return self.__machine(28) def _is_IP30(self): return self.__machine(30) def _is_IP32(self): return self.__machine(32) def _is_IP32_5k(self): return self.__machine(32) and self._is_r5000() def _is_IP32_10k(self): return self.__machine(32) and self._is_r10000() class DarwinCPUInfo(CPUInfoBase): info = None def __init__(self): if self.info is not None: return info = command_info(arch='arch', machine='machine') info['sysctl_hw'] = key_value_from_command('sysctl hw', sep='=') self.__class__.info = info def _not_impl(self): pass def _getNCPUs(self): return int(self.info['sysctl_hw'].get('hw.ncpu', 1)) def _is_Power_Macintosh(self): return self.info['sysctl_hw']['hw.machine']=='Power Macintosh' def _is_i386(self): return self.info['arch']=='i386' def _is_ppc(self): return self.info['arch']=='ppc' def __machine(self, n): return self.info['machine'] == 'ppc%s'%n def _is_ppc601(self): return self.__machine(601) def _is_ppc602(self): return self.__machine(602) def _is_ppc603(self): return self.__machine(603) def _is_ppc603e(self): return self.__machine('603e') def _is_ppc604(self): return self.__machine(604) def _is_ppc604e(self): return self.__machine('604e') def _is_ppc620(self): return self.__machine(620) def _is_ppc630(self): return self.__machine(630) def _is_ppc740(self): return self.__machine(740) def _is_ppc7400(self): return self.__machine(7400) def _is_ppc7450(self): return self.__machine(7450) def _is_ppc750(self): return self.__machine(750) def _is_ppc403(self): return self.__machine(403) def _is_ppc505(self): return self.__machine(505) def _is_ppc801(self): return self.__machine(801) def _is_ppc821(self): return self.__machine(821) def _is_ppc823(self): return self.__machine(823) def _is_ppc860(self): return self.__machine(860) class SunOSCPUInfo(CPUInfoBase): info = None def __init__(self): if self.info is not None: return info = command_info(arch='arch', mach='mach', uname_i='uname_i', isainfo_b='isainfo -b', isainfo_n='isainfo -n', ) info['uname_X'] = key_value_from_command('uname -X', sep='=') for line in command_by_line('psrinfo -v 0'): m = re.match(r'\s*The (?P<p>[\w\d]+) processor operates at', line) if m: info['processor'] = m.group('p') break self.__class__.info = info def _not_impl(self): pass def _is_i386(self): return self.info['isainfo_n']=='i386' def _is_sparc(self): return self.info['isainfo_n']=='sparc' def _is_sparcv9(self): return self.info['isainfo_n']=='sparcv9' def _getNCPUs(self): return int(self.info['uname_X'].get('NumCPU', 1)) def _is_sun4(self): return self.info['arch']=='sun4' def _is_SUNW(self): return re.match(r'SUNW', self.info['uname_i']) is not None def _is_sparcstation5(self): return re.match(r'.*SPARCstation-5', self.info['uname_i']) is not None def _is_ultra1(self): return re.match(r'.*Ultra-1', self.info['uname_i']) is not None def _is_ultra250(self): return re.match(r'.*Ultra-250', self.info['uname_i']) is not None def _is_ultra2(self): return re.match(r'.*Ultra-2', self.info['uname_i']) is not None def _is_ultra30(self): return re.match(r'.*Ultra-30', self.info['uname_i']) is not None def _is_ultra4(self): return re.match(r'.*Ultra-4', self.info['uname_i']) is not None def _is_ultra5_10(self): return re.match(r'.*Ultra-5_10', self.info['uname_i']) is not None def _is_ultra5(self): return re.match(r'.*Ultra-5', self.info['uname_i']) is not None def _is_ultra60(self): return re.match(r'.*Ultra-60', self.info['uname_i']) is not None def _is_ultra80(self): return re.match(r'.*Ultra-80', self.info['uname_i']) is not None def _is_ultraenterprice(self): return re.match(r'.*Ultra-Enterprise', self.info['uname_i']) is not None def _is_ultraenterprice10k(self): return re.match(r'.*Ultra-Enterprise-10000', self.info['uname_i']) is not None def _is_sunfire(self): return re.match(r'.*Sun-Fire', self.info['uname_i']) is not None def _is_ultra(self): return re.match(r'.*Ultra', self.info['uname_i']) is not None def _is_cpusparcv7(self): return self.info['processor']=='sparcv7' def _is_cpusparcv8(self): return self.info['processor']=='sparcv8' def _is_cpusparcv9(self): return self.info['processor']=='sparcv9' class Win32CPUInfo(CPUInfoBase): info = None pkey = r"HARDWARE\DESCRIPTION\System\CentralProcessor" # XXX: what does the value of # HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor\0 # mean? def __init__(self): if self.info is not None: return info = [] try: #XXX: Bad style to use so long `try:...except:...`. Fix it! if sys.version_info[0] >= 3: import winreg else: import _winreg as winreg prgx = re.compile(r"family\s+(?P<FML>\d+)\s+model\s+(?P<MDL>\d+)" r"\s+stepping\s+(?P<STP>\d+)", re.IGNORECASE) chnd=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.pkey) pnum=0 while True: try: proc=winreg.EnumKey(chnd, pnum) except winreg.error: break else: pnum+=1 info.append({"Processor":proc}) phnd=winreg.OpenKey(chnd, proc) pidx=0 while True: try: name, value, vtpe=winreg.EnumValue(phnd, pidx) except winreg.error: break else: pidx=pidx+1 info[-1][name]=value if name=="Identifier": srch=prgx.search(value) if srch: info[-1]["Family"]=int(srch.group("FML")) info[-1]["Model"]=int(srch.group("MDL")) info[-1]["Stepping"]=int(srch.group("STP")) except Exception: print(sys.exc_info()[1], '(ignoring)') self.__class__.info = info def _not_impl(self): pass # Athlon def _is_AMD(self): return self.info[0]['VendorIdentifier']=='AuthenticAMD' def _is_Am486(self): return self.is_AMD() and self.info[0]['Family']==4 def _is_Am5x86(self): return self.is_AMD() and self.info[0]['Family']==4 def _is_AMDK5(self): return self.is_AMD() and self.info[0]['Family']==5 \ and self.info[0]['Model'] in [0, 1, 2, 3] def _is_AMDK6(self): return self.is_AMD() and self.info[0]['Family']==5 \ and self.info[0]['Model'] in [6, 7] def _is_AMDK6_2(self): return self.is_AMD() and self.info[0]['Family']==5 \ and self.info[0]['Model']==8 def _is_AMDK6_3(self): return self.is_AMD() and self.info[0]['Family']==5 \ and self.info[0]['Model']==9 def _is_AMDK7(self): return self.is_AMD() and self.info[0]['Family'] == 6 # To reliably distinguish between the different types of AMD64 chips # (Athlon64, Operton, Athlon64 X2, Semperon, Turion 64, etc.) would # require looking at the 'brand' from cpuid def _is_AMD64(self): return self.is_AMD() and self.info[0]['Family'] == 15 # Intel def _is_Intel(self): return self.info[0]['VendorIdentifier']=='GenuineIntel' def _is_i386(self): return self.info[0]['Family']==3 def _is_i486(self): return self.info[0]['Family']==4 def _is_i586(self): return self.is_Intel() and self.info[0]['Family']==5 def _is_i686(self): return self.is_Intel() and self.info[0]['Family']==6 def _is_Pentium(self): return self.is_Intel() and self.info[0]['Family']==5 def _is_PentiumMMX(self): return self.is_Intel() and self.info[0]['Family']==5 \ and self.info[0]['Model']==4 def _is_PentiumPro(self): return self.is_Intel() and self.info[0]['Family']==6 \ and self.info[0]['Model']==1 def _is_PentiumII(self): return self.is_Intel() and self.info[0]['Family']==6 \ and self.info[0]['Model'] in [3, 5, 6] def _is_PentiumIII(self): return self.is_Intel() and self.info[0]['Family']==6 \ and self.info[0]['Model'] in [7, 8, 9, 10, 11] def _is_PentiumIV(self): return self.is_Intel() and self.info[0]['Family']==15 def _is_PentiumM(self): return self.is_Intel() and self.info[0]['Family'] == 6 \ and self.info[0]['Model'] in [9, 13, 14] def _is_Core2(self): return self.is_Intel() and self.info[0]['Family'] == 6 \ and self.info[0]['Model'] in [15, 16, 17] # Varia def _is_singleCPU(self): return len(self.info) == 1 def _getNCPUs(self): return len(self.info) def _has_mmx(self): if self.is_Intel(): return (self.info[0]['Family']==5 and self.info[0]['Model']==4) \ or (self.info[0]['Family'] in [6, 15]) elif self.is_AMD(): return self.info[0]['Family'] in [5, 6, 15] else: return False def _has_sse(self): if self.is_Intel(): return (self.info[0]['Family']==6 and \ self.info[0]['Model'] in [7, 8, 9, 10, 11]) \ or self.info[0]['Family']==15 elif self.is_AMD(): return (self.info[0]['Family']==6 and \ self.info[0]['Model'] in [6, 7, 8, 10]) \ or self.info[0]['Family']==15 else: return False def _has_sse2(self): if self.is_Intel(): return self.is_Pentium4() or self.is_PentiumM() \ or self.is_Core2() elif self.is_AMD(): return self.is_AMD64() else: return False def _has_3dnow(self): return self.is_AMD() and self.info[0]['Family'] in [5, 6, 15] def _has_3dnowext(self): return self.is_AMD() and self.info[0]['Family'] in [6, 15] if sys.platform.startswith('linux'): # variations: linux2,linux-i386 (any others?) cpuinfo = LinuxCPUInfo elif sys.platform.startswith('irix'): cpuinfo = IRIXCPUInfo elif sys.platform == 'darwin': cpuinfo = DarwinCPUInfo elif sys.platform.startswith('sunos'): cpuinfo = SunOSCPUInfo elif sys.platform.startswith('win32'): cpuinfo = Win32CPUInfo elif sys.platform.startswith('cygwin'): cpuinfo = LinuxCPUInfo #XXX: other OS's. Eg. use _winreg on Win32. Or os.uname on unices. else: cpuinfo = CPUInfoBase cpu = cpuinfo() #if __name__ == "__main__": # # cpu.is_blaa() # cpu.is_Intel() # cpu.is_Alpha() # # print('CPU information:'), # for name in dir(cpuinfo): # if name[0]=='_' and name[1]!='_': # r = getattr(cpu,name[1:])() # if r: # if r!=1: # print('%s=%s' %(name[1:],r)) # else: # print(name[1:]), # print()
23,015
32.164265
86
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/setup.py
#!/usr/bin/env python from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('distutils', parent_package, top_path) config.add_subpackage('command') config.add_subpackage('fcompiler') config.add_data_dir('tests') config.add_data_files('site.cfg') config.add_data_files('mingw/gfortran_vs2003_hack.c') config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
611
33
65
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/extension.py
"""distutils.extension Provides the Extension class, used to describe C/C++ extension modules in setup scripts. Overridden to support f2py. """ from __future__ import division, absolute_import, print_function import sys import re from distutils.extension import Extension as old_Extension if sys.version_info[0] >= 3: basestring = str cxx_ext_re = re.compile(r'.*[.](cpp|cxx|cc)\Z', re.I).match fortran_pyf_ext_re = re.compile(r'.*[.](f90|f95|f77|for|ftn|f|pyf)\Z', re.I).match class Extension(old_Extension): def __init__ ( self, name, sources, include_dirs=None, define_macros=None, undef_macros=None, library_dirs=None, libraries=None, runtime_library_dirs=None, extra_objects=None, extra_compile_args=None, extra_link_args=None, export_symbols=None, swig_opts=None, depends=None, language=None, f2py_options=None, module_dirs=None, extra_f77_compile_args=None, extra_f90_compile_args=None,): old_Extension.__init__( self, name, [], include_dirs=include_dirs, define_macros=define_macros, undef_macros=undef_macros, library_dirs=library_dirs, libraries=libraries, runtime_library_dirs=runtime_library_dirs, extra_objects=extra_objects, extra_compile_args=extra_compile_args, extra_link_args=extra_link_args, export_symbols=export_symbols) # Avoid assert statements checking that sources contains strings: self.sources = sources # Python 2.4 distutils new features self.swig_opts = swig_opts or [] # swig_opts is assumed to be a list. Here we handle the case where it # is specified as a string instead. if isinstance(self.swig_opts, basestring): import warnings msg = "swig_opts is specified as a string instead of a list" warnings.warn(msg, SyntaxWarning, stacklevel=2) self.swig_opts = self.swig_opts.split() # Python 2.3 distutils new features self.depends = depends or [] self.language = language # numpy_distutils features self.f2py_options = f2py_options or [] self.module_dirs = module_dirs or [] self.extra_f77_compile_args = extra_f77_compile_args or [] self.extra_f90_compile_args = extra_f90_compile_args or [] return def has_cxx_sources(self): for source in self.sources: if cxx_ext_re(str(source)): return True return False def has_f2py_sources(self): for source in self.sources: if fortran_pyf_ext_re(source): return True return False # class Extension
2,967
30.574468
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/exec_command.py
""" exec_command Implements exec_command function that is (almost) equivalent to commands.getstatusoutput function but on NT, DOS systems the returned status is actually correct (though, the returned status values may be different by a factor). In addition, exec_command takes keyword arguments for (re-)defining environment variables. Provides functions: exec_command --- execute command in a specified directory and in the modified environment. find_executable --- locate a command using info from environment variable PATH. Equivalent to posix `which` command. Author: Pearu Peterson <[email protected]> Created: 11 January 2003 Requires: Python 2.x Successfully tested on: ======== ============ ================================================= os.name sys.platform comments ======== ============ ================================================= posix linux2 Debian (sid) Linux, Python 2.1.3+, 2.2.3+, 2.3.3 PyCrust 0.9.3, Idle 1.0.2 posix linux2 Red Hat 9 Linux, Python 2.1.3, 2.2.2, 2.3.2 posix sunos5 SunOS 5.9, Python 2.2, 2.3.2 posix darwin Darwin 7.2.0, Python 2.3 nt win32 Windows Me Python 2.3(EE), Idle 1.0, PyCrust 0.7.2 Python 2.1.1 Idle 0.8 nt win32 Windows 98, Python 2.1.1. Idle 0.8 nt win32 Cygwin 98-4.10, Python 2.1.1(MSC) - echo tests fail i.e. redefining environment variables may not work. FIXED: don't use cygwin echo! Comment: also `cmd /c echo` will not work but redefining environment variables do work. posix cygwin Cygwin 98-4.10, Python 2.3.3(cygming special) nt win32 Windows XP, Python 2.3.3 ======== ============ ================================================= Known bugs: * Tests, that send messages to stderr, fail when executed from MSYS prompt because the messages are lost at some point. """ from __future__ import division, absolute_import, print_function __all__ = ['exec_command', 'find_executable'] import os import sys import subprocess from numpy.distutils.misc_util import is_sequence, make_temp_file from numpy.distutils import log def temp_file_name(): fo, name = make_temp_file() fo.close() return name def get_pythonexe(): pythonexe = sys.executable if os.name in ['nt', 'dos']: fdir, fn = os.path.split(pythonexe) fn = fn.upper().replace('PYTHONW', 'PYTHON') pythonexe = os.path.join(fdir, fn) assert os.path.isfile(pythonexe), '%r is not a file' % (pythonexe,) return pythonexe def find_executable(exe, path=None, _cache={}): """Return full path of a executable or None. Symbolic links are not followed. """ key = exe, path try: return _cache[key] except KeyError: pass log.debug('find_executable(%r)' % exe) orig_exe = exe if path is None: path = os.environ.get('PATH', os.defpath) if os.name=='posix': realpath = os.path.realpath else: realpath = lambda a:a if exe.startswith('"'): exe = exe[1:-1] suffixes = [''] if os.name in ['nt', 'dos', 'os2']: fn, ext = os.path.splitext(exe) extra_suffixes = ['.exe', '.com', '.bat'] if ext.lower() not in extra_suffixes: suffixes = extra_suffixes if os.path.isabs(exe): paths = [''] else: paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ] for path in paths: fn = os.path.join(path, exe) for s in suffixes: f_ext = fn+s if not os.path.islink(f_ext): f_ext = realpath(f_ext) if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK): log.info('Found executable %s' % f_ext) _cache[key] = f_ext return f_ext log.warn('Could not locate executable %s' % orig_exe) return None ############################################################ def _preserve_environment( names ): log.debug('_preserve_environment(%r)' % (names)) env = {} for name in names: env[name] = os.environ.get(name) return env def _update_environment( **env ): log.debug('_update_environment(...)') for name, value in env.items(): os.environ[name] = value or '' def _supports_fileno(stream): """ Returns True if 'stream' supports the file descriptor and allows fileno(). """ if hasattr(stream, 'fileno'): try: stream.fileno() return True except IOError: return False else: return False def exec_command(command, execute_in='', use_shell=None, use_tee=None, _with_python = 1, **env ): """ Return (status,output) of executed command. Parameters ---------- command : str A concatenated string of executable and arguments. execute_in : str Before running command ``cd execute_in`` and after ``cd -``. use_shell : {bool, None}, optional If True, execute ``sh -c command``. Default None (True) use_tee : {bool, None}, optional If True use tee. Default None (True) Returns ------- res : str Both stdout and stderr messages. Notes ----- On NT, DOS systems the returned status is correct for external commands. Wild cards will not work for non-posix systems or when use_shell=0. """ log.debug('exec_command(%r,%s)' % (command,\ ','.join(['%s=%r'%kv for kv in env.items()]))) if use_tee is None: use_tee = os.name=='posix' if use_shell is None: use_shell = os.name=='posix' execute_in = os.path.abspath(execute_in) oldcwd = os.path.abspath(os.getcwd()) if __name__[-12:] == 'exec_command': exec_dir = os.path.dirname(os.path.abspath(__file__)) elif os.path.isfile('exec_command.py'): exec_dir = os.path.abspath('.') else: exec_dir = os.path.abspath(sys.argv[0]) if os.path.isfile(exec_dir): exec_dir = os.path.dirname(exec_dir) if oldcwd!=execute_in: os.chdir(execute_in) log.debug('New cwd: %s' % execute_in) else: log.debug('Retaining cwd: %s' % oldcwd) oldenv = _preserve_environment( list(env.keys()) ) _update_environment( **env ) try: st = _exec_command(command, use_shell=use_shell, use_tee=use_tee, **env) finally: if oldcwd!=execute_in: os.chdir(oldcwd) log.debug('Restored cwd to %s' % oldcwd) _update_environment(**oldenv) return st def _exec_command(command, use_shell=None, use_tee = None, **env): """ Internal workhorse for exec_command(). """ if use_shell is None: use_shell = os.name=='posix' if use_tee is None: use_tee = os.name=='posix' if os.name == 'posix' and use_shell: # On POSIX, subprocess always uses /bin/sh, override sh = os.environ.get('SHELL', '/bin/sh') if is_sequence(command): command = [sh, '-c', ' '.join(command)] else: command = [sh, '-c', command] use_shell = False elif os.name == 'nt' and is_sequence(command): # On Windows, join the string for CreateProcess() ourselves as # subprocess does it a bit differently command = ' '.join(_quote_arg(arg) for arg in command) # Inherit environment by default env = env or None try: proc = subprocess.Popen(command, shell=use_shell, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) except EnvironmentError: # Return 127, as os.spawn*() and /bin/sh do return 127, '' text, err = proc.communicate() # Another historical oddity if text[-1:] == '\n': text = text[:-1] if use_tee and text: print(text) return proc.returncode, text def _quote_arg(arg): """ Quote the argument for safe use in a shell command line. """ # If there is a quote in the string, assume relevants parts of the # string are already quoted (e.g. '-I"C:\\Program Files\\..."') if '"' not in arg and ' ' in arg: return '"%s"' % arg return arg ############################################################
8,663
30.391304
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/unixccompiler.py
""" unixccompiler - can handle very long argument lists for ar. """ from __future__ import division, absolute_import, print_function import os from distutils.errors import DistutilsExecError, CompileError from distutils.unixccompiler import * from numpy.distutils.ccompiler import replace_method from numpy.distutils.compat import get_exception from numpy.distutils.misc_util import _commandline_dep_string if sys.version_info[0] < 3: from . import log else: from numpy.distutils import log # Note that UnixCCompiler._compile appeared in Python 2.3 def UnixCCompiler__compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): """Compile a single source files with a Unix-style compiler.""" # HP ad-hoc fix, see ticket 1383 ccomp = self.compiler_so if ccomp[0] == 'aCC': # remove flags that will trigger ANSI-C mode for aCC if '-Ae' in ccomp: ccomp.remove('-Ae') if '-Aa' in ccomp: ccomp.remove('-Aa') # add flags for (almost) sane C++ handling ccomp += ['-AA'] self.compiler_so = ccomp # ensure OPT environment variable is read if 'OPT' in os.environ: from distutils.sysconfig import get_config_vars opt = " ".join(os.environ['OPT'].split()) gcv_opt = " ".join(get_config_vars('OPT')[0].split()) ccomp_s = " ".join(self.compiler_so) if opt not in ccomp_s: ccomp_s = ccomp_s.replace(gcv_opt, opt) self.compiler_so = ccomp_s.split() llink_s = " ".join(self.linker_so) if opt not in llink_s: self.linker_so = llink_s.split() + opt.split() display = '%s: %s' % (os.path.basename(self.compiler_so[0]), src) # gcc style automatic dependencies, outputs a makefile (-MF) that lists # all headers needed by a c file as a side effect of compilation (-MMD) if getattr(self, '_auto_depends', False): deps = ['-MMD', '-MF', obj + '.d'] else: deps = [] try: self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + deps + extra_postargs, display = display) except DistutilsExecError: msg = str(get_exception()) raise CompileError(msg) # add commandline flags to dependency file with open(obj + '.d', 'a') as f: f.write(_commandline_dep_string(cc_args, extra_postargs, pp_opts)) replace_method(UnixCCompiler, '_compile', UnixCCompiler__compile) def UnixCCompiler_create_static_lib(self, objects, output_libname, output_dir=None, debug=0, target_lang=None): """ Build a static library in a separate sub-process. Parameters ---------- objects : list or tuple of str List of paths to object files used to build the static library. output_libname : str The library name as an absolute or relative (if `output_dir` is used) path. output_dir : str, optional The path to the output directory. Default is None, in which case the ``output_dir`` attribute of the UnixCCompiler instance. debug : bool, optional This parameter is not used. target_lang : str, optional This parameter is not used. Returns ------- None """ objects, output_dir = self._fix_object_args(objects, output_dir) output_filename = \ self.library_filename(output_libname, output_dir=output_dir) if self._need_link(objects, output_filename): try: # previous .a may be screwed up; best to remove it first # and recreate. # Also, ar on OS X doesn't handle updating universal archives os.unlink(output_filename) except (IOError, OSError): pass self.mkpath(os.path.dirname(output_filename)) tmp_objects = objects + self.objects while tmp_objects: objects = tmp_objects[:50] tmp_objects = tmp_objects[50:] display = '%s: adding %d object files to %s' % ( os.path.basename(self.archiver[0]), len(objects), output_filename) self.spawn(self.archiver + [output_filename] + objects, display = display) # Not many Unices required ranlib anymore -- SunOS 4.x is, I # think the only major Unix that does. Maybe we need some # platform intelligence here to skip ranlib if it's not # needed -- or maybe Python's configure script took care of # it for us, hence the check for leading colon. if self.ranlib: display = '%s:@ %s' % (os.path.basename(self.ranlib[0]), output_filename) try: self.spawn(self.ranlib + [output_filename], display = display) except DistutilsExecError: msg = str(get_exception()) raise LibError(msg) else: log.debug("skipping %s (up-to-date)", output_filename) return replace_method(UnixCCompiler, 'create_static_lib', UnixCCompiler_create_static_lib)
5,156
36.100719
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/misc_util.py
from __future__ import division, absolute_import, print_function import os import re import sys import copy import glob import atexit import tempfile import subprocess import shutil import distutils from distutils.errors import DistutilsError from distutils.msvccompiler import get_build_architecture try: from threading import local as tlocal except ImportError: from dummy_threading import local as tlocal # stores temporary directory of each thread to only create one per thread _tdata = tlocal() # store all created temporary directories so they can be deleted on exit _tmpdirs = [] def clean_up_temporary_directory(): if _tmpdirs is not None: for d in _tmpdirs: try: shutil.rmtree(d) except OSError: pass atexit.register(clean_up_temporary_directory) from numpy.distutils.compat import get_exception from numpy.compat import basestring from numpy.compat import npy_load_module __all__ = ['Configuration', 'get_numpy_include_dirs', 'default_config_dict', 'dict_append', 'appendpath', 'generate_config_py', 'get_cmd', 'allpath', 'get_mathlibs', 'terminal_has_colors', 'red_text', 'green_text', 'yellow_text', 'blue_text', 'cyan_text', 'cyg2win32', 'mingw32', 'all_strings', 'has_f_sources', 'has_cxx_sources', 'filter_sources', 'get_dependencies', 'is_local_src_dir', 'get_ext_source_files', 'get_script_files', 'get_lib_source_files', 'get_data_files', 'dot_join', 'get_frame', 'minrelpath', 'njoin', 'is_sequence', 'is_string', 'as_list', 'gpaths', 'get_language', 'quote_args', 'get_build_architecture', 'get_info', 'get_pkg_info', 'get_num_build_jobs'] class InstallableLib(object): """ Container to hold information on an installable library. Parameters ---------- name : str Name of the installed library. build_info : dict Dictionary holding build information. target_dir : str Absolute path specifying where to install the library. See Also -------- Configuration.add_installed_library Notes ----- The three parameters are stored as attributes with the same names. """ def __init__(self, name, build_info, target_dir): self.name = name self.build_info = build_info self.target_dir = target_dir def get_num_build_jobs(): """ Get number of parallel build jobs set by the --parallel command line argument of setup.py If the command did not receive a setting the environment variable NPY_NUM_BUILD_JOBS checked and if that is unset it returns 1. Returns ------- out : int number of parallel jobs that can be run """ from numpy.distutils.core import get_distribution envjobs = int(os.environ.get("NPY_NUM_BUILD_JOBS", 1)) dist = get_distribution() # may be None during configuration if dist is None: return envjobs # any of these three may have the job set, take the largest cmdattr = (getattr(dist.get_command_obj('build'), 'parallel', None), getattr(dist.get_command_obj('build_ext'), 'parallel', None), getattr(dist.get_command_obj('build_clib'), 'parallel', None)) if all(x is None for x in cmdattr): return envjobs else: return max(x for x in cmdattr if x is not None) def quote_args(args): # don't used _nt_quote_args as it does not check if # args items already have quotes or not. args = list(args) for i in range(len(args)): a = args[i] if ' ' in a and a[0] not in '"\'': args[i] = '"%s"' % (a) return args def allpath(name): "Convert a /-separated pathname to one using the OS's path separator." splitted = name.split('/') return os.path.join(*splitted) def rel_path(path, parent_path): """Return path relative to parent_path.""" # Use realpath to avoid issues with symlinked dirs (see gh-7707) pd = os.path.realpath(os.path.abspath(parent_path)) apath = os.path.realpath(os.path.abspath(path)) if len(apath) < len(pd): return path if apath == pd: return '' if pd == apath[:len(pd)]: assert apath[len(pd)] in [os.sep], repr((path, apath[len(pd)])) path = apath[len(pd)+1:] return path def get_path_from_frame(frame, parent_path=None): """Return path of the module given a frame object from the call stack. Returned path is relative to parent_path when given, otherwise it is absolute path. """ # First, try to find if the file name is in the frame. try: caller_file = eval('__file__', frame.f_globals, frame.f_locals) d = os.path.dirname(os.path.abspath(caller_file)) except NameError: # __file__ is not defined, so let's try __name__. We try this second # because setuptools spoofs __name__ to be '__main__' even though # sys.modules['__main__'] might be something else, like easy_install(1). caller_name = eval('__name__', frame.f_globals, frame.f_locals) __import__(caller_name) mod = sys.modules[caller_name] if hasattr(mod, '__file__'): d = os.path.dirname(os.path.abspath(mod.__file__)) else: # we're probably running setup.py as execfile("setup.py") # (likely we're building an egg) d = os.path.abspath('.') # hmm, should we use sys.argv[0] like in __builtin__ case? if parent_path is not None: d = rel_path(d, parent_path) return d or '.' def njoin(*path): """Join two or more pathname components + - convert a /-separated pathname to one using the OS's path separator. - resolve `..` and `.` from path. Either passing n arguments as in njoin('a','b'), or a sequence of n names as in njoin(['a','b']) is handled, or a mixture of such arguments. """ paths = [] for p in path: if is_sequence(p): # njoin(['a', 'b'], 'c') paths.append(njoin(*p)) else: assert is_string(p) paths.append(p) path = paths if not path: # njoin() joined = '' else: # njoin('a', 'b') joined = os.path.join(*path) if os.path.sep != '/': joined = joined.replace('/', os.path.sep) return minrelpath(joined) def get_mathlibs(path=None): """Return the MATHLIB line from numpyconfig.h """ if path is not None: config_file = os.path.join(path, '_numpyconfig.h') else: # Look for the file in each of the numpy include directories. dirs = get_numpy_include_dirs() for path in dirs: fn = os.path.join(path, '_numpyconfig.h') if os.path.exists(fn): config_file = fn break else: raise DistutilsError('_numpyconfig.h not found in numpy include ' 'dirs %r' % (dirs,)) fid = open(config_file) mathlibs = [] s = '#define MATHLIB' for line in fid: if line.startswith(s): value = line[len(s):].strip() if value: mathlibs.extend(value.split(',')) fid.close() return mathlibs def minrelpath(path): """Resolve `..` and '.' from path. """ if not is_string(path): return path if '.' not in path: return path l = path.split(os.sep) while l: try: i = l.index('.', 1) except ValueError: break del l[i] j = 1 while l: try: i = l.index('..', j) except ValueError: break if l[i-1]=='..': j += 1 else: del l[i], l[i-1] j = 1 if not l: return '' return os.sep.join(l) def _fix_paths(paths, local_path, include_non_existing): assert is_sequence(paths), repr(type(paths)) new_paths = [] assert not is_string(paths), repr(paths) for n in paths: if is_string(n): if '*' in n or '?' in n: p = glob.glob(n) p2 = glob.glob(njoin(local_path, n)) if p2: new_paths.extend(p2) elif p: new_paths.extend(p) else: if include_non_existing: new_paths.append(n) print('could not resolve pattern in %r: %r' % (local_path, n)) else: n2 = njoin(local_path, n) if os.path.exists(n2): new_paths.append(n2) else: if os.path.exists(n): new_paths.append(n) elif include_non_existing: new_paths.append(n) if not os.path.exists(n): print('non-existing path in %r: %r' % (local_path, n)) elif is_sequence(n): new_paths.extend(_fix_paths(n, local_path, include_non_existing)) else: new_paths.append(n) return [minrelpath(p) for p in new_paths] def gpaths(paths, local_path='', include_non_existing=True): """Apply glob to paths and prepend local_path if needed. """ if is_string(paths): paths = (paths,) return _fix_paths(paths, local_path, include_non_existing) def make_temp_file(suffix='', prefix='', text=True): if not hasattr(_tdata, 'tempdir'): _tdata.tempdir = tempfile.mkdtemp() _tmpdirs.append(_tdata.tempdir) fid, name = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=_tdata.tempdir, text=text) fo = os.fdopen(fid, 'w') return fo, name # Hooks for colored terminal output. # See also http://www.livinglogic.de/Python/ansistyle def terminal_has_colors(): if sys.platform=='cygwin' and 'USE_COLOR' not in os.environ: # Avoid importing curses that causes illegal operation # with a message: # PYTHON2 caused an invalid page fault in # module CYGNURSES7.DLL as 015f:18bbfc28 # Details: Python 2.3.3 [GCC 3.3.1 (cygming special)] # ssh to Win32 machine from debian # curses.version is 2.2 # CYGWIN_98-4.10, release 1.5.7(0.109/3/2)) return 0 if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty(): try: import curses curses.setupterm() if (curses.tigetnum("colors") >= 0 and curses.tigetnum("pairs") >= 0 and ((curses.tigetstr("setf") is not None and curses.tigetstr("setb") is not None) or (curses.tigetstr("setaf") is not None and curses.tigetstr("setab") is not None) or curses.tigetstr("scp") is not None)): return 1 except Exception: pass return 0 if terminal_has_colors(): _colour_codes = dict(black=0, red=1, green=2, yellow=3, blue=4, magenta=5, cyan=6, white=7, default=9) def colour_text(s, fg=None, bg=None, bold=False): seq = [] if bold: seq.append('1') if fg: fgcode = 30 + _colour_codes.get(fg.lower(), 0) seq.append(str(fgcode)) if bg: bgcode = 40 + _colour_codes.get(fg.lower(), 7) seq.append(str(bgcode)) if seq: return '\x1b[%sm%s\x1b[0m' % (';'.join(seq), s) else: return s else: def colour_text(s, fg=None, bg=None): return s def default_text(s): return colour_text(s, 'default') def red_text(s): return colour_text(s, 'red') def green_text(s): return colour_text(s, 'green') def yellow_text(s): return colour_text(s, 'yellow') def cyan_text(s): return colour_text(s, 'cyan') def blue_text(s): return colour_text(s, 'blue') ######################### def cyg2win32(path): if sys.platform=='cygwin' and path.startswith('/cygdrive'): path = path[10] + ':' + os.path.normcase(path[11:]) return path def mingw32(): """Return true when using mingw32 environment. """ if sys.platform=='win32': if os.environ.get('OSTYPE', '')=='msys': return True if os.environ.get('MSYSTEM', '')=='MINGW32': return True return False def msvc_runtime_version(): "Return version of MSVC runtime library, as defined by __MSC_VER__ macro" msc_pos = sys.version.find('MSC v.') if msc_pos != -1: msc_ver = int(sys.version[msc_pos+6:msc_pos+10]) else: msc_ver = None return msc_ver def msvc_runtime_library(): "Return name of MSVC runtime library if Python was built with MSVC >= 7" ver = msvc_runtime_major () if ver: if ver < 140: return "msvcr%i" % ver else: return "vcruntime%i" % ver else: return None def msvc_runtime_major(): "Return major version of MSVC runtime coded like get_build_msvc_version" major = {1300: 70, # MSVC 7.0 1310: 71, # MSVC 7.1 1400: 80, # MSVC 8 1500: 90, # MSVC 9 (aka 2008) 1600: 100, # MSVC 10 (aka 2010) 1900: 140, # MSVC 14 (aka 2015) }.get(msvc_runtime_version(), None) return major ######################### #XXX need support for .C that is also C++ cxx_ext_match = re.compile(r'.*[.](cpp|cxx|cc)\Z', re.I).match fortran_ext_match = re.compile(r'.*[.](f90|f95|f77|for|ftn|f)\Z', re.I).match f90_ext_match = re.compile(r'.*[.](f90|f95)\Z', re.I).match f90_module_name_match = re.compile(r'\s*module\s*(?P<name>[\w_]+)', re.I).match def _get_f90_modules(source): """Return a list of Fortran f90 module names that given source file defines. """ if not f90_ext_match(source): return [] modules = [] f = open(source, 'r') for line in f: m = f90_module_name_match(line) if m: name = m.group('name') modules.append(name) # break # XXX can we assume that there is one module per file? f.close() return modules def is_string(s): return isinstance(s, basestring) def all_strings(lst): """Return True if all items in lst are string objects. """ for item in lst: if not is_string(item): return False return True def is_sequence(seq): if is_string(seq): return False try: len(seq) except Exception: return False return True def is_glob_pattern(s): return is_string(s) and ('*' in s or '?' is s) def as_list(seq): if is_sequence(seq): return list(seq) else: return [seq] def get_language(sources): # not used in numpy/scipy packages, use build_ext.detect_language instead """Determine language value (c,f77,f90) from sources """ language = None for source in sources: if isinstance(source, str): if f90_ext_match(source): language = 'f90' break elif fortran_ext_match(source): language = 'f77' return language def has_f_sources(sources): """Return True if sources contains Fortran files """ for source in sources: if fortran_ext_match(source): return True return False def has_cxx_sources(sources): """Return True if sources contains C++ files """ for source in sources: if cxx_ext_match(source): return True return False def filter_sources(sources): """Return four lists of filenames containing C, C++, Fortran, and Fortran 90 module sources, respectively. """ c_sources = [] cxx_sources = [] f_sources = [] fmodule_sources = [] for source in sources: if fortran_ext_match(source): modules = _get_f90_modules(source) if modules: fmodule_sources.append(source) else: f_sources.append(source) elif cxx_ext_match(source): cxx_sources.append(source) else: c_sources.append(source) return c_sources, cxx_sources, f_sources, fmodule_sources def _get_headers(directory_list): # get *.h files from list of directories headers = [] for d in directory_list: head = glob.glob(os.path.join(d, "*.h")) #XXX: *.hpp files?? headers.extend(head) return headers def _get_directories(list_of_sources): # get unique directories from list of sources. direcs = [] for f in list_of_sources: d = os.path.split(f) if d[0] != '' and not d[0] in direcs: direcs.append(d[0]) return direcs def _commandline_dep_string(cc_args, extra_postargs, pp_opts): """ Return commandline representation used to determine if a file needs to be recompiled """ cmdline = 'commandline: ' cmdline += ' '.join(cc_args) cmdline += ' '.join(extra_postargs) cmdline += ' '.join(pp_opts) + '\n' return cmdline def get_dependencies(sources): #XXX scan sources for include statements return _get_headers(_get_directories(sources)) def is_local_src_dir(directory): """Return true if directory is local directory. """ if not is_string(directory): return False abs_dir = os.path.abspath(directory) c = os.path.commonprefix([os.getcwd(), abs_dir]) new_dir = abs_dir[len(c):].split(os.sep) if new_dir and not new_dir[0]: new_dir = new_dir[1:] if new_dir and new_dir[0]=='build': return False new_dir = os.sep.join(new_dir) return os.path.isdir(new_dir) def general_source_files(top_path): pruned_directories = {'CVS':1, '.svn':1, 'build':1} prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$') for dirpath, dirnames, filenames in os.walk(top_path, topdown=True): pruned = [ d for d in dirnames if d not in pruned_directories ] dirnames[:] = pruned for f in filenames: if not prune_file_pat.search(f): yield os.path.join(dirpath, f) def general_source_directories_files(top_path): """Return a directory name relative to top_path and files contained. """ pruned_directories = ['CVS', '.svn', 'build'] prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$') for dirpath, dirnames, filenames in os.walk(top_path, topdown=True): pruned = [ d for d in dirnames if d not in pruned_directories ] dirnames[:] = pruned for d in dirnames: dpath = os.path.join(dirpath, d) rpath = rel_path(dpath, top_path) files = [] for f in os.listdir(dpath): fn = os.path.join(dpath, f) if os.path.isfile(fn) and not prune_file_pat.search(fn): files.append(fn) yield rpath, files dpath = top_path rpath = rel_path(dpath, top_path) filenames = [os.path.join(dpath, f) for f in os.listdir(dpath) \ if not prune_file_pat.search(f)] files = [f for f in filenames if os.path.isfile(f)] yield rpath, files def get_ext_source_files(ext): # Get sources and any include files in the same directory. filenames = [] sources = [_m for _m in ext.sources if is_string(_m)] filenames.extend(sources) filenames.extend(get_dependencies(sources)) for d in ext.depends: if is_local_src_dir(d): filenames.extend(list(general_source_files(d))) elif os.path.isfile(d): filenames.append(d) return filenames def get_script_files(scripts): scripts = [_m for _m in scripts if is_string(_m)] return scripts def get_lib_source_files(lib): filenames = [] sources = lib[1].get('sources', []) sources = [_m for _m in sources if is_string(_m)] filenames.extend(sources) filenames.extend(get_dependencies(sources)) depends = lib[1].get('depends', []) for d in depends: if is_local_src_dir(d): filenames.extend(list(general_source_files(d))) elif os.path.isfile(d): filenames.append(d) return filenames def get_shared_lib_extension(is_python_ext=False): """Return the correct file extension for shared libraries. Parameters ---------- is_python_ext : bool, optional Whether the shared library is a Python extension. Default is False. Returns ------- so_ext : str The shared library extension. Notes ----- For Python shared libs, `so_ext` will typically be '.so' on Linux and OS X, and '.pyd' on Windows. For Python >= 3.2 `so_ext` has a tag prepended on POSIX systems according to PEP 3149. For Python 3.2 this is implemented on Linux, but not on OS X. """ confvars = distutils.sysconfig.get_config_vars() # SO is deprecated in 3.3.1, use EXT_SUFFIX instead so_ext = confvars.get('EXT_SUFFIX', None) if so_ext is None: so_ext = confvars.get('SO', '') if not is_python_ext: # hardcode known values, config vars (including SHLIB_SUFFIX) are # unreliable (see #3182) # darwin, windows and debug linux are wrong in 3.3.1 and older if (sys.platform.startswith('linux') or sys.platform.startswith('gnukfreebsd')): so_ext = '.so' elif sys.platform.startswith('darwin'): so_ext = '.dylib' elif sys.platform.startswith('win'): so_ext = '.dll' else: # fall back to config vars for unknown platforms # fix long extension for Python >=3.2, see PEP 3149. if 'SOABI' in confvars: # Does nothing unless SOABI config var exists so_ext = so_ext.replace('.' + confvars.get('SOABI'), '', 1) return so_ext def get_data_files(data): if is_string(data): return [data] sources = data[1] filenames = [] for s in sources: if hasattr(s, '__call__'): continue if is_local_src_dir(s): filenames.extend(list(general_source_files(s))) elif is_string(s): if os.path.isfile(s): filenames.append(s) else: print('Not existing data file:', s) else: raise TypeError(repr(s)) return filenames def dot_join(*args): return '.'.join([a for a in args if a]) def get_frame(level=0): """Return frame object from call stack with given level. """ try: return sys._getframe(level+1) except AttributeError: frame = sys.exc_info()[2].tb_frame for _ in range(level+1): frame = frame.f_back return frame ###################### class Configuration(object): _list_keys = ['packages', 'ext_modules', 'data_files', 'include_dirs', 'libraries', 'headers', 'scripts', 'py_modules', 'installed_libraries', 'define_macros'] _dict_keys = ['package_dir', 'installed_pkg_config'] _extra_keys = ['name', 'version'] numpy_include_dirs = [] def __init__(self, package_name=None, parent_name=None, top_path=None, package_path=None, caller_level=1, setup_name='setup.py', **attrs): """Construct configuration instance of a package. package_name -- name of the package Ex.: 'distutils' parent_name -- name of the parent package Ex.: 'numpy' top_path -- directory of the toplevel package Ex.: the directory where the numpy package source sits package_path -- directory of package. Will be computed by magic from the directory of the caller module if not specified Ex.: the directory where numpy.distutils is caller_level -- frame level to caller namespace, internal parameter. """ self.name = dot_join(parent_name, package_name) self.version = None caller_frame = get_frame(caller_level) self.local_path = get_path_from_frame(caller_frame, top_path) # local_path -- directory of a file (usually setup.py) that # defines a configuration() function. # local_path -- directory of a file (usually setup.py) that # defines a configuration() function. if top_path is None: top_path = self.local_path self.local_path = '' if package_path is None: package_path = self.local_path elif os.path.isdir(njoin(self.local_path, package_path)): package_path = njoin(self.local_path, package_path) if not os.path.isdir(package_path or '.'): raise ValueError("%r is not a directory" % (package_path,)) self.top_path = top_path self.package_path = package_path # this is the relative path in the installed package self.path_in_package = os.path.join(*self.name.split('.')) self.list_keys = self._list_keys[:] self.dict_keys = self._dict_keys[:] for n in self.list_keys: v = copy.copy(attrs.get(n, [])) setattr(self, n, as_list(v)) for n in self.dict_keys: v = copy.copy(attrs.get(n, {})) setattr(self, n, v) known_keys = self.list_keys + self.dict_keys self.extra_keys = self._extra_keys[:] for n in attrs.keys(): if n in known_keys: continue a = attrs[n] setattr(self, n, a) if isinstance(a, list): self.list_keys.append(n) elif isinstance(a, dict): self.dict_keys.append(n) else: self.extra_keys.append(n) if os.path.exists(njoin(package_path, '__init__.py')): self.packages.append(self.name) self.package_dir[self.name] = package_path self.options = dict( ignore_setup_xxx_py = False, assume_default_configuration = False, delegate_options_to_subpackages = False, quiet = False, ) caller_instance = None for i in range(1, 3): try: f = get_frame(i) except ValueError: break try: caller_instance = eval('self', f.f_globals, f.f_locals) break except NameError: pass if isinstance(caller_instance, self.__class__): if caller_instance.options['delegate_options_to_subpackages']: self.set_options(**caller_instance.options) self.setup_name = setup_name def todict(self): """ Return a dictionary compatible with the keyword arguments of distutils setup function. Examples -------- >>> setup(**config.todict()) #doctest: +SKIP """ self._optimize_data_files() d = {} known_keys = self.list_keys + self.dict_keys + self.extra_keys for n in known_keys: a = getattr(self, n) if a: d[n] = a return d def info(self, message): if not self.options['quiet']: print(message) def warn(self, message): sys.stderr.write('Warning: %s' % (message,)) def set_options(self, **options): """ Configure Configuration instance. The following options are available: - ignore_setup_xxx_py - assume_default_configuration - delegate_options_to_subpackages - quiet """ for key, value in options.items(): if key in self.options: self.options[key] = value else: raise ValueError('Unknown option: '+key) def get_distribution(self): """Return the distutils distribution object for self.""" from numpy.distutils.core import get_distribution return get_distribution() def _wildcard_get_subpackage(self, subpackage_name, parent_name, caller_level = 1): l = subpackage_name.split('.') subpackage_path = njoin([self.local_path]+l) dirs = [_m for _m in glob.glob(subpackage_path) if os.path.isdir(_m)] config_list = [] for d in dirs: if not os.path.isfile(njoin(d, '__init__.py')): continue if 'build' in d.split(os.sep): continue n = '.'.join(d.split(os.sep)[-len(l):]) c = self.get_subpackage(n, parent_name = parent_name, caller_level = caller_level+1) config_list.extend(c) return config_list def _get_configuration_from_setup_py(self, setup_py, subpackage_name, subpackage_path, parent_name, caller_level = 1): # In case setup_py imports local modules: sys.path.insert(0, os.path.dirname(setup_py)) try: setup_name = os.path.splitext(os.path.basename(setup_py))[0] n = dot_join(self.name, subpackage_name, setup_name) setup_module = npy_load_module('_'.join(n.split('.')), setup_py, ('.py', 'U', 1)) if not hasattr(setup_module, 'configuration'): if not self.options['assume_default_configuration']: self.warn('Assuming default configuration '\ '(%s does not define configuration())'\ % (setup_module)) config = Configuration(subpackage_name, parent_name, self.top_path, subpackage_path, caller_level = caller_level + 1) else: pn = dot_join(*([parent_name] + subpackage_name.split('.')[:-1])) args = (pn,) def fix_args_py2(args): if setup_module.configuration.__code__.co_argcount > 1: args = args + (self.top_path,) return args def fix_args_py3(args): if setup_module.configuration.__code__.co_argcount > 1: args = args + (self.top_path,) return args if sys.version_info[0] < 3: args = fix_args_py2(args) else: args = fix_args_py3(args) config = setup_module.configuration(*args) if config.name!=dot_join(parent_name, subpackage_name): self.warn('Subpackage %r configuration returned as %r' % \ (dot_join(parent_name, subpackage_name), config.name)) finally: del sys.path[0] return config def get_subpackage(self,subpackage_name, subpackage_path=None, parent_name=None, caller_level = 1): """Return list of subpackage configurations. Parameters ---------- subpackage_name : str or None Name of the subpackage to get the configuration. '*' in subpackage_name is handled as a wildcard. subpackage_path : str If None, then the path is assumed to be the local path plus the subpackage_name. If a setup.py file is not found in the subpackage_path, then a default configuration is used. parent_name : str Parent name. """ if subpackage_name is None: if subpackage_path is None: raise ValueError( "either subpackage_name or subpackage_path must be specified") subpackage_name = os.path.basename(subpackage_path) # handle wildcards l = subpackage_name.split('.') if subpackage_path is None and '*' in subpackage_name: return self._wildcard_get_subpackage(subpackage_name, parent_name, caller_level = caller_level+1) assert '*' not in subpackage_name, repr((subpackage_name, subpackage_path, parent_name)) if subpackage_path is None: subpackage_path = njoin([self.local_path] + l) else: subpackage_path = njoin([subpackage_path] + l[:-1]) subpackage_path = self.paths([subpackage_path])[0] setup_py = njoin(subpackage_path, self.setup_name) if not self.options['ignore_setup_xxx_py']: if not os.path.isfile(setup_py): setup_py = njoin(subpackage_path, 'setup_%s.py' % (subpackage_name)) if not os.path.isfile(setup_py): if not self.options['assume_default_configuration']: self.warn('Assuming default configuration '\ '(%s/{setup_%s,setup}.py was not found)' \ % (os.path.dirname(setup_py), subpackage_name)) config = Configuration(subpackage_name, parent_name, self.top_path, subpackage_path, caller_level = caller_level+1) else: config = self._get_configuration_from_setup_py( setup_py, subpackage_name, subpackage_path, parent_name, caller_level = caller_level + 1) if config: return [config] else: return [] def add_subpackage(self,subpackage_name, subpackage_path=None, standalone = False): """Add a sub-package to the current Configuration instance. This is useful in a setup.py script for adding sub-packages to a package. Parameters ---------- subpackage_name : str name of the subpackage subpackage_path : str if given, the subpackage path such as the subpackage is in subpackage_path / subpackage_name. If None,the subpackage is assumed to be located in the local path / subpackage_name. standalone : bool """ if standalone: parent_name = None else: parent_name = self.name config_list = self.get_subpackage(subpackage_name, subpackage_path, parent_name = parent_name, caller_level = 2) if not config_list: self.warn('No configuration returned, assuming unavailable.') for config in config_list: d = config if isinstance(config, Configuration): d = config.todict() assert isinstance(d, dict), repr(type(d)) self.info('Appending %s configuration to %s' \ % (d.get('name'), self.name)) self.dict_append(**d) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized,'\ ' it may be too late to add a subpackage '+ subpackage_name) def add_data_dir(self, data_path): """Recursively add files under data_path to data_files list. Recursively add files under data_path to the list of data_files to be installed (and distributed). The data_path can be either a relative path-name, or an absolute path-name, or a 2-tuple where the first argument shows where in the install directory the data directory should be installed to. Parameters ---------- data_path : seq or str Argument can be either * 2-sequence (<datadir suffix>, <path to data directory>) * path to data directory where python datadir suffix defaults to package dir. Notes ----- Rules for installation paths:: foo/bar -> (foo/bar, foo/bar) -> parent/foo/bar (gun, foo/bar) -> parent/gun foo/* -> (foo/a, foo/a), (foo/b, foo/b) -> parent/foo/a, parent/foo/b (gun, foo/*) -> (gun, foo/a), (gun, foo/b) -> gun (gun/*, foo/*) -> parent/gun/a, parent/gun/b /foo/bar -> (bar, /foo/bar) -> parent/bar (gun, /foo/bar) -> parent/gun (fun/*/gun/*, sun/foo/bar) -> parent/fun/foo/gun/bar Examples -------- For example suppose the source directory contains fun/foo.dat and fun/bar/car.dat: >>> self.add_data_dir('fun') #doctest: +SKIP >>> self.add_data_dir(('sun', 'fun')) #doctest: +SKIP >>> self.add_data_dir(('gun', '/full/path/to/fun'))#doctest: +SKIP Will install data-files to the locations:: <package install directory>/ fun/ foo.dat bar/ car.dat sun/ foo.dat bar/ car.dat gun/ foo.dat car.dat """ if is_sequence(data_path): d, data_path = data_path else: d = None if is_sequence(data_path): [self.add_data_dir((d, p)) for p in data_path] return if not is_string(data_path): raise TypeError("not a string: %r" % (data_path,)) if d is None: if os.path.isabs(data_path): return self.add_data_dir((os.path.basename(data_path), data_path)) return self.add_data_dir((data_path, data_path)) paths = self.paths(data_path, include_non_existing=False) if is_glob_pattern(data_path): if is_glob_pattern(d): pattern_list = allpath(d).split(os.sep) pattern_list.reverse() # /a/*//b/ -> /a/*/b rl = list(range(len(pattern_list)-1)); rl.reverse() for i in rl: if not pattern_list[i]: del pattern_list[i] # for path in paths: if not os.path.isdir(path): print('Not a directory, skipping', path) continue rpath = rel_path(path, self.local_path) path_list = rpath.split(os.sep) path_list.reverse() target_list = [] i = 0 for s in pattern_list: if is_glob_pattern(s): if i>=len(path_list): raise ValueError('cannot fill pattern %r with %r' \ % (d, path)) target_list.append(path_list[i]) else: assert s==path_list[i], repr((s, path_list[i], data_path, d, path, rpath)) target_list.append(s) i += 1 if path_list[i:]: self.warn('mismatch of pattern_list=%s and path_list=%s'\ % (pattern_list, path_list)) target_list.reverse() self.add_data_dir((os.sep.join(target_list), path)) else: for path in paths: self.add_data_dir((d, path)) return assert not is_glob_pattern(d), repr(d) dist = self.get_distribution() if dist is not None and dist.data_files is not None: data_files = dist.data_files else: data_files = self.data_files for path in paths: for d1, f in list(general_source_directories_files(path)): target_path = os.path.join(self.path_in_package, d, d1) data_files.append((target_path, f)) def _optimize_data_files(self): data_dict = {} for p, files in self.data_files: if p not in data_dict: data_dict[p] = set() for f in files: data_dict[p].add(f) self.data_files[:] = [(p, list(files)) for p, files in data_dict.items()] def add_data_files(self,*files): """Add data files to configuration data_files. Parameters ---------- files : sequence Argument(s) can be either * 2-sequence (<datadir prefix>,<path to data file(s)>) * paths to data files where python datadir prefix defaults to package dir. Notes ----- The form of each element of the files sequence is very flexible allowing many combinations of where to get the files from the package and where they should ultimately be installed on the system. The most basic usage is for an element of the files argument sequence to be a simple filename. This will cause that file from the local path to be installed to the installation path of the self.name package (package path). The file argument can also be a relative path in which case the entire relative path will be installed into the package directory. Finally, the file can be an absolute path name in which case the file will be found at the absolute path name but installed to the package path. This basic behavior can be augmented by passing a 2-tuple in as the file argument. The first element of the tuple should specify the relative path (under the package install directory) where the remaining sequence of files should be installed to (it has nothing to do with the file-names in the source distribution). The second element of the tuple is the sequence of files that should be installed. The files in this sequence can be filenames, relative paths, or absolute paths. For absolute paths the file will be installed in the top-level package installation directory (regardless of the first argument). Filenames and relative path names will be installed in the package install directory under the path name given as the first element of the tuple. Rules for installation paths: #. file.txt -> (., file.txt)-> parent/file.txt #. foo/file.txt -> (foo, foo/file.txt) -> parent/foo/file.txt #. /foo/bar/file.txt -> (., /foo/bar/file.txt) -> parent/file.txt #. *.txt -> parent/a.txt, parent/b.txt #. foo/*.txt -> parent/foo/a.txt, parent/foo/b.txt #. */*.txt -> (*, */*.txt) -> parent/c/a.txt, parent/d/b.txt #. (sun, file.txt) -> parent/sun/file.txt #. (sun, bar/file.txt) -> parent/sun/file.txt #. (sun, /foo/bar/file.txt) -> parent/sun/file.txt #. (sun, *.txt) -> parent/sun/a.txt, parent/sun/b.txt #. (sun, bar/*.txt) -> parent/sun/a.txt, parent/sun/b.txt #. (sun/*, */*.txt) -> parent/sun/c/a.txt, parent/d/b.txt An additional feature is that the path to a data-file can actually be a function that takes no arguments and returns the actual path(s) to the data-files. This is useful when the data files are generated while building the package. Examples -------- Add files to the list of data_files to be included with the package. >>> self.add_data_files('foo.dat', ... ('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']), ... 'bar/cat.dat', ... '/full/path/to/can.dat') #doctest: +SKIP will install these data files to:: <package install directory>/ foo.dat fun/ gun.dat nun/ pun.dat sun.dat bar/ car.dat can.dat where <package install directory> is the package (or sub-package) directory such as '/usr/lib/python2.4/site-packages/mypackage' ('C: \\Python2.4 \\Lib \\site-packages \\mypackage') or '/usr/lib/python2.4/site- packages/mypackage/mysubpackage' ('C: \\Python2.4 \\Lib \\site-packages \\mypackage \\mysubpackage'). """ if len(files)>1: for f in files: self.add_data_files(f) return assert len(files)==1 if is_sequence(files[0]): d, files = files[0] else: d = None if is_string(files): filepat = files elif is_sequence(files): if len(files)==1: filepat = files[0] else: for f in files: self.add_data_files((d, f)) return else: raise TypeError(repr(type(files))) if d is None: if hasattr(filepat, '__call__'): d = '' elif os.path.isabs(filepat): d = '' else: d = os.path.dirname(filepat) self.add_data_files((d, files)) return paths = self.paths(filepat, include_non_existing=False) if is_glob_pattern(filepat): if is_glob_pattern(d): pattern_list = d.split(os.sep) pattern_list.reverse() for path in paths: path_list = path.split(os.sep) path_list.reverse() path_list.pop() # filename target_list = [] i = 0 for s in pattern_list: if is_glob_pattern(s): target_list.append(path_list[i]) i += 1 else: target_list.append(s) target_list.reverse() self.add_data_files((os.sep.join(target_list), path)) else: self.add_data_files((d, paths)) return assert not is_glob_pattern(d), repr((d, filepat)) dist = self.get_distribution() if dist is not None and dist.data_files is not None: data_files = dist.data_files else: data_files = self.data_files data_files.append((os.path.join(self.path_in_package, d), paths)) ### XXX Implement add_py_modules def add_define_macros(self, macros): """Add define macros to configuration Add the given sequence of macro name and value duples to the beginning of the define_macros list This list will be visible to all extension modules of the current package. """ dist = self.get_distribution() if dist is not None: if not hasattr(dist, 'define_macros'): dist.define_macros = [] dist.define_macros.extend(macros) else: self.define_macros.extend(macros) def add_include_dirs(self,*paths): """Add paths to configuration include directories. Add the given sequence of paths to the beginning of the include_dirs list. This list will be visible to all extension modules of the current package. """ include_dirs = self.paths(paths) dist = self.get_distribution() if dist is not None: if dist.include_dirs is None: dist.include_dirs = [] dist.include_dirs.extend(include_dirs) else: self.include_dirs.extend(include_dirs) def add_headers(self,*files): """Add installable headers to configuration. Add the given sequence of files to the beginning of the headers list. By default, headers will be installed under <python- include>/<self.name.replace('.','/')>/ directory. If an item of files is a tuple, then its first argument specifies the actual installation location relative to the <python-include> path. Parameters ---------- files : str or seq Argument(s) can be either: * 2-sequence (<includedir suffix>,<path to header file(s)>) * path(s) to header file(s) where python includedir suffix will default to package name. """ headers = [] for path in files: if is_string(path): [headers.append((self.name, p)) for p in self.paths(path)] else: if not isinstance(path, (tuple, list)) or len(path) != 2: raise TypeError(repr(path)) [headers.append((path[0], p)) for p in self.paths(path[1])] dist = self.get_distribution() if dist is not None: if dist.headers is None: dist.headers = [] dist.headers.extend(headers) else: self.headers.extend(headers) def paths(self,*paths,**kws): """Apply glob to paths and prepend local_path if needed. Applies glob.glob(...) to each path in the sequence (if needed) and pre-pends the local_path if needed. Because this is called on all source lists, this allows wildcard characters to be specified in lists of sources for extension modules and libraries and scripts and allows path-names be relative to the source directory. """ include_non_existing = kws.get('include_non_existing', True) return gpaths(paths, local_path = self.local_path, include_non_existing=include_non_existing) def _fix_paths_dict(self, kw): for k in kw.keys(): v = kw[k] if k in ['sources', 'depends', 'include_dirs', 'library_dirs', 'module_dirs', 'extra_objects']: new_v = self.paths(v) kw[k] = new_v def add_extension(self,name,sources,**kw): """Add extension to configuration. Create and add an Extension instance to the ext_modules list. This method also takes the following optional keyword arguments that are passed on to the Extension constructor. Parameters ---------- name : str name of the extension sources : seq list of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built. include_dirs : define_macros : undef_macros : library_dirs : libraries : runtime_library_dirs : extra_objects : extra_compile_args : extra_link_args : extra_f77_compile_args : extra_f90_compile_args : export_symbols : swig_opts : depends : The depends list contains paths to files or directories that the sources of the extension module depend on. If any path in the depends list is newer than the extension module, then the module will be rebuilt. language : f2py_options : module_dirs : extra_info : dict or list dict or list of dict of keywords to be appended to keywords. Notes ----- The self.paths(...) method is applied to all lists that may contain paths. """ ext_args = copy.copy(kw) ext_args['name'] = dot_join(self.name, name) ext_args['sources'] = sources if 'extra_info' in ext_args: extra_info = ext_args['extra_info'] del ext_args['extra_info'] if isinstance(extra_info, dict): extra_info = [extra_info] for info in extra_info: assert isinstance(info, dict), repr(info) dict_append(ext_args,**info) self._fix_paths_dict(ext_args) # Resolve out-of-tree dependencies libraries = ext_args.get('libraries', []) libnames = [] ext_args['libraries'] = [] for libname in libraries: if isinstance(libname, tuple): self._fix_paths_dict(libname[1]) # Handle library names of the form libname@relative/path/to/library if '@' in libname: lname, lpath = libname.split('@', 1) lpath = os.path.abspath(njoin(self.local_path, lpath)) if os.path.isdir(lpath): c = self.get_subpackage(None, lpath, caller_level = 2) if isinstance(c, Configuration): c = c.todict() for l in [l[0] for l in c.get('libraries', [])]: llname = l.split('__OF__', 1)[0] if llname == lname: c.pop('name', None) dict_append(ext_args,**c) break continue libnames.append(libname) ext_args['libraries'] = libnames + ext_args['libraries'] ext_args['define_macros'] = \ self.define_macros + ext_args.get('define_macros', []) from numpy.distutils.core import Extension ext = Extension(**ext_args) self.ext_modules.append(ext) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized,'\ ' it may be too late to add an extension '+name) return ext def add_library(self,name,sources,**build_info): """ Add library to configuration. Parameters ---------- name : str Name of the extension. sources : sequence List of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built. build_info : dict, optional The following keys are allowed: * depends * macros * include_dirs * extra_compiler_args * extra_f77_compile_args * extra_f90_compile_args * f2py_options * language """ self._add_library(name, sources, None, build_info) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized,'\ ' it may be too late to add a library '+ name) def _add_library(self, name, sources, install_dir, build_info): """Common implementation for add_library and add_installed_library. Do not use directly""" build_info = copy.copy(build_info) name = name #+ '__OF__' + self.name build_info['sources'] = sources # Sometimes, depends is not set up to an empty list by default, and if # depends is not given to add_library, distutils barfs (#1134) if not 'depends' in build_info: build_info['depends'] = [] self._fix_paths_dict(build_info) # Add to libraries list so that it is build with build_clib self.libraries.append((name, build_info)) def add_installed_library(self, name, sources, install_dir, build_info=None): """ Similar to add_library, but the specified library is installed. Most C libraries used with `distutils` are only used to build python extensions, but libraries built through this method will be installed so that they can be reused by third-party packages. Parameters ---------- name : str Name of the installed library. sources : sequence List of the library's source files. See `add_library` for details. install_dir : str Path to install the library, relative to the current sub-package. build_info : dict, optional The following keys are allowed: * depends * macros * include_dirs * extra_compiler_args * extra_f77_compile_args * extra_f90_compile_args * f2py_options * language Returns ------- None See Also -------- add_library, add_npy_pkg_config, get_info Notes ----- The best way to encode the options required to link against the specified C libraries is to use a "libname.ini" file, and use `get_info` to retrieve the required options (see `add_npy_pkg_config` for more information). """ if not build_info: build_info = {} install_dir = os.path.join(self.package_path, install_dir) self._add_library(name, sources, install_dir, build_info) self.installed_libraries.append(InstallableLib(name, build_info, install_dir)) def add_npy_pkg_config(self, template, install_dir, subst_dict=None): """ Generate and install a npy-pkg config file from a template. The config file generated from `template` is installed in the given install directory, using `subst_dict` for variable substitution. Parameters ---------- template : str The path of the template, relatively to the current package path. install_dir : str Where to install the npy-pkg config file, relatively to the current package path. subst_dict : dict, optional If given, any string of the form ``@key@`` will be replaced by ``subst_dict[key]`` in the template file when installed. The install prefix is always available through the variable ``@prefix@``, since the install prefix is not easy to get reliably from setup.py. See also -------- add_installed_library, get_info Notes ----- This works for both standard installs and in-place builds, i.e. the ``@prefix@`` refer to the source directory for in-place builds. Examples -------- :: config.add_npy_pkg_config('foo.ini.in', 'lib', {'foo': bar}) Assuming the foo.ini.in file has the following content:: [meta] Name=@foo@ Version=1.0 Description=dummy description [default] Cflags=-I@prefix@/include Libs= The generated file will have the following content:: [meta] Name=bar Version=1.0 Description=dummy description [default] Cflags=-Iprefix_dir/include Libs= and will be installed as foo.ini in the 'lib' subpath. """ if subst_dict is None: subst_dict = {} basename = os.path.splitext(template)[0] template = os.path.join(self.package_path, template) if self.name in self.installed_pkg_config: self.installed_pkg_config[self.name].append((template, install_dir, subst_dict)) else: self.installed_pkg_config[self.name] = [(template, install_dir, subst_dict)] def add_scripts(self,*files): """Add scripts to configuration. Add the sequence of files to the beginning of the scripts list. Scripts will be installed under the <prefix>/bin/ directory. """ scripts = self.paths(files) dist = self.get_distribution() if dist is not None: if dist.scripts is None: dist.scripts = [] dist.scripts.extend(scripts) else: self.scripts.extend(scripts) def dict_append(self,**dict): for key in self.list_keys: a = getattr(self, key) a.extend(dict.get(key, [])) for key in self.dict_keys: a = getattr(self, key) a.update(dict.get(key, {})) known_keys = self.list_keys + self.dict_keys + self.extra_keys for key in dict.keys(): if key not in known_keys: a = getattr(self, key, None) if a and a==dict[key]: continue self.warn('Inheriting attribute %r=%r from %r' \ % (key, dict[key], dict.get('name', '?'))) setattr(self, key, dict[key]) self.extra_keys.append(key) elif key in self.extra_keys: self.info('Ignoring attempt to set %r (from %r to %r)' \ % (key, getattr(self, key), dict[key])) elif key in known_keys: # key is already processed above pass else: raise ValueError("Don't know about key=%r" % (key)) def __str__(self): from pprint import pformat known_keys = self.list_keys + self.dict_keys + self.extra_keys s = '<'+5*'-' + '\n' s += 'Configuration of '+self.name+':\n' known_keys.sort() for k in known_keys: a = getattr(self, k, None) if a: s += '%s = %s\n' % (k, pformat(a)) s += 5*'-' + '>' return s def get_config_cmd(self): """ Returns the numpy.distutils config command instance. """ cmd = get_cmd('config') cmd.ensure_finalized() cmd.dump_source = 0 cmd.noisy = 0 old_path = os.environ.get('PATH') if old_path: path = os.pathsep.join(['.', old_path]) os.environ['PATH'] = path return cmd def get_build_temp_dir(self): """ Return a path to a temporary directory where temporary files should be placed. """ cmd = get_cmd('build') cmd.ensure_finalized() return cmd.build_temp def have_f77c(self): """Check for availability of Fortran 77 compiler. Use it inside source generating function to ensure that setup distribution instance has been initialized. Notes ----- True if a Fortran 77 compiler is available (because a simple Fortran 77 code was able to be compiled successfully). """ simple_fortran_subroutine = ''' subroutine simple end ''' config_cmd = self.get_config_cmd() flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f77') return flag def have_f90c(self): """Check for availability of Fortran 90 compiler. Use it inside source generating function to ensure that setup distribution instance has been initialized. Notes ----- True if a Fortran 90 compiler is available (because a simple Fortran 90 code was able to be compiled successfully) """ simple_fortran_subroutine = ''' subroutine simple end ''' config_cmd = self.get_config_cmd() flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f90') return flag def append_to(self, extlib): """Append libraries, include_dirs to extension or library item. """ if is_sequence(extlib): lib_name, build_info = extlib dict_append(build_info, libraries=self.libraries, include_dirs=self.include_dirs) else: from numpy.distutils.core import Extension assert isinstance(extlib, Extension), repr(extlib) extlib.libraries.extend(self.libraries) extlib.include_dirs.extend(self.include_dirs) def _get_svn_revision(self, path): """Return path's SVN revision number. """ revision = None m = None cwd = os.getcwd() try: os.chdir(path or '.') p = subprocess.Popen(['svnversion'], shell=True, stdout=subprocess.PIPE, stderr=None, close_fds=True) sout = p.stdout m = re.match(r'(?P<revision>\d+)', sout.read()) except Exception: pass os.chdir(cwd) if m: revision = int(m.group('revision')) return revision if sys.platform=='win32' and os.environ.get('SVN_ASP_DOT_NET_HACK', None): entries = njoin(path, '_svn', 'entries') else: entries = njoin(path, '.svn', 'entries') if os.path.isfile(entries): f = open(entries) fstr = f.read() f.close() if fstr[:5] == '<?xml': # pre 1.4 m = re.search(r'revision="(?P<revision>\d+)"', fstr) if m: revision = int(m.group('revision')) else: # non-xml entries file --- check to be sure that m = re.search(r'dir[\n\r]+(?P<revision>\d+)', fstr) if m: revision = int(m.group('revision')) return revision def _get_hg_revision(self, path): """Return path's Mercurial revision number. """ revision = None m = None cwd = os.getcwd() try: os.chdir(path or '.') p = subprocess.Popen(['hg identify --num'], shell=True, stdout=subprocess.PIPE, stderr=None, close_fds=True) sout = p.stdout m = re.match(r'(?P<revision>\d+)', sout.read()) except Exception: pass os.chdir(cwd) if m: revision = int(m.group('revision')) return revision branch_fn = njoin(path, '.hg', 'branch') branch_cache_fn = njoin(path, '.hg', 'branch.cache') if os.path.isfile(branch_fn): branch0 = None f = open(branch_fn) revision0 = f.read().strip() f.close() branch_map = {} for line in file(branch_cache_fn, 'r'): branch1, revision1 = line.split()[:2] if revision1==revision0: branch0 = branch1 try: revision1 = int(revision1) except ValueError: continue branch_map[branch1] = revision1 revision = branch_map.get(branch0) return revision def get_version(self, version_file=None, version_variable=None): """Try to get version string of a package. Return a version string of the current package or None if the version information could not be detected. Notes ----- This method scans files named __version__.py, <packagename>_version.py, version.py, and __svn_version__.py for string variables version, __version__, and <packagename>_version, until a version number is found. """ version = getattr(self, 'version', None) if version is not None: return version # Get version from version file. if version_file is None: files = ['__version__.py', self.name.split('.')[-1]+'_version.py', 'version.py', '__svn_version__.py', '__hg_version__.py'] else: files = [version_file] if version_variable is None: version_vars = ['version', '__version__', self.name.split('.')[-1]+'_version'] else: version_vars = [version_variable] for f in files: fn = njoin(self.local_path, f) if os.path.isfile(fn): info = ('.py', 'U', 1) name = os.path.splitext(os.path.basename(fn))[0] n = dot_join(self.name, name) try: version_module = npy_load_module('_'.join(n.split('.')), fn, info) except ImportError: msg = get_exception() self.warn(str(msg)) version_module = None if version_module is None: continue for a in version_vars: version = getattr(version_module, a, None) if version is not None: break if version is not None: break if version is not None: self.version = version return version # Get version as SVN or Mercurial revision number revision = self._get_svn_revision(self.local_path) if revision is None: revision = self._get_hg_revision(self.local_path) if revision is not None: version = str(revision) self.version = version return version def make_svn_version_py(self, delete=True): """Appends a data function to the data_files list that will generate __svn_version__.py file to the current package directory. Generate package __svn_version__.py file from SVN revision number, it will be removed after python exits but will be available when sdist, etc commands are executed. Notes ----- If __svn_version__.py existed before, nothing is done. This is intended for working with source directories that are in an SVN repository. """ target = njoin(self.local_path, '__svn_version__.py') revision = self._get_svn_revision(self.local_path) if os.path.isfile(target) or revision is None: return else: def generate_svn_version_py(): if not os.path.isfile(target): version = str(revision) self.info('Creating %s (version=%r)' % (target, version)) f = open(target, 'w') f.write('version = %r\n' % (version)) f.close() import atexit def rm_file(f=target,p=self.info): if delete: try: os.remove(f); p('removed '+f) except OSError: pass try: os.remove(f+'c'); p('removed '+f+'c') except OSError: pass atexit.register(rm_file) return target self.add_data_files(('', generate_svn_version_py())) def make_hg_version_py(self, delete=True): """Appends a data function to the data_files list that will generate __hg_version__.py file to the current package directory. Generate package __hg_version__.py file from Mercurial revision, it will be removed after python exits but will be available when sdist, etc commands are executed. Notes ----- If __hg_version__.py existed before, nothing is done. This is intended for working with source directories that are in an Mercurial repository. """ target = njoin(self.local_path, '__hg_version__.py') revision = self._get_hg_revision(self.local_path) if os.path.isfile(target) or revision is None: return else: def generate_hg_version_py(): if not os.path.isfile(target): version = str(revision) self.info('Creating %s (version=%r)' % (target, version)) f = open(target, 'w') f.write('version = %r\n' % (version)) f.close() import atexit def rm_file(f=target,p=self.info): if delete: try: os.remove(f); p('removed '+f) except OSError: pass try: os.remove(f+'c'); p('removed '+f+'c') except OSError: pass atexit.register(rm_file) return target self.add_data_files(('', generate_hg_version_py())) def make_config_py(self,name='__config__'): """Generate package __config__.py file containing system_info information used during building the package. This file is installed to the package installation directory. """ self.py_modules.append((self.name, name, generate_config_py)) def get_info(self,*names): """Get resources information. Return information (from system_info.get_info) for all of the names in the argument list in a single dictionary. """ from .system_info import get_info, dict_append info_dict = {} for a in names: dict_append(info_dict,**get_info(a)) return info_dict def get_cmd(cmdname, _cache={}): if cmdname not in _cache: import distutils.core dist = distutils.core._setup_distribution if dist is None: from distutils.errors import DistutilsInternalError raise DistutilsInternalError( 'setup distribution instance not initialized') cmd = dist.get_command_obj(cmdname) _cache[cmdname] = cmd return _cache[cmdname] def get_numpy_include_dirs(): # numpy_include_dirs are set by numpy/core/setup.py, otherwise [] include_dirs = Configuration.numpy_include_dirs[:] if not include_dirs: import numpy include_dirs = [ numpy.get_include() ] # else running numpy/core/setup.py return include_dirs def get_npy_pkg_dir(): """Return the path where to find the npy-pkg-config directory.""" # XXX: import here for bootstrapping reasons import numpy d = os.path.join(os.path.dirname(numpy.__file__), 'core', 'lib', 'npy-pkg-config') return d def get_pkg_info(pkgname, dirs=None): """ Return library info for the given package. Parameters ---------- pkgname : str Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirs : sequence, optional If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory. Returns ------- pkginfo : class instance The `LibraryInfo` instance containing the build information. Raises ------ PkgNotFound If the package is not found. See Also -------- Configuration.add_npy_pkg_config, Configuration.add_installed_library, get_info """ from numpy.distutils.npy_pkg_config import read_config if dirs: dirs.append(get_npy_pkg_dir()) else: dirs = [get_npy_pkg_dir()] return read_config(pkgname, dirs) def get_info(pkgname, dirs=None): """ Return an info dict for a given C library. The info dict contains the necessary options to use the C library. Parameters ---------- pkgname : str Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirs : sequence, optional If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory. Returns ------- info : dict The dictionary with build information. Raises ------ PkgNotFound If the package is not found. See Also -------- Configuration.add_npy_pkg_config, Configuration.add_installed_library, get_pkg_info Examples -------- To get the necessary information for the npymath library from NumPy: >>> npymath_info = np.distutils.misc_util.get_info('npymath') >>> npymath_info #doctest: +SKIP {'define_macros': [], 'libraries': ['npymath'], 'library_dirs': ['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']} This info dict can then be used as input to a `Configuration` instance:: config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info) """ from numpy.distutils.npy_pkg_config import parse_flags pkg_info = get_pkg_info(pkgname, dirs) # Translate LibraryInfo instance into a build_info dict info = parse_flags(pkg_info.cflags()) for k, v in parse_flags(pkg_info.libs()).items(): info[k].extend(v) # add_extension extra_info argument is ANAL info['define_macros'] = info['macros'] del info['macros'] del info['ignored'] return info def is_bootstrapping(): if sys.version_info[0] >= 3: import builtins else: import __builtin__ as builtins try: builtins.__NUMPY_SETUP__ return True except AttributeError: return False __NUMPY_SETUP__ = False ######################### def default_config_dict(name = None, parent_name = None, local_path=None): """Return a configuration dictionary for usage in configuration() function defined in file setup_<name>.py. """ import warnings warnings.warn('Use Configuration(%r,%r,top_path=%r) instead of '\ 'deprecated default_config_dict(%r,%r,%r)' % (name, parent_name, local_path, name, parent_name, local_path, ), stacklevel=2) c = Configuration(name, parent_name, local_path) return c.todict() def dict_append(d, **kws): for k, v in kws.items(): if k in d: ov = d[k] if isinstance(ov, str): d[k] = v else: d[k].extend(v) else: d[k] = v def appendpath(prefix, path): if os.path.sep != '/': prefix = prefix.replace('/', os.path.sep) path = path.replace('/', os.path.sep) drive = '' if os.path.isabs(path): drive = os.path.splitdrive(prefix)[0] absprefix = os.path.splitdrive(os.path.abspath(prefix))[1] pathdrive, path = os.path.splitdrive(path) d = os.path.commonprefix([absprefix, path]) if os.path.join(absprefix[:len(d)], absprefix[len(d):]) != absprefix \ or os.path.join(path[:len(d)], path[len(d):]) != path: # Handle invalid paths d = os.path.dirname(d) subpath = path[len(d):] if os.path.isabs(subpath): subpath = subpath[1:] else: subpath = path return os.path.normpath(njoin(drive + prefix, subpath)) def generate_config_py(target): """Generate config.py file containing system_info information used during building the package. Usage: config['py_modules'].append((packagename, '__config__',generate_config_py)) """ from numpy.distutils.system_info import system_info from distutils.dir_util import mkpath mkpath(os.path.dirname(target)) f = open(target, 'w') f.write('# This file is generated by numpy\'s %s\n' % (os.path.basename(sys.argv[0]))) f.write('# It contains system_info results at the time of building this package.\n') f.write('__all__ = ["get_info","show"]\n\n') # For gfortran+msvc combination, extra shared libraries may exist f.write(""" import os import sys extra_dll_dir = os.path.join(os.path.dirname(__file__), '.libs') if sys.platform == 'win32' and os.path.isdir(extra_dll_dir): os.environ.setdefault('PATH', '') os.environ['PATH'] += os.pathsep + extra_dll_dir """) for k, i in system_info.saved_results.items(): f.write('%s=%r\n' % (k, i)) f.write(r''' def get_info(name): g = globals() return g.get(name, g.get(name + "_info", {})) def show(): for name,info_dict in globals().items(): if name[0] == "_" or type(info_dict) is not type({}): continue print(name + ":") if not info_dict: print(" NOT AVAILABLE") for k,v in info_dict.items(): v = str(v) if k == "sources" and len(v) > 200: v = v[:60] + " ...\n... " + v[-60:] print(" %s = %s" % (k,v)) ''') f.close() return target def msvc_version(compiler): """Return version major and minor of compiler instance if it is MSVC, raise an exception otherwise.""" if not compiler.compiler_type == "msvc": raise ValueError("Compiler instance is not msvc (%s)"\ % compiler.compiler_type) return compiler._MSVCCompiler__version
82,279
34.374033
102
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/__version__.py
from __future__ import division, absolute_import, print_function major = 0 minor = 4 micro = 0 version = '%(major)d.%(minor)d.%(micro)d' % (locals())
151
20.714286
64
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/pathccompiler.py
from __future__ import division, absolute_import, print_function from distutils.unixccompiler import UnixCCompiler class PathScaleCCompiler(UnixCCompiler): """ PathScale compiler compatible with an gcc built Python. """ compiler_type = 'pathcc' cc_exe = 'pathcc' cxx_exe = 'pathCC' def __init__ (self, verbose=0, dry_run=0, force=0): UnixCCompiler.__init__ (self, verbose, dry_run, force) cc_compiler = self.cc_exe cxx_compiler = self.cxx_exe self.set_executables(compiler=cc_compiler, compiler_so=cc_compiler, compiler_cxx=cxx_compiler, linker_exe=cc_compiler, linker_so=cc_compiler + ' -shared')
779
31.5
64
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/log.py
# Colored log, requires Python 2.3 or up. from __future__ import division, absolute_import, print_function import sys from distutils.log import * from distutils.log import Log as old_Log from distutils.log import _global_log if sys.version_info[0] < 3: from .misc_util import (red_text, default_text, cyan_text, green_text, is_sequence, is_string) else: from numpy.distutils.misc_util import (red_text, default_text, cyan_text, green_text, is_sequence, is_string) def _fix_args(args,flag=1): if is_string(args): return args.replace('%', '%%') if flag and is_sequence(args): return tuple([_fix_args(a, flag=0) for a in args]) return args class Log(old_Log): def _log(self, level, msg, args): if level >= self.threshold: if args: msg = msg % _fix_args(args) if 0: if msg.startswith('copying ') and msg.find(' -> ') != -1: return if msg.startswith('byte-compiling '): return print(_global_color_map[level](msg)) sys.stdout.flush() def good(self, msg, *args): """ If we log WARN messages, log this message as a 'nice' anti-warn message. """ if WARN >= self.threshold: if args: print(green_text(msg % _fix_args(args))) else: print(green_text(msg)) sys.stdout.flush() _global_log.__class__ = Log good = _global_log.good def set_threshold(level, force=False): prev_level = _global_log.threshold if prev_level > DEBUG or force: # If we're running at DEBUG, don't change the threshold, as there's # likely a good reason why we're running at this level. _global_log.threshold = level if level <= DEBUG: info('set_threshold: setting threshold to DEBUG level,' ' it can be changed only with force argument') else: info('set_threshold: not changing threshold from DEBUG level' ' %s to %s' % (prev_level, level)) return prev_level def set_verbosity(v, force=False): prev_level = _global_log.threshold if v < 0: set_threshold(ERROR, force) elif v == 0: set_threshold(WARN, force) elif v == 1: set_threshold(INFO, force) elif v >= 2: set_threshold(DEBUG, force) return {FATAL:-2,ERROR:-1,WARN:0,INFO:1,DEBUG:2}.get(prev_level, 1) _global_color_map = { DEBUG:cyan_text, INFO:default_text, WARN:red_text, ERROR:red_text, FATAL:red_text } # don't use INFO,.. flags in set_verbosity, these flags are for set_threshold. set_verbosity(0, force=True)
2,745
28.212766
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/lib2def.py
from __future__ import division, absolute_import, print_function import re import sys import os import subprocess __doc__ = """This module generates a DEF file from the symbols in an MSVC-compiled DLL import library. It correctly discriminates between data and functions. The data is collected from the output of the program nm(1). Usage: python lib2def.py [libname.lib] [output.def] or python lib2def.py [libname.lib] > output.def libname.lib defaults to python<py_ver>.lib and output.def defaults to stdout Author: Robert Kern <[email protected]> Last Update: April 30, 1999 """ __version__ = '0.1a' py_ver = "%d%d" % tuple(sys.version_info[:2]) DEFAULT_NM = 'nm -Cs' DEF_HEADER = """LIBRARY python%s.dll ;CODE PRELOAD MOVEABLE DISCARDABLE ;DATA PRELOAD SINGLE EXPORTS """ % py_ver # the header of the DEF file FUNC_RE = re.compile(r"^(.*) in python%s\.dll" % py_ver, re.MULTILINE) DATA_RE = re.compile(r"^_imp__(.*) in python%s\.dll" % py_ver, re.MULTILINE) def parse_cmd(): """Parses the command-line arguments. libfile, deffile = parse_cmd()""" if len(sys.argv) == 3: if sys.argv[1][-4:] == '.lib' and sys.argv[2][-4:] == '.def': libfile, deffile = sys.argv[1:] elif sys.argv[1][-4:] == '.def' and sys.argv[2][-4:] == '.lib': deffile, libfile = sys.argv[1:] else: print("I'm assuming that your first argument is the library") print("and the second is the DEF file.") elif len(sys.argv) == 2: if sys.argv[1][-4:] == '.def': deffile = sys.argv[1] libfile = 'python%s.lib' % py_ver elif sys.argv[1][-4:] == '.lib': deffile = None libfile = sys.argv[1] else: libfile = 'python%s.lib' % py_ver deffile = None return libfile, deffile def getnm(nm_cmd = ['nm', '-Cs', 'python%s.lib' % py_ver]): """Returns the output of nm_cmd via a pipe. nm_output = getnam(nm_cmd = 'nm -Cs py_lib')""" f = subprocess.Popen(nm_cmd, shell=True, stdout=subprocess.PIPE, universal_newlines=True) nm_output = f.stdout.read() f.stdout.close() return nm_output def parse_nm(nm_output): """Returns a tuple of lists: dlist for the list of data symbols and flist for the list of function symbols. dlist, flist = parse_nm(nm_output)""" data = DATA_RE.findall(nm_output) func = FUNC_RE.findall(nm_output) flist = [] for sym in data: if sym in func and (sym[:2] == 'Py' or sym[:3] == '_Py' or sym[:4] == 'init'): flist.append(sym) dlist = [] for sym in data: if sym not in flist and (sym[:2] == 'Py' or sym[:3] == '_Py'): dlist.append(sym) dlist.sort() flist.sort() return dlist, flist def output_def(dlist, flist, header, file = sys.stdout): """Outputs the final DEF file to a file defaulting to stdout. output_def(dlist, flist, header, file = sys.stdout)""" for data_sym in dlist: header = header + '\t%s DATA\n' % data_sym header = header + '\n' # blank line for func_sym in flist: header = header + '\t%s\n' % func_sym file.write(header) if __name__ == '__main__': libfile, deffile = parse_cmd() if deffile is None: deffile = sys.stdout else: deffile = open(deffile, 'w') nm_cmd = [str(DEFAULT_NM), str(libfile)] nm_output = getnm(nm_cmd) dlist, flist = parse_nm(nm_output) output_def(dlist, flist, DEF_HEADER, deffile)
3,512
29.025641
93
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/msvc9compiler.py
from __future__ import division, absolute_import, print_function import os from distutils.msvc9compiler import MSVCCompiler as _MSVCCompiler from .system_info import platform_bits def _merge(old, new): """Concatenate two environment paths avoiding repeats. Here `old` is the environment string before the base class initialize function is called and `new` is the string after the call. The new string will be a fixed string if it is not obtained from the current environment, or the same as the old string if obtained from the same environment. The aim here is not to append the new string if it is already contained in the old string so as to limit the growth of the environment string. Parameters ---------- old : string Previous environment string. new : string New environment string. Returns ------- ret : string Updated environment string. """ if not old: return new if new in old: return old # Neither new nor old is empty. Give old priority. return ';'.join([old, new]) class MSVCCompiler(_MSVCCompiler): def __init__(self, verbose=0, dry_run=0, force=0): _MSVCCompiler.__init__(self, verbose, dry_run, force) def initialize(self, plat_name=None): # The 'lib' and 'include' variables may be overwritten # by MSVCCompiler.initialize, so save them for later merge. environ_lib = os.getenv('lib') environ_include = os.getenv('include') _MSVCCompiler.initialize(self, plat_name) # Merge current and previous values of 'lib' and 'include' os.environ['lib'] = _merge(environ_lib, os.environ['lib']) os.environ['include'] = _merge(environ_include, os.environ['include']) # msvc9 building for 32 bits requires SSE2 to work around a # compiler bug. if platform_bits == 32: self.compile_options += ['/arch:SSE2'] self.compile_options_debug += ['/arch:SSE2'] def manifest_setup_ldargs(self, output_filename, build_temp, ld_args): ld_args.append('/MANIFEST') _MSVCCompiler.manifest_setup_ldargs(self, output_filename, build_temp, ld_args)
2,258
33.227273
80
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/from_template.py
#!/usr/bin/env python """ process_file(filename) takes templated file .xxx.src and produces .xxx file where .xxx is .pyf .f90 or .f using the following template rules: '<..>' denotes a template. All function and subroutine blocks in a source file with names that contain '<..>' will be replicated according to the rules in '<..>'. The number of comma-separated words in '<..>' will determine the number of replicates. '<..>' may have two different forms, named and short. For example, named: <p=d,s,z,c> where anywhere inside a block '<p>' will be replaced with 'd', 's', 'z', and 'c' for each replicate of the block. <_c> is already defined: <_c=s,d,c,z> <_t> is already defined: <_t=real,double precision,complex,double complex> short: <s,d,c,z>, a short form of the named, useful when no <p> appears inside a block. In general, '<..>' contains a comma separated list of arbitrary expressions. If these expression must contain a comma|leftarrow|rightarrow, then prepend the comma|leftarrow|rightarrow with a backslash. If an expression matches '\\<index>' then it will be replaced by <index>-th expression. Note that all '<..>' forms in a block must have the same number of comma-separated entries. Predefined named template rules: <prefix=s,d,c,z> <ftype=real,double precision,complex,double complex> <ftypereal=real,double precision,\\0,\\1> <ctype=float,double,complex_float,complex_double> <ctypereal=float,double,\\0,\\1> """ from __future__ import division, absolute_import, print_function __all__ = ['process_str', 'process_file'] import os import sys import re routine_start_re = re.compile(r'(\n|\A)(( (\$|\*))|)\s*(subroutine|function)\b', re.I) routine_end_re = re.compile(r'\n\s*end\s*(subroutine|function)\b.*(\n|\Z)', re.I) function_start_re = re.compile(r'\n (\$|\*)\s*function\b', re.I) def parse_structure(astr): """ Return a list of tuples for each function or subroutine each tuple is the start and end of a subroutine or function to be expanded. """ spanlist = [] ind = 0 while True: m = routine_start_re.search(astr, ind) if m is None: break start = m.start() if function_start_re.match(astr, start, m.end()): while True: i = astr.rfind('\n', ind, start) if i==-1: break start = i if astr[i:i+7]!='\n $': break start += 1 m = routine_end_re.search(astr, m.end()) ind = end = m and m.end()-1 or len(astr) spanlist.append((start, end)) return spanlist template_re = re.compile(r"<\s*(\w[\w\d]*)\s*>") named_re = re.compile(r"<\s*(\w[\w\d]*)\s*=\s*(.*?)\s*>") list_re = re.compile(r"<\s*((.*?))\s*>") def find_repl_patterns(astr): reps = named_re.findall(astr) names = {} for rep in reps: name = rep[0].strip() or unique_key(names) repl = rep[1].replace(r'\,', '@comma@') thelist = conv(repl) names[name] = thelist return names item_re = re.compile(r"\A\\(?P<index>\d+)\Z") def conv(astr): b = astr.split(',') l = [x.strip() for x in b] for i in range(len(l)): m = item_re.match(l[i]) if m: j = int(m.group('index')) l[i] = l[j] return ','.join(l) def unique_key(adict): """ Obtain a unique key given a dictionary.""" allkeys = list(adict.keys()) done = False n = 1 while not done: newkey = '__l%s' % (n) if newkey in allkeys: n += 1 else: done = True return newkey template_name_re = re.compile(r'\A\s*(\w[\w\d]*)\s*\Z') def expand_sub(substr, names): substr = substr.replace(r'\>', '@rightarrow@') substr = substr.replace(r'\<', '@leftarrow@') lnames = find_repl_patterns(substr) substr = named_re.sub(r"<\1>", substr) # get rid of definition templates def listrepl(mobj): thelist = conv(mobj.group(1).replace(r'\,', '@comma@')) if template_name_re.match(thelist): return "<%s>" % (thelist) name = None for key in lnames.keys(): # see if list is already in dictionary if lnames[key] == thelist: name = key if name is None: # this list is not in the dictionary yet name = unique_key(lnames) lnames[name] = thelist return "<%s>" % name substr = list_re.sub(listrepl, substr) # convert all lists to named templates # newnames are constructed as needed numsubs = None base_rule = None rules = {} for r in template_re.findall(substr): if r not in rules: thelist = lnames.get(r, names.get(r, None)) if thelist is None: raise ValueError('No replicates found for <%s>' % (r)) if r not in names and not thelist.startswith('_'): names[r] = thelist rule = [i.replace('@comma@', ',') for i in thelist.split(',')] num = len(rule) if numsubs is None: numsubs = num rules[r] = rule base_rule = r elif num == numsubs: rules[r] = rule else: print("Mismatch in number of replacements (base <%s=%s>)" " for <%s=%s>. Ignoring." % (base_rule, ','.join(rules[base_rule]), r, thelist)) if not rules: return substr def namerepl(mobj): name = mobj.group(1) return rules.get(name, (k+1)*[name])[k] newstr = '' for k in range(numsubs): newstr += template_re.sub(namerepl, substr) + '\n\n' newstr = newstr.replace('@rightarrow@', '>') newstr = newstr.replace('@leftarrow@', '<') return newstr def process_str(allstr): newstr = allstr writestr = '' #_head # using _head will break free-format files struct = parse_structure(newstr) oldend = 0 names = {} names.update(_special_names) for sub in struct: writestr += newstr[oldend:sub[0]] names.update(find_repl_patterns(newstr[oldend:sub[0]])) writestr += expand_sub(newstr[sub[0]:sub[1]], names) oldend = sub[1] writestr += newstr[oldend:] return writestr include_src_re = re.compile(r"(\n|\A)\s*include\s*['\"](?P<name>[\w\d./\\]+[.]src)['\"]", re.I) def resolve_includes(source): d = os.path.dirname(source) fid = open(source) lines = [] for line in fid: m = include_src_re.match(line) if m: fn = m.group('name') if not os.path.isabs(fn): fn = os.path.join(d, fn) if os.path.isfile(fn): print('Including file', fn) lines.extend(resolve_includes(fn)) else: lines.append(line) else: lines.append(line) fid.close() return lines def process_file(source): lines = resolve_includes(source) return process_str(''.join(lines)) _special_names = find_repl_patterns(''' <_c=s,d,c,z> <_t=real,double precision,complex,double complex> <prefix=s,d,c,z> <ftype=real,double precision,complex,double complex> <ctype=float,double,complex_float,complex_double> <ftypereal=real,double precision,\\0,\\1> <ctypereal=float,double,\\0,\\1> ''') if __name__ == "__main__": try: file = sys.argv[1] except IndexError: fid = sys.stdin outfile = sys.stdout else: fid = open(file, 'r') (base, ext) = os.path.splitext(file) newname = base outfile = open(newname, 'w') allstr = fid.read() writestr = process_str(allstr) outfile.write(writestr)
7,830
29.470817
95
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/numpy_distribution.py
# XXX: Handle setuptools ? from __future__ import division, absolute_import, print_function from distutils.core import Distribution # This class is used because we add new files (sconscripts, and so on) with the # scons command class NumpyDistribution(Distribution): def __init__(self, attrs = None): # A list of (sconscripts, pre_hook, post_hook, src, parent_names) self.scons_data = [] # A list of installable libraries self.installed_libraries = [] # A dict of pkg_config files to generate/install self.installed_pkg_config = {} Distribution.__init__(self, attrs) def has_scons_scripts(self): return bool(self.scons_data)
700
34.05
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/msvccompiler.py
from __future__ import division, absolute_import, print_function import os from distutils.msvccompiler import MSVCCompiler as _MSVCCompiler from .system_info import platform_bits def _merge(old, new): """Concatenate two environment paths avoiding repeats. Here `old` is the environment string before the base class initialize function is called and `new` is the string after the call. The new string will be a fixed string if it is not obtained from the current enviroment, or the same as the old string if obtained from the same enviroment. The aim here is not to append the new string if it is already contained in the old string so as to limit the growth of the environment string. Parameters ---------- old : string Previous enviroment string. new : string New environment string. Returns ------- ret : string Updated environment string. """ if new in old: return old if not old: return new # Neither new nor old is empty. Give old priority. return ';'.join([old, new]) class MSVCCompiler(_MSVCCompiler): def __init__(self, verbose=0, dry_run=0, force=0): _MSVCCompiler.__init__(self, verbose, dry_run, force) def initialize(self): # The 'lib' and 'include' variables may be overwritten # by MSVCCompiler.initialize, so save them for later merge. environ_lib = os.getenv('lib', '') environ_include = os.getenv('include', '') _MSVCCompiler.initialize(self) # Merge current and previous values of 'lib' and 'include' os.environ['lib'] = _merge(environ_lib, os.environ['lib']) os.environ['include'] = _merge(environ_include, os.environ['include']) # msvc9 building for 32 bits requires SSE2 to work around a # compiler bug. if platform_bits == 32: self.compile_options += ['/arch:SSE2'] self.compile_options_debug += ['/arch:SSE2']
1,991
31.655738
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/mingw32ccompiler.py
""" Support code for building Python extensions on Windows. # NT stuff # 1. Make sure libpython<version>.a exists for gcc. If not, build it. # 2. Force windows to use gcc (we're struggling with MSVC and g77 support) # 3. Force windows to use g77 """ from __future__ import division, absolute_import, print_function import os import sys import subprocess import re # Overwrite certain distutils.ccompiler functions: import numpy.distutils.ccompiler if sys.version_info[0] < 3: from . import log else: from numpy.distutils import log # NT stuff # 1. Make sure libpython<version>.a exists for gcc. If not, build it. # 2. Force windows to use gcc (we're struggling with MSVC and g77 support) # --> this is done in numpy/distutils/ccompiler.py # 3. Force windows to use g77 import distutils.cygwinccompiler from distutils.version import StrictVersion from numpy.distutils.ccompiler import gen_preprocess_options, gen_lib_options from distutils.unixccompiler import UnixCCompiler from distutils.msvccompiler import get_build_version as get_build_msvc_version from distutils.errors import (DistutilsExecError, CompileError, UnknownFileError) from numpy.distutils.misc_util import (msvc_runtime_library, msvc_runtime_version, msvc_runtime_major, get_build_architecture) def get_msvcr_replacement(): """Replacement for outdated version of get_msvcr from cygwinccompiler""" msvcr = msvc_runtime_library() return [] if msvcr is None else [msvcr] # monkey-patch cygwinccompiler with our updated version from misc_util # to avoid getting an exception raised on Python 3.5 distutils.cygwinccompiler.get_msvcr = get_msvcr_replacement # Useful to generate table of symbols from a dll _START = re.compile(r'\[Ordinal/Name Pointer\] Table') _TABLE = re.compile(r'^\s+\[([\s*[0-9]*)\] ([a-zA-Z0-9_]*)') # the same as cygwin plus some additional parameters class Mingw32CCompiler(distutils.cygwinccompiler.CygwinCCompiler): """ A modified MingW32 compiler compatible with an MSVC built Python. """ compiler_type = 'mingw32' def __init__ (self, verbose=0, dry_run=0, force=0): distutils.cygwinccompiler.CygwinCCompiler.__init__ (self, verbose, dry_run, force) # we need to support 3.2 which doesn't match the standard # get_versions methods regex if self.gcc_version is None: import re p = subprocess.Popen(['gcc', '-dumpversion'], shell=True, stdout=subprocess.PIPE) out_string = p.stdout.read() p.stdout.close() result = re.search(r'(\d+\.\d+)', out_string) if result: self.gcc_version = StrictVersion(result.group(1)) # A real mingw32 doesn't need to specify a different entry point, # but cygwin 2.91.57 in no-cygwin-mode needs it. if self.gcc_version <= "2.91.57": entry_point = '--entry _DllMain@12' else: entry_point = '' if self.linker_dll == 'dllwrap': # Commented out '--driver-name g++' part that fixes weird # g++.exe: g++: No such file or directory # error (mingw 1.0 in Enthon24 tree, gcc-3.4.5). # If the --driver-name part is required for some environment # then make the inclusion of this part specific to that # environment. self.linker = 'dllwrap' # --driver-name g++' elif self.linker_dll == 'gcc': self.linker = 'g++' # **changes: eric jones 4/11/01 # 1. Check for import library on Windows. Build if it doesn't exist. build_import_library() # Check for custom msvc runtime library on Windows. Build if it doesn't exist. msvcr_success = build_msvcr_library() msvcr_dbg_success = build_msvcr_library(debug=True) if msvcr_success or msvcr_dbg_success: # add preprocessor statement for using customized msvcr lib self.define_macro('NPY_MINGW_USE_CUSTOM_MSVCR') # Define the MSVC version as hint for MinGW msvcr_version = msvc_runtime_version() if msvcr_version: self.define_macro('__MSVCRT_VERSION__', '0x%04i' % msvcr_version) # MS_WIN64 should be defined when building for amd64 on windows, # but python headers define it only for MS compilers, which has all # kind of bad consequences, like using Py_ModuleInit4 instead of # Py_ModuleInit4_64, etc... So we add it here if get_build_architecture() == 'AMD64': if self.gcc_version < "4.0": self.set_executables( compiler='gcc -g -DDEBUG -DMS_WIN64 -mno-cygwin -O0 -Wall', compiler_so='gcc -g -DDEBUG -DMS_WIN64 -mno-cygwin -O0' ' -Wall -Wstrict-prototypes', linker_exe='gcc -g -mno-cygwin', linker_so='gcc -g -mno-cygwin -shared') else: # gcc-4 series releases do not support -mno-cygwin option self.set_executables( compiler='gcc -g -DDEBUG -DMS_WIN64 -O0 -Wall', compiler_so='gcc -g -DDEBUG -DMS_WIN64 -O0 -Wall -Wstrict-prototypes', linker_exe='gcc -g', linker_so='gcc -g -shared') else: if self.gcc_version <= "3.0.0": self.set_executables( compiler='gcc -mno-cygwin -O2 -w', compiler_so='gcc -mno-cygwin -mdll -O2 -w' ' -Wstrict-prototypes', linker_exe='g++ -mno-cygwin', linker_so='%s -mno-cygwin -mdll -static %s' % (self.linker, entry_point)) elif self.gcc_version < "4.0": self.set_executables( compiler='gcc -mno-cygwin -O2 -Wall', compiler_so='gcc -mno-cygwin -O2 -Wall' ' -Wstrict-prototypes', linker_exe='g++ -mno-cygwin', linker_so='g++ -mno-cygwin -shared') else: # gcc-4 series releases do not support -mno-cygwin option self.set_executables(compiler='gcc -O2 -Wall', compiler_so='gcc -O2 -Wall -Wstrict-prototypes', linker_exe='g++ ', linker_so='g++ -shared') # added for python2.3 support # we can't pass it through set_executables because pre 2.2 would fail self.compiler_cxx = ['g++'] # Maybe we should also append -mthreads, but then the finished dlls # need another dll (mingwm10.dll see Mingw32 docs) (-mthreads: Support # thread-safe exception handling on `Mingw32') # no additional libraries needed #self.dll_libraries=[] return # __init__ () def link(self, target_desc, objects, output_filename, output_dir, libraries, library_dirs, runtime_library_dirs, export_symbols = None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): # Include the appropriate MSVC runtime library if Python was built # with MSVC >= 7.0 (MinGW standard is msvcrt) runtime_library = msvc_runtime_library() if runtime_library: if not libraries: libraries = [] libraries.append(runtime_library) args = (self, target_desc, objects, output_filename, output_dir, libraries, library_dirs, runtime_library_dirs, None, #export_symbols, we do this in our def-file debug, extra_preargs, extra_postargs, build_temp, target_lang) if self.gcc_version < "3.0.0": func = distutils.cygwinccompiler.CygwinCCompiler.link else: func = UnixCCompiler.link func(*args[:func.__code__.co_argcount]) return def object_filenames (self, source_filenames, strip_dir=0, output_dir=''): if output_dir is None: output_dir = '' obj_names = [] for src_name in source_filenames: # use normcase to make sure '.rc' is really '.rc' and not '.RC' (base, ext) = os.path.splitext (os.path.normcase(src_name)) # added these lines to strip off windows drive letters # without it, .o files are placed next to .c files # instead of the build directory drv, base = os.path.splitdrive(base) if drv: base = base[1:] if ext not in (self.src_extensions + ['.rc', '.res']): raise UnknownFileError( "unknown file type '%s' (from '%s')" % \ (ext, src_name)) if strip_dir: base = os.path.basename (base) if ext == '.res' or ext == '.rc': # these need to be compiled to object files obj_names.append (os.path.join (output_dir, base + ext + self.obj_extension)) else: obj_names.append (os.path.join (output_dir, base + self.obj_extension)) return obj_names # object_filenames () def find_python_dll(): # We can't do much here: # - find it in the virtualenv (sys.prefix) # - find it in python main dir (sys.base_prefix, if in a virtualenv) # - sys.real_prefix is main dir for virtualenvs in Python 2.7 # - in system32, # - ortherwise (Sxs), I don't know how to get it. stems = [sys.prefix] if hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix: stems.append(sys.base_prefix) elif hasattr(sys, 'real_prefix') and sys.real_prefix != sys.prefix: stems.append(sys.real_prefix) sub_dirs = ['', 'lib', 'bin'] # generate possible combinations of directory trees and sub-directories lib_dirs = [] for stem in stems: for folder in sub_dirs: lib_dirs.append(os.path.join(stem, folder)) # add system directory as well if 'SYSTEMROOT' in os.environ: lib_dirs.append(os.path.join(os.environ['SYSTEMROOT'], 'System32')) # search in the file system for possible candidates major_version, minor_version = tuple(sys.version_info[:2]) patterns = ['python%d%d.dll'] for pat in patterns: dllname = pat % (major_version, minor_version) print("Looking for %s" % dllname) for folder in lib_dirs: dll = os.path.join(folder, dllname) if os.path.exists(dll): return dll raise ValueError("%s not found in %s" % (dllname, lib_dirs)) def dump_table(dll): st = subprocess.Popen(["objdump.exe", "-p", dll], stdout=subprocess.PIPE) return st.stdout.readlines() def generate_def(dll, dfile): """Given a dll file location, get all its exported symbols and dump them into the given def file. The .def file will be overwritten""" dump = dump_table(dll) for i in range(len(dump)): if _START.match(dump[i].decode()): break else: raise ValueError("Symbol table not found") syms = [] for j in range(i+1, len(dump)): m = _TABLE.match(dump[j].decode()) if m: syms.append((int(m.group(1).strip()), m.group(2))) else: break if len(syms) == 0: log.warn('No symbols found in %s' % dll) d = open(dfile, 'w') d.write('LIBRARY %s\n' % os.path.basename(dll)) d.write(';CODE PRELOAD MOVEABLE DISCARDABLE\n') d.write(';DATA PRELOAD SINGLE\n') d.write('\nEXPORTS\n') for s in syms: #d.write('@%d %s\n' % (s[0], s[1])) d.write('%s\n' % s[1]) d.close() def find_dll(dll_name): arch = {'AMD64' : 'amd64', 'Intel' : 'x86'}[get_build_architecture()] def _find_dll_in_winsxs(dll_name): # Walk through the WinSxS directory to find the dll. winsxs_path = os.path.join(os.environ.get('WINDIR', r'C:\WINDOWS'), 'winsxs') if not os.path.exists(winsxs_path): return None for root, dirs, files in os.walk(winsxs_path): if dll_name in files and arch in root: return os.path.join(root, dll_name) return None def _find_dll_in_path(dll_name): # First, look in the Python directory, then scan PATH for # the given dll name. for path in [sys.prefix] + os.environ['PATH'].split(';'): filepath = os.path.join(path, dll_name) if os.path.exists(filepath): return os.path.abspath(filepath) return _find_dll_in_winsxs(dll_name) or _find_dll_in_path(dll_name) def build_msvcr_library(debug=False): if os.name != 'nt': return False # If the version number is None, then we couldn't find the MSVC runtime at # all, because we are running on a Python distribution which is customed # compiled; trust that the compiler is the same as the one available to us # now, and that it is capable of linking with the correct runtime without # any extra options. msvcr_ver = msvc_runtime_major() if msvcr_ver is None: log.debug('Skip building import library: ' 'Runtime is not compiled with MSVC') return False # Skip using a custom library for versions < MSVC 8.0 if msvcr_ver < 80: log.debug('Skip building msvcr library:' ' custom functionality not present') return False msvcr_name = msvc_runtime_library() if debug: msvcr_name += 'd' # Skip if custom library already exists out_name = "lib%s.a" % msvcr_name out_file = os.path.join(sys.prefix, 'libs', out_name) if os.path.isfile(out_file): log.debug('Skip building msvcr library: "%s" exists' % (out_file,)) return True # Find the msvcr dll msvcr_dll_name = msvcr_name + '.dll' dll_file = find_dll(msvcr_dll_name) if not dll_file: log.warn('Cannot build msvcr library: "%s" not found' % msvcr_dll_name) return False def_name = "lib%s.def" % msvcr_name def_file = os.path.join(sys.prefix, 'libs', def_name) log.info('Building msvcr library: "%s" (from %s)' \ % (out_file, dll_file)) # Generate a symbol definition file from the msvcr dll generate_def(dll_file, def_file) # Create a custom mingw library for the given symbol definitions cmd = ['dlltool', '-d', def_file, '-l', out_file] retcode = subprocess.call(cmd) # Clean up symbol definitions os.remove(def_file) return (not retcode) def build_import_library(): if os.name != 'nt': return arch = get_build_architecture() if arch == 'AMD64': return _build_import_library_amd64() elif arch == 'Intel': return _build_import_library_x86() else: raise ValueError("Unhandled arch %s" % arch) def _check_for_import_lib(): """Check if an import library for the Python runtime already exists.""" major_version, minor_version = tuple(sys.version_info[:2]) # patterns for the file name of the library itself patterns = ['libpython%d%d.a', 'libpython%d%d.dll.a', 'libpython%d.%d.dll.a'] # directory trees that may contain the library stems = [sys.prefix] if hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix: stems.append(sys.base_prefix) elif hasattr(sys, 'real_prefix') and sys.real_prefix != sys.prefix: stems.append(sys.real_prefix) # possible subdirectories within those trees where it is placed sub_dirs = ['libs', 'lib'] # generate a list of candidate locations candidates = [] for pat in patterns: filename = pat % (major_version, minor_version) for stem_dir in stems: for folder in sub_dirs: candidates.append(os.path.join(stem_dir, folder, filename)) # test the filesystem to see if we can find any of these for fullname in candidates: if os.path.isfile(fullname): # already exists, in location given return (True, fullname) # needs to be built, preferred location given first return (False, candidates[0]) def _build_import_library_amd64(): out_exists, out_file = _check_for_import_lib() if out_exists: log.debug('Skip building import library: "%s" exists', out_file) return # get the runtime dll for which we are building import library dll_file = find_python_dll() log.info('Building import library (arch=AMD64): "%s" (from %s)' % (out_file, dll_file)) # generate symbol list from this library def_name = "python%d%d.def" % tuple(sys.version_info[:2]) def_file = os.path.join(sys.prefix, 'libs', def_name) generate_def(dll_file, def_file) # generate import library from this symbol list cmd = ['dlltool', '-d', def_file, '-l', out_file] subprocess.Popen(cmd) def _build_import_library_x86(): """ Build the import libraries for Mingw32-gcc on Windows """ out_exists, out_file = _check_for_import_lib() if out_exists: log.debug('Skip building import library: "%s" exists', out_file) return lib_name = "python%d%d.lib" % tuple(sys.version_info[:2]) lib_file = os.path.join(sys.prefix, 'libs', lib_name) if not os.path.isfile(lib_file): # didn't find library file in virtualenv, try base distribution, too, # and use that instead if found there. for Python 2.7 venvs, the base # directory is in attribute real_prefix instead of base_prefix. if hasattr(sys, 'base_prefix'): base_lib = os.path.join(sys.base_prefix, 'libs', lib_name) elif hasattr(sys, 'real_prefix'): base_lib = os.path.join(sys.real_prefix, 'libs', lib_name) else: base_lib = '' # os.path.isfile('') == False if os.path.isfile(base_lib): lib_file = base_lib else: log.warn('Cannot build import library: "%s" not found', lib_file) return log.info('Building import library (ARCH=x86): "%s"', out_file) from numpy.distutils import lib2def def_name = "python%d%d.def" % tuple(sys.version_info[:2]) def_file = os.path.join(sys.prefix, 'libs', def_name) nm_cmd = '%s %s' % (lib2def.DEFAULT_NM, lib_file) nm_output = lib2def.getnm(nm_cmd) dlist, flist = lib2def.parse_nm(nm_output) lib2def.output_def(dlist, flist, lib2def.DEF_HEADER, open(def_file, 'w')) dll_name = find_python_dll () args = (dll_name, def_file, out_file) cmd = 'dlltool --dllname "%s" --def "%s" --output-lib "%s"' % args status = os.system(cmd) # for now, fail silently if status: log.warn('Failed to build import library for gcc. Linking will fail.') return #===================================== # Dealing with Visual Studio MANIFESTS #===================================== # Functions to deal with visual studio manifests. Manifest are a mechanism to # enforce strong DLL versioning on windows, and has nothing to do with # distutils MANIFEST. manifests are XML files with version info, and used by # the OS loader; they are necessary when linking against a DLL not in the # system path; in particular, official python 2.6 binary is built against the # MS runtime 9 (the one from VS 2008), which is not available on most windows # systems; python 2.6 installer does install it in the Win SxS (Side by side) # directory, but this requires the manifest for this to work. This is a big # mess, thanks MS for a wonderful system. # XXX: ideally, we should use exactly the same version as used by python. I # submitted a patch to get this version, but it was only included for python # 2.6.1 and above. So for versions below, we use a "best guess". _MSVCRVER_TO_FULLVER = {} if sys.platform == 'win32': try: import msvcrt # I took one version in my SxS directory: no idea if it is the good # one, and we can't retrieve it from python _MSVCRVER_TO_FULLVER['80'] = "8.0.50727.42" _MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8" # Value from msvcrt.CRT_ASSEMBLY_VERSION under Python 3.3.0 # on Windows XP: _MSVCRVER_TO_FULLVER['100'] = "10.0.30319.460" if hasattr(msvcrt, "CRT_ASSEMBLY_VERSION"): major, minor, rest = msvcrt.CRT_ASSEMBLY_VERSION.split(".", 2) _MSVCRVER_TO_FULLVER[major + minor] = msvcrt.CRT_ASSEMBLY_VERSION del major, minor, rest except ImportError: # If we are here, means python was not built with MSVC. Not sure what # to do in that case: manifest building will fail, but it should not be # used in that case anyway log.warn('Cannot import msvcrt: using manifest will not be possible') def msvc_manifest_xml(maj, min): """Given a major and minor version of the MSVCR, returns the corresponding XML file.""" try: fullver = _MSVCRVER_TO_FULLVER[str(maj * 10 + min)] except KeyError: raise ValueError("Version %d,%d of MSVCRT not supported yet" % (maj, min)) # Don't be fooled, it looks like an XML, but it is not. In particular, it # should not have any space before starting, and its size should be # divisible by 4, most likely for alignement constraints when the xml is # embedded in the binary... # This template was copied directly from the python 2.6 binary (using # strings.exe from mingw on python.exe). template = """\ <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel> </requestedPrivileges> </security> </trustInfo> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC%(maj)d%(min)d.CRT" version="%(fullver)s" processorArchitecture="*" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity> </dependentAssembly> </dependency> </assembly>""" return template % {'fullver': fullver, 'maj': maj, 'min': min} def manifest_rc(name, type='dll'): """Return the rc file used to generate the res file which will be embedded as manifest for given manifest file name, of given type ('dll' or 'exe'). Parameters ---------- name : str name of the manifest file to embed type : str {'dll', 'exe'} type of the binary which will embed the manifest """ if type == 'dll': rctype = 2 elif type == 'exe': rctype = 1 else: raise ValueError("Type %s not supported" % type) return """\ #include "winuser.h" %d RT_MANIFEST %s""" % (rctype, name) def check_embedded_msvcr_match_linked(msver): """msver is the ms runtime version used for the MANIFEST.""" # check msvcr major version are the same for linking and # embedding maj = msvc_runtime_major() if maj: if not maj == int(msver): raise ValueError( "Discrepancy between linked msvcr " \ "(%d) and the one about to be embedded " \ "(%d)" % (int(msver), maj)) def configtest_name(config): base = os.path.basename(config._gen_temp_sourcefile("yo", [], "c")) return os.path.splitext(base)[0] def manifest_name(config): # Get configest name (including suffix) root = configtest_name(config) exext = config.compiler.exe_extension return root + exext + ".manifest" def rc_name(config): # Get configtest name (including suffix) root = configtest_name(config) return root + ".rc" def generate_manifest(config): msver = get_build_msvc_version() if msver is not None: if msver >= 8: check_embedded_msvcr_match_linked(msver) ma = int(msver) mi = int((msver - ma) * 10) # Write the manifest file manxml = msvc_manifest_xml(ma, mi) man = open(manifest_name(config), "w") config.temp_files.append(manifest_name(config)) man.write(manxml) man.close()
25,201
37.300912
176
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/info.py
""" Enhanced distutils with Fortran compilers support and more. """ from __future__ import division, absolute_import, print_function postpone_import = True
157
21.571429
64
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/__init__.py
from __future__ import division, absolute_import, print_function import sys from .__version__ import version as __version__ # Must import local ccompiler ASAP in order to get # customized CCompiler.spawn effective. from . import ccompiler from . import unixccompiler from .info import __doc__ from .npy_pkg_config import * # If numpy is installed, add distutils.test() try: from . import __config__ # Normally numpy is installed if the above import works, but an interrupted # in-place build could also have left a __config__.py. In that case the # next import may still fail, so keep it inside the try block. from numpy.testing.nosetester import _numpy_tester test = _numpy_tester().test except ImportError: pass def customized_fcompiler(plat=None, compiler=None): from numpy.distutils.fcompiler import new_fcompiler c = new_fcompiler(plat=plat, compiler=compiler) c.customize() return c def customized_ccompiler(plat=None, compiler=None): c = ccompiler.new_compiler(plat=plat, compiler=compiler) c.customize('') return c
1,088
29.25
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/conv_template.py
#!/usr/bin/env python """ takes templated file .xxx.src and produces .xxx file where .xxx is .i or .c or .h, using the following template rules /**begin repeat -- on a line by itself marks the start of a repeated code segment /**end repeat**/ -- on a line by itself marks it's end After the /**begin repeat and before the */, all the named templates are placed these should all have the same number of replacements Repeat blocks can be nested, with each nested block labeled with its depth, i.e. /**begin repeat1 *.... */ /**end repeat1**/ When using nested loops, you can optionally exclude particular combinations of the variables using (inside the comment portion of the inner loop): :exclude: var1=value1, var2=value2, ... This will exclude the pattern where var1 is value1 and var2 is value2 when the result is being generated. In the main body each replace will use one entry from the list of named replacements Note that all #..# forms in a block must have the same number of comma-separated entries. Example: An input file containing /**begin repeat * #a = 1,2,3# * #b = 1,2,3# */ /**begin repeat1 * #c = ted, jim# */ @a@, @b@, @c@ /**end repeat1**/ /**end repeat**/ produces line 1 "template.c.src" /* ********************************************************************* ** This file was autogenerated from a template DO NOT EDIT!!** ** Changes should be made to the original source (.src) file ** ********************************************************************* */ #line 9 1, 1, ted #line 9 1, 1, jim #line 9 2, 2, ted #line 9 2, 2, jim #line 9 3, 3, ted #line 9 3, 3, jim """ from __future__ import division, absolute_import, print_function __all__ = ['process_str', 'process_file'] import os import sys import re from numpy.distutils.compat import get_exception # names for replacement that are already global. global_names = {} # header placed at the front of head processed file header =\ """ /* ***************************************************************************** ** This file was autogenerated from a template DO NOT EDIT!!!! ** ** Changes should be made to the original source (.src) file ** ***************************************************************************** */ """ # Parse string for repeat loops def parse_structure(astr, level): """ The returned line number is from the beginning of the string, starting at zero. Returns an empty list if no loops found. """ if level == 0 : loopbeg = "/**begin repeat" loopend = "/**end repeat**/" else : loopbeg = "/**begin repeat%d" % level loopend = "/**end repeat%d**/" % level ind = 0 line = 0 spanlist = [] while True: start = astr.find(loopbeg, ind) if start == -1: break start2 = astr.find("*/", start) start2 = astr.find("\n", start2) fini1 = astr.find(loopend, start2) fini2 = astr.find("\n", fini1) line += astr.count("\n", ind, start2+1) spanlist.append((start, start2+1, fini1, fini2+1, line)) line += astr.count("\n", start2+1, fini2) ind = fini2 spanlist.sort() return spanlist def paren_repl(obj): torep = obj.group(1) numrep = obj.group(2) return ','.join([torep]*int(numrep)) parenrep = re.compile(r"[(]([^)]*)[)]\*(\d+)") plainrep = re.compile(r"([^*]+)\*(\d+)") def parse_values(astr): # replaces all occurrences of '(a,b,c)*4' in astr # with 'a,b,c,a,b,c,a,b,c,a,b,c'. Empty braces generate # empty values, i.e., ()*4 yields ',,,'. The result is # split at ',' and a list of values returned. astr = parenrep.sub(paren_repl, astr) # replaces occurrences of xxx*3 with xxx, xxx, xxx astr = ','.join([plainrep.sub(paren_repl, x.strip()) for x in astr.split(',')]) return astr.split(',') stripast = re.compile(r"\n\s*\*?") named_re = re.compile(r"#\s*(\w*)\s*=([^#]*)#") exclude_vars_re = re.compile(r"(\w*)=(\w*)") exclude_re = re.compile(":exclude:") def parse_loop_header(loophead) : """Find all named replacements in the header Returns a list of dictionaries, one for each loop iteration, where each key is a name to be substituted and the corresponding value is the replacement string. Also return a list of exclusions. The exclusions are dictionaries of key value pairs. There can be more than one exclusion. [{'var1':'value1', 'var2', 'value2'[,...]}, ...] """ # Strip out '\n' and leading '*', if any, in continuation lines. # This should not effect code previous to this change as # continuation lines were not allowed. loophead = stripast.sub("", loophead) # parse out the names and lists of values names = [] reps = named_re.findall(loophead) nsub = None for rep in reps: name = rep[0] vals = parse_values(rep[1]) size = len(vals) if nsub is None : nsub = size elif nsub != size : msg = "Mismatch in number of values, %d != %d\n%s = %s" raise ValueError(msg % (nsub, size, name, vals)) names.append((name, vals)) # Find any exclude variables excludes = [] for obj in exclude_re.finditer(loophead): span = obj.span() # find next newline endline = loophead.find('\n', span[1]) substr = loophead[span[1]:endline] ex_names = exclude_vars_re.findall(substr) excludes.append(dict(ex_names)) # generate list of dictionaries, one for each template iteration dlist = [] if nsub is None : raise ValueError("No substitution variables found") for i in range(nsub) : tmp = {} for name, vals in names : tmp[name] = vals[i] dlist.append(tmp) return dlist replace_re = re.compile(r"@([\w]+)@") def parse_string(astr, env, level, line) : lineno = "#line %d\n" % line # local function for string replacement, uses env def replace(match): name = match.group(1) try : val = env[name] except KeyError: msg = 'line %d: no definition of key "%s"'%(line, name) raise ValueError(msg) return val code = [lineno] struct = parse_structure(astr, level) if struct : # recurse over inner loops oldend = 0 newlevel = level + 1 for sub in struct: pref = astr[oldend:sub[0]] head = astr[sub[0]:sub[1]] text = astr[sub[1]:sub[2]] oldend = sub[3] newline = line + sub[4] code.append(replace_re.sub(replace, pref)) try : envlist = parse_loop_header(head) except ValueError: e = get_exception() msg = "line %d: %s" % (newline, e) raise ValueError(msg) for newenv in envlist : newenv.update(env) newcode = parse_string(text, newenv, newlevel, newline) code.extend(newcode) suff = astr[oldend:] code.append(replace_re.sub(replace, suff)) else : # replace keys code.append(replace_re.sub(replace, astr)) code.append('\n') return ''.join(code) def process_str(astr): code = [header] code.extend(parse_string(astr, global_names, 0, 1)) return ''.join(code) include_src_re = re.compile(r"(\n|\A)#include\s*['\"]" r"(?P<name>[\w\d./\\]+[.]src)['\"]", re.I) def resolve_includes(source): d = os.path.dirname(source) fid = open(source) lines = [] for line in fid: m = include_src_re.match(line) if m: fn = m.group('name') if not os.path.isabs(fn): fn = os.path.join(d, fn) if os.path.isfile(fn): print('Including file', fn) lines.extend(resolve_includes(fn)) else: lines.append(line) else: lines.append(line) fid.close() return lines def process_file(source): lines = resolve_includes(source) sourcefile = os.path.normcase(source).replace("\\", "\\\\") try: code = process_str(''.join(lines)) except ValueError: e = get_exception() raise ValueError('In "%s" loop at %s' % (sourcefile, e)) return '#line 1 "%s"\n%s' % (sourcefile, code) def unique_key(adict): # this obtains a unique key given a dictionary # currently it works by appending together n of the letters of the # current keys and increasing n until a unique key is found # -- not particularly quick allkeys = list(adict.keys()) done = False n = 1 while not done: newkey = "".join([x[:n] for x in allkeys]) if newkey in allkeys: n += 1 else: done = True return newkey if __name__ == "__main__": try: file = sys.argv[1] except IndexError: fid = sys.stdin outfile = sys.stdout else: fid = open(file, 'r') (base, ext) = os.path.splitext(file) newname = base outfile = open(newname, 'w') allstr = fid.read() try: writestr = process_str(allstr) except ValueError: e = get_exception() raise ValueError("In %s loop at %s" % (file, e)) outfile.write(writestr)
9,709
27.727811
84
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/npy_pkg_config.py
from __future__ import division, absolute_import, print_function import sys import re import os if sys.version_info[0] < 3: from ConfigParser import RawConfigParser, NoOptionError else: from configparser import RawConfigParser, NoOptionError __all__ = ['FormatError', 'PkgNotFound', 'LibraryInfo', 'VariableSet', 'read_config', 'parse_flags'] _VAR = re.compile(r'\$\{([a-zA-Z0-9_-]+)\}') class FormatError(IOError): """ Exception thrown when there is a problem parsing a configuration file. """ def __init__(self, msg): self.msg = msg def __str__(self): return self.msg class PkgNotFound(IOError): """Exception raised when a package can not be located.""" def __init__(self, msg): self.msg = msg def __str__(self): return self.msg def parse_flags(line): """ Parse a line from a config file containing compile flags. Parameters ---------- line : str A single line containing one or more compile flags. Returns ------- d : dict Dictionary of parsed flags, split into relevant categories. These categories are the keys of `d`: * 'include_dirs' * 'library_dirs' * 'libraries' * 'macros' * 'ignored' """ d = {'include_dirs': [], 'library_dirs': [], 'libraries': [], 'macros': [], 'ignored': []} flags = (' ' + line).split(' -') for flag in flags: flag = '-' + flag if len(flag) > 0: if flag.startswith('-I'): d['include_dirs'].append(flag[2:].strip()) elif flag.startswith('-L'): d['library_dirs'].append(flag[2:].strip()) elif flag.startswith('-l'): d['libraries'].append(flag[2:].strip()) elif flag.startswith('-D'): d['macros'].append(flag[2:].strip()) else: d['ignored'].append(flag) return d def _escape_backslash(val): return val.replace('\\', '\\\\') class LibraryInfo(object): """ Object containing build information about a library. Parameters ---------- name : str The library name. description : str Description of the library. version : str Version string. sections : dict The sections of the configuration file for the library. The keys are the section headers, the values the text under each header. vars : class instance A `VariableSet` instance, which contains ``(name, value)`` pairs for variables defined in the configuration file for the library. requires : sequence, optional The required libraries for the library to be installed. Notes ----- All input parameters (except "sections" which is a method) are available as attributes of the same name. """ def __init__(self, name, description, version, sections, vars, requires=None): self.name = name self.description = description if requires: self.requires = requires else: self.requires = [] self.version = version self._sections = sections self.vars = vars def sections(self): """ Return the section headers of the config file. Parameters ---------- None Returns ------- keys : list of str The list of section headers. """ return list(self._sections.keys()) def cflags(self, section="default"): val = self.vars.interpolate(self._sections[section]['cflags']) return _escape_backslash(val) def libs(self, section="default"): val = self.vars.interpolate(self._sections[section]['libs']) return _escape_backslash(val) def __str__(self): m = ['Name: %s' % self.name, 'Description: %s' % self.description] if self.requires: m.append('Requires:') else: m.append('Requires: %s' % ",".join(self.requires)) m.append('Version: %s' % self.version) return "\n".join(m) class VariableSet(object): """ Container object for the variables defined in a config file. `VariableSet` can be used as a plain dictionary, with the variable names as keys. Parameters ---------- d : dict Dict of items in the "variables" section of the configuration file. """ def __init__(self, d): self._raw_data = dict([(k, v) for k, v in d.items()]) self._re = {} self._re_sub = {} self._init_parse() def _init_parse(self): for k, v in self._raw_data.items(): self._init_parse_var(k, v) def _init_parse_var(self, name, value): self._re[name] = re.compile(r'\$\{%s\}' % name) self._re_sub[name] = value def interpolate(self, value): # Brute force: we keep interpolating until there is no '${var}' anymore # or until interpolated string is equal to input string def _interpolate(value): for k in self._re.keys(): value = self._re[k].sub(self._re_sub[k], value) return value while _VAR.search(value): nvalue = _interpolate(value) if nvalue == value: break value = nvalue return value def variables(self): """ Return the list of variable names. Parameters ---------- None Returns ------- names : list of str The names of all variables in the `VariableSet` instance. """ return list(self._raw_data.keys()) # Emulate a dict to set/get variables values def __getitem__(self, name): return self._raw_data[name] def __setitem__(self, name, value): self._raw_data[name] = value self._init_parse_var(name, value) def parse_meta(config): if not config.has_section('meta'): raise FormatError("No meta section found !") d = {} for name, value in config.items('meta'): d[name] = value for k in ['name', 'description', 'version']: if not k in d: raise FormatError("Option %s (section [meta]) is mandatory, " "but not found" % k) if not 'requires' in d: d['requires'] = [] return d def parse_variables(config): if not config.has_section('variables'): raise FormatError("No variables section found !") d = {} for name, value in config.items("variables"): d[name] = value return VariableSet(d) def parse_sections(config): return meta_d, r def pkg_to_filename(pkg_name): return "%s.ini" % pkg_name def parse_config(filename, dirs=None): if dirs: filenames = [os.path.join(d, filename) for d in dirs] else: filenames = [filename] config = RawConfigParser() n = config.read(filenames) if not len(n) >= 1: raise PkgNotFound("Could not find file(s) %s" % str(filenames)) # Parse meta and variables sections meta = parse_meta(config) vars = {} if config.has_section('variables'): for name, value in config.items("variables"): vars[name] = _escape_backslash(value) # Parse "normal" sections secs = [s for s in config.sections() if not s in ['meta', 'variables']] sections = {} requires = {} for s in secs: d = {} if config.has_option(s, "requires"): requires[s] = config.get(s, 'requires') for name, value in config.items(s): d[name] = value sections[s] = d return meta, vars, sections, requires def _read_config_imp(filenames, dirs=None): def _read_config(f): meta, vars, sections, reqs = parse_config(f, dirs) # recursively add sections and variables of required libraries for rname, rvalue in reqs.items(): nmeta, nvars, nsections, nreqs = _read_config(pkg_to_filename(rvalue)) # Update var dict for variables not in 'top' config file for k, v in nvars.items(): if not k in vars: vars[k] = v # Update sec dict for oname, ovalue in nsections[rname].items(): if ovalue: sections[rname][oname] += ' %s' % ovalue return meta, vars, sections, reqs meta, vars, sections, reqs = _read_config(filenames) # FIXME: document this. If pkgname is defined in the variables section, and # there is no pkgdir variable defined, pkgdir is automatically defined to # the path of pkgname. This requires the package to be imported to work if not 'pkgdir' in vars and "pkgname" in vars: pkgname = vars["pkgname"] if not pkgname in sys.modules: raise ValueError("You should import %s to get information on %s" % (pkgname, meta["name"])) mod = sys.modules[pkgname] vars["pkgdir"] = _escape_backslash(os.path.dirname(mod.__file__)) return LibraryInfo(name=meta["name"], description=meta["description"], version=meta["version"], sections=sections, vars=VariableSet(vars)) # Trivial cache to cache LibraryInfo instances creation. To be really # efficient, the cache should be handled in read_config, since a same file can # be parsed many time outside LibraryInfo creation, but I doubt this will be a # problem in practice _CACHE = {} def read_config(pkgname, dirs=None): """ Return library info for a package from its configuration file. Parameters ---------- pkgname : str Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirs : sequence, optional If given, should be a sequence of directories - usually including the NumPy base directory - where to look for npy-pkg-config files. Returns ------- pkginfo : class instance The `LibraryInfo` instance containing the build information. Raises ------ PkgNotFound If the package is not found. See Also -------- misc_util.get_info, misc_util.get_pkg_info Examples -------- >>> npymath_info = np.distutils.npy_pkg_config.read_config('npymath') >>> type(npymath_info) <class 'numpy.distutils.npy_pkg_config.LibraryInfo'> >>> print(npymath_info) Name: npymath Description: Portable, core math library implementing C99 standard Requires: Version: 0.1 #random """ try: return _CACHE[pkgname] except KeyError: v = _read_config_imp(pkg_to_filename(pkgname), dirs) _CACHE[pkgname] = v return v # TODO: # - implements version comparison (modversion + atleast) # pkg-config simple emulator - useful for debugging, and maybe later to query # the system if __name__ == '__main__': import sys from optparse import OptionParser import glob parser = OptionParser() parser.add_option("--cflags", dest="cflags", action="store_true", help="output all preprocessor and compiler flags") parser.add_option("--libs", dest="libs", action="store_true", help="output all linker flags") parser.add_option("--use-section", dest="section", help="use this section instead of default for options") parser.add_option("--version", dest="version", action="store_true", help="output version") parser.add_option("--atleast-version", dest="min_version", help="Minimal version") parser.add_option("--list-all", dest="list_all", action="store_true", help="Minimal version") parser.add_option("--define-variable", dest="define_variable", help="Replace variable with the given value") (options, args) = parser.parse_args(sys.argv) if len(args) < 2: raise ValueError("Expect package name on the command line:") if options.list_all: files = glob.glob("*.ini") for f in files: info = read_config(f) print("%s\t%s - %s" % (info.name, info.name, info.description)) pkg_name = args[1] import os d = os.environ.get('NPY_PKG_CONFIG_PATH') if d: info = read_config(pkg_name, ['numpy/core/lib/npy-pkg-config', '.', d]) else: info = read_config(pkg_name, ['numpy/core/lib/npy-pkg-config', '.']) if options.section: section = options.section else: section = "default" if options.define_variable: m = re.search(r'([\S]+)=([\S]+)', options.define_variable) if not m: raise ValueError("--define-variable option should be of " \ "the form --define-variable=foo=bar") else: name = m.group(1) value = m.group(2) info.vars[name] = value if options.cflags: print(info.cflags(section)) if options.libs: print(info.libs(section)) if options.version: print(info.version) if options.min_version: print(info.version >= options.min_version)
13,243
28.628635
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/__config__.py
# This file is generated by numpy's setup.py # It contains system_info results at the time of building this package. __all__ = ["get_info","show"] import os import sys extra_dll_dir = os.path.join(os.path.dirname(__file__), '.libs') if sys.platform == 'win32' and os.path.isdir(extra_dll_dir): os.environ.setdefault('PATH', '') os.environ['PATH'] += os.pathsep + extra_dll_dir blas_mkl_info={} blis_info={} openblas_info={} atlas_3_10_blas_threads_info={} atlas_3_10_blas_info={} atlas_blas_threads_info={} atlas_blas_info={} blas_opt_info={'extra_compile_args': ['-msse3', '-I/System/Library/Frameworks/vecLib.framework/Headers'], 'extra_link_args': ['-Wl,-framework', '-Wl,Accelerate'], 'define_macros': [('NO_ATLAS_INFO', 3), ('HAVE_CBLAS', None)]} lapack_mkl_info={} openblas_lapack_info={} openblas_clapack_info={} atlas_3_10_threads_info={} atlas_3_10_info={} atlas_threads_info={} atlas_info={} lapack_opt_info={'extra_compile_args': ['-msse3'], 'extra_link_args': ['-Wl,-framework', '-Wl,Accelerate'], 'define_macros': [('NO_ATLAS_INFO', 3), ('HAVE_CBLAS', None)]} def get_info(name): g = globals() return g.get(name, g.get(name + "_info", {})) def show(): for name,info_dict in globals().items(): if name[0] == "_" or type(info_dict) is not type({}): continue print(name + ":") if not info_dict: print(" NOT AVAILABLE") for k,v in info_dict.items(): v = str(v) if k == "sources" and len(v) > 200: v = v[:60] + " ...\n... " + v[-60:] print(" %s = %s" % (k,v))
1,597
34.511111
225
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/line_endings.py
""" Functions for converting from DOS to UNIX line endings """ from __future__ import division, absolute_import, print_function import sys, re, os def dos2unix(file): "Replace CRLF with LF in argument files. Print names of changed files." if os.path.isdir(file): print(file, "Directory!") return data = open(file, "rb").read() if '\0' in data: print(file, "Binary!") return newdata = re.sub("\r\n", "\n", data) if newdata != data: print('dos2unix:', file) f = open(file, "wb") f.write(newdata) f.close() return file else: print(file, 'ok') def dos2unix_one_dir(modified_files, dir_name, file_names): for file in file_names: full_path = os.path.join(dir_name, file) file = dos2unix(full_path) if file is not None: modified_files.append(file) def dos2unix_dir(dir_name): modified_files = [] os.path.walk(dir_name, dos2unix_one_dir, modified_files) return modified_files #---------------------------------- def unix2dos(file): "Replace LF with CRLF in argument files. Print names of changed files." if os.path.isdir(file): print(file, "Directory!") return data = open(file, "rb").read() if '\0' in data: print(file, "Binary!") return newdata = re.sub("\r\n", "\n", data) newdata = re.sub("\n", "\r\n", newdata) if newdata != data: print('unix2dos:', file) f = open(file, "wb") f.write(newdata) f.close() return file else: print(file, 'ok') def unix2dos_one_dir(modified_files, dir_name, file_names): for file in file_names: full_path = os.path.join(dir_name, file) unix2dos(full_path) if file is not None: modified_files.append(file) def unix2dos_dir(dir_name): modified_files = [] os.path.walk(dir_name, unix2dos_one_dir, modified_files) return modified_files if __name__ == "__main__": dos2unix_dir(sys.argv[1])
2,053
25.675325
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/compat.py
"""Small modules to cope with python 2 vs 3 incompatibilities inside numpy.distutils """ from __future__ import division, absolute_import, print_function import sys def get_exception(): return sys.exc_info()[1]
218
18.909091
68
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/system_info.py
#!/usr/bin/env python """ This file defines a set of system_info classes for getting information about various resources (libraries, library directories, include directories, etc.) in the system. Currently, the following classes are available: atlas_info atlas_threads_info atlas_blas_info atlas_blas_threads_info lapack_atlas_info lapack_atlas_threads_info atlas_3_10_info atlas_3_10_threads_info atlas_3_10_blas_info, atlas_3_10_blas_threads_info, lapack_atlas_3_10_info lapack_atlas_3_10_threads_info blas_info lapack_info openblas_info blis_info blas_opt_info # usage recommended lapack_opt_info # usage recommended fftw_info,dfftw_info,sfftw_info fftw_threads_info,dfftw_threads_info,sfftw_threads_info djbfft_info x11_info lapack_src_info blas_src_info numpy_info numarray_info numpy_info boost_python_info agg2_info wx_info gdk_pixbuf_xlib_2_info gdk_pixbuf_2_info gdk_x11_2_info gtkp_x11_2_info gtkp_2_info xft_info freetype2_info umfpack_info Usage: info_dict = get_info(<name>) where <name> is a string 'atlas','x11','fftw','lapack','blas', 'lapack_src', 'blas_src', etc. For a complete list of allowed names, see the definition of get_info() function below. Returned info_dict is a dictionary which is compatible with distutils.setup keyword arguments. If info_dict == {}, then the asked resource is not available (system_info could not find it). Several *_info classes specify an environment variable to specify the locations of software. When setting the corresponding environment variable to 'None' then the software will be ignored, even when it is available in system. Global parameters: system_info.search_static_first - search static libraries (.a) in precedence to shared ones (.so, .sl) if enabled. system_info.verbosity - output the results to stdout if enabled. The file 'site.cfg' is looked for in 1) Directory of main setup.py file being run. 2) Home directory of user running the setup.py file as ~/.numpy-site.cfg 3) System wide directory (location of this file...) The first one found is used to get system configuration options The format is that used by ConfigParser (i.e., Windows .INI style). The section ALL has options that are the default for each section. The available sections are fftw, atlas, and x11. Appropriate defaults are used if nothing is specified. The order of finding the locations of resources is the following: 1. environment variable 2. section in site.cfg 3. ALL section in site.cfg Only the first complete match is returned. Example: ---------- [ALL] library_dirs = /usr/lib:/usr/local/lib:/opt/lib include_dirs = /usr/include:/usr/local/include:/opt/include src_dirs = /usr/local/src:/opt/src # search static libraries (.a) in preference to shared ones (.so) search_static_first = 0 [fftw] fftw_libs = rfftw, fftw fftw_opt_libs = rfftw_threaded, fftw_threaded # if the above aren't found, look for {s,d}fftw_libs and {s,d}fftw_opt_libs [atlas] library_dirs = /usr/lib/3dnow:/usr/lib/3dnow/atlas # for overriding the names of the atlas libraries atlas_libs = lapack, f77blas, cblas, atlas [x11] library_dirs = /usr/X11R6/lib include_dirs = /usr/X11R6/include ---------- Authors: Pearu Peterson <[email protected]>, February 2002 David M. Cooke <[email protected]>, April 2002 Copyright 2002 Pearu Peterson all rights reserved, Pearu Peterson <[email protected]> Permission to use, modify, and distribute this software is given under the terms of the NumPy (BSD style) license. See LICENSE.txt that came with this distribution for specifics. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. """ from __future__ import division, absolute_import, print_function import sys import os import re import copy import warnings import atexit from glob import glob from functools import reduce if sys.version_info[0] < 3: from ConfigParser import NoOptionError from ConfigParser import RawConfigParser as ConfigParser else: from configparser import NoOptionError from configparser import RawConfigParser as ConfigParser # It seems that some people are importing ConfigParser from here so is # good to keep its class name. Use of RawConfigParser is needed in # order to be able to load path names with percent in them, like # `feature%2Fcool` which is common on git flow branch names. from distutils.errors import DistutilsError from distutils.dist import Distribution import distutils.sysconfig from distutils import log from distutils.util import get_platform from numpy.distutils.exec_command import ( find_executable, exec_command, get_pythonexe) from numpy.distutils.misc_util import (is_sequence, is_string, get_shared_lib_extension) from numpy.distutils.command.config import config as cmd_config from numpy.distutils.compat import get_exception from numpy.distutils import customized_ccompiler import distutils.ccompiler import tempfile import shutil # Determine number of bits import platform _bits = {'32bit': 32, '64bit': 64} platform_bits = _bits[platform.architecture()[0]] def libpaths(paths, bits): """Return a list of library paths valid on 32 or 64 bit systems. Inputs: paths : sequence A sequence of strings (typically paths) bits : int An integer, the only valid values are 32 or 64. A ValueError exception is raised otherwise. Examples: Consider a list of directories >>> paths = ['/usr/X11R6/lib','/usr/X11/lib','/usr/lib'] For a 32-bit platform, this is already valid: >>> np.distutils.system_info.libpaths(paths,32) ['/usr/X11R6/lib', '/usr/X11/lib', '/usr/lib'] On 64 bits, we prepend the '64' postfix >>> np.distutils.system_info.libpaths(paths,64) ['/usr/X11R6/lib64', '/usr/X11R6/lib', '/usr/X11/lib64', '/usr/X11/lib', '/usr/lib64', '/usr/lib'] """ if bits not in (32, 64): raise ValueError("Invalid bit size in libpaths: 32 or 64 only") # Handle 32bit case if bits == 32: return paths # Handle 64bit case out = [] for p in paths: out.extend([p + '64', p]) return out if sys.platform == 'win32': default_lib_dirs = ['C:\\', os.path.join(distutils.sysconfig.EXEC_PREFIX, 'libs')] default_runtime_dirs = [] default_include_dirs = [] default_src_dirs = ['.'] default_x11_lib_dirs = [] default_x11_include_dirs = [] _include_dirs = [ 'include', 'include/suitesparse', ] _lib_dirs = [ 'lib', ] _include_dirs = [d.replace('/', os.sep) for d in _include_dirs] _lib_dirs = [d.replace('/', os.sep) for d in _lib_dirs] def add_system_root(library_root): """Add a package manager root to the include directories""" global default_lib_dirs global default_include_dirs library_root = os.path.normpath(library_root) default_lib_dirs.extend( os.path.join(library_root, d) for d in _lib_dirs) default_include_dirs.extend( os.path.join(library_root, d) for d in _include_dirs) if sys.version_info >= (3, 3): # VCpkg is the de-facto package manager on windows for C/C++ # libraries. If it is on the PATH, then we append its paths here. # We also don't re-implement shutil.which for Python 2.7 because # vcpkg doesn't support MSVC 2008. vcpkg = shutil.which('vcpkg') if vcpkg: vcpkg_dir = os.path.dirname(vcpkg) if platform.architecture() == '32bit': specifier = 'x86' else: specifier = 'x64' vcpkg_installed = os.path.join(vcpkg_dir, 'installed') for vcpkg_root in [ os.path.join(vcpkg_installed, specifier + '-windows'), os.path.join(vcpkg_installed, specifier + '-windows-static'), ]: add_system_root(vcpkg_root) # Conda is another popular package manager that provides libraries conda = shutil.which('conda') if conda: conda_dir = os.path.dirname(conda) add_system_root(os.path.join(conda_dir, '..', 'Library')) add_system_root(os.path.join(conda_dir, 'Library')) else: default_lib_dirs = libpaths(['/usr/local/lib', '/opt/lib', '/usr/lib', '/opt/local/lib', '/sw/lib'], platform_bits) default_runtime_dirs = [] default_include_dirs = ['/usr/local/include', '/opt/include', '/usr/include', # path of umfpack under macports '/opt/local/include/ufsparse', '/opt/local/include', '/sw/include', '/usr/include/suitesparse'] default_src_dirs = ['.', '/usr/local/src', '/opt/src', '/sw/src'] default_x11_lib_dirs = libpaths(['/usr/X11R6/lib', '/usr/X11/lib', '/usr/lib'], platform_bits) default_x11_include_dirs = ['/usr/X11R6/include', '/usr/X11/include', '/usr/include'] if os.path.exists('/usr/lib/X11'): globbed_x11_dir = glob('/usr/lib/*/libX11.so') if globbed_x11_dir: x11_so_dir = os.path.split(globbed_x11_dir[0])[0] default_x11_lib_dirs.extend([x11_so_dir, '/usr/lib/X11']) default_x11_include_dirs.extend(['/usr/lib/X11/include', '/usr/include/X11']) import subprocess as sp tmp = None try: # Explicitly open/close file to avoid ResourceWarning when # tests are run in debug mode Python 3. tmp = open(os.devnull, 'w') p = sp.Popen(["gcc", "-print-multiarch"], stdout=sp.PIPE, stderr=tmp) except (OSError, DistutilsError): # OSError if gcc is not installed, or SandboxViolation (DistutilsError # subclass) if an old setuptools bug is triggered (see gh-3160). pass else: triplet = str(p.communicate()[0].decode().strip()) if p.returncode == 0: # gcc supports the "-print-multiarch" option default_x11_lib_dirs += [os.path.join("/usr/lib/", triplet)] default_lib_dirs += [os.path.join("/usr/lib/", triplet)] finally: if tmp is not None: tmp.close() if os.path.join(sys.prefix, 'lib') not in default_lib_dirs: default_lib_dirs.insert(0, os.path.join(sys.prefix, 'lib')) default_include_dirs.append(os.path.join(sys.prefix, 'include')) default_src_dirs.append(os.path.join(sys.prefix, 'src')) default_lib_dirs = [_m for _m in default_lib_dirs if os.path.isdir(_m)] default_runtime_dirs = [_m for _m in default_runtime_dirs if os.path.isdir(_m)] default_include_dirs = [_m for _m in default_include_dirs if os.path.isdir(_m)] default_src_dirs = [_m for _m in default_src_dirs if os.path.isdir(_m)] so_ext = get_shared_lib_extension() def get_standard_file(fname): """Returns a list of files named 'fname' from 1) System-wide directory (directory-location of this module) 2) Users HOME directory (os.environ['HOME']) 3) Local directory """ # System-wide file filenames = [] try: f = __file__ except NameError: f = sys.argv[0] else: sysfile = os.path.join(os.path.split(os.path.abspath(f))[0], fname) if os.path.isfile(sysfile): filenames.append(sysfile) # Home directory # And look for the user config file try: f = os.path.expanduser('~') except KeyError: pass else: user_file = os.path.join(f, fname) if os.path.isfile(user_file): filenames.append(user_file) # Local file if os.path.isfile(fname): filenames.append(os.path.abspath(fname)) return filenames def get_info(name, notfound_action=0): """ notfound_action: 0 - do nothing 1 - display warning message 2 - raise error """ cl = {'atlas': atlas_info, # use lapack_opt or blas_opt instead 'atlas_threads': atlas_threads_info, # ditto 'atlas_blas': atlas_blas_info, 'atlas_blas_threads': atlas_blas_threads_info, 'lapack_atlas': lapack_atlas_info, # use lapack_opt instead 'lapack_atlas_threads': lapack_atlas_threads_info, # ditto 'atlas_3_10': atlas_3_10_info, # use lapack_opt or blas_opt instead 'atlas_3_10_threads': atlas_3_10_threads_info, # ditto 'atlas_3_10_blas': atlas_3_10_blas_info, 'atlas_3_10_blas_threads': atlas_3_10_blas_threads_info, 'lapack_atlas_3_10': lapack_atlas_3_10_info, # use lapack_opt instead 'lapack_atlas_3_10_threads': lapack_atlas_3_10_threads_info, # ditto 'mkl': mkl_info, # openblas which may or may not have embedded lapack 'openblas': openblas_info, # use blas_opt instead # openblas with embedded lapack 'openblas_lapack': openblas_lapack_info, # use blas_opt instead 'openblas_clapack': openblas_clapack_info, # use blas_opt instead 'blis': blis_info, # use blas_opt instead 'lapack_mkl': lapack_mkl_info, # use lapack_opt instead 'blas_mkl': blas_mkl_info, # use blas_opt instead 'x11': x11_info, 'fft_opt': fft_opt_info, 'fftw': fftw_info, 'fftw2': fftw2_info, 'fftw3': fftw3_info, 'dfftw': dfftw_info, 'sfftw': sfftw_info, 'fftw_threads': fftw_threads_info, 'dfftw_threads': dfftw_threads_info, 'sfftw_threads': sfftw_threads_info, 'djbfft': djbfft_info, 'blas': blas_info, # use blas_opt instead 'lapack': lapack_info, # use lapack_opt instead 'lapack_src': lapack_src_info, 'blas_src': blas_src_info, 'numpy': numpy_info, 'f2py': f2py_info, 'Numeric': Numeric_info, 'numeric': Numeric_info, 'numarray': numarray_info, 'numerix': numerix_info, 'lapack_opt': lapack_opt_info, 'blas_opt': blas_opt_info, 'boost_python': boost_python_info, 'agg2': agg2_info, 'wx': wx_info, 'gdk_pixbuf_xlib_2': gdk_pixbuf_xlib_2_info, 'gdk-pixbuf-xlib-2.0': gdk_pixbuf_xlib_2_info, 'gdk_pixbuf_2': gdk_pixbuf_2_info, 'gdk-pixbuf-2.0': gdk_pixbuf_2_info, 'gdk': gdk_info, 'gdk_2': gdk_2_info, 'gdk-2.0': gdk_2_info, 'gdk_x11_2': gdk_x11_2_info, 'gdk-x11-2.0': gdk_x11_2_info, 'gtkp_x11_2': gtkp_x11_2_info, 'gtk+-x11-2.0': gtkp_x11_2_info, 'gtkp_2': gtkp_2_info, 'gtk+-2.0': gtkp_2_info, 'xft': xft_info, 'freetype2': freetype2_info, 'umfpack': umfpack_info, 'amd': amd_info, }.get(name.lower(), system_info) return cl().get_info(notfound_action) class NotFoundError(DistutilsError): """Some third-party program or library is not found.""" class AtlasNotFoundError(NotFoundError): """ Atlas (http://math-atlas.sourceforge.net/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [atlas]) or by setting the ATLAS environment variable.""" class LapackNotFoundError(NotFoundError): """ Lapack (http://www.netlib.org/lapack/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [lapack]) or by setting the LAPACK environment variable.""" class LapackSrcNotFoundError(LapackNotFoundError): """ Lapack (http://www.netlib.org/lapack/) sources not found. Directories to search for the sources can be specified in the numpy/distutils/site.cfg file (section [lapack_src]) or by setting the LAPACK_SRC environment variable.""" class BlasNotFoundError(NotFoundError): """ Blas (http://www.netlib.org/blas/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [blas]) or by setting the BLAS environment variable.""" class BlasSrcNotFoundError(BlasNotFoundError): """ Blas (http://www.netlib.org/blas/) sources not found. Directories to search for the sources can be specified in the numpy/distutils/site.cfg file (section [blas_src]) or by setting the BLAS_SRC environment variable.""" class FFTWNotFoundError(NotFoundError): """ FFTW (http://www.fftw.org/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [fftw]) or by setting the FFTW environment variable.""" class DJBFFTNotFoundError(NotFoundError): """ DJBFFT (http://cr.yp.to/djbfft.html) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [djbfft]) or by setting the DJBFFT environment variable.""" class NumericNotFoundError(NotFoundError): """ Numeric (http://www.numpy.org/) module not found. Get it from above location, install it, and retry setup.py.""" class X11NotFoundError(NotFoundError): """X11 libraries not found.""" class UmfpackNotFoundError(NotFoundError): """ UMFPACK sparse solver (http://www.cise.ufl.edu/research/sparse/umfpack/) not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [umfpack]) or by setting the UMFPACK environment variable.""" class system_info(object): """ get_info() is the only public method. Don't use others. """ section = 'ALL' dir_env_var = None search_static_first = 0 # XXX: disabled by default, may disappear in # future unless it is proved to be useful. verbosity = 1 saved_results = {} notfounderror = NotFoundError def __init__(self, default_lib_dirs=default_lib_dirs, default_include_dirs=default_include_dirs, verbosity=1, ): self.__class__.info = {} self.local_prefixes = [] defaults = {'library_dirs': os.pathsep.join(default_lib_dirs), 'include_dirs': os.pathsep.join(default_include_dirs), 'runtime_library_dirs': os.pathsep.join(default_runtime_dirs), 'rpath': '', 'src_dirs': os.pathsep.join(default_src_dirs), 'search_static_first': str(self.search_static_first), 'extra_compile_args': '', 'extra_link_args': ''} self.cp = ConfigParser(defaults) self.files = [] self.files.extend(get_standard_file('.numpy-site.cfg')) self.files.extend(get_standard_file('site.cfg')) self.parse_config_files() if self.section is not None: self.search_static_first = self.cp.getboolean( self.section, 'search_static_first') assert isinstance(self.search_static_first, int) def parse_config_files(self): self.cp.read(self.files) if not self.cp.has_section(self.section): if self.section is not None: self.cp.add_section(self.section) def calc_libraries_info(self): libs = self.get_libraries() dirs = self.get_lib_dirs() # The extensions use runtime_library_dirs r_dirs = self.get_runtime_lib_dirs() # Intrinsic distutils use rpath, we simply append both entries # as though they were one entry r_dirs.extend(self.get_runtime_lib_dirs(key='rpath')) info = {} for lib in libs: i = self.check_libs(dirs, [lib]) if i is not None: dict_append(info, **i) else: log.info('Library %s was not found. Ignoring' % (lib)) if r_dirs: i = self.check_libs(r_dirs, [lib]) if i is not None: # Swap library keywords found to runtime_library_dirs # the libraries are insisting on the user having defined # them using the library_dirs, and not necessarily by # runtime_library_dirs del i['libraries'] i['runtime_library_dirs'] = i.pop('library_dirs') dict_append(info, **i) else: log.info('Runtime library %s was not found. Ignoring' % (lib)) return info def set_info(self, **info): if info: lib_info = self.calc_libraries_info() dict_append(info, **lib_info) # Update extra information extra_info = self.calc_extra_info() dict_append(info, **extra_info) self.saved_results[self.__class__.__name__] = info def has_info(self): return self.__class__.__name__ in self.saved_results def calc_extra_info(self): """ Updates the information in the current information with respect to these flags: extra_compile_args extra_link_args """ info = {} for key in ['extra_compile_args', 'extra_link_args']: # Get values opt = self.cp.get(self.section, key) if opt: tmp = {key : [opt]} dict_append(info, **tmp) return info def get_info(self, notfound_action=0): """ Return a dictonary with items that are compatible with numpy.distutils.setup keyword arguments. """ flag = 0 if not self.has_info(): flag = 1 log.info(self.__class__.__name__ + ':') if hasattr(self, 'calc_info'): self.calc_info() if notfound_action: if not self.has_info(): if notfound_action == 1: warnings.warn(self.notfounderror.__doc__, stacklevel=2) elif notfound_action == 2: raise self.notfounderror(self.notfounderror.__doc__) else: raise ValueError(repr(notfound_action)) if not self.has_info(): log.info(' NOT AVAILABLE') self.set_info() else: log.info(' FOUND:') res = self.saved_results.get(self.__class__.__name__) if self.verbosity > 0 and flag: for k, v in res.items(): v = str(v) if k in ['sources', 'libraries'] and len(v) > 270: v = v[:120] + '...\n...\n...' + v[-120:] log.info(' %s = %s', k, v) log.info('') return copy.deepcopy(res) def get_paths(self, section, key): dirs = self.cp.get(section, key).split(os.pathsep) env_var = self.dir_env_var if env_var: if is_sequence(env_var): e0 = env_var[-1] for e in env_var: if e in os.environ: e0 = e break if not env_var[0] == e0: log.info('Setting %s=%s' % (env_var[0], e0)) env_var = e0 if env_var and env_var in os.environ: d = os.environ[env_var] if d == 'None': log.info('Disabled %s: %s', self.__class__.__name__, '(%s is None)' % (env_var,)) return [] if os.path.isfile(d): dirs = [os.path.dirname(d)] + dirs l = getattr(self, '_lib_names', []) if len(l) == 1: b = os.path.basename(d) b = os.path.splitext(b)[0] if b[:3] == 'lib': log.info('Replacing _lib_names[0]==%r with %r' \ % (self._lib_names[0], b[3:])) self._lib_names[0] = b[3:] else: ds = d.split(os.pathsep) ds2 = [] for d in ds: if os.path.isdir(d): ds2.append(d) for dd in ['include', 'lib']: d1 = os.path.join(d, dd) if os.path.isdir(d1): ds2.append(d1) dirs = ds2 + dirs default_dirs = self.cp.get(self.section, key).split(os.pathsep) dirs.extend(default_dirs) ret = [] for d in dirs: if len(d) > 0 and not os.path.isdir(d): warnings.warn('Specified path %s is invalid.' % d, stacklevel=2) continue if d not in ret: ret.append(d) log.debug('( %s = %s )', key, ':'.join(ret)) return ret def get_lib_dirs(self, key='library_dirs'): return self.get_paths(self.section, key) def get_runtime_lib_dirs(self, key='runtime_library_dirs'): path = self.get_paths(self.section, key) if path == ['']: path = [] return path def get_include_dirs(self, key='include_dirs'): return self.get_paths(self.section, key) def get_src_dirs(self, key='src_dirs'): return self.get_paths(self.section, key) def get_libs(self, key, default): try: libs = self.cp.get(self.section, key) except NoOptionError: if not default: return [] if is_string(default): return [default] return default return [b for b in [a.strip() for a in libs.split(',')] if b] def get_libraries(self, key='libraries'): if hasattr(self, '_lib_names'): return self.get_libs(key, default=self._lib_names) else: return self.get_libs(key, '') def library_extensions(self): c = customized_ccompiler() static_exts = [] if c.compiler_type != 'msvc': # MSVC doesn't understand binutils static_exts.append('.a') if sys.platform == 'win32': static_exts.append('.lib') # .lib is used by MSVC and others if self.search_static_first: exts = static_exts + [so_ext] else: exts = [so_ext] + static_exts if sys.platform == 'cygwin': exts.append('.dll.a') if sys.platform == 'darwin': exts.append('.dylib') return exts def check_libs(self, lib_dirs, libs, opt_libs=[]): """If static or shared libraries are available then return their info dictionary. Checks for all libraries as shared libraries first, then static (or vice versa if self.search_static_first is True). """ exts = self.library_extensions() info = None for ext in exts: info = self._check_libs(lib_dirs, libs, opt_libs, [ext]) if info is not None: break if not info: log.info(' libraries %s not found in %s', ','.join(libs), lib_dirs) return info def check_libs2(self, lib_dirs, libs, opt_libs=[]): """If static or shared libraries are available then return their info dictionary. Checks each library for shared or static. """ exts = self.library_extensions() info = self._check_libs(lib_dirs, libs, opt_libs, exts) if not info: log.info(' libraries %s not found in %s', ','.join(libs), lib_dirs) return info def _find_lib(self, lib_dir, lib, exts): assert is_string(lib_dir) # under windows first try without 'lib' prefix if sys.platform == 'win32': lib_prefixes = ['', 'lib'] else: lib_prefixes = ['lib'] # for each library name, see if we can find a file for it. for ext in exts: for prefix in lib_prefixes: p = self.combine_paths(lib_dir, prefix + lib + ext) if p: break if p: assert len(p) == 1 # ??? splitext on p[0] would do this for cygwin # doesn't seem correct if ext == '.dll.a': lib += '.dll' return lib return False def _find_libs(self, lib_dirs, libs, exts): # make sure we preserve the order of libs, as it can be important found_dirs, found_libs = [], [] for lib in libs: for lib_dir in lib_dirs: found_lib = self._find_lib(lib_dir, lib, exts) if found_lib: found_libs.append(found_lib) if lib_dir not in found_dirs: found_dirs.append(lib_dir) break return found_dirs, found_libs def _check_libs(self, lib_dirs, libs, opt_libs, exts): """Find mandatory and optional libs in expected paths. Missing optional libraries are silently forgotten. """ if not is_sequence(lib_dirs): lib_dirs = [lib_dirs] # First, try to find the mandatory libraries found_dirs, found_libs = self._find_libs(lib_dirs, libs, exts) if len(found_libs) > 0 and len(found_libs) == len(libs): # Now, check for optional libraries opt_found_dirs, opt_found_libs = self._find_libs(lib_dirs, opt_libs, exts) found_libs.extend(opt_found_libs) for lib_dir in opt_found_dirs: if lib_dir not in found_dirs: found_dirs.append(lib_dir) info = {'libraries': found_libs, 'library_dirs': found_dirs} return info else: return None def combine_paths(self, *args): """Return a list of existing paths composed by all combinations of items from the arguments. """ return combine_paths(*args, **{'verbosity': self.verbosity}) class fft_opt_info(system_info): def calc_info(self): info = {} fftw_info = get_info('fftw3') or get_info('fftw2') or get_info('dfftw') djbfft_info = get_info('djbfft') if fftw_info: dict_append(info, **fftw_info) if djbfft_info: dict_append(info, **djbfft_info) self.set_info(**info) return class fftw_info(system_info): #variables to override section = 'fftw' dir_env_var = 'FFTW' notfounderror = FFTWNotFoundError ver_info = [{'name':'fftw3', 'libs':['fftw3'], 'includes':['fftw3.h'], 'macros':[('SCIPY_FFTW3_H', None)]}, {'name':'fftw2', 'libs':['rfftw', 'fftw'], 'includes':['fftw.h', 'rfftw.h'], 'macros':[('SCIPY_FFTW_H', None)]}] def calc_ver_info(self, ver_param): """Returns True on successful version detection, else False""" lib_dirs = self.get_lib_dirs() incl_dirs = self.get_include_dirs() libs = self.get_libs(self.section + '_libs', ver_param['libs']) info = self.check_libs(lib_dirs, libs) if info is not None: flag = 0 for d in incl_dirs: if len(self.combine_paths(d, ver_param['includes'])) \ == len(ver_param['includes']): dict_append(info, include_dirs=[d]) flag = 1 incl_dirs = [d] break if flag: dict_append(info, define_macros=ver_param['macros']) else: info = None if info is not None: self.set_info(**info) return True else: log.info(' %s not found' % (ver_param['name'])) return False def calc_info(self): for i in self.ver_info: if self.calc_ver_info(i): break class fftw2_info(fftw_info): #variables to override section = 'fftw' dir_env_var = 'FFTW' notfounderror = FFTWNotFoundError ver_info = [{'name':'fftw2', 'libs':['rfftw', 'fftw'], 'includes':['fftw.h', 'rfftw.h'], 'macros':[('SCIPY_FFTW_H', None)]} ] class fftw3_info(fftw_info): #variables to override section = 'fftw3' dir_env_var = 'FFTW3' notfounderror = FFTWNotFoundError ver_info = [{'name':'fftw3', 'libs':['fftw3'], 'includes':['fftw3.h'], 'macros':[('SCIPY_FFTW3_H', None)]}, ] class dfftw_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name':'dfftw', 'libs':['drfftw', 'dfftw'], 'includes':['dfftw.h', 'drfftw.h'], 'macros':[('SCIPY_DFFTW_H', None)]}] class sfftw_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name':'sfftw', 'libs':['srfftw', 'sfftw'], 'includes':['sfftw.h', 'srfftw.h'], 'macros':[('SCIPY_SFFTW_H', None)]}] class fftw_threads_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name':'fftw threads', 'libs':['rfftw_threads', 'fftw_threads'], 'includes':['fftw_threads.h', 'rfftw_threads.h'], 'macros':[('SCIPY_FFTW_THREADS_H', None)]}] class dfftw_threads_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name':'dfftw threads', 'libs':['drfftw_threads', 'dfftw_threads'], 'includes':['dfftw_threads.h', 'drfftw_threads.h'], 'macros':[('SCIPY_DFFTW_THREADS_H', None)]}] class sfftw_threads_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name':'sfftw threads', 'libs':['srfftw_threads', 'sfftw_threads'], 'includes':['sfftw_threads.h', 'srfftw_threads.h'], 'macros':[('SCIPY_SFFTW_THREADS_H', None)]}] class djbfft_info(system_info): section = 'djbfft' dir_env_var = 'DJBFFT' notfounderror = DJBFFTNotFoundError def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend(self.combine_paths(d, ['djbfft']) + [d]) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): lib_dirs = self.get_lib_dirs() incl_dirs = self.get_include_dirs() info = None for d in lib_dirs: p = self.combine_paths(d, ['djbfft.a']) if p: info = {'extra_objects': p} break p = self.combine_paths(d, ['libdjbfft.a', 'libdjbfft' + so_ext]) if p: info = {'libraries': ['djbfft'], 'library_dirs': [d]} break if info is None: return for d in incl_dirs: if len(self.combine_paths(d, ['fftc8.h', 'fftfreq.h'])) == 2: dict_append(info, include_dirs=[d], define_macros=[('SCIPY_DJBFFT_H', None)]) self.set_info(**info) return return class mkl_info(system_info): section = 'mkl' dir_env_var = 'MKLROOT' _lib_mkl = ['mkl_rt'] def get_mkl_rootdir(self): mklroot = os.environ.get('MKLROOT', None) if mklroot is not None: return mklroot paths = os.environ.get('LD_LIBRARY_PATH', '').split(os.pathsep) ld_so_conf = '/etc/ld.so.conf' if os.path.isfile(ld_so_conf): with open(ld_so_conf, 'r') as f: for d in f: d = d.strip() if d: paths.append(d) intel_mkl_dirs = [] for path in paths: path_atoms = path.split(os.sep) for m in path_atoms: if m.startswith('mkl'): d = os.sep.join(path_atoms[:path_atoms.index(m) + 2]) intel_mkl_dirs.append(d) break for d in paths: dirs = glob(os.path.join(d, 'mkl', '*')) dirs += glob(os.path.join(d, 'mkl*')) for d in dirs: if os.path.isdir(os.path.join(d, 'lib')): return d return None def __init__(self): mklroot = self.get_mkl_rootdir() if mklroot is None: system_info.__init__(self) else: from .cpuinfo import cpu if cpu.is_Itanium(): plt = '64' elif cpu.is_Intel() and cpu.is_64bit(): plt = 'intel64' else: plt = '32' system_info.__init__( self, default_lib_dirs=[os.path.join(mklroot, 'lib', plt)], default_include_dirs=[os.path.join(mklroot, 'include')]) def calc_info(self): lib_dirs = self.get_lib_dirs() incl_dirs = self.get_include_dirs() mkl_libs = self.get_libs('mkl_libs', self._lib_mkl) info = self.check_libs2(lib_dirs, mkl_libs) if info is None: return dict_append(info, define_macros=[('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)], include_dirs=incl_dirs) if sys.platform == 'win32': pass # win32 has no pthread library else: dict_append(info, libraries=['pthread']) self.set_info(**info) class lapack_mkl_info(mkl_info): pass class blas_mkl_info(mkl_info): pass class atlas_info(system_info): section = 'atlas' dir_env_var = 'ATLAS' _lib_names = ['f77blas', 'cblas'] if sys.platform[:7] == 'freebsd': _lib_atlas = ['atlas_r'] _lib_lapack = ['alapack_r'] else: _lib_atlas = ['atlas'] _lib_lapack = ['lapack'] notfounderror = AtlasNotFoundError def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend(self.combine_paths(d, ['atlas*', 'ATLAS*', 'sse', '3dnow', 'sse2']) + [d]) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): lib_dirs = self.get_lib_dirs() info = {} atlas_libs = self.get_libs('atlas_libs', self._lib_names + self._lib_atlas) lapack_libs = self.get_libs('lapack_libs', self._lib_lapack) atlas = None lapack = None atlas_1 = None for d in lib_dirs: atlas = self.check_libs2(d, atlas_libs, []) lapack_atlas = self.check_libs2(d, ['lapack_atlas'], []) if atlas is not None: lib_dirs2 = [d] + self.combine_paths(d, ['atlas*', 'ATLAS*']) lapack = self.check_libs2(lib_dirs2, lapack_libs, []) if lapack is not None: break if atlas: atlas_1 = atlas log.info(self.__class__) if atlas is None: atlas = atlas_1 if atlas is None: return include_dirs = self.get_include_dirs() h = (self.combine_paths(lib_dirs + include_dirs, 'cblas.h') or [None]) h = h[0] if h: h = os.path.dirname(h) dict_append(info, include_dirs=[h]) info['language'] = 'c' if lapack is not None: dict_append(info, **lapack) dict_append(info, **atlas) elif 'lapack_atlas' in atlas['libraries']: dict_append(info, **atlas) dict_append(info, define_macros=[('ATLAS_WITH_LAPACK_ATLAS', None)]) self.set_info(**info) return else: dict_append(info, **atlas) dict_append(info, define_macros=[('ATLAS_WITHOUT_LAPACK', None)]) message = """ ********************************************************************* Could not find lapack library within the ATLAS installation. ********************************************************************* """ warnings.warn(message, stacklevel=2) self.set_info(**info) return # Check if lapack library is complete, only warn if it is not. lapack_dir = lapack['library_dirs'][0] lapack_name = lapack['libraries'][0] lapack_lib = None lib_prefixes = ['lib'] if sys.platform == 'win32': lib_prefixes.append('') for e in self.library_extensions(): for prefix in lib_prefixes: fn = os.path.join(lapack_dir, prefix + lapack_name + e) if os.path.exists(fn): lapack_lib = fn break if lapack_lib: break if lapack_lib is not None: sz = os.stat(lapack_lib)[6] if sz <= 4000 * 1024: message = """ ********************************************************************* Lapack library (from ATLAS) is probably incomplete: size of %s is %sk (expected >4000k) Follow the instructions in the KNOWN PROBLEMS section of the file numpy/INSTALL.txt. ********************************************************************* """ % (lapack_lib, sz / 1024) warnings.warn(message, stacklevel=2) else: info['language'] = 'f77' atlas_version, atlas_extra_info = get_atlas_version(**atlas) dict_append(info, **atlas_extra_info) self.set_info(**info) class atlas_blas_info(atlas_info): _lib_names = ['f77blas', 'cblas'] def calc_info(self): lib_dirs = self.get_lib_dirs() info = {} atlas_libs = self.get_libs('atlas_libs', self._lib_names + self._lib_atlas) atlas = self.check_libs2(lib_dirs, atlas_libs, []) if atlas is None: return include_dirs = self.get_include_dirs() h = (self.combine_paths(lib_dirs + include_dirs, 'cblas.h') or [None]) h = h[0] if h: h = os.path.dirname(h) dict_append(info, include_dirs=[h]) info['language'] = 'c' info['define_macros'] = [('HAVE_CBLAS', None)] atlas_version, atlas_extra_info = get_atlas_version(**atlas) dict_append(atlas, **atlas_extra_info) dict_append(info, **atlas) self.set_info(**info) return class atlas_threads_info(atlas_info): dir_env_var = ['PTATLAS', 'ATLAS'] _lib_names = ['ptf77blas', 'ptcblas'] class atlas_blas_threads_info(atlas_blas_info): dir_env_var = ['PTATLAS', 'ATLAS'] _lib_names = ['ptf77blas', 'ptcblas'] class lapack_atlas_info(atlas_info): _lib_names = ['lapack_atlas'] + atlas_info._lib_names class lapack_atlas_threads_info(atlas_threads_info): _lib_names = ['lapack_atlas'] + atlas_threads_info._lib_names class atlas_3_10_info(atlas_info): _lib_names = ['satlas'] _lib_atlas = _lib_names _lib_lapack = _lib_names class atlas_3_10_blas_info(atlas_3_10_info): _lib_names = ['satlas'] def calc_info(self): lib_dirs = self.get_lib_dirs() info = {} atlas_libs = self.get_libs('atlas_libs', self._lib_names) atlas = self.check_libs2(lib_dirs, atlas_libs, []) if atlas is None: return include_dirs = self.get_include_dirs() h = (self.combine_paths(lib_dirs + include_dirs, 'cblas.h') or [None]) h = h[0] if h: h = os.path.dirname(h) dict_append(info, include_dirs=[h]) info['language'] = 'c' info['define_macros'] = [('HAVE_CBLAS', None)] atlas_version, atlas_extra_info = get_atlas_version(**atlas) dict_append(atlas, **atlas_extra_info) dict_append(info, **atlas) self.set_info(**info) return class atlas_3_10_threads_info(atlas_3_10_info): dir_env_var = ['PTATLAS', 'ATLAS'] _lib_names = ['tatlas'] _lib_atlas = _lib_names _lib_lapack = _lib_names class atlas_3_10_blas_threads_info(atlas_3_10_blas_info): dir_env_var = ['PTATLAS', 'ATLAS'] _lib_names = ['tatlas'] class lapack_atlas_3_10_info(atlas_3_10_info): pass class lapack_atlas_3_10_threads_info(atlas_3_10_threads_info): pass class lapack_info(system_info): section = 'lapack' dir_env_var = 'LAPACK' _lib_names = ['lapack'] notfounderror = LapackNotFoundError def calc_info(self): lib_dirs = self.get_lib_dirs() lapack_libs = self.get_libs('lapack_libs', self._lib_names) info = self.check_libs(lib_dirs, lapack_libs, []) if info is None: return info['language'] = 'f77' self.set_info(**info) class lapack_src_info(system_info): section = 'lapack_src' dir_env_var = 'LAPACK_SRC' notfounderror = LapackSrcNotFoundError def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend([d] + self.combine_paths(d, ['LAPACK*/SRC', 'SRC'])) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): src_dirs = self.get_src_dirs() src_dir = '' for d in src_dirs: if os.path.isfile(os.path.join(d, 'dgesv.f')): src_dir = d break if not src_dir: #XXX: Get sources from netlib. May be ask first. return # The following is extracted from LAPACK-3.0/SRC/Makefile. # Added missing names from lapack-lite-3.1.1/SRC/Makefile # while keeping removed names for Lapack-3.0 compatibility. allaux = ''' ilaenv ieeeck lsame lsamen xerbla iparmq ''' # *.f laux = ''' bdsdc bdsqr disna labad lacpy ladiv lae2 laebz laed0 laed1 laed2 laed3 laed4 laed5 laed6 laed7 laed8 laed9 laeda laev2 lagtf lagts lamch lamrg lanst lapy2 lapy3 larnv larrb larre larrf lartg laruv las2 lascl lasd0 lasd1 lasd2 lasd3 lasd4 lasd5 lasd6 lasd7 lasd8 lasd9 lasda lasdq lasdt laset lasq1 lasq2 lasq3 lasq4 lasq5 lasq6 lasr lasrt lassq lasv2 pttrf stebz stedc steqr sterf larra larrc larrd larr larrk larrj larrr laneg laisnan isnan lazq3 lazq4 ''' # [s|d]*.f lasrc = ''' gbbrd gbcon gbequ gbrfs gbsv gbsvx gbtf2 gbtrf gbtrs gebak gebal gebd2 gebrd gecon geequ gees geesx geev geevx gegs gegv gehd2 gehrd gelq2 gelqf gels gelsd gelss gelsx gelsy geql2 geqlf geqp3 geqpf geqr2 geqrf gerfs gerq2 gerqf gesc2 gesdd gesv gesvd gesvx getc2 getf2 getrf getri getrs ggbak ggbal gges ggesx ggev ggevx ggglm gghrd gglse ggqrf ggrqf ggsvd ggsvp gtcon gtrfs gtsv gtsvx gttrf gttrs gtts2 hgeqz hsein hseqr labrd lacon laein lags2 lagtm lahqr lahrd laic1 lals0 lalsa lalsd langb lange langt lanhs lansb lansp lansy lantb lantp lantr lapll lapmt laqgb laqge laqp2 laqps laqsb laqsp laqsy lar1v lar2v larf larfb larfg larft larfx largv larrv lartv larz larzb larzt laswp lasyf latbs latdf latps latrd latrs latrz latzm lauu2 lauum pbcon pbequ pbrfs pbstf pbsv pbsvx pbtf2 pbtrf pbtrs pocon poequ porfs posv posvx potf2 potrf potri potrs ppcon ppequ pprfs ppsv ppsvx pptrf pptri pptrs ptcon pteqr ptrfs ptsv ptsvx pttrs ptts2 spcon sprfs spsv spsvx sptrf sptri sptrs stegr stein sycon syrfs sysv sysvx sytf2 sytrf sytri sytrs tbcon tbrfs tbtrs tgevc tgex2 tgexc tgsen tgsja tgsna tgsy2 tgsyl tpcon tprfs tptri tptrs trcon trevc trexc trrfs trsen trsna trsyl trti2 trtri trtrs tzrqf tzrzf lacn2 lahr2 stemr laqr0 laqr1 laqr2 laqr3 laqr4 laqr5 ''' # [s|c|d|z]*.f sd_lasrc = ''' laexc lag2 lagv2 laln2 lanv2 laqtr lasy2 opgtr opmtr org2l org2r orgbr orghr orgl2 orglq orgql orgqr orgr2 orgrq orgtr orm2l orm2r ormbr ormhr orml2 ormlq ormql ormqr ormr2 ormr3 ormrq ormrz ormtr rscl sbev sbevd sbevx sbgst sbgv sbgvd sbgvx sbtrd spev spevd spevx spgst spgv spgvd spgvx sptrd stev stevd stevr stevx syev syevd syevr syevx sygs2 sygst sygv sygvd sygvx sytd2 sytrd ''' # [s|d]*.f cz_lasrc = ''' bdsqr hbev hbevd hbevx hbgst hbgv hbgvd hbgvx hbtrd hecon heev heevd heevr heevx hegs2 hegst hegv hegvd hegvx herfs hesv hesvx hetd2 hetf2 hetrd hetrf hetri hetrs hpcon hpev hpevd hpevx hpgst hpgv hpgvd hpgvx hprfs hpsv hpsvx hptrd hptrf hptri hptrs lacgv lacp2 lacpy lacrm lacrt ladiv laed0 laed7 laed8 laesy laev2 lahef lanhb lanhe lanhp lanht laqhb laqhe laqhp larcm larnv lartg lascl laset lasr lassq pttrf rot spmv spr stedc steqr symv syr ung2l ung2r ungbr unghr ungl2 unglq ungql ungqr ungr2 ungrq ungtr unm2l unm2r unmbr unmhr unml2 unmlq unmql unmqr unmr2 unmr3 unmrq unmrz unmtr upgtr upmtr ''' # [c|z]*.f ####### sclaux = laux + ' econd ' # s*.f dzlaux = laux + ' secnd ' # d*.f slasrc = lasrc + sd_lasrc # s*.f dlasrc = lasrc + sd_lasrc # d*.f clasrc = lasrc + cz_lasrc + ' srot srscl ' # c*.f zlasrc = lasrc + cz_lasrc + ' drot drscl ' # z*.f oclasrc = ' icmax1 scsum1 ' # *.f ozlasrc = ' izmax1 dzsum1 ' # *.f sources = ['s%s.f' % f for f in (sclaux + slasrc).split()] \ + ['d%s.f' % f for f in (dzlaux + dlasrc).split()] \ + ['c%s.f' % f for f in (clasrc).split()] \ + ['z%s.f' % f for f in (zlasrc).split()] \ + ['%s.f' % f for f in (allaux + oclasrc + ozlasrc).split()] sources = [os.path.join(src_dir, f) for f in sources] # Lapack 3.1: src_dir2 = os.path.join(src_dir, '..', 'INSTALL') sources += [os.path.join(src_dir2, p + 'lamch.f') for p in 'sdcz'] # Lapack 3.2.1: sources += [os.path.join(src_dir, p + 'larfp.f') for p in 'sdcz'] sources += [os.path.join(src_dir, 'ila' + p + 'lr.f') for p in 'sdcz'] sources += [os.path.join(src_dir, 'ila' + p + 'lc.f') for p in 'sdcz'] # Should we check here actual existence of source files? # Yes, the file listing is different between 3.0 and 3.1 # versions. sources = [f for f in sources if os.path.isfile(f)] info = {'sources': sources, 'language': 'f77'} self.set_info(**info) atlas_version_c_text = r''' /* This file is generated from numpy/distutils/system_info.py */ void ATL_buildinfo(void); int main(void) { ATL_buildinfo(); return 0; } ''' _cached_atlas_version = {} def get_atlas_version(**config): libraries = config.get('libraries', []) library_dirs = config.get('library_dirs', []) key = (tuple(libraries), tuple(library_dirs)) if key in _cached_atlas_version: return _cached_atlas_version[key] c = cmd_config(Distribution()) atlas_version = None info = {} try: s, o = c.get_output(atlas_version_c_text, libraries=libraries, library_dirs=library_dirs, use_tee=(system_info.verbosity > 0)) if s and re.search(r'undefined reference to `_gfortran', o, re.M): s, o = c.get_output(atlas_version_c_text, libraries=libraries + ['gfortran'], library_dirs=library_dirs, use_tee=(system_info.verbosity > 0)) if not s: warnings.warn(""" ***************************************************** Linkage with ATLAS requires gfortran. Use python setup.py config_fc --fcompiler=gnu95 ... when building extension libraries that use ATLAS. Make sure that -lgfortran is used for C++ extensions. ***************************************************** """, stacklevel=2) dict_append(info, language='f90', define_macros=[('ATLAS_REQUIRES_GFORTRAN', None)]) except Exception: # failed to get version from file -- maybe on Windows # look at directory name for o in library_dirs: m = re.search(r'ATLAS_(?P<version>\d+[.]\d+[.]\d+)_', o) if m: atlas_version = m.group('version') if atlas_version is not None: break # final choice --- look at ATLAS_VERSION environment # variable if atlas_version is None: atlas_version = os.environ.get('ATLAS_VERSION', None) if atlas_version: dict_append(info, define_macros=[( 'ATLAS_INFO', '"\\"%s\\""' % atlas_version) ]) else: dict_append(info, define_macros=[('NO_ATLAS_INFO', -1)]) return atlas_version or '?.?.?', info if not s: m = re.search(r'ATLAS version (?P<version>\d+[.]\d+[.]\d+)', o) if m: atlas_version = m.group('version') if atlas_version is None: if re.search(r'undefined symbol: ATL_buildinfo', o, re.M): atlas_version = '3.2.1_pre3.3.6' else: log.info('Status: %d', s) log.info('Output: %s', o) if atlas_version == '3.2.1_pre3.3.6': dict_append(info, define_macros=[('NO_ATLAS_INFO', -2)]) else: dict_append(info, define_macros=[( 'ATLAS_INFO', '"\\"%s\\""' % atlas_version) ]) result = _cached_atlas_version[key] = atlas_version, info return result class lapack_opt_info(system_info): notfounderror = LapackNotFoundError def calc_info(self): lapack_mkl_info = get_info('lapack_mkl') if lapack_mkl_info: self.set_info(**lapack_mkl_info) return openblas_info = get_info('openblas_lapack') if openblas_info: self.set_info(**openblas_info) return openblas_info = get_info('openblas_clapack') if openblas_info: self.set_info(**openblas_info) return atlas_info = get_info('atlas_3_10_threads') if not atlas_info: atlas_info = get_info('atlas_3_10') if not atlas_info: atlas_info = get_info('atlas_threads') if not atlas_info: atlas_info = get_info('atlas') if sys.platform == 'darwin' and not (atlas_info or openblas_info or lapack_mkl_info): # Use the system lapack from Accelerate or vecLib under OSX args = [] link_args = [] if get_platform()[-4:] == 'i386' or 'intel' in get_platform() or \ 'x86_64' in get_platform() or \ 'i386' in platform.platform(): intel = 1 else: intel = 0 if os.path.exists('/System/Library/Frameworks' '/Accelerate.framework/'): if intel: args.extend(['-msse3']) else: args.extend(['-faltivec']) link_args.extend(['-Wl,-framework', '-Wl,Accelerate']) elif os.path.exists('/System/Library/Frameworks' '/vecLib.framework/'): if intel: args.extend(['-msse3']) else: args.extend(['-faltivec']) link_args.extend(['-Wl,-framework', '-Wl,vecLib']) if args: self.set_info(extra_compile_args=args, extra_link_args=link_args, define_macros=[('NO_ATLAS_INFO', 3), ('HAVE_CBLAS', None)]) return need_lapack = 0 need_blas = 0 info = {} if atlas_info: l = atlas_info.get('define_macros', []) if ('ATLAS_WITH_LAPACK_ATLAS', None) in l \ or ('ATLAS_WITHOUT_LAPACK', None) in l: need_lapack = 1 info = atlas_info else: warnings.warn(AtlasNotFoundError.__doc__, stacklevel=2) need_blas = 1 need_lapack = 1 dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)]) if need_lapack: lapack_info = get_info('lapack') #lapack_info = {} ## uncomment for testing if lapack_info: dict_append(info, **lapack_info) else: warnings.warn(LapackNotFoundError.__doc__, stacklevel=2) lapack_src_info = get_info('lapack_src') if not lapack_src_info: warnings.warn(LapackSrcNotFoundError.__doc__, stacklevel=2) return dict_append(info, libraries=[('flapack_src', lapack_src_info)]) if need_blas: blas_info = get_info('blas') if blas_info: dict_append(info, **blas_info) else: warnings.warn(BlasNotFoundError.__doc__, stacklevel=2) blas_src_info = get_info('blas_src') if not blas_src_info: warnings.warn(BlasSrcNotFoundError.__doc__, stacklevel=2) return dict_append(info, libraries=[('fblas_src', blas_src_info)]) self.set_info(**info) return class blas_opt_info(system_info): notfounderror = BlasNotFoundError def calc_info(self): blas_mkl_info = get_info('blas_mkl') if blas_mkl_info: self.set_info(**blas_mkl_info) return blis_info = get_info('blis') if blis_info: self.set_info(**blis_info) return openblas_info = get_info('openblas') if openblas_info: self.set_info(**openblas_info) return atlas_info = get_info('atlas_3_10_blas_threads') if not atlas_info: atlas_info = get_info('atlas_3_10_blas') if not atlas_info: atlas_info = get_info('atlas_blas_threads') if not atlas_info: atlas_info = get_info('atlas_blas') if sys.platform == 'darwin' and not (atlas_info or openblas_info or blas_mkl_info or blis_info): # Use the system BLAS from Accelerate or vecLib under OSX args = [] link_args = [] if get_platform()[-4:] == 'i386' or 'intel' in get_platform() or \ 'x86_64' in get_platform() or \ 'i386' in platform.platform(): intel = 1 else: intel = 0 if os.path.exists('/System/Library/Frameworks' '/Accelerate.framework/'): if intel: args.extend(['-msse3']) else: args.extend(['-faltivec']) args.extend([ '-I/System/Library/Frameworks/vecLib.framework/Headers']) link_args.extend(['-Wl,-framework', '-Wl,Accelerate']) elif os.path.exists('/System/Library/Frameworks' '/vecLib.framework/'): if intel: args.extend(['-msse3']) else: args.extend(['-faltivec']) args.extend([ '-I/System/Library/Frameworks/vecLib.framework/Headers']) link_args.extend(['-Wl,-framework', '-Wl,vecLib']) if args: self.set_info(extra_compile_args=args, extra_link_args=link_args, define_macros=[('NO_ATLAS_INFO', 3), ('HAVE_CBLAS', None)]) return need_blas = 0 info = {} if atlas_info: info = atlas_info else: warnings.warn(AtlasNotFoundError.__doc__, stacklevel=2) need_blas = 1 dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)]) if need_blas: blas_info = get_info('blas') if blas_info: dict_append(info, **blas_info) else: warnings.warn(BlasNotFoundError.__doc__, stacklevel=2) blas_src_info = get_info('blas_src') if not blas_src_info: warnings.warn(BlasSrcNotFoundError.__doc__, stacklevel=2) return dict_append(info, libraries=[('fblas_src', blas_src_info)]) self.set_info(**info) return class blas_info(system_info): section = 'blas' dir_env_var = 'BLAS' _lib_names = ['blas'] notfounderror = BlasNotFoundError def calc_info(self): lib_dirs = self.get_lib_dirs() blas_libs = self.get_libs('blas_libs', self._lib_names) info = self.check_libs(lib_dirs, blas_libs, []) if info is None: return else: info['include_dirs'] = self.get_include_dirs() if platform.system() == 'Windows': # The check for windows is needed because has_cblas uses the # same compiler that was used to compile Python and msvc is # often not installed when mingw is being used. This rough # treatment is not desirable, but windows is tricky. info['language'] = 'f77' # XXX: is it generally true? else: lib = self.has_cblas(info) if lib is not None: info['language'] = 'c' info['libraries'] = [lib] info['define_macros'] = [('HAVE_CBLAS', None)] self.set_info(**info) def has_cblas(self, info): # primitive cblas check by looking for the header and trying to link # cblas or blas res = False c = customized_ccompiler() tmpdir = tempfile.mkdtemp() s = """#include <cblas.h> int main(int argc, const char *argv[]) { double a[4] = {1,2,3,4}; double b[4] = {5,6,7,8}; return cblas_ddot(4, a, 1, b, 1) > 10; }""" src = os.path.join(tmpdir, 'source.c') try: with open(src, 'wt') as f: f.write(s) try: # check we can compile (find headers) obj = c.compile([src], output_dir=tmpdir, include_dirs=self.get_include_dirs()) # check we can link (find library) # some systems have separate cblas and blas libs. First # check for cblas lib, and if not present check for blas lib. try: c.link_executable(obj, os.path.join(tmpdir, "a.out"), libraries=["cblas"], library_dirs=info['library_dirs'], extra_postargs=info.get('extra_link_args', [])) res = "cblas" except distutils.ccompiler.LinkError: c.link_executable(obj, os.path.join(tmpdir, "a.out"), libraries=["blas"], library_dirs=info['library_dirs'], extra_postargs=info.get('extra_link_args', [])) res = "blas" except distutils.ccompiler.CompileError: res = None finally: shutil.rmtree(tmpdir) return res class openblas_info(blas_info): section = 'openblas' dir_env_var = 'OPENBLAS' _lib_names = ['openblas'] notfounderror = BlasNotFoundError def check_embedded_lapack(self, info): return True def calc_info(self): c = customized_ccompiler() lib_dirs = self.get_lib_dirs() openblas_libs = self.get_libs('libraries', self._lib_names) if openblas_libs == self._lib_names: # backward compat with 1.8.0 openblas_libs = self.get_libs('openblas_libs', self._lib_names) info = self.check_libs(lib_dirs, openblas_libs, []) if c.compiler_type == "msvc" and info is None: from numpy.distutils.fcompiler import new_fcompiler f = new_fcompiler(c_compiler=c) if f and f.compiler_type == 'gnu95': # Try gfortran-compatible library files info = self.check_msvc_gfortran_libs(lib_dirs, openblas_libs) # Skip lapack check, we'd need build_ext to do it assume_lapack = True elif info: assume_lapack = False info['language'] = 'c' if info is None: return # Add extra info for OpenBLAS extra_info = self.calc_extra_info() dict_append(info, **extra_info) if not (assume_lapack or self.check_embedded_lapack(info)): return info['define_macros'] = [('HAVE_CBLAS', None)] self.set_info(**info) def check_msvc_gfortran_libs(self, library_dirs, libraries): # First, find the full path to each library directory library_paths = [] for library in libraries: for library_dir in library_dirs: # MinGW static ext will be .a fullpath = os.path.join(library_dir, library + '.a') if os.path.isfile(fullpath): library_paths.append(fullpath) break else: return None # Generate numpy.distutils virtual static library file tmpdir = os.path.join(os.getcwd(), 'build', 'openblas') if not os.path.isdir(tmpdir): os.makedirs(tmpdir) info = {'library_dirs': [tmpdir], 'libraries': ['openblas'], 'language': 'f77'} fake_lib_file = os.path.join(tmpdir, 'openblas.fobjects') fake_clib_file = os.path.join(tmpdir, 'openblas.cobjects') with open(fake_lib_file, 'w') as f: f.write("\n".join(library_paths)) with open(fake_clib_file, 'w') as f: pass return info class openblas_lapack_info(openblas_info): section = 'openblas' dir_env_var = 'OPENBLAS' _lib_names = ['openblas'] notfounderror = BlasNotFoundError def check_embedded_lapack(self, info): res = False c = customized_ccompiler() tmpdir = tempfile.mkdtemp() s = """void zungqr_(); int main(int argc, const char *argv[]) { zungqr_(); return 0; }""" src = os.path.join(tmpdir, 'source.c') out = os.path.join(tmpdir, 'a.out') # Add the additional "extra" arguments try: extra_args = info['extra_link_args'] except Exception: extra_args = [] if sys.version_info < (3, 5) and sys.version_info > (3, 0) and c.compiler_type == "msvc": extra_args.append("/MANIFEST") try: with open(src, 'wt') as f: f.write(s) obj = c.compile([src], output_dir=tmpdir) try: c.link_executable(obj, out, libraries=info['libraries'], library_dirs=info['library_dirs'], extra_postargs=extra_args) res = True except distutils.ccompiler.LinkError: res = False finally: shutil.rmtree(tmpdir) return res class openblas_clapack_info(openblas_lapack_info): _lib_names = ['openblas', 'lapack'] class blis_info(blas_info): section = 'blis' dir_env_var = 'BLIS' _lib_names = ['blis'] notfounderror = BlasNotFoundError def calc_info(self): lib_dirs = self.get_lib_dirs() blis_libs = self.get_libs('libraries', self._lib_names) if blis_libs == self._lib_names: blis_libs = self.get_libs('blis_libs', self._lib_names) info = self.check_libs2(lib_dirs, blis_libs, []) if info is None: return # Add include dirs incl_dirs = self.get_include_dirs() dict_append(info, language='c', define_macros=[('HAVE_CBLAS', None)], include_dirs=incl_dirs) self.set_info(**info) class blas_src_info(system_info): section = 'blas_src' dir_env_var = 'BLAS_SRC' notfounderror = BlasSrcNotFoundError def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend([d] + self.combine_paths(d, ['blas'])) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): src_dirs = self.get_src_dirs() src_dir = '' for d in src_dirs: if os.path.isfile(os.path.join(d, 'daxpy.f')): src_dir = d break if not src_dir: #XXX: Get sources from netlib. May be ask first. return blas1 = ''' caxpy csscal dnrm2 dzasum saxpy srotg zdotc ccopy cswap drot dznrm2 scasum srotm zdotu cdotc dasum drotg icamax scnrm2 srotmg zdrot cdotu daxpy drotm idamax scopy sscal zdscal crotg dcabs1 drotmg isamax sdot sswap zrotg cscal dcopy dscal izamax snrm2 zaxpy zscal csrot ddot dswap sasum srot zcopy zswap scabs1 ''' blas2 = ''' cgbmv chpmv ctrsv dsymv dtrsv sspr2 strmv zhemv ztpmv cgemv chpr dgbmv dsyr lsame ssymv strsv zher ztpsv cgerc chpr2 dgemv dsyr2 sgbmv ssyr xerbla zher2 ztrmv cgeru ctbmv dger dtbmv sgemv ssyr2 zgbmv zhpmv ztrsv chbmv ctbsv dsbmv dtbsv sger stbmv zgemv zhpr chemv ctpmv dspmv dtpmv ssbmv stbsv zgerc zhpr2 cher ctpsv dspr dtpsv sspmv stpmv zgeru ztbmv cher2 ctrmv dspr2 dtrmv sspr stpsv zhbmv ztbsv ''' blas3 = ''' cgemm csymm ctrsm dsyrk sgemm strmm zhemm zsyr2k chemm csyr2k dgemm dtrmm ssymm strsm zher2k zsyrk cher2k csyrk dsymm dtrsm ssyr2k zherk ztrmm cherk ctrmm dsyr2k ssyrk zgemm zsymm ztrsm ''' sources = [os.path.join(src_dir, f + '.f') \ for f in (blas1 + blas2 + blas3).split()] #XXX: should we check here actual existence of source files? sources = [f for f in sources if os.path.isfile(f)] info = {'sources': sources, 'language': 'f77'} self.set_info(**info) class x11_info(system_info): section = 'x11' notfounderror = X11NotFoundError def __init__(self): system_info.__init__(self, default_lib_dirs=default_x11_lib_dirs, default_include_dirs=default_x11_include_dirs) def calc_info(self): if sys.platform in ['win32']: return lib_dirs = self.get_lib_dirs() include_dirs = self.get_include_dirs() x11_libs = self.get_libs('x11_libs', ['X11']) info = self.check_libs(lib_dirs, x11_libs, []) if info is None: return inc_dir = None for d in include_dirs: if self.combine_paths(d, 'X11/X.h'): inc_dir = d break if inc_dir is not None: dict_append(info, include_dirs=[inc_dir]) self.set_info(**info) class _numpy_info(system_info): section = 'Numeric' modulename = 'Numeric' notfounderror = NumericNotFoundError def __init__(self): include_dirs = [] try: module = __import__(self.modulename) prefix = [] for name in module.__file__.split(os.sep): if name == 'lib': break prefix.append(name) # Ask numpy for its own include path before attempting # anything else try: include_dirs.append(getattr(module, 'get_include')()) except AttributeError: pass include_dirs.append(distutils.sysconfig.get_python_inc( prefix=os.sep.join(prefix))) except ImportError: pass py_incl_dir = distutils.sysconfig.get_python_inc() include_dirs.append(py_incl_dir) py_pincl_dir = distutils.sysconfig.get_python_inc(plat_specific=True) if py_pincl_dir not in include_dirs: include_dirs.append(py_pincl_dir) for d in default_include_dirs: d = os.path.join(d, os.path.basename(py_incl_dir)) if d not in include_dirs: include_dirs.append(d) system_info.__init__(self, default_lib_dirs=[], default_include_dirs=include_dirs) def calc_info(self): try: module = __import__(self.modulename) except ImportError: return info = {} macros = [] for v in ['__version__', 'version']: vrs = getattr(module, v, None) if vrs is None: continue macros = [(self.modulename.upper() + '_VERSION', '"\\"%s\\""' % (vrs)), (self.modulename.upper(), None)] break dict_append(info, define_macros=macros) include_dirs = self.get_include_dirs() inc_dir = None for d in include_dirs: if self.combine_paths(d, os.path.join(self.modulename, 'arrayobject.h')): inc_dir = d break if inc_dir is not None: dict_append(info, include_dirs=[inc_dir]) if info: self.set_info(**info) return class numarray_info(_numpy_info): section = 'numarray' modulename = 'numarray' class Numeric_info(_numpy_info): section = 'Numeric' modulename = 'Numeric' class numpy_info(_numpy_info): section = 'numpy' modulename = 'numpy' class numerix_info(system_info): section = 'numerix' def calc_info(self): which = None, None if os.getenv("NUMERIX"): which = os.getenv("NUMERIX"), "environment var" # If all the above fail, default to numpy. if which[0] is None: which = "numpy", "defaulted" try: import numpy which = "numpy", "defaulted" except ImportError: msg1 = str(get_exception()) try: import Numeric which = "numeric", "defaulted" except ImportError: msg2 = str(get_exception()) try: import numarray which = "numarray", "defaulted" except ImportError: msg3 = str(get_exception()) log.info(msg1) log.info(msg2) log.info(msg3) which = which[0].strip().lower(), which[1] if which[0] not in ["numeric", "numarray", "numpy"]: raise ValueError("numerix selector must be either 'Numeric' " "or 'numarray' or 'numpy' but the value obtained" " from the %s was '%s'." % (which[1], which[0])) os.environ['NUMERIX'] = which[0] self.set_info(**get_info(which[0])) class f2py_info(system_info): def calc_info(self): try: import numpy.f2py as f2py except ImportError: return f2py_dir = os.path.join(os.path.dirname(f2py.__file__), 'src') self.set_info(sources=[os.path.join(f2py_dir, 'fortranobject.c')], include_dirs=[f2py_dir]) return class boost_python_info(system_info): section = 'boost_python' dir_env_var = 'BOOST' def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend([d] + self.combine_paths(d, ['boost*'])) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): src_dirs = self.get_src_dirs() src_dir = '' for d in src_dirs: if os.path.isfile(os.path.join(d, 'libs', 'python', 'src', 'module.cpp')): src_dir = d break if not src_dir: return py_incl_dirs = [distutils.sysconfig.get_python_inc()] py_pincl_dir = distutils.sysconfig.get_python_inc(plat_specific=True) if py_pincl_dir not in py_incl_dirs: py_incl_dirs.append(py_pincl_dir) srcs_dir = os.path.join(src_dir, 'libs', 'python', 'src') bpl_srcs = glob(os.path.join(srcs_dir, '*.cpp')) bpl_srcs += glob(os.path.join(srcs_dir, '*', '*.cpp')) info = {'libraries': [('boost_python_src', {'include_dirs': [src_dir] + py_incl_dirs, 'sources':bpl_srcs} )], 'include_dirs': [src_dir], } if info: self.set_info(**info) return class agg2_info(system_info): section = 'agg2' dir_env_var = 'AGG2' def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend([d] + self.combine_paths(d, ['agg2*'])) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): src_dirs = self.get_src_dirs() src_dir = '' for d in src_dirs: if os.path.isfile(os.path.join(d, 'src', 'agg_affine_matrix.cpp')): src_dir = d break if not src_dir: return if sys.platform == 'win32': agg2_srcs = glob(os.path.join(src_dir, 'src', 'platform', 'win32', 'agg_win32_bmp.cpp')) else: agg2_srcs = glob(os.path.join(src_dir, 'src', '*.cpp')) agg2_srcs += [os.path.join(src_dir, 'src', 'platform', 'X11', 'agg_platform_support.cpp')] info = {'libraries': [('agg2_src', {'sources': agg2_srcs, 'include_dirs': [os.path.join(src_dir, 'include')], } )], 'include_dirs': [os.path.join(src_dir, 'include')], } if info: self.set_info(**info) return class _pkg_config_info(system_info): section = None config_env_var = 'PKG_CONFIG' default_config_exe = 'pkg-config' append_config_exe = '' version_macro_name = None release_macro_name = None version_flag = '--modversion' cflags_flag = '--cflags' def get_config_exe(self): if self.config_env_var in os.environ: return os.environ[self.config_env_var] return self.default_config_exe def get_config_output(self, config_exe, option): cmd = config_exe + ' ' + self.append_config_exe + ' ' + option s, o = exec_command(cmd, use_tee=0) if not s: return o def calc_info(self): config_exe = find_executable(self.get_config_exe()) if not config_exe: log.warn('File not found: %s. Cannot determine %s info.' \ % (config_exe, self.section)) return info = {} macros = [] libraries = [] library_dirs = [] include_dirs = [] extra_link_args = [] extra_compile_args = [] version = self.get_config_output(config_exe, self.version_flag) if version: macros.append((self.__class__.__name__.split('.')[-1].upper(), '"\\"%s\\""' % (version))) if self.version_macro_name: macros.append((self.version_macro_name + '_%s' % (version.replace('.', '_')), None)) if self.release_macro_name: release = self.get_config_output(config_exe, '--release') if release: macros.append((self.release_macro_name + '_%s' % (release.replace('.', '_')), None)) opts = self.get_config_output(config_exe, '--libs') if opts: for opt in opts.split(): if opt[:2] == '-l': libraries.append(opt[2:]) elif opt[:2] == '-L': library_dirs.append(opt[2:]) else: extra_link_args.append(opt) opts = self.get_config_output(config_exe, self.cflags_flag) if opts: for opt in opts.split(): if opt[:2] == '-I': include_dirs.append(opt[2:]) elif opt[:2] == '-D': if '=' in opt: n, v = opt[2:].split('=') macros.append((n, v)) else: macros.append((opt[2:], None)) else: extra_compile_args.append(opt) if macros: dict_append(info, define_macros=macros) if libraries: dict_append(info, libraries=libraries) if library_dirs: dict_append(info, library_dirs=library_dirs) if include_dirs: dict_append(info, include_dirs=include_dirs) if extra_link_args: dict_append(info, extra_link_args=extra_link_args) if extra_compile_args: dict_append(info, extra_compile_args=extra_compile_args) if info: self.set_info(**info) return class wx_info(_pkg_config_info): section = 'wx' config_env_var = 'WX_CONFIG' default_config_exe = 'wx-config' append_config_exe = '' version_macro_name = 'WX_VERSION' release_macro_name = 'WX_RELEASE' version_flag = '--version' cflags_flag = '--cxxflags' class gdk_pixbuf_xlib_2_info(_pkg_config_info): section = 'gdk_pixbuf_xlib_2' append_config_exe = 'gdk-pixbuf-xlib-2.0' version_macro_name = 'GDK_PIXBUF_XLIB_VERSION' class gdk_pixbuf_2_info(_pkg_config_info): section = 'gdk_pixbuf_2' append_config_exe = 'gdk-pixbuf-2.0' version_macro_name = 'GDK_PIXBUF_VERSION' class gdk_x11_2_info(_pkg_config_info): section = 'gdk_x11_2' append_config_exe = 'gdk-x11-2.0' version_macro_name = 'GDK_X11_VERSION' class gdk_2_info(_pkg_config_info): section = 'gdk_2' append_config_exe = 'gdk-2.0' version_macro_name = 'GDK_VERSION' class gdk_info(_pkg_config_info): section = 'gdk' append_config_exe = 'gdk' version_macro_name = 'GDK_VERSION' class gtkp_x11_2_info(_pkg_config_info): section = 'gtkp_x11_2' append_config_exe = 'gtk+-x11-2.0' version_macro_name = 'GTK_X11_VERSION' class gtkp_2_info(_pkg_config_info): section = 'gtkp_2' append_config_exe = 'gtk+-2.0' version_macro_name = 'GTK_VERSION' class xft_info(_pkg_config_info): section = 'xft' append_config_exe = 'xft' version_macro_name = 'XFT_VERSION' class freetype2_info(_pkg_config_info): section = 'freetype2' append_config_exe = 'freetype2' version_macro_name = 'FREETYPE2_VERSION' class amd_info(system_info): section = 'amd' dir_env_var = 'AMD' _lib_names = ['amd'] def calc_info(self): lib_dirs = self.get_lib_dirs() amd_libs = self.get_libs('amd_libs', self._lib_names) info = self.check_libs(lib_dirs, amd_libs, []) if info is None: return include_dirs = self.get_include_dirs() inc_dir = None for d in include_dirs: p = self.combine_paths(d, 'amd.h') if p: inc_dir = os.path.dirname(p[0]) break if inc_dir is not None: dict_append(info, include_dirs=[inc_dir], define_macros=[('SCIPY_AMD_H', None)], swig_opts=['-I' + inc_dir]) self.set_info(**info) return class umfpack_info(system_info): section = 'umfpack' dir_env_var = 'UMFPACK' notfounderror = UmfpackNotFoundError _lib_names = ['umfpack'] def calc_info(self): lib_dirs = self.get_lib_dirs() umfpack_libs = self.get_libs('umfpack_libs', self._lib_names) info = self.check_libs(lib_dirs, umfpack_libs, []) if info is None: return include_dirs = self.get_include_dirs() inc_dir = None for d in include_dirs: p = self.combine_paths(d, ['', 'umfpack'], 'umfpack.h') if p: inc_dir = os.path.dirname(p[0]) break if inc_dir is not None: dict_append(info, include_dirs=[inc_dir], define_macros=[('SCIPY_UMFPACK_H', None)], swig_opts=['-I' + inc_dir]) amd = get_info('amd') dict_append(info, **get_info('amd')) self.set_info(**info) return def combine_paths(*args, **kws): """ Return a list of existing paths composed by all combinations of items from arguments. """ r = [] for a in args: if not a: continue if is_string(a): a = [a] r.append(a) args = r if not args: return [] if len(args) == 1: result = reduce(lambda a, b: a + b, map(glob, args[0]), []) elif len(args) == 2: result = [] for a0 in args[0]: for a1 in args[1]: result.extend(glob(os.path.join(a0, a1))) else: result = combine_paths(*(combine_paths(args[0], args[1]) + args[2:])) log.debug('(paths: %s)', ','.join(result)) return result language_map = {'c': 0, 'c++': 1, 'f77': 2, 'f90': 3} inv_language_map = {0: 'c', 1: 'c++', 2: 'f77', 3: 'f90'} def dict_append(d, **kws): languages = [] for k, v in kws.items(): if k == 'language': languages.append(v) continue if k in d: if k in ['library_dirs', 'include_dirs', 'extra_compile_args', 'extra_link_args', 'runtime_library_dirs', 'define_macros']: [d[k].append(vv) for vv in v if vv not in d[k]] else: d[k].extend(v) else: d[k] = v if languages: l = inv_language_map[max([language_map.get(l, 0) for l in languages])] d['language'] = l return def parseCmdLine(argv=(None,)): import optparse parser = optparse.OptionParser("usage: %prog [-v] [info objs]") parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='be verbose and print more messages') opts, args = parser.parse_args(args=argv[1:]) return opts, args def show_all(argv=None): import inspect if argv is None: argv = sys.argv opts, args = parseCmdLine(argv) if opts.verbose: log.set_threshold(log.DEBUG) else: log.set_threshold(log.INFO) show_only = [] for n in args: if n[-5:] != '_info': n = n + '_info' show_only.append(n) show_all = not show_only _gdict_ = globals().copy() for name, c in _gdict_.items(): if not inspect.isclass(c): continue if not issubclass(c, system_info) or c is system_info: continue if not show_all: if name not in show_only: continue del show_only[show_only.index(name)] conf = c() conf.verbosity = 2 r = conf.get_info() if show_only: log.info('Info classes not defined: %s', ','.join(show_only)) if __name__ == "__main__": show_all()
89,502
34.223534
97
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/intelccompiler.py
from __future__ import division, absolute_import, print_function import platform from distutils.unixccompiler import UnixCCompiler from numpy.distutils.exec_command import find_executable from numpy.distutils.ccompiler import simple_version_match if platform.system() == 'Windows': from numpy.distutils.msvc9compiler import MSVCCompiler class IntelCCompiler(UnixCCompiler): """A modified Intel compiler compatible with a GCC-built Python.""" compiler_type = 'intel' cc_exe = 'icc' cc_args = 'fPIC' def __init__(self, verbose=0, dry_run=0, force=0): UnixCCompiler.__init__(self, verbose, dry_run, force) v = self.get_version() mpopt = 'openmp' if v and v < '15' else 'qopenmp' self.cc_exe = ('icc -fPIC -fp-model strict -O3 ' '-fomit-frame-pointer -{}').format(mpopt) compiler = self.cc_exe if platform.system() == 'Darwin': shared_flag = '-Wl,-undefined,dynamic_lookup' else: shared_flag = '-shared' self.set_executables(compiler=compiler, compiler_so=compiler, compiler_cxx=compiler, archiver='xiar' + ' cru', linker_exe=compiler + ' -shared-intel', linker_so=compiler + ' ' + shared_flag + ' -shared-intel') class IntelItaniumCCompiler(IntelCCompiler): compiler_type = 'intele' # On Itanium, the Intel Compiler used to be called ecc, let's search for # it (now it's also icc, so ecc is last in the search). for cc_exe in map(find_executable, ['icc', 'ecc']): if cc_exe: break class IntelEM64TCCompiler(UnixCCompiler): """ A modified Intel x86_64 compiler compatible with a 64bit GCC-built Python. """ compiler_type = 'intelem' cc_exe = 'icc -m64' cc_args = '-fPIC' def __init__(self, verbose=0, dry_run=0, force=0): UnixCCompiler.__init__(self, verbose, dry_run, force) v = self.get_version() mpopt = 'openmp' if v and v < '15' else 'qopenmp' self.cc_exe = ('icc -m64 -fPIC -fp-model strict -O3 ' '-fomit-frame-pointer -{}').format(mpopt) compiler = self.cc_exe if platform.system() == 'Darwin': shared_flag = '-Wl,-undefined,dynamic_lookup' else: shared_flag = '-shared' self.set_executables(compiler=compiler, compiler_so=compiler, compiler_cxx=compiler, archiver='xiar' + ' cru', linker_exe=compiler + ' -shared-intel', linker_so=compiler + ' ' + shared_flag + ' -shared-intel') if platform.system() == 'Windows': class IntelCCompilerW(MSVCCompiler): """ A modified Intel compiler compatible with an MSVC-built Python. """ compiler_type = 'intelw' compiler_cxx = 'icl' def __init__(self, verbose=0, dry_run=0, force=0): MSVCCompiler.__init__(self, verbose, dry_run, force) version_match = simple_version_match(start=r'Intel\(R\).*?32,') self.__version = version_match def initialize(self, plat_name=None): MSVCCompiler.initialize(self, plat_name) self.cc = self.find_exe('icl.exe') self.lib = self.find_exe('xilib') self.linker = self.find_exe('xilink') self.compile_options = ['/nologo', '/O3', '/MD', '/W3', '/Qstd=c99'] self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/Qstd=c99', '/Z7', '/D_DEBUG'] class IntelEM64TCCompilerW(IntelCCompilerW): """ A modified Intel x86_64 compiler compatible with a 64bit MSVC-built Python. """ compiler_type = 'intelemw' def __init__(self, verbose=0, dry_run=0, force=0): MSVCCompiler.__init__(self, verbose, dry_run, force) version_match = simple_version_match(start=r'Intel\(R\).*?64,') self.__version = version_match
4,291
36.649123
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/mingw/gfortran_vs2003_hack.c
int _get_output_format(void) { return 0; } int _imp____lc_codepage = 0;
74
9.714286
28
c
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/sdist.py
from __future__ import division, absolute_import, print_function import sys if 'setuptools' in sys.modules: from setuptools.command.sdist import sdist as old_sdist else: from distutils.command.sdist import sdist as old_sdist from numpy.distutils.misc_util import get_data_files class sdist(old_sdist): def add_defaults (self): old_sdist.add_defaults(self) dist = self.distribution if dist.has_data_files(): for data in dist.data_files: self.filelist.extend(get_data_files(data)) if dist.has_headers(): headers = [] for h in dist.headers: if isinstance(h, str): headers.append(h) else: headers.append(h[1]) self.filelist.extend(headers) return
799
25.666667
64
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/build_clib.py
""" Modified version of build_clib that handles fortran source files. """ from __future__ import division, absolute_import, print_function import os from glob import glob import shutil from distutils.command.build_clib import build_clib as old_build_clib from distutils.errors import DistutilsSetupError, DistutilsError, \ DistutilsFileError from numpy.distutils import log from distutils.dep_util import newer_group from numpy.distutils.misc_util import filter_sources, has_f_sources,\ has_cxx_sources, all_strings, get_lib_source_files, is_sequence, \ get_numpy_include_dirs # Fix Python distutils bug sf #1718574: _l = old_build_clib.user_options for _i in range(len(_l)): if _l[_i][0] in ['build-clib', 'build-temp']: _l[_i] = (_l[_i][0] + '=',) + _l[_i][1:] # class build_clib(old_build_clib): description = "build C/C++/F libraries used by Python extensions" user_options = old_build_clib.user_options + [ ('fcompiler=', None, "specify the Fortran compiler type"), ('inplace', 'i', 'Build in-place'), ('parallel=', 'j', "number of parallel jobs"), ] boolean_options = old_build_clib.boolean_options + ['inplace'] def initialize_options(self): old_build_clib.initialize_options(self) self.fcompiler = None self.inplace = 0 self.parallel = None def finalize_options(self): if self.parallel: try: self.parallel = int(self.parallel) except ValueError: raise ValueError("--parallel/-j argument must be an integer") old_build_clib.finalize_options(self) self.set_undefined_options('build', ('parallel', 'parallel')) def have_f_sources(self): for (lib_name, build_info) in self.libraries: if has_f_sources(build_info.get('sources', [])): return True return False def have_cxx_sources(self): for (lib_name, build_info) in self.libraries: if has_cxx_sources(build_info.get('sources', [])): return True return False def run(self): if not self.libraries: return # Make sure that library sources are complete. languages = [] # Make sure that extension sources are complete. self.run_command('build_src') for (lib_name, build_info) in self.libraries: l = build_info.get('language', None) if l and l not in languages: languages.append(l) from distutils.ccompiler import new_compiler self.compiler = new_compiler(compiler=self.compiler, dry_run=self.dry_run, force=self.force) self.compiler.customize(self.distribution, need_cxx=self.have_cxx_sources()) libraries = self.libraries self.libraries = None self.compiler.customize_cmd(self) self.libraries = libraries self.compiler.show_customization() if self.have_f_sources(): from numpy.distutils.fcompiler import new_fcompiler self._f_compiler = new_fcompiler(compiler=self.fcompiler, verbose=self.verbose, dry_run=self.dry_run, force=self.force, requiref90='f90' in languages, c_compiler=self.compiler) if self._f_compiler is not None: self._f_compiler.customize(self.distribution) libraries = self.libraries self.libraries = None self._f_compiler.customize_cmd(self) self.libraries = libraries self._f_compiler.show_customization() else: self._f_compiler = None self.build_libraries(self.libraries) if self.inplace: for l in self.distribution.installed_libraries: libname = self.compiler.library_filename(l.name) source = os.path.join(self.build_clib, libname) target = os.path.join(l.target_dir, libname) self.mkpath(l.target_dir) shutil.copy(source, target) def get_source_files(self): self.check_library_list(self.libraries) filenames = [] for lib in self.libraries: filenames.extend(get_lib_source_files(lib)) return filenames def build_libraries(self, libraries): for (lib_name, build_info) in libraries: self.build_a_library(build_info, lib_name, libraries) def build_a_library(self, build_info, lib_name, libraries): # default compilers compiler = self.compiler fcompiler = self._f_compiler sources = build_info.get('sources') if sources is None or not is_sequence(sources): raise DistutilsSetupError(("in 'libraries' option (library '%s'), " + "'sources' must be present and must be " + "a list of source filenames") % lib_name) sources = list(sources) c_sources, cxx_sources, f_sources, fmodule_sources \ = filter_sources(sources) requiref90 = not not fmodule_sources or \ build_info.get('language', 'c') == 'f90' # save source type information so that build_ext can use it. source_languages = [] if c_sources: source_languages.append('c') if cxx_sources: source_languages.append('c++') if requiref90: source_languages.append('f90') elif f_sources: source_languages.append('f77') build_info['source_languages'] = source_languages lib_file = compiler.library_filename(lib_name, output_dir=self.build_clib) depends = sources + build_info.get('depends', []) if not (self.force or newer_group(depends, lib_file, 'newer')): log.debug("skipping '%s' library (up-to-date)", lib_name) return else: log.info("building '%s' library", lib_name) config_fc = build_info.get('config_fc', {}) if fcompiler is not None and config_fc: log.info('using additional config_fc from setup script ' 'for fortran compiler: %s' % (config_fc,)) from numpy.distutils.fcompiler import new_fcompiler fcompiler = new_fcompiler(compiler=fcompiler.compiler_type, verbose=self.verbose, dry_run=self.dry_run, force=self.force, requiref90=requiref90, c_compiler=self.compiler) if fcompiler is not None: dist = self.distribution base_config_fc = dist.get_option_dict('config_fc').copy() base_config_fc.update(config_fc) fcompiler.customize(base_config_fc) # check availability of Fortran compilers if (f_sources or fmodule_sources) and fcompiler is None: raise DistutilsError("library %s has Fortran sources" " but no Fortran compiler found" % (lib_name)) if fcompiler is not None: fcompiler.extra_f77_compile_args = build_info.get( 'extra_f77_compile_args') or [] fcompiler.extra_f90_compile_args = build_info.get( 'extra_f90_compile_args') or [] macros = build_info.get('macros') include_dirs = build_info.get('include_dirs') if include_dirs is None: include_dirs = [] extra_postargs = build_info.get('extra_compiler_args') or [] include_dirs.extend(get_numpy_include_dirs()) # where compiled F90 module files are: module_dirs = build_info.get('module_dirs') or [] module_build_dir = os.path.dirname(lib_file) if requiref90: self.mkpath(module_build_dir) if compiler.compiler_type == 'msvc': # this hack works around the msvc compiler attributes # problem, msvc uses its own convention :( c_sources += cxx_sources cxx_sources = [] objects = [] if c_sources: log.info("compiling C sources") objects = compiler.compile(c_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs) if cxx_sources: log.info("compiling C++ sources") cxx_compiler = compiler.cxx_compiler() cxx_objects = cxx_compiler.compile(cxx_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs) objects.extend(cxx_objects) if f_sources or fmodule_sources: extra_postargs = [] f_objects = [] if requiref90: if fcompiler.module_dir_switch is None: existing_modules = glob('*.mod') extra_postargs += fcompiler.module_options( module_dirs, module_build_dir) if fmodule_sources: log.info("compiling Fortran 90 module sources") f_objects += fcompiler.compile(fmodule_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs) if requiref90 and self._f_compiler.module_dir_switch is None: # move new compiled F90 module files to module_build_dir for f in glob('*.mod'): if f in existing_modules: continue t = os.path.join(module_build_dir, f) if os.path.abspath(f) == os.path.abspath(t): continue if os.path.isfile(t): os.remove(t) try: self.move_file(f, module_build_dir) except DistutilsFileError: log.warn('failed to move %r to %r' % (f, module_build_dir)) if f_sources: log.info("compiling Fortran sources") f_objects += fcompiler.compile(f_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs) else: f_objects = [] if f_objects and not fcompiler.can_ccompiler_link(compiler): # Default linker cannot link Fortran object files, and results # need to be wrapped later. Instead of creating a real static # library, just keep track of the object files. listfn = os.path.join(self.build_clib, lib_name + '.fobjects') with open(listfn, 'w') as f: f.write("\n".join(os.path.abspath(obj) for obj in f_objects)) listfn = os.path.join(self.build_clib, lib_name + '.cobjects') with open(listfn, 'w') as f: f.write("\n".join(os.path.abspath(obj) for obj in objects)) # create empty "library" file for dependency tracking lib_fname = os.path.join(self.build_clib, lib_name + compiler.static_lib_extension) with open(lib_fname, 'wb') as f: pass else: # assume that default linker is suitable for # linking Fortran object files objects.extend(f_objects) compiler.create_static_lib(objects, lib_name, output_dir=self.build_clib, debug=self.debug) # fix library dependencies clib_libraries = build_info.get('libraries', []) for lname, binfo in libraries: if lname in clib_libraries: clib_libraries.extend(binfo.get('libraries', [])) if clib_libraries: build_info['libraries'] = clib_libraries
13,389
40.32716
81
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/build_src.py
""" Build swig and f2py sources. """ from __future__ import division, absolute_import, print_function import os import re import sys import shlex import copy from distutils.command import build_ext from distutils.dep_util import newer_group, newer from distutils.util import get_platform from distutils.errors import DistutilsError, DistutilsSetupError # this import can't be done here, as it uses numpy stuff only available # after it's installed #import numpy.f2py from numpy.distutils import log from numpy.distutils.misc_util import ( fortran_ext_match, appendpath, is_string, is_sequence, get_cmd ) from numpy.distutils.from_template import process_file as process_f_file from numpy.distutils.conv_template import process_file as process_c_file def subst_vars(target, source, d): """Substitute any occurrence of @foo@ by d['foo'] from source file into target.""" var = re.compile('@([a-zA-Z_]+)@') fs = open(source, 'r') try: ft = open(target, 'w') try: for l in fs: m = var.search(l) if m: ft.write(l.replace('@%s@' % m.group(1), d[m.group(1)])) else: ft.write(l) finally: ft.close() finally: fs.close() class build_src(build_ext.build_ext): description = "build sources from SWIG, F2PY files or a function" user_options = [ ('build-src=', 'd', "directory to \"build\" sources to"), ('f2py-opts=', None, "list of f2py command line options"), ('swig=', None, "path to the SWIG executable"), ('swig-opts=', None, "list of SWIG command line options"), ('swig-cpp', None, "make SWIG create C++ files (default is autodetected from sources)"), ('f2pyflags=', None, "additional flags to f2py (use --f2py-opts= instead)"), # obsolete ('swigflags=', None, "additional flags to swig (use --swig-opts= instead)"), # obsolete ('force', 'f', "forcibly build everything (ignore file timestamps)"), ('inplace', 'i', "ignore build-lib and put compiled extensions into the source " + "directory alongside your pure Python modules"), ] boolean_options = ['force', 'inplace'] help_options = [] def initialize_options(self): self.extensions = None self.package = None self.py_modules = None self.py_modules_dict = None self.build_src = None self.build_lib = None self.build_base = None self.force = None self.inplace = None self.package_dir = None self.f2pyflags = None # obsolete self.f2py_opts = None self.swigflags = None # obsolete self.swig_opts = None self.swig_cpp = None self.swig = None def finalize_options(self): self.set_undefined_options('build', ('build_base', 'build_base'), ('build_lib', 'build_lib'), ('force', 'force')) if self.package is None: self.package = self.distribution.ext_package self.extensions = self.distribution.ext_modules self.libraries = self.distribution.libraries or [] self.py_modules = self.distribution.py_modules or [] self.data_files = self.distribution.data_files or [] if self.build_src is None: plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3]) self.build_src = os.path.join(self.build_base, 'src'+plat_specifier) # py_modules_dict is used in build_py.find_package_modules self.py_modules_dict = {} if self.f2pyflags: if self.f2py_opts: log.warn('ignoring --f2pyflags as --f2py-opts already used') else: self.f2py_opts = self.f2pyflags self.f2pyflags = None if self.f2py_opts is None: self.f2py_opts = [] else: self.f2py_opts = shlex.split(self.f2py_opts) if self.swigflags: if self.swig_opts: log.warn('ignoring --swigflags as --swig-opts already used') else: self.swig_opts = self.swigflags self.swigflags = None if self.swig_opts is None: self.swig_opts = [] else: self.swig_opts = shlex.split(self.swig_opts) # use options from build_ext command build_ext = self.get_finalized_command('build_ext') if self.inplace is None: self.inplace = build_ext.inplace if self.swig_cpp is None: self.swig_cpp = build_ext.swig_cpp for c in ['swig', 'swig_opt']: o = '--'+c.replace('_', '-') v = getattr(build_ext, c, None) if v: if getattr(self, c): log.warn('both build_src and build_ext define %s option' % (o)) else: log.info('using "%s=%s" option from build_ext command' % (o, v)) setattr(self, c, v) def run(self): log.info("build_src") if not (self.extensions or self.libraries): return self.build_sources() def build_sources(self): if self.inplace: self.get_package_dir = \ self.get_finalized_command('build_py').get_package_dir self.build_py_modules_sources() for libname_info in self.libraries: self.build_library_sources(*libname_info) if self.extensions: self.check_extensions_list(self.extensions) for ext in self.extensions: self.build_extension_sources(ext) self.build_data_files_sources() self.build_npy_pkg_config() def build_data_files_sources(self): if not self.data_files: return log.info('building data_files sources') from numpy.distutils.misc_util import get_data_files new_data_files = [] for data in self.data_files: if isinstance(data, str): new_data_files.append(data) elif isinstance(data, tuple): d, files = data if self.inplace: build_dir = self.get_package_dir('.'.join(d.split(os.sep))) else: build_dir = os.path.join(self.build_src, d) funcs = [f for f in files if hasattr(f, '__call__')] files = [f for f in files if not hasattr(f, '__call__')] for f in funcs: if f.__code__.co_argcount==1: s = f(build_dir) else: s = f() if s is not None: if isinstance(s, list): files.extend(s) elif isinstance(s, str): files.append(s) else: raise TypeError(repr(s)) filenames = get_data_files((d, files)) new_data_files.append((d, filenames)) else: raise TypeError(repr(data)) self.data_files[:] = new_data_files def _build_npy_pkg_config(self, info, gd): import shutil template, install_dir, subst_dict = info template_dir = os.path.dirname(template) for k, v in gd.items(): subst_dict[k] = v if self.inplace == 1: generated_dir = os.path.join(template_dir, install_dir) else: generated_dir = os.path.join(self.build_src, template_dir, install_dir) generated = os.path.basename(os.path.splitext(template)[0]) generated_path = os.path.join(generated_dir, generated) if not os.path.exists(generated_dir): os.makedirs(generated_dir) subst_vars(generated_path, template, subst_dict) # Where to install relatively to install prefix full_install_dir = os.path.join(template_dir, install_dir) return full_install_dir, generated_path def build_npy_pkg_config(self): log.info('build_src: building npy-pkg config files') # XXX: another ugly workaround to circumvent distutils brain damage. We # need the install prefix here, but finalizing the options of the # install command when only building sources cause error. Instead, we # copy the install command instance, and finalize the copy so that it # does not disrupt how distutils want to do things when with the # original install command instance. install_cmd = copy.copy(get_cmd('install')) if not install_cmd.finalized == 1: install_cmd.finalize_options() build_npkg = False gd = {} if self.inplace == 1: top_prefix = '.' build_npkg = True elif hasattr(install_cmd, 'install_libbase'): top_prefix = install_cmd.install_libbase build_npkg = True if build_npkg: for pkg, infos in self.distribution.installed_pkg_config.items(): pkg_path = self.distribution.package_dir[pkg] prefix = os.path.join(os.path.abspath(top_prefix), pkg_path) d = {'prefix': prefix} for info in infos: install_dir, generated = self._build_npy_pkg_config(info, d) self.distribution.data_files.append((install_dir, [generated])) def build_py_modules_sources(self): if not self.py_modules: return log.info('building py_modules sources') new_py_modules = [] for source in self.py_modules: if is_sequence(source) and len(source)==3: package, module_base, source = source if self.inplace: build_dir = self.get_package_dir(package) else: build_dir = os.path.join(self.build_src, os.path.join(*package.split('.'))) if hasattr(source, '__call__'): target = os.path.join(build_dir, module_base + '.py') source = source(target) if source is None: continue modules = [(package, module_base, source)] if package not in self.py_modules_dict: self.py_modules_dict[package] = [] self.py_modules_dict[package] += modules else: new_py_modules.append(source) self.py_modules[:] = new_py_modules def build_library_sources(self, lib_name, build_info): sources = list(build_info.get('sources', [])) if not sources: return log.info('building library "%s" sources' % (lib_name)) sources = self.generate_sources(sources, (lib_name, build_info)) sources = self.template_sources(sources, (lib_name, build_info)) sources, h_files = self.filter_h_files(sources) if h_files: log.info('%s - nothing done with h_files = %s', self.package, h_files) #for f in h_files: # self.distribution.headers.append((lib_name,f)) build_info['sources'] = sources return def build_extension_sources(self, ext): sources = list(ext.sources) log.info('building extension "%s" sources' % (ext.name)) fullname = self.get_ext_fullname(ext.name) modpath = fullname.split('.') package = '.'.join(modpath[0:-1]) if self.inplace: self.ext_target_dir = self.get_package_dir(package) sources = self.generate_sources(sources, ext) sources = self.template_sources(sources, ext) sources = self.swig_sources(sources, ext) sources = self.f2py_sources(sources, ext) sources = self.pyrex_sources(sources, ext) sources, py_files = self.filter_py_files(sources) if package not in self.py_modules_dict: self.py_modules_dict[package] = [] modules = [] for f in py_files: module = os.path.splitext(os.path.basename(f))[0] modules.append((package, module, f)) self.py_modules_dict[package] += modules sources, h_files = self.filter_h_files(sources) if h_files: log.info('%s - nothing done with h_files = %s', package, h_files) #for f in h_files: # self.distribution.headers.append((package,f)) ext.sources = sources def generate_sources(self, sources, extension): new_sources = [] func_sources = [] for source in sources: if is_string(source): new_sources.append(source) else: func_sources.append(source) if not func_sources: return new_sources if self.inplace and not is_sequence(extension): build_dir = self.ext_target_dir else: if is_sequence(extension): name = extension[0] # if 'include_dirs' not in extension[1]: # extension[1]['include_dirs'] = [] # incl_dirs = extension[1]['include_dirs'] else: name = extension.name # incl_dirs = extension.include_dirs #if self.build_src not in incl_dirs: # incl_dirs.append(self.build_src) build_dir = os.path.join(*([self.build_src]\ +name.split('.')[:-1])) self.mkpath(build_dir) for func in func_sources: source = func(extension, build_dir) if not source: continue if is_sequence(source): [log.info(" adding '%s' to sources." % (s,)) for s in source] new_sources.extend(source) else: log.info(" adding '%s' to sources." % (source,)) new_sources.append(source) return new_sources def filter_py_files(self, sources): return self.filter_files(sources, ['.py']) def filter_h_files(self, sources): return self.filter_files(sources, ['.h', '.hpp', '.inc']) def filter_files(self, sources, exts = []): new_sources = [] files = [] for source in sources: (base, ext) = os.path.splitext(source) if ext in exts: files.append(source) else: new_sources.append(source) return new_sources, files def template_sources(self, sources, extension): new_sources = [] if is_sequence(extension): depends = extension[1].get('depends') include_dirs = extension[1].get('include_dirs') else: depends = extension.depends include_dirs = extension.include_dirs for source in sources: (base, ext) = os.path.splitext(source) if ext == '.src': # Template file if self.inplace: target_dir = os.path.dirname(base) else: target_dir = appendpath(self.build_src, os.path.dirname(base)) self.mkpath(target_dir) target_file = os.path.join(target_dir, os.path.basename(base)) if (self.force or newer_group([source] + depends, target_file)): if _f_pyf_ext_match(base): log.info("from_template:> %s" % (target_file)) outstr = process_f_file(source) else: log.info("conv_template:> %s" % (target_file)) outstr = process_c_file(source) fid = open(target_file, 'w') fid.write(outstr) fid.close() if _header_ext_match(target_file): d = os.path.dirname(target_file) if d not in include_dirs: log.info(" adding '%s' to include_dirs." % (d)) include_dirs.append(d) new_sources.append(target_file) else: new_sources.append(source) return new_sources def pyrex_sources(self, sources, extension): """Pyrex not supported; this remains for Cython support (see below)""" new_sources = [] ext_name = extension.name.split('.')[-1] for source in sources: (base, ext) = os.path.splitext(source) if ext == '.pyx': target_file = self.generate_a_pyrex_source(base, ext_name, source, extension) new_sources.append(target_file) else: new_sources.append(source) return new_sources def generate_a_pyrex_source(self, base, ext_name, source, extension): """Pyrex is not supported, but some projects monkeypatch this method. That allows compiling Cython code, see gh-6955. This method will remain here for compatibility reasons. """ return [] def f2py_sources(self, sources, extension): new_sources = [] f2py_sources = [] f_sources = [] f2py_targets = {} target_dirs = [] ext_name = extension.name.split('.')[-1] skip_f2py = 0 for source in sources: (base, ext) = os.path.splitext(source) if ext == '.pyf': # F2PY interface file if self.inplace: target_dir = os.path.dirname(base) else: target_dir = appendpath(self.build_src, os.path.dirname(base)) if os.path.isfile(source): name = get_f2py_modulename(source) if name != ext_name: raise DistutilsSetupError('mismatch of extension names: %s ' 'provides %r but expected %r' % ( source, name, ext_name)) target_file = os.path.join(target_dir, name+'module.c') else: log.debug(' source %s does not exist: skipping f2py\'ing.' \ % (source)) name = ext_name skip_f2py = 1 target_file = os.path.join(target_dir, name+'module.c') if not os.path.isfile(target_file): log.warn(' target %s does not exist:\n '\ 'Assuming %smodule.c was generated with '\ '"build_src --inplace" command.' \ % (target_file, name)) target_dir = os.path.dirname(base) target_file = os.path.join(target_dir, name+'module.c') if not os.path.isfile(target_file): raise DistutilsSetupError("%r missing" % (target_file,)) log.info(' Yes! Using %r as up-to-date target.' \ % (target_file)) target_dirs.append(target_dir) f2py_sources.append(source) f2py_targets[source] = target_file new_sources.append(target_file) elif fortran_ext_match(ext): f_sources.append(source) else: new_sources.append(source) if not (f2py_sources or f_sources): return new_sources for d in target_dirs: self.mkpath(d) f2py_options = extension.f2py_options + self.f2py_opts if self.distribution.libraries: for name, build_info in self.distribution.libraries: if name in extension.libraries: f2py_options.extend(build_info.get('f2py_options', [])) log.info("f2py options: %s" % (f2py_options)) if f2py_sources: if len(f2py_sources) != 1: raise DistutilsSetupError( 'only one .pyf file is allowed per extension module but got'\ ' more: %r' % (f2py_sources,)) source = f2py_sources[0] target_file = f2py_targets[source] target_dir = os.path.dirname(target_file) or '.' depends = [source] + extension.depends if (self.force or newer_group(depends, target_file, 'newer')) \ and not skip_f2py: log.info("f2py: %s" % (source)) import numpy.f2py numpy.f2py.run_main(f2py_options + ['--build-dir', target_dir, source]) else: log.debug(" skipping '%s' f2py interface (up-to-date)" % (source)) else: #XXX TODO: --inplace support for sdist command if is_sequence(extension): name = extension[0] else: name = extension.name target_dir = os.path.join(*([self.build_src]\ +name.split('.')[:-1])) target_file = os.path.join(target_dir, ext_name + 'module.c') new_sources.append(target_file) depends = f_sources + extension.depends if (self.force or newer_group(depends, target_file, 'newer')) \ and not skip_f2py: log.info("f2py:> %s" % (target_file)) self.mkpath(target_dir) import numpy.f2py numpy.f2py.run_main(f2py_options + ['--lower', '--build-dir', target_dir]+\ ['-m', ext_name]+f_sources) else: log.debug(" skipping f2py fortran files for '%s' (up-to-date)"\ % (target_file)) if not os.path.isfile(target_file): raise DistutilsError("f2py target file %r not generated" % (target_file,)) build_dir = os.path.join(self.build_src, target_dir) target_c = os.path.join(build_dir, 'fortranobject.c') target_h = os.path.join(build_dir, 'fortranobject.h') log.info(" adding '%s' to sources." % (target_c)) new_sources.append(target_c) if build_dir not in extension.include_dirs: log.info(" adding '%s' to include_dirs." % (build_dir)) extension.include_dirs.append(build_dir) if not skip_f2py: import numpy.f2py d = os.path.dirname(numpy.f2py.__file__) source_c = os.path.join(d, 'src', 'fortranobject.c') source_h = os.path.join(d, 'src', 'fortranobject.h') if newer(source_c, target_c) or newer(source_h, target_h): self.mkpath(os.path.dirname(target_c)) self.copy_file(source_c, target_c) self.copy_file(source_h, target_h) else: if not os.path.isfile(target_c): raise DistutilsSetupError("f2py target_c file %r not found" % (target_c,)) if not os.path.isfile(target_h): raise DistutilsSetupError("f2py target_h file %r not found" % (target_h,)) for name_ext in ['-f2pywrappers.f', '-f2pywrappers2.f90']: filename = os.path.join(target_dir, ext_name + name_ext) if os.path.isfile(filename): log.info(" adding '%s' to sources." % (filename)) f_sources.append(filename) return new_sources + f_sources def swig_sources(self, sources, extension): # Assuming SWIG 1.3.14 or later. See compatibility note in # http://www.swig.org/Doc1.3/Python.html#Python_nn6 new_sources = [] swig_sources = [] swig_targets = {} target_dirs = [] py_files = [] # swig generated .py files target_ext = '.c' if '-c++' in extension.swig_opts: typ = 'c++' is_cpp = True extension.swig_opts.remove('-c++') elif self.swig_cpp: typ = 'c++' is_cpp = True else: typ = None is_cpp = False skip_swig = 0 ext_name = extension.name.split('.')[-1] for source in sources: (base, ext) = os.path.splitext(source) if ext == '.i': # SWIG interface file # the code below assumes that the sources list # contains not more than one .i SWIG interface file if self.inplace: target_dir = os.path.dirname(base) py_target_dir = self.ext_target_dir else: target_dir = appendpath(self.build_src, os.path.dirname(base)) py_target_dir = target_dir if os.path.isfile(source): name = get_swig_modulename(source) if name != ext_name[1:]: raise DistutilsSetupError( 'mismatch of extension names: %s provides %r' ' but expected %r' % (source, name, ext_name[1:])) if typ is None: typ = get_swig_target(source) is_cpp = typ=='c++' else: typ2 = get_swig_target(source) if typ2 is None: log.warn('source %r does not define swig target, assuming %s swig target' \ % (source, typ)) elif typ!=typ2: log.warn('expected %r but source %r defines %r swig target' \ % (typ, source, typ2)) if typ2=='c++': log.warn('resetting swig target to c++ (some targets may have .c extension)') is_cpp = True else: log.warn('assuming that %r has c++ swig target' % (source)) if is_cpp: target_ext = '.cpp' target_file = os.path.join(target_dir, '%s_wrap%s' \ % (name, target_ext)) else: log.warn(' source %s does not exist: skipping swig\'ing.' \ % (source)) name = ext_name[1:] skip_swig = 1 target_file = _find_swig_target(target_dir, name) if not os.path.isfile(target_file): log.warn(' target %s does not exist:\n '\ 'Assuming %s_wrap.{c,cpp} was generated with '\ '"build_src --inplace" command.' \ % (target_file, name)) target_dir = os.path.dirname(base) target_file = _find_swig_target(target_dir, name) if not os.path.isfile(target_file): raise DistutilsSetupError("%r missing" % (target_file,)) log.warn(' Yes! Using %r as up-to-date target.' \ % (target_file)) target_dirs.append(target_dir) new_sources.append(target_file) py_files.append(os.path.join(py_target_dir, name+'.py')) swig_sources.append(source) swig_targets[source] = new_sources[-1] else: new_sources.append(source) if not swig_sources: return new_sources if skip_swig: return new_sources + py_files for d in target_dirs: self.mkpath(d) swig = self.swig or self.find_swig() swig_cmd = [swig, "-python"] + extension.swig_opts if is_cpp: swig_cmd.append('-c++') for d in extension.include_dirs: swig_cmd.append('-I'+d) for source in swig_sources: target = swig_targets[source] depends = [source] + extension.depends if self.force or newer_group(depends, target, 'newer'): log.info("%s: %s" % (os.path.basename(swig) \ + (is_cpp and '++' or ''), source)) self.spawn(swig_cmd + self.swig_opts \ + ["-o", target, '-outdir', py_target_dir, source]) else: log.debug(" skipping '%s' swig interface (up-to-date)" \ % (source)) return new_sources + py_files _f_pyf_ext_match = re.compile(r'.*[.](f90|f95|f77|for|ftn|f|pyf)\Z', re.I).match _header_ext_match = re.compile(r'.*[.](inc|h|hpp)\Z', re.I).match #### SWIG related auxiliary functions #### _swig_module_name_match = re.compile(r'\s*%module\s*(.*\(\s*package\s*=\s*"(?P<package>[\w_]+)".*\)|)\s*(?P<name>[\w_]+)', re.I).match _has_c_header = re.compile(r'-[*]-\s*c\s*-[*]-', re.I).search _has_cpp_header = re.compile(r'-[*]-\s*c[+][+]\s*-[*]-', re.I).search def get_swig_target(source): f = open(source, 'r') result = None line = f.readline() if _has_cpp_header(line): result = 'c++' if _has_c_header(line): result = 'c' f.close() return result def get_swig_modulename(source): f = open(source, 'r') name = None for line in f: m = _swig_module_name_match(line) if m: name = m.group('name') break f.close() return name def _find_swig_target(target_dir, name): for ext in ['.cpp', '.c']: target = os.path.join(target_dir, '%s_wrap%s' % (name, ext)) if os.path.isfile(target): break return target #### F2PY related auxiliary functions #### _f2py_module_name_match = re.compile(r'\s*python\s*module\s*(?P<name>[\w_]+)', re.I).match _f2py_user_module_name_match = re.compile(r'\s*python\s*module\s*(?P<name>[\w_]*?' r'__user__[\w_]*)', re.I).match def get_f2py_modulename(source): name = None f = open(source) for line in f: m = _f2py_module_name_match(line) if m: if _f2py_user_module_name_match(line): # skip *__user__* names continue name = m.group('name') break f.close() return name ##########################################
30,946
38.828829
122
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/build_ext.py
""" Modified version of build_ext that handles fortran source files. """ from __future__ import division, absolute_import, print_function import os import sys import shutil from glob import glob from distutils.dep_util import newer_group from distutils.command.build_ext import build_ext as old_build_ext from distutils.errors import DistutilsFileError, DistutilsSetupError,\ DistutilsError from distutils.file_util import copy_file from numpy.distutils import log from numpy.distutils.exec_command import exec_command from numpy.distutils.system_info import combine_paths, system_info from numpy.distutils.misc_util import filter_sources, has_f_sources, \ has_cxx_sources, get_ext_source_files, \ get_numpy_include_dirs, is_sequence, get_build_architecture, \ msvc_version from numpy.distutils.command.config_compiler import show_fortran_compilers class build_ext (old_build_ext): description = "build C/C++/F extensions (compile/link to build directory)" user_options = old_build_ext.user_options + [ ('fcompiler=', None, "specify the Fortran compiler type"), ('parallel=', 'j', "number of parallel jobs"), ] help_options = old_build_ext.help_options + [ ('help-fcompiler', None, "list available Fortran compilers", show_fortran_compilers), ] def initialize_options(self): old_build_ext.initialize_options(self) self.fcompiler = None self.parallel = None def finalize_options(self): if self.parallel: try: self.parallel = int(self.parallel) except ValueError: raise ValueError("--parallel/-j argument must be an integer") # Ensure that self.include_dirs and self.distribution.include_dirs # refer to the same list object. finalize_options will modify # self.include_dirs, but self.distribution.include_dirs is used # during the actual build. # self.include_dirs is None unless paths are specified with # --include-dirs. # The include paths will be passed to the compiler in the order: # numpy paths, --include-dirs paths, Python include path. if isinstance(self.include_dirs, str): self.include_dirs = self.include_dirs.split(os.pathsep) incl_dirs = self.include_dirs or [] if self.distribution.include_dirs is None: self.distribution.include_dirs = [] self.include_dirs = self.distribution.include_dirs self.include_dirs.extend(incl_dirs) old_build_ext.finalize_options(self) self.set_undefined_options('build', ('parallel', 'parallel')) def run(self): if not self.extensions: return # Make sure that extension sources are complete. self.run_command('build_src') if self.distribution.has_c_libraries(): if self.inplace: if self.distribution.have_run.get('build_clib'): log.warn('build_clib already run, it is too late to ' 'ensure in-place build of build_clib') build_clib = self.distribution.get_command_obj( 'build_clib') else: build_clib = self.distribution.get_command_obj( 'build_clib') build_clib.inplace = 1 build_clib.ensure_finalized() build_clib.run() self.distribution.have_run['build_clib'] = 1 else: self.run_command('build_clib') build_clib = self.get_finalized_command('build_clib') self.library_dirs.append(build_clib.build_clib) else: build_clib = None # Not including C libraries to the list of # extension libraries automatically to prevent # bogus linking commands. Extensions must # explicitly specify the C libraries that they use. from distutils.ccompiler import new_compiler from numpy.distutils.fcompiler import new_fcompiler compiler_type = self.compiler # Initialize C compiler: self.compiler = new_compiler(compiler=compiler_type, verbose=self.verbose, dry_run=self.dry_run, force=self.force) self.compiler.customize(self.distribution) self.compiler.customize_cmd(self) self.compiler.show_customization() # Setup directory for storing generated extra DLL files on Windows self.extra_dll_dir = os.path.join(self.build_temp, 'extra-dll') if not os.path.isdir(self.extra_dll_dir): os.makedirs(self.extra_dll_dir) # Create mapping of libraries built by build_clib: clibs = {} if build_clib is not None: for libname, build_info in build_clib.libraries or []: if libname in clibs and clibs[libname] != build_info: log.warn('library %r defined more than once,' ' overwriting build_info\n%s... \nwith\n%s...' % (libname, repr(clibs[libname])[:300], repr(build_info)[:300])) clibs[libname] = build_info # .. and distribution libraries: for libname, build_info in self.distribution.libraries or []: if libname in clibs: # build_clib libraries have a precedence before distribution ones continue clibs[libname] = build_info # Determine if C++/Fortran 77/Fortran 90 compilers are needed. # Update extension libraries, library_dirs, and macros. all_languages = set() for ext in self.extensions: ext_languages = set() c_libs = [] c_lib_dirs = [] macros = [] for libname in ext.libraries: if libname in clibs: binfo = clibs[libname] c_libs += binfo.get('libraries', []) c_lib_dirs += binfo.get('library_dirs', []) for m in binfo.get('macros', []): if m not in macros: macros.append(m) for l in clibs.get(libname, {}).get('source_languages', []): ext_languages.add(l) if c_libs: new_c_libs = ext.libraries + c_libs log.info('updating extension %r libraries from %r to %r' % (ext.name, ext.libraries, new_c_libs)) ext.libraries = new_c_libs ext.library_dirs = ext.library_dirs + c_lib_dirs if macros: log.info('extending extension %r defined_macros with %r' % (ext.name, macros)) ext.define_macros = ext.define_macros + macros # determine extension languages if has_f_sources(ext.sources): ext_languages.add('f77') if has_cxx_sources(ext.sources): ext_languages.add('c++') l = ext.language or self.compiler.detect_language(ext.sources) if l: ext_languages.add(l) # reset language attribute for choosing proper linker if 'c++' in ext_languages: ext_language = 'c++' elif 'f90' in ext_languages: ext_language = 'f90' elif 'f77' in ext_languages: ext_language = 'f77' else: ext_language = 'c' # default if l and l != ext_language and ext.language: log.warn('resetting extension %r language from %r to %r.' % (ext.name, l, ext_language)) ext.language = ext_language # global language all_languages.update(ext_languages) need_f90_compiler = 'f90' in all_languages need_f77_compiler = 'f77' in all_languages need_cxx_compiler = 'c++' in all_languages # Initialize C++ compiler: if need_cxx_compiler: self._cxx_compiler = new_compiler(compiler=compiler_type, verbose=self.verbose, dry_run=self.dry_run, force=self.force) compiler = self._cxx_compiler compiler.customize(self.distribution, need_cxx=need_cxx_compiler) compiler.customize_cmd(self) compiler.show_customization() self._cxx_compiler = compiler.cxx_compiler() else: self._cxx_compiler = None # Initialize Fortran 77 compiler: if need_f77_compiler: ctype = self.fcompiler self._f77_compiler = new_fcompiler(compiler=self.fcompiler, verbose=self.verbose, dry_run=self.dry_run, force=self.force, requiref90=False, c_compiler=self.compiler) fcompiler = self._f77_compiler if fcompiler: ctype = fcompiler.compiler_type fcompiler.customize(self.distribution) if fcompiler and fcompiler.get_version(): fcompiler.customize_cmd(self) fcompiler.show_customization() else: self.warn('f77_compiler=%s is not available.' % (ctype)) self._f77_compiler = None else: self._f77_compiler = None # Initialize Fortran 90 compiler: if need_f90_compiler: ctype = self.fcompiler self._f90_compiler = new_fcompiler(compiler=self.fcompiler, verbose=self.verbose, dry_run=self.dry_run, force=self.force, requiref90=True, c_compiler=self.compiler) fcompiler = self._f90_compiler if fcompiler: ctype = fcompiler.compiler_type fcompiler.customize(self.distribution) if fcompiler and fcompiler.get_version(): fcompiler.customize_cmd(self) fcompiler.show_customization() else: self.warn('f90_compiler=%s is not available.' % (ctype)) self._f90_compiler = None else: self._f90_compiler = None # Build extensions self.build_extensions() # Copy over any extra DLL files runtime_lib_dir = os.path.join( self.build_lib, self.distribution.get_name(), '.libs') for fn in os.listdir(self.extra_dll_dir): if not fn.lower().endswith('.dll'): continue if not os.path.isdir(runtime_lib_dir): os.makedirs(runtime_lib_dir) runtime_lib = os.path.join(self.extra_dll_dir, fn) copy_file(runtime_lib, runtime_lib_dir) def swig_sources(self, sources): # Do nothing. Swig sources have beed handled in build_src command. return sources def build_extension(self, ext): sources = ext.sources if sources is None or not is_sequence(sources): raise DistutilsSetupError( ("in 'ext_modules' option (extension '%s'), " + "'sources' must be present and must be " + "a list of source filenames") % ext.name) sources = list(sources) if not sources: return fullname = self.get_ext_fullname(ext.name) if self.inplace: modpath = fullname.split('.') package = '.'.join(modpath[0:-1]) base = modpath[-1] build_py = self.get_finalized_command('build_py') package_dir = build_py.get_package_dir(package) ext_filename = os.path.join(package_dir, self.get_ext_filename(base)) else: ext_filename = os.path.join(self.build_lib, self.get_ext_filename(fullname)) depends = sources + ext.depends if not (self.force or newer_group(depends, ext_filename, 'newer')): log.debug("skipping '%s' extension (up-to-date)", ext.name) return else: log.info("building '%s' extension", ext.name) extra_args = ext.extra_compile_args or [] macros = ext.define_macros[:] for undef in ext.undef_macros: macros.append((undef,)) c_sources, cxx_sources, f_sources, fmodule_sources = \ filter_sources(ext.sources) if self.compiler.compiler_type == 'msvc': if cxx_sources: # Needed to compile kiva.agg._agg extension. extra_args.append('/Zm1000') # this hack works around the msvc compiler attributes # problem, msvc uses its own convention :( c_sources += cxx_sources cxx_sources = [] # Set Fortran/C++ compilers for compilation and linking. if ext.language == 'f90': fcompiler = self._f90_compiler elif ext.language == 'f77': fcompiler = self._f77_compiler else: # in case ext.language is c++, for instance fcompiler = self._f90_compiler or self._f77_compiler if fcompiler is not None: fcompiler.extra_f77_compile_args = (ext.extra_f77_compile_args or []) if hasattr( ext, 'extra_f77_compile_args') else [] fcompiler.extra_f90_compile_args = (ext.extra_f90_compile_args or []) if hasattr( ext, 'extra_f90_compile_args') else [] cxx_compiler = self._cxx_compiler # check for the availability of required compilers if cxx_sources and cxx_compiler is None: raise DistutilsError("extension %r has C++ sources" "but no C++ compiler found" % (ext.name)) if (f_sources or fmodule_sources) and fcompiler is None: raise DistutilsError("extension %r has Fortran sources " "but no Fortran compiler found" % (ext.name)) if ext.language in ['f77', 'f90'] and fcompiler is None: self.warn("extension %r has Fortran libraries " "but no Fortran linker found, using default linker" % (ext.name)) if ext.language == 'c++' and cxx_compiler is None: self.warn("extension %r has C++ libraries " "but no C++ linker found, using default linker" % (ext.name)) kws = {'depends': ext.depends} output_dir = self.build_temp include_dirs = ext.include_dirs + get_numpy_include_dirs() c_objects = [] if c_sources: log.info("compiling C sources") c_objects = self.compiler.compile(c_sources, output_dir=output_dir, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_args, **kws) if cxx_sources: log.info("compiling C++ sources") c_objects += cxx_compiler.compile(cxx_sources, output_dir=output_dir, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_args, **kws) extra_postargs = [] f_objects = [] if fmodule_sources: log.info("compiling Fortran 90 module sources") module_dirs = ext.module_dirs[:] module_build_dir = os.path.join( self.build_temp, os.path.dirname( self.get_ext_filename(fullname))) self.mkpath(module_build_dir) if fcompiler.module_dir_switch is None: existing_modules = glob('*.mod') extra_postargs += fcompiler.module_options( module_dirs, module_build_dir) f_objects += fcompiler.compile(fmodule_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs, depends=ext.depends) if fcompiler.module_dir_switch is None: for f in glob('*.mod'): if f in existing_modules: continue t = os.path.join(module_build_dir, f) if os.path.abspath(f) == os.path.abspath(t): continue if os.path.isfile(t): os.remove(t) try: self.move_file(f, module_build_dir) except DistutilsFileError: log.warn('failed to move %r to %r' % (f, module_build_dir)) if f_sources: log.info("compiling Fortran sources") f_objects += fcompiler.compile(f_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs, depends=ext.depends) if f_objects and not fcompiler.can_ccompiler_link(self.compiler): unlinkable_fobjects = f_objects objects = c_objects else: unlinkable_fobjects = [] objects = c_objects + f_objects if ext.extra_objects: objects.extend(ext.extra_objects) extra_args = ext.extra_link_args or [] libraries = self.get_libraries(ext)[:] library_dirs = ext.library_dirs[:] linker = self.compiler.link_shared_object # Always use system linker when using MSVC compiler. if self.compiler.compiler_type in ('msvc', 'intelw', 'intelemw'): # expand libraries with fcompiler libraries as we are # not using fcompiler linker self._libs_with_msvc_and_fortran( fcompiler, libraries, library_dirs) elif ext.language in ['f77', 'f90'] and fcompiler is not None: linker = fcompiler.link_shared_object if ext.language == 'c++' and cxx_compiler is not None: linker = cxx_compiler.link_shared_object if fcompiler is not None: objects, libraries = self._process_unlinkable_fobjects( objects, libraries, fcompiler, library_dirs, unlinkable_fobjects) linker(objects, ext_filename, libraries=libraries, library_dirs=library_dirs, runtime_library_dirs=ext.runtime_library_dirs, extra_postargs=extra_args, export_symbols=self.get_export_symbols(ext), debug=self.debug, build_temp=self.build_temp, target_lang=ext.language) def _add_dummy_mingwex_sym(self, c_sources): build_src = self.get_finalized_command("build_src").build_src build_clib = self.get_finalized_command("build_clib").build_clib objects = self.compiler.compile([os.path.join(build_src, "gfortran_vs2003_hack.c")], output_dir=self.build_temp) self.compiler.create_static_lib( objects, "_gfortran_workaround", output_dir=build_clib, debug=self.debug) def _process_unlinkable_fobjects(self, objects, libraries, fcompiler, library_dirs, unlinkable_fobjects): libraries = list(libraries) objects = list(objects) unlinkable_fobjects = list(unlinkable_fobjects) # Expand possible fake static libraries to objects for lib in list(libraries): for libdir in library_dirs: fake_lib = os.path.join(libdir, lib + '.fobjects') if os.path.isfile(fake_lib): # Replace fake static library libraries.remove(lib) with open(fake_lib, 'r') as f: unlinkable_fobjects.extend(f.read().splitlines()) # Expand C objects c_lib = os.path.join(libdir, lib + '.cobjects') with open(c_lib, 'r') as f: objects.extend(f.read().splitlines()) # Wrap unlinkable objects to a linkable one if unlinkable_fobjects: fobjects = [os.path.relpath(obj) for obj in unlinkable_fobjects] wrapped = fcompiler.wrap_unlinkable_objects( fobjects, output_dir=self.build_temp, extra_dll_dir=self.extra_dll_dir) objects.extend(wrapped) return objects, libraries def _libs_with_msvc_and_fortran(self, fcompiler, c_libraries, c_library_dirs): if fcompiler is None: return for libname in c_libraries: if libname.startswith('msvc'): continue fileexists = False for libdir in c_library_dirs or []: libfile = os.path.join(libdir, '%s.lib' % (libname)) if os.path.isfile(libfile): fileexists = True break if fileexists: continue # make g77-compiled static libs available to MSVC fileexists = False for libdir in c_library_dirs: libfile = os.path.join(libdir, 'lib%s.a' % (libname)) if os.path.isfile(libfile): # copy libname.a file to name.lib so that MSVC linker # can find it libfile2 = os.path.join(self.build_temp, libname + '.lib') copy_file(libfile, libfile2) if self.build_temp not in c_library_dirs: c_library_dirs.append(self.build_temp) fileexists = True break if fileexists: continue log.warn('could not find library %r in directories %s' % (libname, c_library_dirs)) # Always use system linker when using MSVC compiler. f_lib_dirs = [] for dir in fcompiler.library_dirs: # correct path when compiling in Cygwin but with normal Win # Python if dir.startswith('/usr/lib'): s, o = exec_command(['cygpath', '-w', dir], use_tee=False) if not s: dir = o f_lib_dirs.append(dir) c_library_dirs.extend(f_lib_dirs) # make g77-compiled static libs available to MSVC for lib in fcompiler.libraries: if not lib.startswith('msvc'): c_libraries.append(lib) p = combine_paths(f_lib_dirs, 'lib' + lib + '.a') if p: dst_name = os.path.join(self.build_temp, lib + '.lib') if not os.path.isfile(dst_name): copy_file(p[0], dst_name) if self.build_temp not in c_library_dirs: c_library_dirs.append(self.build_temp) def get_source_files(self): self.check_extensions_list(self.extensions) filenames = [] for ext in self.extensions: filenames.extend(get_ext_source_files(ext)) return filenames def get_outputs(self): self.check_extensions_list(self.extensions) outputs = [] for ext in self.extensions: if not ext.sources: continue fullname = self.get_ext_fullname(ext.name) outputs.append(os.path.join(self.build_lib, self.get_ext_filename(fullname))) return outputs
25,264
42.040886
93
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/install_data.py
from __future__ import division, absolute_import, print_function import sys have_setuptools = ('setuptools' in sys.modules) from distutils.command.install_data import install_data as old_install_data #data installer with improved intelligence over distutils #data files are copied into the project directory instead #of willy-nilly class install_data (old_install_data): def run(self): old_install_data.run(self) if have_setuptools: # Run install_clib again, since setuptools does not run sub-commands # of install automatically self.run_command('install_clib') def finalize_options (self): self.set_undefined_options('install', ('install_lib', 'install_dir'), ('root', 'root'), ('force', 'force'), )
914
32.888889
80
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/install.py
from __future__ import division, absolute_import, print_function import sys if 'setuptools' in sys.modules: import setuptools.command.install as old_install_mod have_setuptools = True else: import distutils.command.install as old_install_mod have_setuptools = False from distutils.file_util import write_file old_install = old_install_mod.install class install(old_install): # Always run install_clib - the command is cheap, so no need to bypass it; # but it's not run by setuptools -- so it's run again in install_data sub_commands = old_install.sub_commands + [ ('install_clib', lambda x: True) ] def finalize_options (self): old_install.finalize_options(self) self.install_lib = self.install_libbase def setuptools_run(self): """ The setuptools version of the .run() method. We must pull in the entire code so we can override the level used in the _getframe() call since we wrap this call by one more level. """ from distutils.command.install import install as distutils_install # Explicit request for old-style install? Just do it if self.old_and_unmanageable or self.single_version_externally_managed: return distutils_install.run(self) # Attempt to detect whether we were called from setup() or by another # command. If we were called by setup(), our caller will be the # 'run_command' method in 'distutils.dist', and *its* caller will be # the 'run_commands' method. If we were called any other way, our # immediate caller *might* be 'run_command', but it won't have been # called by 'run_commands'. This is slightly kludgy, but seems to # work. # caller = sys._getframe(3) caller_module = caller.f_globals.get('__name__', '') caller_name = caller.f_code.co_name if caller_module != 'distutils.dist' or caller_name!='run_commands': # We weren't called from the command line or setup(), so we # should run in backward-compatibility mode to support bdist_* # commands. distutils_install.run(self) else: self.do_egg_install() def run(self): if not have_setuptools: r = old_install.run(self) else: r = self.setuptools_run() if self.record: # bdist_rpm fails when INSTALLED_FILES contains # paths with spaces. Such paths must be enclosed # with double-quotes. f = open(self.record, 'r') lines = [] need_rewrite = False for l in f: l = l.rstrip() if ' ' in l: need_rewrite = True l = '"%s"' % (l) lines.append(l) f.close() if need_rewrite: self.execute(write_file, (self.record, lines), "re-writing list of installed files to '%s'" % self.record) return r
3,127
36.686747
80
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/develop.py
""" Override the develop command from setuptools so we can ensure that our generated files (from build_src or build_scripts) are properly converted to real files with filenames. """ from __future__ import division, absolute_import, print_function from setuptools.command.develop import develop as old_develop class develop(old_develop): __doc__ = old_develop.__doc__ def install_for_development(self): # Build sources in-place, too. self.reinitialize_command('build_src', inplace=1) # Make sure scripts are built. self.run_command('build_scripts') old_develop.install_for_development(self)
641
34.666667
80
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/bdist_rpm.py
from __future__ import division, absolute_import, print_function import os import sys if 'setuptools' in sys.modules: from setuptools.command.bdist_rpm import bdist_rpm as old_bdist_rpm else: from distutils.command.bdist_rpm import bdist_rpm as old_bdist_rpm class bdist_rpm(old_bdist_rpm): def _make_spec_file(self): spec_file = old_bdist_rpm._make_spec_file(self) # Replace hardcoded setup.py script name # with the real setup script name. setup_py = os.path.basename(sys.argv[0]) if setup_py == 'setup.py': return spec_file new_spec_file = [] for line in spec_file: line = line.replace('setup.py', setup_py) new_spec_file.append(line) return new_spec_file
775
30.04
71
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/egg_info.py
from __future__ import division, absolute_import, print_function import sys from setuptools.command.egg_info import egg_info as _egg_info class egg_info(_egg_info): def run(self): if 'sdist' in sys.argv: import warnings import textwrap msg = textwrap.dedent(""" `build_src` is being run, this may lead to missing files in your sdist! You want to use distutils.sdist instead of the setuptools version: from distutils.command.sdist import sdist cmdclass={'sdist': sdist}" See numpy's setup.py or gh-7131 for details.""") warnings.warn(msg, UserWarning, stacklevel=2) # We need to ensure that build_src has been executed in order to give # setuptools' egg_info command real filenames instead of functions which # generate files. self.run_command("build_src") _egg_info.run(self)
987
34.285714
80
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/build_scripts.py
""" Modified version of build_scripts that handles building scripts from functions. """ from __future__ import division, absolute_import, print_function from distutils.command.build_scripts import build_scripts as old_build_scripts from numpy.distutils import log from numpy.distutils.misc_util import is_string class build_scripts(old_build_scripts): def generate_scripts(self, scripts): new_scripts = [] func_scripts = [] for script in scripts: if is_string(script): new_scripts.append(script) else: func_scripts.append(script) if not func_scripts: return new_scripts build_dir = self.build_dir self.mkpath(build_dir) for func in func_scripts: script = func(build_dir) if not script: continue if is_string(script): log.info(" adding '%s' to scripts" % (script,)) new_scripts.append(script) else: [log.info(" adding '%s' to scripts" % (s,)) for s in script] new_scripts.extend(list(script)) return new_scripts def run (self): if not self.scripts: return self.scripts = self.generate_scripts(self.scripts) # Now make sure that the distribution object has this list of scripts. # setuptools' develop command requires that this be a list of filenames, # not functions. self.distribution.scripts = self.scripts return old_build_scripts.run(self) def get_source_files(self): from numpy.distutils.misc_util import get_script_files return get_script_files(self.scripts)
1,731
32.307692
83
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/autodist.py
"""This module implements additional tests ala autoconf which can be useful. """ from __future__ import division, absolute_import, print_function # We put them here since they could be easily reused outside numpy.distutils def check_inline(cmd): """Return the inline identifier (may be empty).""" cmd._check_compiler() body = """ #ifndef __cplusplus static %(inline)s int static_func (void) { return 0; } %(inline)s int nostatic_func (void) { return 0; } #endif""" for kw in ['inline', '__inline__', '__inline']: st = cmd.try_compile(body % {'inline': kw}, None, None) if st: return kw return '' def check_restrict(cmd): """Return the restrict identifier (may be empty).""" cmd._check_compiler() body = """ static int static_func (char * %(restrict)s a) { return 0; } """ for kw in ['restrict', '__restrict__', '__restrict']: st = cmd.try_compile(body % {'restrict': kw}, None, None) if st: return kw return '' def check_compiler_gcc4(cmd): """Return True if the C compiler is GCC 4.x.""" cmd._check_compiler() body = """ int main() { #if (! defined __GNUC__) || (__GNUC__ < 4) #error gcc >= 4 required #endif return 0; } """ return cmd.try_compile(body, None, None) def check_gcc_function_attribute(cmd, attribute, name): """Return True if the given function attribute is supported.""" cmd._check_compiler() body = """ #pragma GCC diagnostic error "-Wattributes" #pragma clang diagnostic error "-Wattributes" int %s %s(void*); int main() { return 0; } """ % (attribute, name) return cmd.try_compile(body, None, None) != 0 def check_gcc_variable_attribute(cmd, attribute): """Return True if the given variable attribute is supported.""" cmd._check_compiler() body = """ #pragma GCC diagnostic error "-Wattributes" #pragma clang diagnostic error "-Wattributes" int %s foo; int main() { return 0; } """ % (attribute, ) return cmd.try_compile(body, None, None) != 0
2,048
20.123711
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/install_headers.py
from __future__ import division, absolute_import, print_function import os from distutils.command.install_headers import install_headers as old_install_headers class install_headers (old_install_headers): def run (self): headers = self.distribution.headers if not headers: return prefix = os.path.dirname(self.install_dir) for header in headers: if isinstance(header, tuple): # Kind of a hack, but I don't know where else to change this... if header[0] == 'numpy.core': header = ('numpy', header[1]) if os.path.splitext(header[1])[1] == '.inc': continue d = os.path.join(*([prefix]+header[0].split('.'))) header = header[1] else: d = self.install_dir self.mkpath(d) (out, _) = self.copy_file(header, d) self.outfiles.append(out)
985
34.214286
84
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/config.py
# Added Fortran compiler support to config. Currently useful only for # try_compile call. try_run works but is untested for most of Fortran # compilers (they must define linker_exe first). # Pearu Peterson from __future__ import division, absolute_import, print_function import os, signal import warnings import sys from distutils.command.config import config as old_config from distutils.command.config import LANG_EXT from distutils import log from distutils.file_util import copy_file from distutils.ccompiler import CompileError, LinkError import distutils from numpy.distutils.exec_command import exec_command from numpy.distutils.mingw32ccompiler import generate_manifest from numpy.distutils.command.autodist import (check_gcc_function_attribute, check_gcc_variable_attribute, check_inline, check_restrict, check_compiler_gcc4) from numpy.distutils.compat import get_exception LANG_EXT['f77'] = '.f' LANG_EXT['f90'] = '.f90' class config(old_config): old_config.user_options += [ ('fcompiler=', None, "specify the Fortran compiler type"), ] def initialize_options(self): self.fcompiler = None old_config.initialize_options(self) def _check_compiler (self): old_config._check_compiler(self) from numpy.distutils.fcompiler import FCompiler, new_fcompiler if sys.platform == 'win32' and (self.compiler.compiler_type in ('msvc', 'intelw', 'intelemw')): # XXX: hack to circumvent a python 2.6 bug with msvc9compiler: # initialize call query_vcvarsall, which throws an IOError, and # causes an error along the way without much information. We try to # catch it here, hoping it is early enough, and print an helpful # message instead of Error: None. if not self.compiler.initialized: try: self.compiler.initialize() except IOError: e = get_exception() msg = """\ Could not initialize compiler instance: do you have Visual Studio installed? If you are trying to build with MinGW, please use "python setup.py build -c mingw32" instead. If you have Visual Studio installed, check it is correctly installed, and the right version (VS 2008 for python 2.6, 2.7 and 3.2, VS 2010 for >= 3.3). Original exception was: %s, and the Compiler class was %s ============================================================================""" \ % (e, self.compiler.__class__.__name__) print ("""\ ============================================================================""") raise distutils.errors.DistutilsPlatformError(msg) # After MSVC is initialized, add an explicit /MANIFEST to linker # flags. See issues gh-4245 and gh-4101 for details. Also # relevant are issues 4431 and 16296 on the Python bug tracker. from distutils import msvc9compiler if msvc9compiler.get_build_version() >= 10: for ldflags in [self.compiler.ldflags_shared, self.compiler.ldflags_shared_debug]: if '/MANIFEST' not in ldflags: ldflags.append('/MANIFEST') if not isinstance(self.fcompiler, FCompiler): self.fcompiler = new_fcompiler(compiler=self.fcompiler, dry_run=self.dry_run, force=1, c_compiler=self.compiler) if self.fcompiler is not None: self.fcompiler.customize(self.distribution) if self.fcompiler.get_version(): self.fcompiler.customize_cmd(self) self.fcompiler.show_customization() def _wrap_method(self, mth, lang, args): from distutils.ccompiler import CompileError from distutils.errors import DistutilsExecError save_compiler = self.compiler if lang in ['f77', 'f90']: self.compiler = self.fcompiler try: ret = mth(*((self,)+args)) except (DistutilsExecError, CompileError): msg = str(get_exception()) self.compiler = save_compiler raise CompileError self.compiler = save_compiler return ret def _compile (self, body, headers, include_dirs, lang): return self._wrap_method(old_config._compile, lang, (body, headers, include_dirs, lang)) def _link (self, body, headers, include_dirs, libraries, library_dirs, lang): if self.compiler.compiler_type=='msvc': libraries = (libraries or [])[:] library_dirs = (library_dirs or [])[:] if lang in ['f77', 'f90']: lang = 'c' # always use system linker when using MSVC compiler if self.fcompiler: for d in self.fcompiler.library_dirs or []: # correct path when compiling in Cygwin but with # normal Win Python if d.startswith('/usr/lib'): s, o = exec_command(['cygpath', '-w', d], use_tee=False) if not s: d = o library_dirs.append(d) for libname in self.fcompiler.libraries or []: if libname not in libraries: libraries.append(libname) for libname in libraries: if libname.startswith('msvc'): continue fileexists = False for libdir in library_dirs or []: libfile = os.path.join(libdir, '%s.lib' % (libname)) if os.path.isfile(libfile): fileexists = True break if fileexists: continue # make g77-compiled static libs available to MSVC fileexists = False for libdir in library_dirs: libfile = os.path.join(libdir, 'lib%s.a' % (libname)) if os.path.isfile(libfile): # copy libname.a file to name.lib so that MSVC linker # can find it libfile2 = os.path.join(libdir, '%s.lib' % (libname)) copy_file(libfile, libfile2) self.temp_files.append(libfile2) fileexists = True break if fileexists: continue log.warn('could not find library %r in directories %s' \ % (libname, library_dirs)) elif self.compiler.compiler_type == 'mingw32': generate_manifest(self) return self._wrap_method(old_config._link, lang, (body, headers, include_dirs, libraries, library_dirs, lang)) def check_header(self, header, include_dirs=None, library_dirs=None, lang='c'): self._check_compiler() return self.try_compile( "/* we need a dummy line to make distutils happy */", [header], include_dirs) def check_decl(self, symbol, headers=None, include_dirs=None): self._check_compiler() body = """ int main(void) { #ifndef %s (void) %s; #endif ; return 0; }""" % (symbol, symbol) return self.try_compile(body, headers, include_dirs) def check_macro_true(self, symbol, headers=None, include_dirs=None): self._check_compiler() body = """ int main(void) { #if %s #else #error false or undefined macro #endif ; return 0; }""" % (symbol,) return self.try_compile(body, headers, include_dirs) def check_type(self, type_name, headers=None, include_dirs=None, library_dirs=None): """Check type availability. Return True if the type can be compiled, False otherwise""" self._check_compiler() # First check the type can be compiled body = r""" int main(void) { if ((%(name)s *) 0) return 0; if (sizeof (%(name)s)) return 0; } """ % {'name': type_name} st = False try: try: self._compile(body % {'type': type_name}, headers, include_dirs, 'c') st = True except distutils.errors.CompileError: st = False finally: self._clean() return st def check_type_size(self, type_name, headers=None, include_dirs=None, library_dirs=None, expected=None): """Check size of a given type.""" self._check_compiler() # First check the type can be compiled body = r""" typedef %(type)s npy_check_sizeof_type; int main (void) { static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) >= 0)]; test_array [0] = 0 ; return 0; } """ self._compile(body % {'type': type_name}, headers, include_dirs, 'c') self._clean() if expected: body = r""" typedef %(type)s npy_check_sizeof_type; int main (void) { static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) == %(size)s)]; test_array [0] = 0 ; return 0; } """ for size in expected: try: self._compile(body % {'type': type_name, 'size': size}, headers, include_dirs, 'c') self._clean() return size except CompileError: pass # this fails to *compile* if size > sizeof(type) body = r""" typedef %(type)s npy_check_sizeof_type; int main (void) { static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) <= %(size)s)]; test_array [0] = 0 ; return 0; } """ # The principle is simple: we first find low and high bounds of size # for the type, where low/high are looked up on a log scale. Then, we # do a binary search to find the exact size between low and high low = 0 mid = 0 while True: try: self._compile(body % {'type': type_name, 'size': mid}, headers, include_dirs, 'c') self._clean() break except CompileError: #log.info("failure to test for bound %d" % mid) low = mid + 1 mid = 2 * mid + 1 high = mid # Binary search: while low != high: mid = (high - low) // 2 + low try: self._compile(body % {'type': type_name, 'size': mid}, headers, include_dirs, 'c') self._clean() high = mid except CompileError: low = mid + 1 return low def check_func(self, func, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, call_args=None): # clean up distutils's config a bit: add void to main(), and # return a value. self._check_compiler() body = [] if decl: if type(decl) == str: body.append(decl) else: body.append("int %s (void);" % func) # Handle MSVC intrinsics: force MS compiler to make a function call. # Useful to test for some functions when built with optimization on, to # avoid build error because the intrinsic and our 'fake' test # declaration do not match. body.append("#ifdef _MSC_VER") body.append("#pragma function(%s)" % func) body.append("#endif") body.append("int main (void) {") if call: if call_args is None: call_args = '' body.append(" %s(%s);" % (func, call_args)) else: body.append(" %s;" % func) body.append(" return 0;") body.append("}") body = '\n'.join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs) def check_funcs_once(self, funcs, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, call_args=None): """Check a list of functions at once. This is useful to speed up things, since all the functions in the funcs list will be put in one compilation unit. Arguments --------- funcs : seq list of functions to test include_dirs : seq list of header paths libraries : seq list of libraries to link the code snippet to library_dirs : seq list of library paths decl : dict for every (key, value), the declaration in the value will be used for function in key. If a function is not in the dictionay, no declaration will be used. call : dict for every item (f, value), if the value is True, a call will be done to the function f. """ self._check_compiler() body = [] if decl: for f, v in decl.items(): if v: body.append("int %s (void);" % f) # Handle MS intrinsics. See check_func for more info. body.append("#ifdef _MSC_VER") for func in funcs: body.append("#pragma function(%s)" % func) body.append("#endif") body.append("int main (void) {") if call: for f in funcs: if f in call and call[f]: if not (call_args and f in call_args and call_args[f]): args = '' else: args = call_args[f] body.append(" %s(%s);" % (f, args)) else: body.append(" %s;" % f) else: for f in funcs: body.append(" %s;" % f) body.append(" return 0;") body.append("}") body = '\n'.join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs) def check_inline(self): """Return the inline keyword recognized by the compiler, empty string otherwise.""" return check_inline(self) def check_restrict(self): """Return the restrict keyword recognized by the compiler, empty string otherwise.""" return check_restrict(self) def check_compiler_gcc4(self): """Return True if the C compiler is gcc >= 4.""" return check_compiler_gcc4(self) def check_gcc_function_attribute(self, attribute, name): return check_gcc_function_attribute(self, attribute, name) def check_gcc_variable_attribute(self, attribute): return check_gcc_variable_attribute(self, attribute) def get_output(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c", use_tee=None): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Returns the exit status code of the program and its output. """ # 2008-11-16, RemoveMe warnings.warn("\n+++++++++++++++++++++++++++++++++++++++++++++++++\n" \ "Usage of get_output is deprecated: please do not \n" \ "use it anymore, and avoid configuration checks \n" \ "involving running executable on the target machine.\n" \ "+++++++++++++++++++++++++++++++++++++++++++++++++\n", DeprecationWarning, stacklevel=2) from distutils.ccompiler import CompileError, LinkError self._check_compiler() exitcode, output = 255, '' try: grabber = GrabStdout() try: src, obj, exe = self._link(body, headers, include_dirs, libraries, library_dirs, lang) grabber.restore() except Exception: output = grabber.data grabber.restore() raise exe = os.path.join('.', exe) exitstatus, output = exec_command(exe, execute_in='.', use_tee=use_tee) if hasattr(os, 'WEXITSTATUS'): exitcode = os.WEXITSTATUS(exitstatus) if os.WIFSIGNALED(exitstatus): sig = os.WTERMSIG(exitstatus) log.error('subprocess exited with signal %d' % (sig,)) if sig == signal.SIGINT: # control-C raise KeyboardInterrupt else: exitcode = exitstatus log.info("success!") except (CompileError, LinkError): log.info("failure.") self._clean() return exitcode, output class GrabStdout(object): def __init__(self): self.sys_stdout = sys.stdout self.data = '' sys.stdout = self def write (self, data): self.sys_stdout.write(data) self.data += data def flush (self): self.sys_stdout.flush() def restore(self): sys.stdout = self.sys_stdout
18,010
36.289855
108
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/__init__.py
"""distutils.command Package containing implementation of all the standard Distutils commands. """ from __future__ import division, absolute_import, print_function def test_na_writable_attributes_deletion(): a = np.NA(2) attr = ['payload', 'dtype'] for s in attr: assert_raises(AttributeError, delattr, a, s) __revision__ = "$Id: __init__.py,v 1.3 2005/05/16 11:08:49 pearu Exp $" distutils_all = [ #'build_py', 'clean', 'install_clib', 'install_scripts', 'bdist', 'bdist_dumb', 'bdist_wininst', ] __import__('distutils.command', globals(), locals(), distutils_all) __all__ = ['build', 'config_compiler', 'config', 'build_src', 'build_py', 'build_ext', 'build_clib', 'build_scripts', 'install', 'install_data', 'install_headers', 'install_lib', 'bdist_rpm', 'sdist', ] + distutils_all
1,098
23.977273
71
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/config_compiler.py
from __future__ import division, absolute_import, print_function from distutils.core import Command from numpy.distutils import log #XXX: Linker flags def show_fortran_compilers(_cache=[]): # Using cache to prevent infinite recursion if _cache: return _cache.append(1) from numpy.distutils.fcompiler import show_fcompilers import distutils.core dist = distutils.core._setup_distribution show_fcompilers(dist) class config_fc(Command): """ Distutils command to hold user specified options to Fortran compilers. config_fc command is used by the FCompiler.customize() method. """ description = "specify Fortran 77/Fortran 90 compiler information" user_options = [ ('fcompiler=', None, "specify Fortran compiler type"), ('f77exec=', None, "specify F77 compiler command"), ('f90exec=', None, "specify F90 compiler command"), ('f77flags=', None, "specify F77 compiler flags"), ('f90flags=', None, "specify F90 compiler flags"), ('opt=', None, "specify optimization flags"), ('arch=', None, "specify architecture specific optimization flags"), ('debug', 'g', "compile with debugging information"), ('noopt', None, "compile without optimization"), ('noarch', None, "compile without arch-dependent optimization"), ] help_options = [ ('help-fcompiler', None, "list available Fortran compilers", show_fortran_compilers), ] boolean_options = ['debug', 'noopt', 'noarch'] def initialize_options(self): self.fcompiler = None self.f77exec = None self.f90exec = None self.f77flags = None self.f90flags = None self.opt = None self.arch = None self.debug = None self.noopt = None self.noarch = None def finalize_options(self): log.info('unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options') build_clib = self.get_finalized_command('build_clib') build_ext = self.get_finalized_command('build_ext') config = self.get_finalized_command('config') build = self.get_finalized_command('build') cmd_list = [self, config, build_clib, build_ext, build] for a in ['fcompiler']: l = [] for c in cmd_list: v = getattr(c, a) if v is not None: if not isinstance(v, str): v = v.compiler_type if v not in l: l.append(v) if not l: v1 = None else: v1 = l[0] if len(l)>1: log.warn(' commands have different --%s options: %s'\ ', using first in list as default' % (a, l)) if v1: for c in cmd_list: if getattr(c, a) is None: setattr(c, a, v1) def run(self): # Do nothing. return class config_cc(Command): """ Distutils command to hold user specified options to C/C++ compilers. """ description = "specify C/C++ compiler information" user_options = [ ('compiler=', None, "specify C/C++ compiler type"), ] def initialize_options(self): self.compiler = None def finalize_options(self): log.info('unifing config_cc, config, build_clib, build_ext, build commands --compiler options') build_clib = self.get_finalized_command('build_clib') build_ext = self.get_finalized_command('build_ext') config = self.get_finalized_command('config') build = self.get_finalized_command('build') cmd_list = [self, config, build_clib, build_ext, build] for a in ['compiler']: l = [] for c in cmd_list: v = getattr(c, a) if v is not None: if not isinstance(v, str): v = v.compiler_type if v not in l: l.append(v) if not l: v1 = None else: v1 = l[0] if len(l)>1: log.warn(' commands have different --%s options: %s'\ ', using first in list as default' % (a, l)) if v1: for c in cmd_list: if getattr(c, a) is None: setattr(c, a, v1) return def run(self): # Do nothing. return
4,379
33.761905
104
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/build_py.py
from __future__ import division, absolute_import, print_function from distutils.command.build_py import build_py as old_build_py from numpy.distutils.misc_util import is_string class build_py(old_build_py): def run(self): build_src = self.get_finalized_command('build_src') if build_src.py_modules_dict and self.packages is None: self.packages = list(build_src.py_modules_dict.keys ()) old_build_py.run(self) def find_package_modules(self, package, package_dir): modules = old_build_py.find_package_modules(self, package, package_dir) # Find build_src generated *.py files. build_src = self.get_finalized_command('build_src') modules += build_src.py_modules_dict.get(package, []) return modules def find_modules(self): old_py_modules = self.py_modules[:] new_py_modules = [_m for _m in self.py_modules if is_string(_m)] self.py_modules[:] = new_py_modules modules = old_build_py.find_modules(self) self.py_modules[:] = old_py_modules return modules # XXX: Fix find_source_files for item in py_modules such that item is 3-tuple # and item[2] is source file.
1,210
34.617647
81
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/install_clib.py
from __future__ import division, absolute_import, print_function import os from distutils.core import Command from distutils.ccompiler import new_compiler from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): build_clib_cmd = get_cmd("build_clib") build_dir = build_clib_cmd.build_clib # We need the compiler to get the library name -> filename association if not build_clib_cmd.compiler: compiler = new_compiler(compiler=None) compiler.customize(self.distribution) else: compiler = build_clib_cmd.compiler for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles
1,315
31.9
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/command/build.py
from __future__ import division, absolute_import, print_function import os import sys from distutils.command.build import build as old_build from distutils.util import get_platform from numpy.distutils.command.config_compiler import show_fortran_compilers class build(old_build): sub_commands = [('config_cc', lambda *args: True), ('config_fc', lambda *args: True), ('build_src', old_build.has_ext_modules), ] + old_build.sub_commands user_options = old_build.user_options + [ ('fcompiler=', None, "specify the Fortran compiler type"), ('parallel=', 'j', "number of parallel jobs"), ] help_options = old_build.help_options + [ ('help-fcompiler', None, "list available Fortran compilers", show_fortran_compilers), ] def initialize_options(self): old_build.initialize_options(self) self.fcompiler = None self.parallel = None def finalize_options(self): if self.parallel: try: self.parallel = int(self.parallel) except ValueError: raise ValueError("--parallel/-j argument must be an integer") build_scripts = self.build_scripts old_build.finalize_options(self) plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3]) if build_scripts is None: self.build_scripts = os.path.join(self.build_base, 'scripts' + plat_specifier) def run(self): old_build.run(self)
1,618
32.729167
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/tests/test_fcompiler_intel.py
from __future__ import division, absolute_import, print_function import numpy.distutils.fcompiler from numpy.testing import run_module_suite, assert_ intel_32bit_version_strings = [ ("Intel(R) Fortran Intel(R) 32-bit Compiler Professional for applications" "running on Intel(R) 32, Version 11.1", '11.1'), ] intel_64bit_version_strings = [ ("Intel(R) Fortran IA-64 Compiler Professional for applications" "running on IA-64, Version 11.0", '11.0'), ("Intel(R) Fortran Intel(R) 64 Compiler Professional for applications" "running on Intel(R) 64, Version 11.1", '11.1') ] class TestIntelFCompilerVersions(object): def test_32bit_version(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='intel') for vs, version in intel_32bit_version_strings: v = fc.version_match(vs) assert_(v == version) class TestIntelEM64TFCompilerVersions(object): def test_64bit_version(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='intelem') for vs, version in intel_64bit_version_strings: v = fc.version_match(vs) assert_(v == version) if __name__ == '__main__': run_module_suite()
1,210
31.72973
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/tests/test_exec_command.py
from __future__ import division, absolute_import, print_function import os import sys from tempfile import TemporaryFile from numpy.distutils import exec_command from numpy.distutils.exec_command import get_pythonexe from numpy.testing import run_module_suite, tempdir, assert_ # In python 3 stdout, stderr are text (unicode compliant) devices, so to # emulate them import StringIO from the io module. if sys.version_info[0] >= 3: from io import StringIO else: from StringIO import StringIO class redirect_stdout(object): """Context manager to redirect stdout for exec_command test.""" def __init__(self, stdout=None): self._stdout = stdout or sys.stdout def __enter__(self): self.old_stdout = sys.stdout sys.stdout = self._stdout def __exit__(self, exc_type, exc_value, traceback): self._stdout.flush() sys.stdout = self.old_stdout # note: closing sys.stdout won't close it. self._stdout.close() class redirect_stderr(object): """Context manager to redirect stderr for exec_command test.""" def __init__(self, stderr=None): self._stderr = stderr or sys.stderr def __enter__(self): self.old_stderr = sys.stderr sys.stderr = self._stderr def __exit__(self, exc_type, exc_value, traceback): self._stderr.flush() sys.stderr = self.old_stderr # note: closing sys.stderr won't close it. self._stderr.close() class emulate_nonposix(object): """Context manager to emulate os.name != 'posix' """ def __init__(self, osname='non-posix'): self._new_name = osname def __enter__(self): self._old_name = os.name os.name = self._new_name def __exit__(self, exc_type, exc_value, traceback): os.name = self._old_name def test_exec_command_stdout(): # Regression test for gh-2999 and gh-2915. # There are several packages (nose, scipy.weave.inline, Sage inline # Fortran) that replace stdout, in which case it doesn't have a fileno # method. This is tested here, with a do-nothing command that fails if the # presence of fileno() is assumed in exec_command. # The code has a special case for posix systems, so if we are on posix test # both that the special case works and that the generic code works. # Test posix version: with redirect_stdout(StringIO()): with redirect_stderr(TemporaryFile()): exec_command.exec_command("cd '.'") if os.name == 'posix': # Test general (non-posix) version: with emulate_nonposix(): with redirect_stdout(StringIO()): with redirect_stderr(TemporaryFile()): exec_command.exec_command("cd '.'") def test_exec_command_stderr(): # Test posix version: with redirect_stdout(TemporaryFile(mode='w+')): with redirect_stderr(StringIO()): exec_command.exec_command("cd '.'") if os.name == 'posix': # Test general (non-posix) version: with emulate_nonposix(): with redirect_stdout(TemporaryFile()): with redirect_stderr(StringIO()): exec_command.exec_command("cd '.'") class TestExecCommand(object): def setup(self): self.pyexe = get_pythonexe() def check_nt(self, **kws): s, o = exec_command.exec_command('cmd /C echo path=%path%') assert_(s == 0) assert_(o != '') s, o = exec_command.exec_command( '"%s" -c "import sys;sys.stderr.write(sys.platform)"' % self.pyexe) assert_(s == 0) assert_(o == 'win32') def check_posix(self, **kws): s, o = exec_command.exec_command("echo Hello", **kws) assert_(s == 0) assert_(o == 'Hello') s, o = exec_command.exec_command('echo $AAA', **kws) assert_(s == 0) assert_(o == '') s, o = exec_command.exec_command('echo "$AAA"', AAA='Tere', **kws) assert_(s == 0) assert_(o == 'Tere') s, o = exec_command.exec_command('echo "$AAA"', **kws) assert_(s == 0) assert_(o == '') if 'BBB' not in os.environ: os.environ['BBB'] = 'Hi' s, o = exec_command.exec_command('echo "$BBB"', **kws) assert_(s == 0) assert_(o == 'Hi') s, o = exec_command.exec_command('echo "$BBB"', BBB='Hey', **kws) assert_(s == 0) assert_(o == 'Hey') s, o = exec_command.exec_command('echo "$BBB"', **kws) assert_(s == 0) assert_(o == 'Hi') del os.environ['BBB'] s, o = exec_command.exec_command('echo "$BBB"', **kws) assert_(s == 0) assert_(o == '') s, o = exec_command.exec_command('this_is_not_a_command', **kws) assert_(s != 0) assert_(o != '') s, o = exec_command.exec_command('echo path=$PATH', **kws) assert_(s == 0) assert_(o != '') s, o = exec_command.exec_command( '"%s" -c "import sys,os;sys.stderr.write(os.name)"' % self.pyexe, **kws) assert_(s == 0) assert_(o == 'posix') def check_basic(self, *kws): s, o = exec_command.exec_command( '"%s" -c "raise \'Ignore me.\'"' % self.pyexe, **kws) assert_(s != 0) assert_(o != '') s, o = exec_command.exec_command( '"%s" -c "import sys;sys.stderr.write(\'0\');' 'sys.stderr.write(\'1\');sys.stderr.write(\'2\')"' % self.pyexe, **kws) assert_(s == 0) assert_(o == '012') s, o = exec_command.exec_command( '"%s" -c "import sys;sys.exit(15)"' % self.pyexe, **kws) assert_(s == 15) assert_(o == '') s, o = exec_command.exec_command( '"%s" -c "print(\'Heipa\'")' % self.pyexe, **kws) assert_(s == 0) assert_(o == 'Heipa') def check_execute_in(self, **kws): with tempdir() as tmpdir: fn = "file" tmpfile = os.path.join(tmpdir, fn) f = open(tmpfile, 'w') f.write('Hello') f.close() s, o = exec_command.exec_command( '"%s" -c "f = open(\'%s\', \'r\'); f.close()"' % (self.pyexe, fn), **kws) assert_(s != 0) assert_(o != '') s, o = exec_command.exec_command( '"%s" -c "f = open(\'%s\', \'r\'); print(f.read()); ' 'f.close()"' % (self.pyexe, fn), execute_in=tmpdir, **kws) assert_(s == 0) assert_(o == 'Hello') def test_basic(self): with redirect_stdout(StringIO()): with redirect_stderr(StringIO()): if os.name == "posix": self.check_posix(use_tee=0) self.check_posix(use_tee=1) elif os.name == "nt": self.check_nt(use_tee=0) self.check_nt(use_tee=1) self.check_execute_in(use_tee=0) self.check_execute_in(use_tee=1) if __name__ == "__main__": run_module_suite()
7,216
31.804545
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/tests/test_npy_pkg_config.py
from __future__ import division, absolute_import, print_function import os from numpy.distutils.npy_pkg_config import read_config, parse_flags from numpy.testing import run_module_suite, temppath, assert_ simple = """\ [meta] Name = foo Description = foo lib Version = 0.1 [default] cflags = -I/usr/include libs = -L/usr/lib """ simple_d = {'cflags': '-I/usr/include', 'libflags': '-L/usr/lib', 'version': '0.1', 'name': 'foo'} simple_variable = """\ [meta] Name = foo Description = foo lib Version = 0.1 [variables] prefix = /foo/bar libdir = ${prefix}/lib includedir = ${prefix}/include [default] cflags = -I${includedir} libs = -L${libdir} """ simple_variable_d = {'cflags': '-I/foo/bar/include', 'libflags': '-L/foo/bar/lib', 'version': '0.1', 'name': 'foo'} class TestLibraryInfo(object): def test_simple(self): with temppath('foo.ini') as path: with open(path, 'w') as f: f.write(simple) pkg = os.path.splitext(path)[0] out = read_config(pkg) assert_(out.cflags() == simple_d['cflags']) assert_(out.libs() == simple_d['libflags']) assert_(out.name == simple_d['name']) assert_(out.version == simple_d['version']) def test_simple_variable(self): with temppath('foo.ini') as path: with open(path, 'w') as f: f.write(simple_variable) pkg = os.path.splitext(path)[0] out = read_config(pkg) assert_(out.cflags() == simple_variable_d['cflags']) assert_(out.libs() == simple_variable_d['libflags']) assert_(out.name == simple_variable_d['name']) assert_(out.version == simple_variable_d['version']) out.vars['prefix'] = '/Users/david' assert_(out.cflags() == '-I/Users/david/include') class TestParseFlags(object): def test_simple_cflags(self): d = parse_flags("-I/usr/include") assert_(d['include_dirs'] == ['/usr/include']) d = parse_flags("-I/usr/include -DFOO") assert_(d['include_dirs'] == ['/usr/include']) assert_(d['macros'] == ['FOO']) d = parse_flags("-I /usr/include -DFOO") assert_(d['include_dirs'] == ['/usr/include']) assert_(d['macros'] == ['FOO']) def test_simple_lflags(self): d = parse_flags("-L/usr/lib -lfoo -L/usr/lib -lbar") assert_(d['library_dirs'] == ['/usr/lib', '/usr/lib']) assert_(d['libraries'] == ['foo', 'bar']) d = parse_flags("-L /usr/lib -lfoo -L/usr/lib -lbar") assert_(d['library_dirs'] == ['/usr/lib', '/usr/lib']) assert_(d['libraries'] == ['foo', 'bar']) if __name__ == '__main__': run_module_suite()
2,709
28.78022
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/tests/test_fcompiler_nagfor.py
from __future__ import division, absolute_import, print_function from numpy.testing import assert_, run_module_suite import numpy.distutils.fcompiler nag_version_strings = [('nagfor', 'NAG Fortran Compiler Release ' '6.2(Chiyoda) Build 6200', '6.2'), ('nagfor', 'NAG Fortran Compiler Release ' '6.1(Tozai) Build 6136', '6.1'), ('nagfor', 'NAG Fortran Compiler Release ' '6.0(Hibiya) Build 1021', '6.0'), ('nagfor', 'NAG Fortran Compiler Release ' '5.3.2(971)', '5.3.2'), ('nag', 'NAGWare Fortran 95 compiler Release 5.1' '(347,355-367,375,380-383,389,394,399,401-402,407,' '431,435,437,446,459-460,463,472,494,496,503,508,' '511,517,529,555,557,565)', '5.1')] class TestNagFCompilerVersions(object): def test_version_match(self): for comp, vs, version in nag_version_strings: fc = numpy.distutils.fcompiler.new_fcompiler(compiler=comp) v = fc.version_match(vs) assert_(v == version) if __name__ == '__main__': run_module_suite()
1,247
40.6
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/tests/__init__.py
0
0
0
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/tests/test_fcompiler_gnu.py
from __future__ import division, absolute_import, print_function from numpy.testing import assert_, run_module_suite import numpy.distutils.fcompiler g77_version_strings = [ ('GNU Fortran 0.5.25 20010319 (prerelease)', '0.5.25'), ('GNU Fortran (GCC 3.2) 3.2 20020814 (release)', '3.2'), ('GNU Fortran (GCC) 3.3.3 20040110 (prerelease) (Debian)', '3.3.3'), ('GNU Fortran (GCC) 3.3.3 (Debian 20040401)', '3.3.3'), ('GNU Fortran (GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)) 3.2.2' ' 20030222 (Red Hat Linux 3.2.2-5)', '3.2.2'), ] gfortran_version_strings = [ ('GNU Fortran 95 (GCC 4.0.3 20051023 (prerelease) (Debian 4.0.2-3))', '4.0.3'), ('GNU Fortran 95 (GCC) 4.1.0', '4.1.0'), ('GNU Fortran 95 (GCC) 4.2.0 20060218 (experimental)', '4.2.0'), ('GNU Fortran (GCC) 4.3.0 20070316 (experimental)', '4.3.0'), ('GNU Fortran (rubenvb-4.8.0) 4.8.0', '4.8.0'), ('4.8.0', '4.8.0'), ('4.0.3-7', '4.0.3'), ("gfortran: warning: couldn't understand kern.osversion '14.1.0\n4.9.1", '4.9.1'), ("gfortran: warning: couldn't understand kern.osversion '14.1.0\n" "gfortran: warning: yet another warning\n4.9.1", '4.9.1'), ('GNU Fortran (crosstool-NG 8a21ab48) 7.2.0', '7.2.0') ] class TestG77Versions(object): def test_g77_version(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu') for vs, version in g77_version_strings: v = fc.version_match(vs) assert_(v == version, (vs, v)) def test_not_g77(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu') for vs, _ in gfortran_version_strings: v = fc.version_match(vs) assert_(v is None, (vs, v)) class TestGFortranVersions(object): def test_gfortran_version(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu95') for vs, version in gfortran_version_strings: v = fc.version_match(vs) assert_(v == version, (vs, v)) def test_not_gfortran(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu95') for vs, _ in g77_version_strings: v = fc.version_match(vs) assert_(v is None, (vs, v)) if __name__ == '__main__': run_module_suite()
2,288
35.919355
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/tests/test_misc_util.py
from __future__ import division, absolute_import, print_function from os.path import join, sep, dirname from numpy.distutils.misc_util import ( appendpath, minrelpath, gpaths, get_shared_lib_extension, get_info ) from numpy.testing import ( run_module_suite, assert_, assert_equal ) ajoin = lambda *paths: join(*((sep,)+paths)) class TestAppendpath(object): def test_1(self): assert_equal(appendpath('prefix', 'name'), join('prefix', 'name')) assert_equal(appendpath('/prefix', 'name'), ajoin('prefix', 'name')) assert_equal(appendpath('/prefix', '/name'), ajoin('prefix', 'name')) assert_equal(appendpath('prefix', '/name'), join('prefix', 'name')) def test_2(self): assert_equal(appendpath('prefix/sub', 'name'), join('prefix', 'sub', 'name')) assert_equal(appendpath('prefix/sub', 'sup/name'), join('prefix', 'sub', 'sup', 'name')) assert_equal(appendpath('/prefix/sub', '/prefix/name'), ajoin('prefix', 'sub', 'name')) def test_3(self): assert_equal(appendpath('/prefix/sub', '/prefix/sup/name'), ajoin('prefix', 'sub', 'sup', 'name')) assert_equal(appendpath('/prefix/sub/sub2', '/prefix/sup/sup2/name'), ajoin('prefix', 'sub', 'sub2', 'sup', 'sup2', 'name')) assert_equal(appendpath('/prefix/sub/sub2', '/prefix/sub/sup/name'), ajoin('prefix', 'sub', 'sub2', 'sup', 'name')) class TestMinrelpath(object): def test_1(self): n = lambda path: path.replace('/', sep) assert_equal(minrelpath(n('aa/bb')), n('aa/bb')) assert_equal(minrelpath('..'), '..') assert_equal(minrelpath(n('aa/..')), '') assert_equal(minrelpath(n('aa/../bb')), 'bb') assert_equal(minrelpath(n('aa/bb/..')), 'aa') assert_equal(minrelpath(n('aa/bb/../..')), '') assert_equal(minrelpath(n('aa/bb/../cc/../dd')), n('aa/dd')) assert_equal(minrelpath(n('.././..')), n('../..')) assert_equal(minrelpath(n('aa/bb/.././../dd')), n('dd')) class TestGpaths(object): def test_gpaths(self): local_path = minrelpath(join(dirname(__file__), '..')) ls = gpaths('command/*.py', local_path) assert_(join(local_path, 'command', 'build_src.py') in ls, repr(ls)) f = gpaths('system_info.py', local_path) assert_(join(local_path, 'system_info.py') == f[0], repr(f)) class TestSharedExtension(object): def test_get_shared_lib_extension(self): import sys ext = get_shared_lib_extension(is_python_ext=False) if sys.platform.startswith('linux'): assert_equal(ext, '.so') elif sys.platform.startswith('gnukfreebsd'): assert_equal(ext, '.so') elif sys.platform.startswith('darwin'): assert_equal(ext, '.dylib') elif sys.platform.startswith('win'): assert_equal(ext, '.dll') # just check for no crash assert_(get_shared_lib_extension(is_python_ext=True)) def test_installed_npymath_ini(): # Regression test for gh-7707. If npymath.ini wasn't installed, then this # will give an error. info = get_info('npymath') if __name__ == "__main__": run_module_suite()
3,308
37.476744
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/tests/test_system_info.py
from __future__ import division, print_function import os import shutil from tempfile import mkstemp, mkdtemp from subprocess import Popen, PIPE from distutils.errors import DistutilsError from numpy.distutils import ccompiler, customized_ccompiler from numpy.testing import ( run_module_suite, assert_, assert_equal, dec ) from numpy.distutils.system_info import system_info, ConfigParser from numpy.distutils.system_info import default_lib_dirs, default_include_dirs def get_class(name, notfound_action=1): """ notfound_action: 0 - do nothing 1 - display warning message 2 - raise error """ cl = {'temp1': Temp1Info, 'temp2': Temp2Info }.get(name.lower(), _system_info) return cl() simple_site = """ [ALL] library_dirs = {dir1:s}{pathsep:s}{dir2:s} libraries = {lib1:s},{lib2:s} extra_compile_args = -I/fake/directory runtime_library_dirs = {dir1:s} [temp1] library_dirs = {dir1:s} libraries = {lib1:s} runtime_library_dirs = {dir1:s} [temp2] library_dirs = {dir2:s} libraries = {lib2:s} extra_link_args = -Wl,-rpath={lib2:s} rpath = {dir2:s} """ site_cfg = simple_site fakelib_c_text = """ /* This file is generated from numpy/distutils/testing/test_system_info.py */ #include<stdio.h> void foo(void) { printf("Hello foo"); } void bar(void) { printf("Hello bar"); } """ def have_compiler(): """ Return True if there appears to be an executable compiler """ compiler = customized_ccompiler() try: cmd = compiler.compiler # Unix compilers except AttributeError: try: if not compiler.initialized: compiler.initialize() # MSVC is different except (DistutilsError, ValueError): return False cmd = [compiler.cc] try: p = Popen(cmd, stdout=PIPE, stderr=PIPE) p.stdout.close() p.stderr.close() p.wait() except OSError: return False return True HAVE_COMPILER = have_compiler() class _system_info(system_info): def __init__(self, default_lib_dirs=default_lib_dirs, default_include_dirs=default_include_dirs, verbosity=1, ): self.__class__.info = {} self.local_prefixes = [] defaults = {'library_dirs': '', 'include_dirs': '', 'runtime_library_dirs': '', 'rpath': '', 'src_dirs': '', 'search_static_first': "0", 'extra_compile_args': '', 'extra_link_args': ''} self.cp = ConfigParser(defaults) # We have to parse the config files afterwards # to have a consistent temporary filepath def _check_libs(self, lib_dirs, libs, opt_libs, exts): """Override _check_libs to return with all dirs """ info = {'libraries': libs, 'library_dirs': lib_dirs} return info class Temp1Info(_system_info): """For testing purposes""" section = 'temp1' class Temp2Info(_system_info): """For testing purposes""" section = 'temp2' class TestSystemInfoReading(object): def setup(self): """ Create the libraries """ # Create 2 sources and 2 libraries self._dir1 = mkdtemp() self._src1 = os.path.join(self._dir1, 'foo.c') self._lib1 = os.path.join(self._dir1, 'libfoo.so') self._dir2 = mkdtemp() self._src2 = os.path.join(self._dir2, 'bar.c') self._lib2 = os.path.join(self._dir2, 'libbar.so') # Update local site.cfg global simple_site, site_cfg site_cfg = simple_site.format(**{ 'dir1': self._dir1, 'lib1': self._lib1, 'dir2': self._dir2, 'lib2': self._lib2, 'pathsep': os.pathsep }) # Write site.cfg fd, self._sitecfg = mkstemp() os.close(fd) with open(self._sitecfg, 'w') as fd: fd.write(site_cfg) # Write the sources with open(self._src1, 'w') as fd: fd.write(fakelib_c_text) with open(self._src2, 'w') as fd: fd.write(fakelib_c_text) # We create all class-instances def site_and_parse(c, site_cfg): c.files = [site_cfg] c.parse_config_files() return c self.c_default = site_and_parse(get_class('default'), self._sitecfg) self.c_temp1 = site_and_parse(get_class('temp1'), self._sitecfg) self.c_temp2 = site_and_parse(get_class('temp2'), self._sitecfg) def tearDown(self): # Do each removal separately try: shutil.rmtree(self._dir1) except Exception: pass try: shutil.rmtree(self._dir2) except Exception: pass try: os.remove(self._sitecfg) except Exception: pass def test_all(self): # Read in all information in the ALL block tsi = self.c_default assert_equal(tsi.get_lib_dirs(), [self._dir1, self._dir2]) assert_equal(tsi.get_libraries(), [self._lib1, self._lib2]) assert_equal(tsi.get_runtime_lib_dirs(), [self._dir1]) extra = tsi.calc_extra_info() assert_equal(extra['extra_compile_args'], ['-I/fake/directory']) def test_temp1(self): # Read in all information in the temp1 block tsi = self.c_temp1 assert_equal(tsi.get_lib_dirs(), [self._dir1]) assert_equal(tsi.get_libraries(), [self._lib1]) assert_equal(tsi.get_runtime_lib_dirs(), [self._dir1]) def test_temp2(self): # Read in all information in the temp2 block tsi = self.c_temp2 assert_equal(tsi.get_lib_dirs(), [self._dir2]) assert_equal(tsi.get_libraries(), [self._lib2]) # Now from rpath and not runtime_library_dirs assert_equal(tsi.get_runtime_lib_dirs(key='rpath'), [self._dir2]) extra = tsi.calc_extra_info() assert_equal(extra['extra_link_args'], ['-Wl,-rpath=' + self._lib2]) @dec.skipif(not HAVE_COMPILER) def test_compile1(self): # Compile source and link the first source c = customized_ccompiler() previousDir = os.getcwd() try: # Change directory to not screw up directories os.chdir(self._dir1) c.compile([os.path.basename(self._src1)], output_dir=self._dir1) # Ensure that the object exists assert_(os.path.isfile(self._src1.replace('.c', '.o')) or os.path.isfile(self._src1.replace('.c', '.obj'))) finally: os.chdir(previousDir) @dec.skipif(not HAVE_COMPILER) @dec.skipif('msvc' in repr(ccompiler.new_compiler())) def test_compile2(self): # Compile source and link the second source tsi = self.c_temp2 c = customized_ccompiler() extra_link_args = tsi.calc_extra_info()['extra_link_args'] previousDir = os.getcwd() try: # Change directory to not screw up directories os.chdir(self._dir2) c.compile([os.path.basename(self._src2)], output_dir=self._dir2, extra_postargs=extra_link_args) # Ensure that the object exists assert_(os.path.isfile(self._src2.replace('.c', '.o'))) finally: os.chdir(previousDir) if __name__ == '__main__': run_module_suite()
7,485
30.191667
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/mips.py
from __future__ import division, absolute_import, print_function from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler compilers = ['MIPSFCompiler'] class MIPSFCompiler(FCompiler): compiler_type = 'mips' description = 'MIPSpro Fortran Compiler' version_pattern = r'MIPSpro Compilers: Version (?P<version>[^\s*,]*)' executables = { 'version_cmd' : ["<F90>", "-version"], 'compiler_f77' : ["f77", "-f77"], 'compiler_fix' : ["f90", "-fixedform"], 'compiler_f90' : ["f90"], 'linker_so' : ["f90", "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : None } module_dir_switch = None #XXX: fix me module_include_switch = None #XXX: fix me pic_flags = ['-KPIC'] def get_flags(self): return self.pic_flags + ['-n32'] def get_flags_opt(self): return ['-O3'] def get_flags_arch(self): opt = [] for a in '19 20 21 22_4k 22_5k 24 25 26 27 28 30 32_5k 32_10k'.split(): if getattr(cpu, 'is_IP%s'%a)(): opt.append('-TARG:platform=IP%s' % a) break return opt def get_flags_arch_f77(self): r = None if cpu.is_r10000(): r = 10000 elif cpu.is_r12000(): r = 12000 elif cpu.is_r8000(): r = 8000 elif cpu.is_r5000(): r = 5000 elif cpu.is_r4000(): r = 4000 if r is not None: return ['r%s' % (r)] return [] def get_flags_arch_f90(self): r = self.get_flags_arch_f77() if r: r[0] = '-' + r[0] return r if __name__ == '__main__': from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='mips').get_version())
1,780
30.245614
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/g95.py
# http://g95.sourceforge.net/ from __future__ import division, absolute_import, print_function from numpy.distutils.fcompiler import FCompiler compilers = ['G95FCompiler'] class G95FCompiler(FCompiler): compiler_type = 'g95' description = 'G95 Fortran Compiler' # version_pattern = r'G95 \((GCC (?P<gccversion>[\d.]+)|.*?) \(g95!\) (?P<version>.*)\).*' # $ g95 --version # G95 (GCC 4.0.3 (g95!) May 22 2006) version_pattern = r'G95 \((GCC (?P<gccversion>[\d.]+)|.*?) \(g95 (?P<version>.*)!\) (?P<date>.*)\).*' # $ g95 --version # G95 (GCC 4.0.3 (g95 0.90!) Aug 22 2006) executables = { 'version_cmd' : ["<F90>", "--version"], 'compiler_f77' : ["g95", "-ffixed-form"], 'compiler_fix' : ["g95", "-ffixed-form"], 'compiler_f90' : ["g95"], 'linker_so' : ["<F90>", "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } pic_flags = ['-fpic'] module_dir_switch = '-fmod=' module_include_switch = '-I' def get_flags(self): return ['-fno-second-underscore'] def get_flags_opt(self): return ['-O'] def get_flags_debug(self): return ['-g'] if __name__ == '__main__': from distutils import log from numpy.distutils import customized_fcompiler log.set_verbosity(2) print(customized_fcompiler('g95').get_version())
1,396
30.044444
105
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/compaq.py
#http://www.compaq.com/fortran/docs/ from __future__ import division, absolute_import, print_function import os import sys from numpy.distutils.fcompiler import FCompiler from numpy.distutils.compat import get_exception from distutils.errors import DistutilsPlatformError compilers = ['CompaqFCompiler'] if os.name != 'posix' or sys.platform[:6] == 'cygwin' : # Otherwise we'd get a false positive on posix systems with # case-insensitive filesystems (like darwin), because we'll pick # up /bin/df compilers.append('CompaqVisualFCompiler') class CompaqFCompiler(FCompiler): compiler_type = 'compaq' description = 'Compaq Fortran Compiler' version_pattern = r'Compaq Fortran (?P<version>[^\s]*).*' if sys.platform[:5]=='linux': fc_exe = 'fort' else: fc_exe = 'f90' executables = { 'version_cmd' : ['<F90>', "-version"], 'compiler_f77' : [fc_exe, "-f77rtl", "-fixed"], 'compiler_fix' : [fc_exe, "-fixed"], 'compiler_f90' : [fc_exe], 'linker_so' : ['<F90>'], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } module_dir_switch = '-module ' # not tested module_include_switch = '-I' def get_flags(self): return ['-assume no2underscore', '-nomixed_str_len_arg'] def get_flags_debug(self): return ['-g', '-check bounds'] def get_flags_opt(self): return ['-O4', '-align dcommons', '-assume bigarrays', '-assume nozsize', '-math_library fast'] def get_flags_arch(self): return ['-arch host', '-tune host'] def get_flags_linker_so(self): if sys.platform[:5]=='linux': return ['-shared'] return ['-shared', '-Wl,-expect_unresolved,*'] class CompaqVisualFCompiler(FCompiler): compiler_type = 'compaqv' description = 'DIGITAL or Compaq Visual Fortran Compiler' version_pattern = (r'(DIGITAL|Compaq) Visual Fortran Optimizing Compiler' r' Version (?P<version>[^\s]*).*') compile_switch = '/compile_only' object_switch = '/object:' library_switch = '/OUT:' #No space after /OUT:! static_lib_extension = ".lib" static_lib_format = "%s%s" module_dir_switch = '/module:' module_include_switch = '/I' ar_exe = 'lib.exe' fc_exe = 'DF' if sys.platform=='win32': from numpy.distutils.msvccompiler import MSVCCompiler try: m = MSVCCompiler() m.initialize() ar_exe = m.lib except DistutilsPlatformError: pass except AttributeError: msg = get_exception() if '_MSVCCompiler__root' in str(msg): print('Ignoring "%s" (I think it is msvccompiler.py bug)' % (msg)) else: raise except IOError: e = get_exception() if not "vcvarsall.bat" in str(e): print("Unexpected IOError in", __file__) raise e except ValueError: e = get_exception() if not "path']" in str(e): print("Unexpected ValueError in", __file__) raise e executables = { 'version_cmd' : ['<F90>', "/what"], 'compiler_f77' : [fc_exe, "/f77rtl", "/fixed"], 'compiler_fix' : [fc_exe, "/fixed"], 'compiler_f90' : [fc_exe], 'linker_so' : ['<F90>'], 'archiver' : [ar_exe, "/OUT:"], 'ranlib' : None } def get_flags(self): return ['/nologo', '/MD', '/WX', '/iface=(cref,nomixed_str_len_arg)', '/names:lowercase', '/assume:underscore'] def get_flags_opt(self): return ['/Ox', '/fast', '/optimize:5', '/unroll:0', '/math_library:fast'] def get_flags_arch(self): return ['/threads'] def get_flags_debug(self): return ['/debug'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='compaq').get_version())
4,109
31.362205
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/gnu.py
from __future__ import division, absolute_import, print_function import re import os import sys import warnings import platform import tempfile import hashlib import base64 from subprocess import Popen, PIPE, STDOUT from copy import copy from numpy.distutils.fcompiler import FCompiler from numpy.distutils.exec_command import exec_command from numpy.distutils.compat import get_exception from numpy.distutils.system_info import system_info compilers = ['GnuFCompiler', 'Gnu95FCompiler'] TARGET_R = re.compile(r"Target: ([a-zA-Z0-9_\-]*)") # XXX: handle cross compilation def is_win64(): return sys.platform == "win32" and platform.architecture()[0] == "64bit" if is_win64(): #_EXTRAFLAGS = ["-fno-leading-underscore"] _EXTRAFLAGS = [] else: _EXTRAFLAGS = [] class GnuFCompiler(FCompiler): compiler_type = 'gnu' compiler_aliases = ('g77', ) description = 'GNU Fortran 77 compiler' def gnu_version_match(self, version_string): """Handle the different versions of GNU fortran compilers""" # Strip warning(s) that may be emitted by gfortran while version_string.startswith('gfortran: warning'): version_string = version_string[version_string.find('\n') + 1:] # Gfortran versions from after 2010 will output a simple string # (usually "x.y", "x.y.z" or "x.y.z-q") for ``-dumpversion``; older # gfortrans may still return long version strings (``-dumpversion`` was # an alias for ``--version``) if len(version_string) <= 20: # Try to find a valid version string m = re.search(r'([0-9.]+)', version_string) if m: # g77 provides a longer version string that starts with GNU # Fortran if version_string.startswith('GNU Fortran'): return ('g77', m.group(1)) # gfortran only outputs a version string such as #.#.#, so check # if the match is at the start of the string elif m.start() == 0: return ('gfortran', m.group(1)) else: # Output probably from --version, try harder: m = re.search(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string) if m: return ('gfortran', m.group(1)) m = re.search( r'GNU Fortran.*?\-?([0-9-.]+\.[0-9-.]+)', version_string) if m: v = m.group(1) if v.startswith('0') or v.startswith('2') or v.startswith('3'): # the '0' is for early g77's return ('g77', v) else: # at some point in the 4.x series, the ' 95' was dropped # from the version string return ('gfortran', v) # If still nothing, raise an error to make the problem easy to find. err = 'A valid Fortran version was not found in this string:\n' raise ValueError(err + version_string) def version_match(self, version_string): v = self.gnu_version_match(version_string) if not v or v[0] != 'g77': return None return v[1] possible_executables = ['g77', 'f77'] executables = { 'version_cmd' : [None, "-dumpversion"], 'compiler_f77' : [None, "-g", "-Wall", "-fno-second-underscore"], 'compiler_f90' : None, # Use --fcompiler=gnu95 for f90 codes 'compiler_fix' : None, 'linker_so' : [None, "-g", "-Wall"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"], 'linker_exe' : [None, "-g", "-Wall"] } module_dir_switch = None module_include_switch = None # Cygwin: f771: warning: -fPIC ignored for target (all code is # position independent) if os.name != 'nt' and sys.platform != 'cygwin': pic_flags = ['-fPIC'] # use -mno-cygwin for g77 when Python is not Cygwin-Python if sys.platform == 'win32': for key in ['version_cmd', 'compiler_f77', 'linker_so', 'linker_exe']: executables[key].append('-mno-cygwin') g2c = 'g2c' suggested_f90_compiler = 'gnu95' def get_flags_linker_so(self): opt = self.linker_so[1:] if sys.platform == 'darwin': target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', None) # If MACOSX_DEPLOYMENT_TARGET is set, we simply trust the value # and leave it alone. But, distutils will complain if the # environment's value is different from the one in the Python # Makefile used to build Python. We let disutils handle this # error checking. if not target: # If MACOSX_DEPLOYMENT_TARGET is not set in the environment, # we try to get it first from the Python Makefile and then we # fall back to setting it to 10.3 to maximize the set of # versions we can work with. This is a reasonable default # even when using the official Python dist and those derived # from it. import distutils.sysconfig as sc g = {} try: get_makefile_filename = sc.get_makefile_filename except AttributeError: pass # i.e. PyPy else: filename = get_makefile_filename() sc.parse_makefile(filename, g) target = g.get('MACOSX_DEPLOYMENT_TARGET', '10.3') os.environ['MACOSX_DEPLOYMENT_TARGET'] = target if target == '10.3': s = 'Env. variable MACOSX_DEPLOYMENT_TARGET set to 10.3' warnings.warn(s, stacklevel=2) opt.extend(['-undefined', 'dynamic_lookup', '-bundle']) else: opt.append("-shared") if sys.platform.startswith('sunos'): # SunOS often has dynamically loaded symbols defined in the # static library libg2c.a The linker doesn't like this. To # ignore the problem, use the -mimpure-text flag. It isn't # the safest thing, but seems to work. 'man gcc' says: # ".. Instead of using -mimpure-text, you should compile all # source code with -fpic or -fPIC." opt.append('-mimpure-text') return opt def get_libgcc_dir(self): status, output = exec_command( self.compiler_f77 + ['-print-libgcc-file-name'], use_tee=0) if not status: return os.path.dirname(output) return None def get_libgfortran_dir(self): if sys.platform[:5] == 'linux': libgfortran_name = 'libgfortran.so' elif sys.platform == 'darwin': libgfortran_name = 'libgfortran.dylib' else: libgfortran_name = None libgfortran_dir = None if libgfortran_name: find_lib_arg = ['-print-file-name={0}'.format(libgfortran_name)] status, output = exec_command( self.compiler_f77 + find_lib_arg, use_tee=0) if not status: libgfortran_dir = os.path.dirname(output) return libgfortran_dir def get_library_dirs(self): opt = [] if sys.platform[:5] != 'linux': d = self.get_libgcc_dir() if d: # if windows and not cygwin, libg2c lies in a different folder if sys.platform == 'win32' and not d.startswith('/usr/lib'): d = os.path.normpath(d) path = os.path.join(d, "lib%s.a" % self.g2c) if not os.path.exists(path): root = os.path.join(d, *((os.pardir, ) * 4)) d2 = os.path.abspath(os.path.join(root, 'lib')) path = os.path.join(d2, "lib%s.a" % self.g2c) if os.path.exists(path): opt.append(d2) opt.append(d) # For Macports / Linux, libgfortran and libgcc are not co-located lib_gfortran_dir = self.get_libgfortran_dir() if lib_gfortran_dir: opt.append(lib_gfortran_dir) return opt def get_libraries(self): opt = [] d = self.get_libgcc_dir() if d is not None: g2c = self.g2c + '-pic' f = self.static_lib_format % (g2c, self.static_lib_extension) if not os.path.isfile(os.path.join(d, f)): g2c = self.g2c else: g2c = self.g2c if g2c is not None: opt.append(g2c) c_compiler = self.c_compiler if sys.platform == 'win32' and c_compiler and \ c_compiler.compiler_type == 'msvc': opt.append('gcc') if sys.platform == 'darwin': opt.append('cc_dynamic') return opt def get_flags_debug(self): return ['-g'] def get_flags_opt(self): v = self.get_version() if v and v <= '3.3.3': # With this compiler version building Fortran BLAS/LAPACK # with -O3 caused failures in lib.lapack heevr,syevr tests. opt = ['-O2'] else: opt = ['-O3'] opt.append('-funroll-loops') return opt def _c_arch_flags(self): """ Return detected arch flags from CFLAGS """ from distutils import sysconfig try: cflags = sysconfig.get_config_vars()['CFLAGS'] except KeyError: return [] arch_re = re.compile(r"-arch\s+(\w+)") arch_flags = [] for arch in arch_re.findall(cflags): arch_flags += ['-arch', arch] return arch_flags def get_flags_arch(self): return [] def runtime_library_dir_option(self, dir): sep = ',' if sys.platform == 'darwin' else '=' return '-Wl,-rpath%s"%s"' % (sep, dir) class Gnu95FCompiler(GnuFCompiler): compiler_type = 'gnu95' compiler_aliases = ('gfortran', ) description = 'GNU Fortran 95 compiler' def version_match(self, version_string): v = self.gnu_version_match(version_string) if not v or v[0] != 'gfortran': return None v = v[1] if v >= '4.': # gcc-4 series releases do not support -mno-cygwin option pass else: # use -mno-cygwin flag for gfortran when Python is not # Cygwin-Python if sys.platform == 'win32': for key in [ 'version_cmd', 'compiler_f77', 'compiler_f90', 'compiler_fix', 'linker_so', 'linker_exe' ]: self.executables[key].append('-mno-cygwin') return v possible_executables = ['gfortran', 'f95'] executables = { 'version_cmd' : ["<F90>", "-dumpversion"], 'compiler_f77' : [None, "-Wall", "-g", "-ffixed-form", "-fno-second-underscore"] + _EXTRAFLAGS, 'compiler_f90' : [None, "-Wall", "-g", "-fno-second-underscore"] + _EXTRAFLAGS, 'compiler_fix' : [None, "-Wall", "-g","-ffixed-form", "-fno-second-underscore"] + _EXTRAFLAGS, 'linker_so' : ["<F90>", "-Wall", "-g"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"], 'linker_exe' : [None, "-Wall"] } module_dir_switch = '-J' module_include_switch = '-I' g2c = 'gfortran' def _universal_flags(self, cmd): """Return a list of -arch flags for every supported architecture.""" if not sys.platform == 'darwin': return [] arch_flags = [] # get arches the C compiler gets. c_archs = self._c_arch_flags() if "i386" in c_archs: c_archs[c_archs.index("i386")] = "i686" # check the arches the Fortran compiler supports, and compare with # arch flags from C compiler for arch in ["ppc", "i686", "x86_64", "ppc64"]: if _can_target(cmd, arch) and arch in c_archs: arch_flags.extend(["-arch", arch]) return arch_flags def get_flags(self): flags = GnuFCompiler.get_flags(self) arch_flags = self._universal_flags(self.compiler_f90) if arch_flags: flags[:0] = arch_flags return flags def get_flags_linker_so(self): flags = GnuFCompiler.get_flags_linker_so(self) arch_flags = self._universal_flags(self.linker_so) if arch_flags: flags[:0] = arch_flags return flags def get_library_dirs(self): opt = GnuFCompiler.get_library_dirs(self) if sys.platform == 'win32': c_compiler = self.c_compiler if c_compiler and c_compiler.compiler_type == "msvc": target = self.get_target() if target: d = os.path.normpath(self.get_libgcc_dir()) root = os.path.join(d, *((os.pardir, ) * 4)) path = os.path.join(root, "lib") mingwdir = os.path.normpath(path) if os.path.exists(os.path.join(mingwdir, "libmingwex.a")): opt.append(mingwdir) # For Macports / Linux, libgfortran and libgcc are not co-located lib_gfortran_dir = self.get_libgfortran_dir() if lib_gfortran_dir: opt.append(lib_gfortran_dir) return opt def get_libraries(self): opt = GnuFCompiler.get_libraries(self) if sys.platform == 'darwin': opt.remove('cc_dynamic') if sys.platform == 'win32': c_compiler = self.c_compiler if c_compiler and c_compiler.compiler_type == "msvc": if "gcc" in opt: i = opt.index("gcc") opt.insert(i + 1, "mingwex") opt.insert(i + 1, "mingw32") c_compiler = self.c_compiler if c_compiler and c_compiler.compiler_type == "msvc": return [] else: pass return opt def get_target(self): status, output = exec_command(self.compiler_f77 + ['-v'], use_tee=0) if not status: m = TARGET_R.search(output) if m: return m.group(1) return "" def _hash_files(self, filenames): h = hashlib.sha1() for fn in filenames: with open(fn, 'rb') as f: while True: block = f.read(131072) if not block: break h.update(block) text = base64.b32encode(h.digest()) if sys.version_info[0] >= 3: text = text.decode('ascii') return text.rstrip('=') def _link_wrapper_lib(self, objects, output_dir, extra_dll_dir, chained_dlls, is_archive): """Create a wrapper shared library for the given objects Return an MSVC-compatible lib """ c_compiler = self.c_compiler if c_compiler.compiler_type != "msvc": raise ValueError("This method only supports MSVC") object_hash = self._hash_files(list(objects) + list(chained_dlls)) if is_win64(): tag = 'win_amd64' else: tag = 'win32' basename = 'lib' + os.path.splitext( os.path.basename(objects[0]))[0][:8] root_name = basename + '.' + object_hash + '.gfortran-' + tag dll_name = root_name + '.dll' def_name = root_name + '.def' lib_name = root_name + '.lib' dll_path = os.path.join(extra_dll_dir, dll_name) def_path = os.path.join(output_dir, def_name) lib_path = os.path.join(output_dir, lib_name) if os.path.isfile(lib_path): # Nothing to do return lib_path, dll_path if is_archive: objects = (["-Wl,--whole-archive"] + list(objects) + ["-Wl,--no-whole-archive"]) self.link_shared_object( objects, dll_name, output_dir=extra_dll_dir, extra_postargs=list(chained_dlls) + [ '-Wl,--allow-multiple-definition', '-Wl,--output-def,' + def_path, '-Wl,--export-all-symbols', '-Wl,--enable-auto-import', '-static', '-mlong-double-64', ]) # No PowerPC! if is_win64(): specifier = '/MACHINE:X64' else: specifier = '/MACHINE:X86' # MSVC specific code lib_args = ['/def:' + def_path, '/OUT:' + lib_path, specifier] if not c_compiler.initialized: c_compiler.initialize() c_compiler.spawn([c_compiler.lib] + lib_args) return lib_path, dll_path def can_ccompiler_link(self, compiler): # MSVC cannot link objects compiled by GNU fortran return compiler.compiler_type not in ("msvc", ) def wrap_unlinkable_objects(self, objects, output_dir, extra_dll_dir): """ Convert a set of object files that are not compatible with the default linker, to a file that is compatible. """ if self.c_compiler.compiler_type == "msvc": # Compile a DLL and return the lib for the DLL as # the object. Also keep track of previous DLLs that # we have compiled so that we can link against them. # If there are .a archives, assume they are self-contained # static libraries, and build separate DLLs for each archives = [] plain_objects = [] for obj in objects: if obj.lower().endswith('.a'): archives.append(obj) else: plain_objects.append(obj) chained_libs = [] chained_dlls = [] for archive in archives[::-1]: lib, dll = self._link_wrapper_lib( [archive], output_dir, extra_dll_dir, chained_dlls=chained_dlls, is_archive=True) chained_libs.insert(0, lib) chained_dlls.insert(0, dll) if not plain_objects: return chained_libs lib, dll = self._link_wrapper_lib( plain_objects, output_dir, extra_dll_dir, chained_dlls=chained_dlls, is_archive=False) return [lib] + chained_libs else: raise ValueError("Unsupported C compiler") def _can_target(cmd, arch): """Return true if the architecture supports the -arch flag""" newcmd = cmd[:] fid, filename = tempfile.mkstemp(suffix=".f") os.close(fid) try: d = os.path.dirname(filename) output = os.path.splitext(filename)[0] + ".o" try: newcmd.extend(["-arch", arch, "-c", filename]) p = Popen(newcmd, stderr=STDOUT, stdout=PIPE, cwd=d) p.communicate() return p.returncode == 0 finally: if os.path.exists(output): os.remove(output) finally: os.remove(filename) return False if __name__ == '__main__': from distutils import log from numpy.distutils import customized_fcompiler log.set_verbosity(2) print(customized_fcompiler('gnu').get_version()) try: print(customized_fcompiler('g95').get_version()) except Exception: print(get_exception())
19,763
35.6
80
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/nag.py
from __future__ import division, absolute_import, print_function import sys import re from numpy.distutils.fcompiler import FCompiler compilers = ['NAGFCompiler', 'NAGFORCompiler'] class BaseNAGFCompiler(FCompiler): version_pattern = r'NAG.* Release (?P<version>[^(\s]*)' def version_match(self, version_string): m = re.search(self.version_pattern, version_string) if m: return m.group('version') else: return None def get_flags_linker_so(self): return ["-Wl,-shared"] def get_flags_opt(self): return ['-O4'] def get_flags_arch(self): return [''] class NAGFCompiler(BaseNAGFCompiler): compiler_type = 'nag' description = 'NAGWare Fortran 95 Compiler' executables = { 'version_cmd' : ["<F90>", "-V"], 'compiler_f77' : ["f95", "-fixed"], 'compiler_fix' : ["f95", "-fixed"], 'compiler_f90' : ["f95"], 'linker_so' : ["<F90>"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } def get_flags_linker_so(self): if sys.platform == 'darwin': return ['-unsharedf95', '-Wl,-bundle,-flat_namespace,-undefined,suppress'] return BaseNAGFCompiler.get_flags_linker_so(self) def get_flags_arch(self): version = self.get_version() if version and version < '5.1': return ['-target=native'] else: return BaseNAGFCompiler.get_flags_arch(self) def get_flags_debug(self): return ['-g', '-gline', '-g90', '-nan', '-C'] class NAGFORCompiler(BaseNAGFCompiler): compiler_type = 'nagfor' description = 'NAG Fortran Compiler' executables = { 'version_cmd' : ["nagfor", "-V"], 'compiler_f77' : ["nagfor", "-fixed"], 'compiler_fix' : ["nagfor", "-fixed"], 'compiler_f90' : ["nagfor"], 'linker_so' : ["nagfor"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } def get_flags_debug(self): version = self.get_version() if version and version > '6.1': return ['-g', '-u', '-nan', '-C=all', '-thread_safe', '-kind=unique', '-Warn=allocation', '-Warn=subnormal'] else: return ['-g', '-nan', '-C=all', '-u', '-thread_safe'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler compiler = customized_fcompiler(compiler='nagfor') print(compiler.get_version()) print(compiler.get_flags_debug())
2,608
29.694118
86
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/intel.py
# http://developer.intel.com/software/products/compilers/flin/ from __future__ import division, absolute_import, print_function import sys from numpy.distutils.ccompiler import simple_version_match from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file compilers = ['IntelFCompiler', 'IntelVisualFCompiler', 'IntelItaniumFCompiler', 'IntelItaniumVisualFCompiler', 'IntelEM64VisualFCompiler', 'IntelEM64TFCompiler'] def intel_version_match(type): # Match against the important stuff in the version string return simple_version_match(start=r'Intel.*?Fortran.*?(?:%s).*?Version' % (type,)) class BaseIntelFCompiler(FCompiler): def update_executables(self): f = dummy_fortran_file() self.executables['version_cmd'] = ['<F77>', '-FI', '-V', '-c', f + '.f', '-o', f + '.o'] def runtime_library_dir_option(self, dir): return '-Wl,-rpath="%s"' % dir class IntelFCompiler(BaseIntelFCompiler): compiler_type = 'intel' compiler_aliases = ('ifort',) description = 'Intel Fortran Compiler for 32-bit apps' version_match = intel_version_match('32-bit|IA-32') possible_executables = ['ifort', 'ifc'] executables = { 'version_cmd' : None, # set by update_executables 'compiler_f77' : [None, "-72", "-w90", "-w95"], 'compiler_f90' : [None], 'compiler_fix' : [None, "-FI"], 'linker_so' : ["<F90>", "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } pic_flags = ['-fPIC'] module_dir_switch = '-module ' # Don't remove ending space! module_include_switch = '-I' def get_flags_free(self): return ['-FR'] def get_flags(self): return ['-fPIC'] def get_flags_opt(self): # Scipy test failures with -O2 v = self.get_version() mpopt = 'openmp' if v and v < '15' else 'qopenmp' return ['-fp-model strict -O1 -{}'.format(mpopt)] def get_flags_arch(self): return [] def get_flags_linker_so(self): opt = FCompiler.get_flags_linker_so(self) v = self.get_version() if v and v >= '8.0': opt.append('-nofor_main') if sys.platform == 'darwin': # Here, it's -dynamiclib try: idx = opt.index('-shared') opt.remove('-shared') except ValueError: idx = 0 opt[idx:idx] = ['-dynamiclib', '-Wl,-undefined,dynamic_lookup'] return opt class IntelItaniumFCompiler(IntelFCompiler): compiler_type = 'intele' compiler_aliases = () description = 'Intel Fortran Compiler for Itanium apps' version_match = intel_version_match('Itanium|IA-64') possible_executables = ['ifort', 'efort', 'efc'] executables = { 'version_cmd' : None, 'compiler_f77' : [None, "-FI", "-w90", "-w95"], 'compiler_fix' : [None, "-FI"], 'compiler_f90' : [None], 'linker_so' : ['<F90>', "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } class IntelEM64TFCompiler(IntelFCompiler): compiler_type = 'intelem' compiler_aliases = () description = 'Intel Fortran Compiler for 64-bit apps' version_match = intel_version_match('EM64T-based|Intel\\(R\\) 64|64|IA-64|64-bit') possible_executables = ['ifort', 'efort', 'efc'] executables = { 'version_cmd' : None, 'compiler_f77' : [None, "-FI"], 'compiler_fix' : [None, "-FI"], 'compiler_f90' : [None], 'linker_so' : ['<F90>', "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } def get_flags(self): return ['-fPIC'] def get_flags_opt(self): # Scipy test failures with -O2 v = self.get_version() mpopt = 'openmp' if v and v < '15' else 'qopenmp' return ['-fp-model strict -O1 -{}'.format(mpopt)] def get_flags_arch(self): return [''] # Is there no difference in the version string between the above compilers # and the Visual compilers? class IntelVisualFCompiler(BaseIntelFCompiler): compiler_type = 'intelv' description = 'Intel Visual Fortran Compiler for 32-bit apps' version_match = intel_version_match('32-bit|IA-32') def update_executables(self): f = dummy_fortran_file() self.executables['version_cmd'] = ['<F77>', '/FI', '/c', f + '.f', '/o', f + '.o'] ar_exe = 'lib.exe' possible_executables = ['ifort', 'ifl'] executables = { 'version_cmd' : None, 'compiler_f77' : [None], 'compiler_fix' : [None], 'compiler_f90' : [None], 'linker_so' : [None], 'archiver' : [ar_exe, "/verbose", "/OUT:"], 'ranlib' : None } compile_switch = '/c ' object_switch = '/Fo' # No space after /Fo! library_switch = '/OUT:' # No space after /OUT:! module_dir_switch = '/module:' # No space after /module: module_include_switch = '/I' def get_flags(self): opt = ['/nologo', '/MD', '/nbs', '/names:lowercase', '/assume:underscore'] return opt def get_flags_free(self): return [] def get_flags_debug(self): return ['/4Yb', '/d2'] def get_flags_opt(self): return ['/O1'] # Scipy test failures with /O2 def get_flags_arch(self): return ["/arch:IA32", "/QaxSSE3"] def runtime_library_dir_option(self, dir): raise NotImplementedError class IntelItaniumVisualFCompiler(IntelVisualFCompiler): compiler_type = 'intelev' description = 'Intel Visual Fortran Compiler for Itanium apps' version_match = intel_version_match('Itanium') possible_executables = ['efl'] # XXX this is a wild guess ar_exe = IntelVisualFCompiler.ar_exe executables = { 'version_cmd' : None, 'compiler_f77' : [None, "-FI", "-w90", "-w95"], 'compiler_fix' : [None, "-FI", "-4L72", "-w"], 'compiler_f90' : [None], 'linker_so' : ['<F90>', "-shared"], 'archiver' : [ar_exe, "/verbose", "/OUT:"], 'ranlib' : None } class IntelEM64VisualFCompiler(IntelVisualFCompiler): compiler_type = 'intelvem' description = 'Intel Visual Fortran Compiler for 64-bit apps' version_match = simple_version_match(start=r'Intel\(R\).*?64,') def get_flags_arch(self): return [''] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='intel').get_version())
6,773
29.790909
86
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/lahey.py
from __future__ import division, absolute_import, print_function import os from numpy.distutils.fcompiler import FCompiler compilers = ['LaheyFCompiler'] class LaheyFCompiler(FCompiler): compiler_type = 'lahey' description = 'Lahey/Fujitsu Fortran 95 Compiler' version_pattern = r'Lahey/Fujitsu Fortran 95 Compiler Release (?P<version>[^\s*]*)' executables = { 'version_cmd' : ["<F90>", "--version"], 'compiler_f77' : ["lf95", "--fix"], 'compiler_fix' : ["lf95", "--fix"], 'compiler_f90' : ["lf95"], 'linker_so' : ["lf95", "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } module_dir_switch = None #XXX Fix me module_include_switch = None #XXX Fix me def get_flags_opt(self): return ['-O'] def get_flags_debug(self): return ['-g', '--chk', '--chkglobal'] def get_library_dirs(self): opt = [] d = os.environ.get('LAHEY') if d: opt.append(os.path.join(d, 'lib')) return opt def get_libraries(self): opt = [] opt.extend(['fj9f6', 'fj9i6', 'fj9ipp', 'fj9e6']) return opt if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='lahey').get_version())
1,393
28.041667
88
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/none.py
from __future__ import division, absolute_import, print_function from numpy.distutils.fcompiler import FCompiler from numpy.distutils import customized_fcompiler compilers = ['NoneFCompiler'] class NoneFCompiler(FCompiler): compiler_type = 'none' description = 'Fake Fortran compiler' executables = {'compiler_f77': None, 'compiler_f90': None, 'compiler_fix': None, 'linker_so': None, 'linker_exe': None, 'archiver': None, 'ranlib': None, 'version_cmd': None, } def find_executables(self): pass if __name__ == '__main__': from distutils import log log.set_verbosity(2) print(customized_fcompiler(compiler='none').get_version())
824
25.612903
64
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/pg.py
# http://www.pgroup.com from __future__ import division, absolute_import, print_function import sys import os from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file from sys import platform from os.path import join, dirname, normpath compilers = ['PGroupFCompiler', 'PGroupFlangCompiler'] class PGroupFCompiler(FCompiler): compiler_type = 'pg' description = 'Portland Group Fortran Compiler' version_pattern = r'\s*pg(f77|f90|hpf|fortran) (?P<version>[\d.-]+).*' if platform == 'darwin': executables = { 'version_cmd': ["<F77>", "-V"], 'compiler_f77': ["pgfortran", "-dynamiclib"], 'compiler_fix': ["pgfortran", "-Mfixed", "-dynamiclib"], 'compiler_f90': ["pgfortran", "-dynamiclib"], 'linker_so': ["libtool"], 'archiver': ["ar", "-cr"], 'ranlib': ["ranlib"] } pic_flags = [''] else: executables = { 'version_cmd': ["<F77>", "-V"], 'compiler_f77': ["pgfortran"], 'compiler_fix': ["pgfortran", "-Mfixed"], 'compiler_f90': ["pgfortran"], 'linker_so': ["pgfortran", "-shared", "-fpic"], 'archiver': ["ar", "-cr"], 'ranlib': ["ranlib"] } pic_flags = ['-fpic'] module_dir_switch = '-module ' module_include_switch = '-I' def get_flags(self): opt = ['-Minform=inform', '-Mnosecond_underscore'] return self.pic_flags + opt def get_flags_opt(self): return ['-fast'] def get_flags_debug(self): return ['-g'] if platform == 'darwin': def get_flags_linker_so(self): return ["-dynamic", '-undefined', 'dynamic_lookup'] def runtime_library_dir_option(self, dir): return '-R"%s"' % dir if sys.version_info >= (3, 5): import subprocess import shlex import functools class PGroupFlangCompiler(FCompiler): compiler_type = 'flang' description = 'Portland Group Fortran LLVM Compiler' version_pattern = r'\s*(flang|clang) version (?P<version>[\d.-]+).*' ar_exe = 'lib.exe' possible_executables = ['flang'] executables = { 'version_cmd': ["<F77>", "--version"], 'compiler_f77': ["flang"], 'compiler_fix': ["flang"], 'compiler_f90': ["flang"], 'linker_so': [None], 'archiver': [ar_exe, "/verbose", "/OUT:"], 'ranlib': None } library_switch = '/OUT:' # No space after /OUT:! module_dir_switch = '-module ' # Don't remove ending space! def get_libraries(self): opt = FCompiler.get_libraries(self) opt.extend(['flang', 'flangrti', 'ompstub']) return opt @functools.lru_cache(maxsize=128) def get_library_dirs(self): """List of compiler library directories.""" opt = FCompiler.get_library_dirs(self) flang_dir = dirname(self.executables['compiler_f77'][0]) opt.append(normpath(join(flang_dir, '..', 'lib'))) return opt def get_flags(self): return [] def get_flags_free(self): return [] def get_flags_debug(self): return ['-g'] def get_flags_opt(self): return ['-O3'] def get_flags_arch(self): return [] def runtime_library_dir_option(self, dir): raise NotImplementedError else: from numpy.distutils.fcompiler import CompilerNotFound # No point in supporting on older Pythons because not ABI compatible class PGroupFlangCompiler(FCompiler): compiler_type = 'flang' description = 'Portland Group Fortran LLVM Compiler' def get_version(self): raise CompilerNotFound('Flang unsupported on Python < 3.5') if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler if 'flang' in sys.argv: print(customized_fcompiler(compiler='flang').get_version()) else: print(customized_fcompiler(compiler='pg').get_version())
4,213
28.676056
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/ibm.py
from __future__ import division, absolute_import, print_function import os import re import sys from numpy.distutils.fcompiler import FCompiler from numpy.distutils.exec_command import exec_command, find_executable from numpy.distutils.misc_util import make_temp_file from distutils import log compilers = ['IBMFCompiler'] class IBMFCompiler(FCompiler): compiler_type = 'ibm' description = 'IBM XL Fortran Compiler' version_pattern = r'(xlf\(1\)\s*|)IBM XL Fortran ((Advanced Edition |)Version |Enterprise Edition V|for AIX, V)(?P<version>[^\s*]*)' #IBM XL Fortran Enterprise Edition V10.1 for AIX \nVersion: 10.01.0000.0004 executables = { 'version_cmd' : ["<F77>", "-qversion"], 'compiler_f77' : ["xlf"], 'compiler_fix' : ["xlf90", "-qfixed"], 'compiler_f90' : ["xlf90"], 'linker_so' : ["xlf95"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } def get_version(self,*args,**kwds): version = FCompiler.get_version(self,*args,**kwds) if version is None and sys.platform.startswith('aix'): # use lslpp to find out xlf version lslpp = find_executable('lslpp') xlf = find_executable('xlf') if os.path.exists(xlf) and os.path.exists(lslpp): s, o = exec_command(lslpp + ' -Lc xlfcmp') m = re.search(r'xlfcmp:(?P<version>\d+([.]\d+)+)', o) if m: version = m.group('version') xlf_dir = '/etc/opt/ibmcmp/xlf' if version is None and os.path.isdir(xlf_dir): # linux: # If the output of xlf does not contain version info # (that's the case with xlf 8.1, for instance) then # let's try another method: l = sorted(os.listdir(xlf_dir)) l.reverse() l = [d for d in l if os.path.isfile(os.path.join(xlf_dir, d, 'xlf.cfg'))] if l: from distutils.version import LooseVersion self.version = version = LooseVersion(l[0]) return version def get_flags(self): return ['-qextname'] def get_flags_debug(self): return ['-g'] def get_flags_linker_so(self): opt = [] if sys.platform=='darwin': opt.append('-Wl,-bundle,-flat_namespace,-undefined,suppress') else: opt.append('-bshared') version = self.get_version(ok_status=[0, 40]) if version is not None: if sys.platform.startswith('aix'): xlf_cfg = '/etc/xlf.cfg' else: xlf_cfg = '/etc/opt/ibmcmp/xlf/%s/xlf.cfg' % version fo, new_cfg = make_temp_file(suffix='_xlf.cfg') log.info('Creating '+new_cfg) fi = open(xlf_cfg, 'r') crt1_match = re.compile(r'\s*crt\s*[=]\s*(?P<path>.*)/crt1.o').match for line in fi: m = crt1_match(line) if m: fo.write('crt = %s/bundle1.o\n' % (m.group('path'))) else: fo.write(line) fi.close() fo.close() opt.append('-F'+new_cfg) return opt def get_flags_opt(self): return ['-O3'] if __name__ == '__main__': from numpy.distutils import customized_fcompiler log.set_verbosity(2) print(customized_fcompiler(compiler='ibm').get_version())
3,435
34.791667
137
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/absoft.py
# http://www.absoft.com/literature/osxuserguide.pdf # http://www.absoft.com/documentation.html # Notes: # - when using -g77 then use -DUNDERSCORE_G77 to compile f2py # generated extension modules (works for f2py v2.45.241_1936 and up) from __future__ import division, absolute_import, print_function import os from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file from numpy.distutils.misc_util import cyg2win32 compilers = ['AbsoftFCompiler'] class AbsoftFCompiler(FCompiler): compiler_type = 'absoft' description = 'Absoft Corp Fortran Compiler' #version_pattern = r'FORTRAN 77 Compiler (?P<version>[^\s*,]*).*?Absoft Corp' version_pattern = r'(f90:.*?(Absoft Pro FORTRAN Version|FORTRAN 77 Compiler|Absoft Fortran Compiler Version|Copyright Absoft Corporation.*?Version))'+\ r' (?P<version>[^\s*,]*)(.*?Absoft Corp|)' # on windows: f90 -V -c dummy.f # f90: Copyright Absoft Corporation 1994-1998 mV2; Cray Research, Inc. 1994-1996 CF90 (2.x.x.x f36t87) Version 2.3 Wed Apr 19, 2006 13:05:16 # samt5735(8)$ f90 -V -c dummy.f # f90: Copyright Absoft Corporation 1994-2002; Absoft Pro FORTRAN Version 8.0 # Note that fink installs g77 as f77, so need to use f90 for detection. executables = { 'version_cmd' : None, # set by update_executables 'compiler_f77' : ["f77"], 'compiler_fix' : ["f90"], 'compiler_f90' : ["f90"], 'linker_so' : ["<F90>"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } if os.name=='nt': library_switch = '/out:' #No space after /out:! module_dir_switch = None module_include_switch = '-p' def update_executables(self): f = cyg2win32(dummy_fortran_file()) self.executables['version_cmd'] = ['<F90>', '-V', '-c', f+'.f', '-o', f+'.o'] def get_flags_linker_so(self): if os.name=='nt': opt = ['/dll'] # The "-K shared" switches are being left in for pre-9.0 versions # of Absoft though I don't think versions earlier than 9 can # actually be used to build shared libraries. In fact, version # 8 of Absoft doesn't recognize "-K shared" and will fail. elif self.get_version() >= '9.0': opt = ['-shared'] else: opt = ["-K", "shared"] return opt def library_dir_option(self, dir): if os.name=='nt': return ['-link', '/PATH:"%s"' % (dir)] return "-L" + dir def library_option(self, lib): if os.name=='nt': return '%s.lib' % (lib) return "-l" + lib def get_library_dirs(self): opt = FCompiler.get_library_dirs(self) d = os.environ.get('ABSOFT') if d: if self.get_version() >= '10.0': # use shared libraries, the static libraries were not compiled -fPIC prefix = 'sh' else: prefix = '' if cpu.is_64bit(): suffix = '64' else: suffix = '' opt.append(os.path.join(d, '%slib%s' % (prefix, suffix))) return opt def get_libraries(self): opt = FCompiler.get_libraries(self) if self.get_version() >= '11.0': opt.extend(['af90math', 'afio', 'af77math', 'amisc']) elif self.get_version() >= '10.0': opt.extend(['af90math', 'afio', 'af77math', 'U77']) elif self.get_version() >= '8.0': opt.extend(['f90math', 'fio', 'f77math', 'U77']) else: opt.extend(['fio', 'f90math', 'fmath', 'U77']) if os.name =='nt': opt.append('COMDLG32') return opt def get_flags(self): opt = FCompiler.get_flags(self) if os.name != 'nt': opt.extend(['-s']) if self.get_version(): if self.get_version()>='8.2': opt.append('-fpic') return opt def get_flags_f77(self): opt = FCompiler.get_flags_f77(self) opt.extend(['-N22', '-N90', '-N110']) v = self.get_version() if os.name == 'nt': if v and v>='8.0': opt.extend(['-f', '-N15']) else: opt.append('-f') if v: if v<='4.6': opt.append('-B108') else: # Though -N15 is undocumented, it works with # Absoft 8.0 on Linux opt.append('-N15') return opt def get_flags_f90(self): opt = FCompiler.get_flags_f90(self) opt.extend(["-YCFRL=1", "-YCOM_NAMES=LCS", "-YCOM_PFX", "-YEXT_PFX", "-YCOM_SFX=_", "-YEXT_SFX=_", "-YEXT_NAMES=LCS"]) if self.get_version(): if self.get_version()>'4.6': opt.extend(["-YDEALLOC=ALL"]) return opt def get_flags_fix(self): opt = FCompiler.get_flags_fix(self) opt.extend(["-YCFRL=1", "-YCOM_NAMES=LCS", "-YCOM_PFX", "-YEXT_PFX", "-YCOM_SFX=_", "-YEXT_SFX=_", "-YEXT_NAMES=LCS"]) opt.extend(["-f", "fixed"]) return opt def get_flags_opt(self): opt = ['-O'] return opt if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='absoft').get_version())
5,567
34.018868
155
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/__init__.py
"""numpy.distutils.fcompiler Contains FCompiler, an abstract base class that defines the interface for the numpy.distutils Fortran compiler abstraction model. Terminology: To be consistent, where the term 'executable' is used, it means the single file, like 'gcc', that is executed, and should be a string. In contrast, 'command' means the entire command line, like ['gcc', '-c', 'file.c'], and should be a list. But note that FCompiler.executables is actually a dictionary of commands. """ from __future__ import division, absolute_import, print_function __all__ = ['FCompiler', 'new_fcompiler', 'show_fcompilers', 'dummy_fortran_file'] import os import sys import re import types from numpy.compat import open_latin1 from distutils.sysconfig import get_python_lib from distutils.fancy_getopt import FancyGetopt from distutils.errors import DistutilsModuleError, \ DistutilsExecError, CompileError, LinkError, DistutilsPlatformError from distutils.util import split_quoted, strtobool from numpy.distutils.ccompiler import CCompiler, gen_lib_options from numpy.distutils import log from numpy.distutils.misc_util import is_string, all_strings, is_sequence, \ make_temp_file, get_shared_lib_extension from numpy.distutils.environment import EnvironmentConfig from numpy.distutils.exec_command import find_executable from numpy.distutils.compat import get_exception __metaclass__ = type class CompilerNotFound(Exception): pass def flaglist(s): if is_string(s): return split_quoted(s) else: return s def str2bool(s): if is_string(s): return strtobool(s) return bool(s) def is_sequence_of_strings(seq): return is_sequence(seq) and all_strings(seq) class FCompiler(CCompiler): """Abstract base class to define the interface that must be implemented by real Fortran compiler classes. Methods that subclasses may redefine: update_executables(), find_executables(), get_version() get_flags(), get_flags_opt(), get_flags_arch(), get_flags_debug() get_flags_f77(), get_flags_opt_f77(), get_flags_arch_f77(), get_flags_debug_f77(), get_flags_f90(), get_flags_opt_f90(), get_flags_arch_f90(), get_flags_debug_f90(), get_flags_fix(), get_flags_linker_so() DON'T call these methods (except get_version) after constructing a compiler instance or inside any other method. All methods, except update_executables() and find_executables(), may call the get_version() method. After constructing a compiler instance, always call customize(dist=None) method that finalizes compiler construction and makes the following attributes available: compiler_f77 compiler_f90 compiler_fix linker_so archiver ranlib libraries library_dirs """ # These are the environment variables and distutils keys used. # Each configuration description is # (<hook name>, <environment variable>, <key in distutils.cfg>, <convert>) # The hook names are handled by the self._environment_hook method. # - names starting with 'self.' call methods in this class # - names starting with 'exe.' return the key in the executables dict # - names like 'flags.YYY' return self.get_flag_YYY() # convert is either None or a function to convert a string to the # appropriate type used. distutils_vars = EnvironmentConfig( distutils_section='config_fc', noopt = (None, None, 'noopt', str2bool), noarch = (None, None, 'noarch', str2bool), debug = (None, None, 'debug', str2bool), verbose = (None, None, 'verbose', str2bool), ) command_vars = EnvironmentConfig( distutils_section='config_fc', compiler_f77 = ('exe.compiler_f77', 'F77', 'f77exec', None), compiler_f90 = ('exe.compiler_f90', 'F90', 'f90exec', None), compiler_fix = ('exe.compiler_fix', 'F90', 'f90exec', None), version_cmd = ('exe.version_cmd', None, None, None), linker_so = ('exe.linker_so', 'LDSHARED', 'ldshared', None), linker_exe = ('exe.linker_exe', 'LD', 'ld', None), archiver = (None, 'AR', 'ar', None), ranlib = (None, 'RANLIB', 'ranlib', None), ) flag_vars = EnvironmentConfig( distutils_section='config_fc', f77 = ('flags.f77', 'F77FLAGS', 'f77flags', flaglist), f90 = ('flags.f90', 'F90FLAGS', 'f90flags', flaglist), free = ('flags.free', 'FREEFLAGS', 'freeflags', flaglist), fix = ('flags.fix', None, None, flaglist), opt = ('flags.opt', 'FOPT', 'opt', flaglist), opt_f77 = ('flags.opt_f77', None, None, flaglist), opt_f90 = ('flags.opt_f90', None, None, flaglist), arch = ('flags.arch', 'FARCH', 'arch', flaglist), arch_f77 = ('flags.arch_f77', None, None, flaglist), arch_f90 = ('flags.arch_f90', None, None, flaglist), debug = ('flags.debug', 'FDEBUG', 'fdebug', flaglist), debug_f77 = ('flags.debug_f77', None, None, flaglist), debug_f90 = ('flags.debug_f90', None, None, flaglist), flags = ('self.get_flags', 'FFLAGS', 'fflags', flaglist), linker_so = ('flags.linker_so', 'LDFLAGS', 'ldflags', flaglist), linker_exe = ('flags.linker_exe', 'LDFLAGS', 'ldflags', flaglist), ar = ('flags.ar', 'ARFLAGS', 'arflags', flaglist), ) language_map = {'.f': 'f77', '.for': 'f77', '.F': 'f77', # XXX: needs preprocessor '.ftn': 'f77', '.f77': 'f77', '.f90': 'f90', '.F90': 'f90', # XXX: needs preprocessor '.f95': 'f90', } language_order = ['f90', 'f77'] # These will be set by the subclass compiler_type = None compiler_aliases = () version_pattern = None possible_executables = [] executables = { 'version_cmd': ["f77", "-v"], 'compiler_f77': ["f77"], 'compiler_f90': ["f90"], 'compiler_fix': ["f90", "-fixed"], 'linker_so': ["f90", "-shared"], 'linker_exe': ["f90"], 'archiver': ["ar", "-cr"], 'ranlib': None, } # If compiler does not support compiling Fortran 90 then it can # suggest using another compiler. For example, gnu would suggest # gnu95 compiler type when there are F90 sources. suggested_f90_compiler = None compile_switch = "-c" object_switch = "-o " # Ending space matters! It will be stripped # but if it is missing then object_switch # will be prefixed to object file name by # string concatenation. library_switch = "-o " # Ditto! # Switch to specify where module files are created and searched # for USE statement. Normally it is a string and also here ending # space matters. See above. module_dir_switch = None # Switch to specify where module files are searched for USE statement. module_include_switch = '-I' pic_flags = [] # Flags to create position-independent code src_extensions = ['.for', '.ftn', '.f77', '.f', '.f90', '.f95', '.F', '.F90', '.FOR'] obj_extension = ".o" shared_lib_extension = get_shared_lib_extension() static_lib_extension = ".a" # or .lib static_lib_format = "lib%s%s" # or %s%s shared_lib_format = "%s%s" exe_extension = "" _exe_cache = {} _executable_keys = ['version_cmd', 'compiler_f77', 'compiler_f90', 'compiler_fix', 'linker_so', 'linker_exe', 'archiver', 'ranlib'] # This will be set by new_fcompiler when called in # command/{build_ext.py, build_clib.py, config.py} files. c_compiler = None # extra_{f77,f90}_compile_args are set by build_ext.build_extension method extra_f77_compile_args = [] extra_f90_compile_args = [] def __init__(self, *args, **kw): CCompiler.__init__(self, *args, **kw) self.distutils_vars = self.distutils_vars.clone(self._environment_hook) self.command_vars = self.command_vars.clone(self._environment_hook) self.flag_vars = self.flag_vars.clone(self._environment_hook) self.executables = self.executables.copy() for e in self._executable_keys: if e not in self.executables: self.executables[e] = None # Some methods depend on .customize() being called first, so # this keeps track of whether that's happened yet. self._is_customised = False def __copy__(self): obj = self.__new__(self.__class__) obj.__dict__.update(self.__dict__) obj.distutils_vars = obj.distutils_vars.clone(obj._environment_hook) obj.command_vars = obj.command_vars.clone(obj._environment_hook) obj.flag_vars = obj.flag_vars.clone(obj._environment_hook) obj.executables = obj.executables.copy() return obj def copy(self): return self.__copy__() # Use properties for the attributes used by CCompiler. Setting them # as attributes from the self.executables dictionary is error-prone, # so we get them from there each time. def _command_property(key): def fget(self): assert self._is_customised return self.executables[key] return property(fget=fget) version_cmd = _command_property('version_cmd') compiler_f77 = _command_property('compiler_f77') compiler_f90 = _command_property('compiler_f90') compiler_fix = _command_property('compiler_fix') linker_so = _command_property('linker_so') linker_exe = _command_property('linker_exe') archiver = _command_property('archiver') ranlib = _command_property('ranlib') # Make our terminology consistent. def set_executable(self, key, value): self.set_command(key, value) def set_commands(self, **kw): for k, v in kw.items(): self.set_command(k, v) def set_command(self, key, value): if not key in self._executable_keys: raise ValueError( "unknown executable '%s' for class %s" % (key, self.__class__.__name__)) if is_string(value): value = split_quoted(value) assert value is None or is_sequence_of_strings(value[1:]), (key, value) self.executables[key] = value ###################################################################### ## Methods that subclasses may redefine. But don't call these methods! ## They are private to FCompiler class and may return unexpected ## results if used elsewhere. So, you have been warned.. def find_executables(self): """Go through the self.executables dictionary, and attempt to find and assign appropriate executables. Executable names are looked for in the environment (environment variables, the distutils.cfg, and command line), the 0th-element of the command list, and the self.possible_executables list. Also, if the 0th element is "<F77>" or "<F90>", the Fortran 77 or the Fortran 90 compiler executable is used, unless overridden by an environment setting. Subclasses should call this if overridden. """ assert self._is_customised exe_cache = self._exe_cache def cached_find_executable(exe): if exe in exe_cache: return exe_cache[exe] fc_exe = find_executable(exe) exe_cache[exe] = exe_cache[fc_exe] = fc_exe return fc_exe def verify_command_form(name, value): if value is not None and not is_sequence_of_strings(value): raise ValueError( "%s value %r is invalid in class %s" % (name, value, self.__class__.__name__)) def set_exe(exe_key, f77=None, f90=None): cmd = self.executables.get(exe_key, None) if not cmd: return None # Note that we get cmd[0] here if the environment doesn't # have anything set exe_from_environ = getattr(self.command_vars, exe_key) if not exe_from_environ: possibles = [f90, f77] + self.possible_executables else: possibles = [exe_from_environ] + self.possible_executables seen = set() unique_possibles = [] for e in possibles: if e == '<F77>': e = f77 elif e == '<F90>': e = f90 if not e or e in seen: continue seen.add(e) unique_possibles.append(e) for exe in unique_possibles: fc_exe = cached_find_executable(exe) if fc_exe: cmd[0] = fc_exe return fc_exe self.set_command(exe_key, None) return None ctype = self.compiler_type f90 = set_exe('compiler_f90') if not f90: f77 = set_exe('compiler_f77') if f77: log.warn('%s: no Fortran 90 compiler found' % ctype) else: raise CompilerNotFound('%s: f90 nor f77' % ctype) else: f77 = set_exe('compiler_f77', f90=f90) if not f77: log.warn('%s: no Fortran 77 compiler found' % ctype) set_exe('compiler_fix', f90=f90) set_exe('linker_so', f77=f77, f90=f90) set_exe('linker_exe', f77=f77, f90=f90) set_exe('version_cmd', f77=f77, f90=f90) set_exe('archiver') set_exe('ranlib') def update_executables(elf): """Called at the beginning of customisation. Subclasses should override this if they need to set up the executables dictionary. Note that self.find_executables() is run afterwards, so the self.executables dictionary values can contain <F77> or <F90> as the command, which will be replaced by the found F77 or F90 compiler. """ pass def get_flags(self): """List of flags common to all compiler types.""" return [] + self.pic_flags def _get_command_flags(self, key): cmd = self.executables.get(key, None) if cmd is None: return [] return cmd[1:] def get_flags_f77(self): """List of Fortran 77 specific flags.""" return self._get_command_flags('compiler_f77') def get_flags_f90(self): """List of Fortran 90 specific flags.""" return self._get_command_flags('compiler_f90') def get_flags_free(self): """List of Fortran 90 free format specific flags.""" return [] def get_flags_fix(self): """List of Fortran 90 fixed format specific flags.""" return self._get_command_flags('compiler_fix') def get_flags_linker_so(self): """List of linker flags to build a shared library.""" return self._get_command_flags('linker_so') def get_flags_linker_exe(self): """List of linker flags to build an executable.""" return self._get_command_flags('linker_exe') def get_flags_ar(self): """List of archiver flags. """ return self._get_command_flags('archiver') def get_flags_opt(self): """List of architecture independent compiler flags.""" return [] def get_flags_arch(self): """List of architecture dependent compiler flags.""" return [] def get_flags_debug(self): """List of compiler flags to compile with debugging information.""" return [] get_flags_opt_f77 = get_flags_opt_f90 = get_flags_opt get_flags_arch_f77 = get_flags_arch_f90 = get_flags_arch get_flags_debug_f77 = get_flags_debug_f90 = get_flags_debug def get_libraries(self): """List of compiler libraries.""" return self.libraries[:] def get_library_dirs(self): """List of compiler library directories.""" return self.library_dirs[:] def get_version(self, force=False, ok_status=[0]): assert self._is_customised version = CCompiler.get_version(self, force=force, ok_status=ok_status) if version is None: raise CompilerNotFound() return version ############################################################ ## Public methods: def customize(self, dist = None): """Customize Fortran compiler. This method gets Fortran compiler specific information from (i) class definition, (ii) environment, (iii) distutils config files, and (iv) command line (later overrides earlier). This method should be always called after constructing a compiler instance. But not in __init__ because Distribution instance is needed for (iii) and (iv). """ log.info('customize %s' % (self.__class__.__name__)) self._is_customised = True self.distutils_vars.use_distribution(dist) self.command_vars.use_distribution(dist) self.flag_vars.use_distribution(dist) self.update_executables() # find_executables takes care of setting the compiler commands, # version_cmd, linker_so, linker_exe, ar, and ranlib self.find_executables() noopt = self.distutils_vars.get('noopt', False) noarch = self.distutils_vars.get('noarch', noopt) debug = self.distutils_vars.get('debug', False) f77 = self.command_vars.compiler_f77 f90 = self.command_vars.compiler_f90 f77flags = [] f90flags = [] freeflags = [] fixflags = [] if f77: f77flags = self.flag_vars.f77 if f90: f90flags = self.flag_vars.f90 freeflags = self.flag_vars.free # XXX Assuming that free format is default for f90 compiler. fix = self.command_vars.compiler_fix if fix: fixflags = self.flag_vars.fix + f90flags oflags, aflags, dflags = [], [], [] # examine get_flags_<tag>_<compiler> for extra flags # only add them if the method is different from get_flags_<tag> def get_flags(tag, flags): # note that self.flag_vars.<tag> calls self.get_flags_<tag>() flags.extend(getattr(self.flag_vars, tag)) this_get = getattr(self, 'get_flags_' + tag) for name, c, flagvar in [('f77', f77, f77flags), ('f90', f90, f90flags), ('f90', fix, fixflags)]: t = '%s_%s' % (tag, name) if c and this_get is not getattr(self, 'get_flags_' + t): flagvar.extend(getattr(self.flag_vars, t)) if not noopt: get_flags('opt', oflags) if not noarch: get_flags('arch', aflags) if debug: get_flags('debug', dflags) fflags = self.flag_vars.flags + dflags + oflags + aflags if f77: self.set_commands(compiler_f77=[f77]+f77flags+fflags) if f90: self.set_commands(compiler_f90=[f90]+freeflags+f90flags+fflags) if fix: self.set_commands(compiler_fix=[fix]+fixflags+fflags) #XXX: Do we need LDSHARED->SOSHARED, LDFLAGS->SOFLAGS linker_so = self.linker_so if linker_so: linker_so_flags = self.flag_vars.linker_so if sys.platform.startswith('aix'): python_lib = get_python_lib(standard_lib=1) ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix') python_exp = os.path.join(python_lib, 'config', 'python.exp') linker_so = [ld_so_aix] + linker_so + ['-bI:'+python_exp] self.set_commands(linker_so=linker_so+linker_so_flags) linker_exe = self.linker_exe if linker_exe: linker_exe_flags = self.flag_vars.linker_exe self.set_commands(linker_exe=linker_exe+linker_exe_flags) ar = self.command_vars.archiver if ar: arflags = self.flag_vars.ar self.set_commands(archiver=[ar]+arflags) self.set_library_dirs(self.get_library_dirs()) self.set_libraries(self.get_libraries()) def dump_properties(self): """Print out the attributes of a compiler instance.""" props = [] for key in list(self.executables.keys()) + \ ['version', 'libraries', 'library_dirs', 'object_switch', 'compile_switch']: if hasattr(self, key): v = getattr(self, key) props.append((key, None, '= '+repr(v))) props.sort() pretty_printer = FancyGetopt(props) for l in pretty_printer.generate_help("%s instance properties:" \ % (self.__class__.__name__)): if l[:4]==' --': l = ' ' + l[4:] print(l) ################### def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): """Compile 'src' to product 'obj'.""" src_flags = {} if is_f_file(src) and not has_f90_header(src): flavor = ':f77' compiler = self.compiler_f77 src_flags = get_f77flags(src) extra_compile_args = self.extra_f77_compile_args or [] elif is_free_format(src): flavor = ':f90' compiler = self.compiler_f90 if compiler is None: raise DistutilsExecError('f90 not supported by %s needed for %s'\ % (self.__class__.__name__, src)) extra_compile_args = self.extra_f90_compile_args or [] else: flavor = ':fix' compiler = self.compiler_fix if compiler is None: raise DistutilsExecError('f90 (fixed) not supported by %s needed for %s'\ % (self.__class__.__name__, src)) extra_compile_args = self.extra_f90_compile_args or [] if self.object_switch[-1]==' ': o_args = [self.object_switch.strip(), obj] else: o_args = [self.object_switch.strip()+obj] assert self.compile_switch.strip() s_args = [self.compile_switch, src] if extra_compile_args: log.info('extra %s options: %r' \ % (flavor[1:], ' '.join(extra_compile_args))) extra_flags = src_flags.get(self.compiler_type, []) if extra_flags: log.info('using compile options from source: %r' \ % ' '.join(extra_flags)) command = compiler + cc_args + extra_flags + s_args + o_args \ + extra_postargs + extra_compile_args display = '%s: %s' % (os.path.basename(compiler[0]) + flavor, src) try: self.spawn(command, display=display) except DistutilsExecError: msg = str(get_exception()) raise CompileError(msg) def module_options(self, module_dirs, module_build_dir): options = [] if self.module_dir_switch is not None: if self.module_dir_switch[-1]==' ': options.extend([self.module_dir_switch.strip(), module_build_dir]) else: options.append(self.module_dir_switch.strip()+module_build_dir) else: print('XXX: module_build_dir=%r option ignored' % (module_build_dir)) print('XXX: Fix module_dir_switch for ', self.__class__.__name__) if self.module_include_switch is not None: for d in [module_build_dir]+module_dirs: options.append('%s%s' % (self.module_include_switch, d)) else: print('XXX: module_dirs=%r option ignored' % (module_dirs)) print('XXX: Fix module_include_switch for ', self.__class__.__name__) return options def library_option(self, lib): return "-l" + lib def library_dir_option(self, dir): return "-L" + dir def link(self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): objects, output_dir = self._fix_object_args(objects, output_dir) libraries, library_dirs, runtime_library_dirs = \ self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries) if is_string(output_dir): output_filename = os.path.join(output_dir, output_filename) elif output_dir is not None: raise TypeError("'output_dir' must be a string or None") if self._need_link(objects, output_filename): if self.library_switch[-1]==' ': o_args = [self.library_switch.strip(), output_filename] else: o_args = [self.library_switch.strip()+output_filename] if is_string(self.objects): ld_args = objects + [self.objects] else: ld_args = objects + self.objects ld_args = ld_args + lib_opts + o_args if debug: ld_args[:0] = ['-g'] if extra_preargs: ld_args[:0] = extra_preargs if extra_postargs: ld_args.extend(extra_postargs) self.mkpath(os.path.dirname(output_filename)) if target_desc == CCompiler.EXECUTABLE: linker = self.linker_exe[:] else: linker = self.linker_so[:] command = linker + ld_args try: self.spawn(command) except DistutilsExecError: msg = str(get_exception()) raise LinkError(msg) else: log.debug("skipping %s (up-to-date)", output_filename) def _environment_hook(self, name, hook_name): if hook_name is None: return None if is_string(hook_name): if hook_name.startswith('self.'): hook_name = hook_name[5:] hook = getattr(self, hook_name) return hook() elif hook_name.startswith('exe.'): hook_name = hook_name[4:] var = self.executables[hook_name] if var: return var[0] else: return None elif hook_name.startswith('flags.'): hook_name = hook_name[6:] hook = getattr(self, 'get_flags_' + hook_name) return hook() else: return hook_name() def can_ccompiler_link(self, ccompiler): """ Check if the given C compiler can link objects produced by this compiler. """ return True def wrap_unlinkable_objects(self, objects, output_dir, extra_dll_dir): """ Convert a set of object files that are not compatible with the default linker, to a file that is compatible. Parameters ---------- objects : list List of object files to include. output_dir : str Output directory to place generated object files. extra_dll_dir : str Output directory to place extra DLL files that need to be included on Windows. Returns ------- converted_objects : list of str List of converted object files. Note that the number of output files is not necessarily the same as inputs. """ raise NotImplementedError() ## class FCompiler _default_compilers = ( # sys.platform mappings ('win32', ('gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem', 'flang')), ('cygwin.*', ('gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95')), ('linux.*', ('gnu95', 'intel', 'lahey', 'pg', 'absoft', 'nag', 'vast', 'compaq', 'intele', 'intelem', 'gnu', 'g95', 'pathf95', 'nagfor')), ('darwin.*', ('gnu95', 'nag', 'absoft', 'ibm', 'intel', 'gnu', 'g95', 'pg')), ('sunos.*', ('sun', 'gnu', 'gnu95', 'g95')), ('irix.*', ('mips', 'gnu', 'gnu95',)), ('aix.*', ('ibm', 'gnu', 'gnu95',)), # os.name mappings ('posix', ('gnu', 'gnu95',)), ('nt', ('gnu', 'gnu95',)), ('mac', ('gnu95', 'gnu', 'pg')), ) fcompiler_class = None fcompiler_aliases = None def load_all_fcompiler_classes(): """Cache all the FCompiler classes found in modules in the numpy.distutils.fcompiler package. """ from glob import glob global fcompiler_class, fcompiler_aliases if fcompiler_class is not None: return pys = os.path.join(os.path.dirname(__file__), '*.py') fcompiler_class = {} fcompiler_aliases = {} for fname in glob(pys): module_name, ext = os.path.splitext(os.path.basename(fname)) module_name = 'numpy.distutils.fcompiler.' + module_name __import__ (module_name) module = sys.modules[module_name] if hasattr(module, 'compilers'): for cname in module.compilers: klass = getattr(module, cname) desc = (klass.compiler_type, klass, klass.description) fcompiler_class[klass.compiler_type] = desc for alias in klass.compiler_aliases: if alias in fcompiler_aliases: raise ValueError("alias %r defined for both %s and %s" % (alias, klass.__name__, fcompiler_aliases[alias][1].__name__)) fcompiler_aliases[alias] = desc def _find_existing_fcompiler(compiler_types, osname=None, platform=None, requiref90=False, c_compiler=None): from numpy.distutils.core import get_distribution dist = get_distribution(always=True) for compiler_type in compiler_types: v = None try: c = new_fcompiler(plat=platform, compiler=compiler_type, c_compiler=c_compiler) c.customize(dist) v = c.get_version() if requiref90 and c.compiler_f90 is None: v = None new_compiler = c.suggested_f90_compiler if new_compiler: log.warn('Trying %r compiler as suggested by %r ' 'compiler for f90 support.' % (compiler_type, new_compiler)) c = new_fcompiler(plat=platform, compiler=new_compiler, c_compiler=c_compiler) c.customize(dist) v = c.get_version() if v is not None: compiler_type = new_compiler if requiref90 and c.compiler_f90 is None: raise ValueError('%s does not support compiling f90 codes, ' 'skipping.' % (c.__class__.__name__)) except DistutilsModuleError: log.debug("_find_existing_fcompiler: compiler_type='%s' raised DistutilsModuleError", compiler_type) except CompilerNotFound: log.debug("_find_existing_fcompiler: compiler_type='%s' not found", compiler_type) if v is not None: return compiler_type return None def available_fcompilers_for_platform(osname=None, platform=None): if osname is None: osname = os.name if platform is None: platform = sys.platform matching_compiler_types = [] for pattern, compiler_type in _default_compilers: if re.match(pattern, platform) or re.match(pattern, osname): for ct in compiler_type: if ct not in matching_compiler_types: matching_compiler_types.append(ct) if not matching_compiler_types: matching_compiler_types.append('gnu') return matching_compiler_types def get_default_fcompiler(osname=None, platform=None, requiref90=False, c_compiler=None): """Determine the default Fortran compiler to use for the given platform.""" matching_compiler_types = available_fcompilers_for_platform(osname, platform) log.info("get_default_fcompiler: matching types: '%s'", matching_compiler_types) compiler_type = _find_existing_fcompiler(matching_compiler_types, osname=osname, platform=platform, requiref90=requiref90, c_compiler=c_compiler) return compiler_type # Flag to avoid rechecking for Fortran compiler every time failed_fcompilers = set() def new_fcompiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0, requiref90=False, c_compiler = None): """Generate an instance of some FCompiler subclass for the supplied platform/compiler combination. """ global failed_fcompilers fcompiler_key = (plat, compiler) if fcompiler_key in failed_fcompilers: return None load_all_fcompiler_classes() if plat is None: plat = os.name if compiler is None: compiler = get_default_fcompiler(plat, requiref90=requiref90, c_compiler=c_compiler) if compiler in fcompiler_class: module_name, klass, long_description = fcompiler_class[compiler] elif compiler in fcompiler_aliases: module_name, klass, long_description = fcompiler_aliases[compiler] else: msg = "don't know how to compile Fortran code on platform '%s'" % plat if compiler is not None: msg = msg + " with '%s' compiler." % compiler msg = msg + " Supported compilers are: %s)" \ % (','.join(fcompiler_class.keys())) log.warn(msg) failed_fcompilers.add(fcompiler_key) return None compiler = klass(verbose=verbose, dry_run=dry_run, force=force) compiler.c_compiler = c_compiler return compiler def show_fcompilers(dist=None): """Print list of available compilers (used by the "--help-fcompiler" option to "config_fc"). """ if dist is None: from distutils.dist import Distribution from numpy.distutils.command.config_compiler import config_fc dist = Distribution() dist.script_name = os.path.basename(sys.argv[0]) dist.script_args = ['config_fc'] + sys.argv[1:] try: dist.script_args.remove('--help-fcompiler') except ValueError: pass dist.cmdclass['config_fc'] = config_fc dist.parse_config_files() dist.parse_command_line() compilers = [] compilers_na = [] compilers_ni = [] if not fcompiler_class: load_all_fcompiler_classes() platform_compilers = available_fcompilers_for_platform() for compiler in platform_compilers: v = None log.set_verbosity(-2) try: c = new_fcompiler(compiler=compiler, verbose=dist.verbose) c.customize(dist) v = c.get_version() except (DistutilsModuleError, CompilerNotFound): e = get_exception() log.debug("show_fcompilers: %s not found" % (compiler,)) log.debug(repr(e)) if v is None: compilers_na.append(("fcompiler="+compiler, None, fcompiler_class[compiler][2])) else: c.dump_properties() compilers.append(("fcompiler="+compiler, None, fcompiler_class[compiler][2] + ' (%s)' % v)) compilers_ni = list(set(fcompiler_class.keys()) - set(platform_compilers)) compilers_ni = [("fcompiler="+fc, None, fcompiler_class[fc][2]) for fc in compilers_ni] compilers.sort() compilers_na.sort() compilers_ni.sort() pretty_printer = FancyGetopt(compilers) pretty_printer.print_help("Fortran compilers found:") pretty_printer = FancyGetopt(compilers_na) pretty_printer.print_help("Compilers available for this " "platform, but not found:") if compilers_ni: pretty_printer = FancyGetopt(compilers_ni) pretty_printer.print_help("Compilers not available on this platform:") print("For compiler details, run 'config_fc --verbose' setup command.") def dummy_fortran_file(): fo, name = make_temp_file(suffix='.f') fo.write(" subroutine dummy()\n end\n") fo.close() return name[:-2] is_f_file = re.compile(r'.*[.](for|ftn|f77|f)\Z', re.I).match _has_f_header = re.compile(r'-[*]-\s*fortran\s*-[*]-', re.I).search _has_f90_header = re.compile(r'-[*]-\s*f90\s*-[*]-', re.I).search _has_fix_header = re.compile(r'-[*]-\s*fix\s*-[*]-', re.I).search _free_f90_start = re.compile(r'[^c*!]\s*[^\s\d\t]', re.I).match def is_free_format(file): """Check if file is in free format Fortran.""" # f90 allows both fixed and free format, assuming fixed unless # signs of free format are detected. result = 0 f = open_latin1(file, 'r') line = f.readline() n = 10000 # the number of non-comment lines to scan for hints if _has_f_header(line): n = 0 elif _has_f90_header(line): n = 0 result = 1 while n>0 and line: line = line.rstrip() if line and line[0]!='!': n -= 1 if (line[0]!='\t' and _free_f90_start(line[:5])) or line[-1:]=='&': result = 1 break line = f.readline() f.close() return result def has_f90_header(src): f = open_latin1(src, 'r') line = f.readline() f.close() return _has_f90_header(line) or _has_fix_header(line) _f77flags_re = re.compile(r'(c|)f77flags\s*\(\s*(?P<fcname>\w+)\s*\)\s*=\s*(?P<fflags>.*)', re.I) def get_f77flags(src): """ Search the first 20 lines of fortran 77 code for line pattern `CF77FLAGS(<fcompiler type>)=<f77 flags>` Return a dictionary {<fcompiler type>:<f77 flags>}. """ flags = {} f = open_latin1(src, 'r') i = 0 for line in f: i += 1 if i>20: break m = _f77flags_re.match(line) if not m: continue fcname = m.group('fcname').strip() fflags = m.group('fflags').strip() flags[fcname] = split_quoted(fflags) f.close() return flags # TODO: implement get_f90flags and use it in _compile similarly to get_f77flags if __name__ == '__main__': show_fcompilers()
39,347
37.538688
112
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/sun.py
from __future__ import division, absolute_import, print_function from numpy.distutils.ccompiler import simple_version_match from numpy.distutils.fcompiler import FCompiler compilers = ['SunFCompiler'] class SunFCompiler(FCompiler): compiler_type = 'sun' description = 'Sun or Forte Fortran 95 Compiler' # ex: # f90: Sun WorkShop 6 update 2 Fortran 95 6.2 Patch 111690-10 2003/08/28 version_match = simple_version_match( start=r'f9[05]: (Sun|Forte|WorkShop).*Fortran 95') executables = { 'version_cmd' : ["<F90>", "-V"], 'compiler_f77' : ["f90"], 'compiler_fix' : ["f90", "-fixed"], 'compiler_f90' : ["f90"], 'linker_so' : ["<F90>", "-Bdynamic", "-G"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } module_dir_switch = '-moddir=' module_include_switch = '-M' pic_flags = ['-xcode=pic32'] def get_flags_f77(self): ret = ["-ftrap=%none"] if (self.get_version() or '') >= '7': ret.append("-f77") else: ret.append("-fixed") return ret def get_opt(self): return ['-fast', '-dalign'] def get_arch(self): return ['-xtarget=generic'] def get_libraries(self): opt = [] opt.extend(['fsu', 'sunmath', 'mvec']) return opt def runtime_library_dir_option(self, dir): return '-R"%s"' % dir if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='sun').get_version())
1,645
29.481481
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/vast.py
from __future__ import division, absolute_import, print_function import os from numpy.distutils.fcompiler.gnu import GnuFCompiler compilers = ['VastFCompiler'] class VastFCompiler(GnuFCompiler): compiler_type = 'vast' compiler_aliases = () description = 'Pacific-Sierra Research Fortran 90 Compiler' version_pattern = (r'\s*Pacific-Sierra Research vf90 ' r'(Personal|Professional)\s+(?P<version>[^\s]*)') # VAST f90 does not support -o with -c. So, object files are created # to the current directory and then moved to build directory object_switch = ' && function _mvfile { mv -v `basename $1` $1 ; } && _mvfile ' executables = { 'version_cmd' : ["vf90", "-v"], 'compiler_f77' : ["g77"], 'compiler_fix' : ["f90", "-Wv,-ya"], 'compiler_f90' : ["f90"], 'linker_so' : ["<F90>"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } module_dir_switch = None #XXX Fix me module_include_switch = None #XXX Fix me def find_executables(self): pass def get_version_cmd(self): f90 = self.compiler_f90[0] d, b = os.path.split(f90) vf90 = os.path.join(d, 'v'+b) return vf90 def get_flags_arch(self): vast_version = self.get_version() gnu = GnuFCompiler() gnu.customize(None) self.version = gnu.get_version() opt = GnuFCompiler.get_flags_arch(self) self.version = vast_version return opt if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='vast').get_version())
1,733
30.527273
83
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/hpux.py
from __future__ import division, absolute_import, print_function from numpy.distutils.fcompiler import FCompiler compilers = ['HPUXFCompiler'] class HPUXFCompiler(FCompiler): compiler_type = 'hpux' description = 'HP Fortran 90 Compiler' version_pattern = r'HP F90 (?P<version>[^\s*,]*)' executables = { 'version_cmd' : ["f90", "+version"], 'compiler_f77' : ["f90"], 'compiler_fix' : ["f90"], 'compiler_f90' : ["f90"], 'linker_so' : ["ld", "-b"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } module_dir_switch = None #XXX: fix me module_include_switch = None #XXX: fix me pic_flags = ['+Z'] def get_flags(self): return self.pic_flags + ['+ppu', '+DD64'] def get_flags_opt(self): return ['-O3'] def get_libraries(self): return ['m'] def get_library_dirs(self): opt = ['/usr/lib/hpux64'] return opt def get_version(self, force=0, ok_status=[256, 0, 1]): # XXX status==256 may indicate 'unrecognized option' or # 'no input file'. So, version_cmd needs more work. return FCompiler.get_version(self, force, ok_status) if __name__ == '__main__': from distutils import log log.set_verbosity(10) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='hpux').get_version())
1,419
31.272727
64
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/distutils/fcompiler/pathf95.py
from __future__ import division, absolute_import, print_function from numpy.distutils.fcompiler import FCompiler compilers = ['PathScaleFCompiler'] class PathScaleFCompiler(FCompiler): compiler_type = 'pathf95' description = 'PathScale Fortran Compiler' version_pattern = r'PathScale\(TM\) Compiler Suite: Version (?P<version>[\d.]+)' executables = { 'version_cmd' : ["pathf95", "-version"], 'compiler_f77' : ["pathf95", "-fixedform"], 'compiler_fix' : ["pathf95", "-fixedform"], 'compiler_f90' : ["pathf95"], 'linker_so' : ["pathf95", "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } pic_flags = ['-fPIC'] module_dir_switch = '-module ' # Don't remove ending space! module_include_switch = '-I' def get_flags_opt(self): return ['-O3'] def get_flags_debug(self): return ['-g'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='pathf95').get_version())
1,127
30.333333
85
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/testing/setup.py
#!/usr/bin/env python from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('testing', parent_package, top_path) config.add_subpackage('nose_tools') config.add_data_dir('tests') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(maintainer="NumPy Developers", maintainer_email="[email protected]", description="NumPy test module", url="http://www.numpy.org", license="NumPy License (BSD Style)", configuration=configuration, )
677
29.818182
63
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/testing/noseclasses.py
""" Back compatibility noseclasses module. It will import the appropriate set of tools """ from .nose_tools.noseclasses import *
130
17.714286
69
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/numpy/testing/utils.py
""" Back compatibility utils module. It will import the appropriate set of tools """ __all__ = [ 'assert_equal', 'assert_almost_equal', 'assert_approx_equal', 'assert_array_equal', 'assert_array_less', 'assert_string_equal', 'assert_array_almost_equal', 'assert_raises', 'build_err_msg', 'decorate_methods', 'jiffies', 'memusage', 'print_assert_equal', 'raises', 'rand', 'rundocs', 'runstring', 'verbose', 'measure', 'assert_', 'assert_array_almost_equal_nulp', 'assert_raises_regex', 'assert_array_max_ulp', 'assert_warns', 'assert_no_warnings', 'assert_allclose', 'IgnoreException', 'clear_and_catch_warnings', 'SkipTest', 'KnownFailureException', 'temppath', 'tempdir', 'IS_PYPY', 'HAS_REFCOUNT', 'suppress_warnings', 'assert_array_compare', '_assert_valid_refcount', '_gen_alignment_data', ] from .nose_tools.utils import *
926
43.142857
78
py