diff options
Diffstat (limited to 'numpy/core')
41 files changed, 2595 insertions, 2595 deletions
diff --git a/numpy/core/__init__.py b/numpy/core/__init__.py index 50af6e548..79bc72a8c 100644 --- a/numpy/core/__init__.py +++ b/numpy/core/__init__.py @@ -32,7 +32,7 @@ from .fromnumeric import amax as max, amin as min, \ round_ as round from .numeric import absolute as abs -__all__ = ['char','rec','memmap'] +__all__ = ['char', 'rec', 'memmap'] __all__ += numeric.__all__ __all__ += fromnumeric.__all__ __all__ += rec.__all__ @@ -58,7 +58,7 @@ def _ufunc_reconstruct(module, name): def _ufunc_reduce(func): from pickle import whichmodule name = func.__name__ - return _ufunc_reconstruct, (whichmodule(func,name), name) + return _ufunc_reconstruct, (whichmodule(func, name), name) import sys diff --git a/numpy/core/_internal.py b/numpy/core/_internal.py index 8046de149..d32f59390 100644 --- a/numpy/core/_internal.py +++ b/numpy/core/_internal.py @@ -24,7 +24,7 @@ def _makenames_list(adict, align): for fname in fnames: obj = adict[fname] n = len(obj) - if not isinstance(obj, tuple) or n not in [2,3]: + if not isinstance(obj, tuple) or n not in [2, 3]: raise ValueError("entry not a 2- or 3- tuple") if (n > 2) and (obj[2] == fname): continue @@ -108,10 +108,10 @@ def _array_descr(descriptor): for field in ordered_fields: if field[1] > offset: num = field[1] - offset - result.append(('','|V%d' % num)) + result.append(('', '|V%d' % num)) offset += num if len(field) > 3: - name = (field[2],field[3]) + name = (field[2], field[3]) else: name = field[2] if field[0].subdtype: diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index 18b008a3f..db491e6f5 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -214,7 +214,7 @@ def _leading_trailing(a): l = [_leading_trailing(a[i]) for i in range( min(len(a), _summaryEdgeItems))] l.extend([_leading_trailing(a[-i]) for i in range( - min(len(a), _summaryEdgeItems),0,-1)]) + min(len(a), _summaryEdgeItems), 0, -1)]) else: l = [_leading_trailing(a[i]) for i in range(0, len(a))] b = _nc.concatenate(tuple(l)) @@ -510,7 +510,7 @@ def _formatArray(a, format_function, rank, max_line_len, s += _formatArray(a[i], format_function, rank-1, max_line_len, " " + next_line_prefix, separator, edge_items, summary_insert) - s = s.rstrip() + sep.rstrip() + '\n'*max(rank-1,1) + s = s.rstrip() + sep.rstrip() + '\n'*max(rank-1, 1) if summary_insert1: s += next_line_prefix + summary_insert1 + "\n" @@ -521,7 +521,7 @@ def _formatArray(a, format_function, rank, max_line_len, s += _formatArray(a[-i], format_function, rank-1, max_line_len, " " + next_line_prefix, separator, edge_items, summary_insert) - s = s.rstrip() + sep.rstrip() + '\n'*max(rank-1,1) + s = s.rstrip() + sep.rstrip() + '\n'*max(rank-1, 1) if leading_items or trailing_items > 1: s += next_line_prefix s += _formatArray(a[-1], format_function, rank-1, max_line_len, diff --git a/numpy/core/code_generators/genapi.py b/numpy/core/code_generators/genapi.py index 62e4f9fc8..ad054920a 100644 --- a/numpy/core/code_generators/genapi.py +++ b/numpy/core/code_generators/genapi.py @@ -72,7 +72,7 @@ def remove_whitespace(s): return ''.join(s.split()) def _repl(str): - return str.replace('Bool','npy_bool') + return str.replace('Bool', 'npy_bool') class Function(object): def __init__(self, name, return_type, args, doc=''): diff --git a/numpy/core/code_generators/generate_umath.py b/numpy/core/code_generators/generate_umath.py index 1bc22d777..e02cb8709 100644 --- a/numpy/core/code_generators/generate_umath.py +++ b/numpy/core/code_generators/generate_umath.py @@ -237,7 +237,7 @@ for code in 'bhilq': # an object which expands a list of character codes into an array of # TypeDescriptions. defdict = { -'add' : +'add': Ufunc(2, 1, Zero, docstrings.get('numpy.core.umath.add'), 'PyUFunc_AdditionTypeResolver', @@ -248,7 +248,7 @@ defdict = { ], TD(O, f='PyNumber_Add'), ), -'subtract' : +'subtract': Ufunc(2, 1, None, # Zero is only a unit to the right, not the left docstrings.get('numpy.core.umath.subtract'), 'PyUFunc_SubtractionTypeResolver', @@ -259,7 +259,7 @@ defdict = { ], TD(O, f='PyNumber_Subtract'), ), -'multiply' : +'multiply': Ufunc(2, 1, One, docstrings.get('numpy.core.umath.multiply'), 'PyUFunc_MultiplicationTypeResolver', @@ -271,7 +271,7 @@ defdict = { ], TD(O, f='PyNumber_Multiply'), ), -'divide' : +'divide': Ufunc(2, 1, None, # One is only a unit to the right, not the left docstrings.get('numpy.core.umath.divide'), 'PyUFunc_DivisionTypeResolver', @@ -282,7 +282,7 @@ defdict = { ], TD(O, f='PyNumber_Divide'), ), -'floor_divide' : +'floor_divide': Ufunc(2, 1, None, # One is only a unit to the right, not the left docstrings.get('numpy.core.umath.floor_divide'), 'PyUFunc_DivisionTypeResolver', @@ -293,7 +293,7 @@ defdict = { ], TD(O, f='PyNumber_FloorDivide'), ), -'true_divide' : +'true_divide': Ufunc(2, 1, None, # One is only a unit to the right, not the left docstrings.get('numpy.core.umath.true_divide'), 'PyUFunc_DivisionTypeResolver', @@ -306,14 +306,14 @@ defdict = { ], TD(O, f='PyNumber_TrueDivide'), ), -'conjugate' : +'conjugate': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.conjugate'), None, TD(ints+flts+cmplx), TD(P, f='conjugate'), ), -'fmod' : +'fmod': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.fmod'), None, @@ -321,14 +321,14 @@ defdict = { TD(flts, f='fmod', astype={'e':'f'}), TD(P, f='fmod'), ), -'square' : +'square': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.square'), None, TD(ints+inexact), TD(O, f='Py_square'), ), -'reciprocal' : +'reciprocal': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.reciprocal'), None, @@ -337,14 +337,14 @@ defdict = { ), # This is no longer used as numpy.ones_like, however it is # still used by some internal calls. -'_ones_like' : +'_ones_like': Ufunc(1, 1, None, docstrings.get('numpy.core.umath._ones_like'), 'PyUFunc_OnesLikeTypeResolver', TD(noobj), TD(O, f='Py_get_one'), ), -'power' : +'power': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.power'), None, @@ -352,7 +352,7 @@ defdict = { TD(inexact, f='pow', astype={'e':'f'}), TD(O, f='npy_ObjectPower'), ), -'absolute' : +'absolute': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.absolute'), 'PyUFunc_AbsoluteTypeResolver', @@ -360,13 +360,13 @@ defdict = { TD(cmplx, out=('f', 'd', 'g')), TD(O, f='PyNumber_Absolute'), ), -'_arg' : +'_arg': Ufunc(1, 1, None, docstrings.get('numpy.core.umath._arg'), None, TD(cmplx, out=('f', 'd', 'g')), ), -'negative' : +'negative': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.negative'), 'PyUFunc_SimpleUnaryOperationTypeResolver', @@ -374,316 +374,316 @@ defdict = { TD(cmplx, f='neg'), TD(O, f='PyNumber_Negative'), ), -'sign' : +'sign': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.sign'), 'PyUFunc_SimpleUnaryOperationTypeResolver', TD(nobool_or_datetime), ), -'greater' : +'greater': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.greater'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(all, out='?'), ), -'greater_equal' : +'greater_equal': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.greater_equal'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(all, out='?'), ), -'less' : +'less': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.less'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(all, out='?'), ), -'less_equal' : +'less_equal': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.less_equal'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(all, out='?'), ), -'equal' : +'equal': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.equal'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(all, out='?'), ), -'not_equal' : +'not_equal': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.not_equal'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(all, out='?'), ), -'logical_and' : +'logical_and': Ufunc(2, 1, One, docstrings.get('numpy.core.umath.logical_and'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(nodatetime_or_obj, out='?'), TD(O, f='npy_ObjectLogicalAnd'), ), -'logical_not' : +'logical_not': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.logical_not'), None, TD(nodatetime_or_obj, out='?'), TD(O, f='npy_ObjectLogicalNot'), ), -'logical_or' : +'logical_or': Ufunc(2, 1, Zero, docstrings.get('numpy.core.umath.logical_or'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(nodatetime_or_obj, out='?'), TD(O, f='npy_ObjectLogicalOr'), ), -'logical_xor' : +'logical_xor': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.logical_xor'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(nodatetime_or_obj, out='?'), TD(P, f='logical_xor'), ), -'maximum' : +'maximum': Ufunc(2, 1, ReorderableNone, docstrings.get('numpy.core.umath.maximum'), 'PyUFunc_SimpleBinaryOperationTypeResolver', TD(noobj), TD(O, f='npy_ObjectMax') ), -'minimum' : +'minimum': Ufunc(2, 1, ReorderableNone, docstrings.get('numpy.core.umath.minimum'), 'PyUFunc_SimpleBinaryOperationTypeResolver', TD(noobj), TD(O, f='npy_ObjectMin') ), -'fmax' : +'fmax': Ufunc(2, 1, ReorderableNone, docstrings.get('numpy.core.umath.fmax'), 'PyUFunc_SimpleBinaryOperationTypeResolver', TD(noobj), TD(O, f='npy_ObjectMax') ), -'fmin' : +'fmin': Ufunc(2, 1, ReorderableNone, docstrings.get('numpy.core.umath.fmin'), 'PyUFunc_SimpleBinaryOperationTypeResolver', TD(noobj), TD(O, f='npy_ObjectMin') ), -'logaddexp' : +'logaddexp': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.logaddexp'), None, TD(flts, f="logaddexp", astype={'e':'f'}) ), -'logaddexp2' : +'logaddexp2': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.logaddexp2'), None, TD(flts, f="logaddexp2", astype={'e':'f'}) ), -'bitwise_and' : +'bitwise_and': Ufunc(2, 1, One, docstrings.get('numpy.core.umath.bitwise_and'), None, TD(bints), TD(O, f='PyNumber_And'), ), -'bitwise_or' : +'bitwise_or': Ufunc(2, 1, Zero, docstrings.get('numpy.core.umath.bitwise_or'), None, TD(bints), TD(O, f='PyNumber_Or'), ), -'bitwise_xor' : +'bitwise_xor': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.bitwise_xor'), None, TD(bints), TD(O, f='PyNumber_Xor'), ), -'invert' : +'invert': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.invert'), None, TD(bints), TD(O, f='PyNumber_Invert'), ), -'left_shift' : +'left_shift': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.left_shift'), None, TD(ints), TD(O, f='PyNumber_Lshift'), ), -'right_shift' : +'right_shift': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.right_shift'), None, TD(ints), TD(O, f='PyNumber_Rshift'), ), -'degrees' : +'degrees': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.degrees'), None, TD(fltsP, f='degrees', astype={'e':'f'}), ), -'rad2deg' : +'rad2deg': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.rad2deg'), None, TD(fltsP, f='rad2deg', astype={'e':'f'}), ), -'radians' : +'radians': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.radians'), None, TD(fltsP, f='radians', astype={'e':'f'}), ), -'deg2rad' : +'deg2rad': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.deg2rad'), None, TD(fltsP, f='deg2rad', astype={'e':'f'}), ), -'arccos' : +'arccos': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.arccos'), None, TD(inexact, f='acos', astype={'e':'f'}), TD(P, f='arccos'), ), -'arccosh' : +'arccosh': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.arccosh'), None, TD(inexact, f='acosh', astype={'e':'f'}), TD(P, f='arccosh'), ), -'arcsin' : +'arcsin': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.arcsin'), None, TD(inexact, f='asin', astype={'e':'f'}), TD(P, f='arcsin'), ), -'arcsinh' : +'arcsinh': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.arcsinh'), None, TD(inexact, f='asinh', astype={'e':'f'}), TD(P, f='arcsinh'), ), -'arctan' : +'arctan': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.arctan'), None, TD(inexact, f='atan', astype={'e':'f'}), TD(P, f='arctan'), ), -'arctanh' : +'arctanh': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.arctanh'), None, TD(inexact, f='atanh', astype={'e':'f'}), TD(P, f='arctanh'), ), -'cos' : +'cos': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.cos'), None, TD(inexact, f='cos', astype={'e':'f'}), TD(P, f='cos'), ), -'sin' : +'sin': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.sin'), None, TD(inexact, f='sin', astype={'e':'f'}), TD(P, f='sin'), ), -'tan' : +'tan': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.tan'), None, TD(inexact, f='tan', astype={'e':'f'}), TD(P, f='tan'), ), -'cosh' : +'cosh': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.cosh'), None, TD(inexact, f='cosh', astype={'e':'f'}), TD(P, f='cosh'), ), -'sinh' : +'sinh': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.sinh'), None, TD(inexact, f='sinh', astype={'e':'f'}), TD(P, f='sinh'), ), -'tanh' : +'tanh': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.tanh'), None, TD(inexact, f='tanh', astype={'e':'f'}), TD(P, f='tanh'), ), -'exp' : +'exp': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.exp'), None, TD(inexact, f='exp', astype={'e':'f'}), TD(P, f='exp'), ), -'exp2' : +'exp2': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.exp2'), None, TD(inexact, f='exp2', astype={'e':'f'}), TD(P, f='exp2'), ), -'expm1' : +'expm1': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.expm1'), None, TD(inexact, f='expm1', astype={'e':'f'}), TD(P, f='expm1'), ), -'log' : +'log': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.log'), None, TD(inexact, f='log', astype={'e':'f'}), TD(P, f='log'), ), -'log2' : +'log2': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.log2'), None, TD(inexact, f='log2', astype={'e':'f'}), TD(P, f='log2'), ), -'log10' : +'log10': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.log10'), None, TD(inexact, f='log10', astype={'e':'f'}), TD(P, f='log10'), ), -'log1p' : +'log1p': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.log1p'), None, TD(inexact, f='log1p', astype={'e':'f'}), TD(P, f='log1p'), ), -'sqrt' : +'sqrt': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.sqrt'), None, @@ -691,105 +691,105 @@ defdict = { TD(inexact, f='sqrt', astype={'e':'f'}), TD(P, f='sqrt'), ), -'ceil' : +'ceil': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.ceil'), None, TD(flts, f='ceil', astype={'e':'f'}), TD(P, f='ceil'), ), -'trunc' : +'trunc': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.trunc'), None, TD(flts, f='trunc', astype={'e':'f'}), TD(P, f='trunc'), ), -'fabs' : +'fabs': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.fabs'), None, TD(flts, f='fabs', astype={'e':'f'}), TD(P, f='fabs'), ), -'floor' : +'floor': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.floor'), None, TD(flts, f='floor', astype={'e':'f'}), TD(P, f='floor'), ), -'rint' : +'rint': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.rint'), None, TD(inexact, f='rint', astype={'e':'f'}), TD(P, f='rint'), ), -'arctan2' : +'arctan2': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.arctan2'), None, TD(flts, f='atan2', astype={'e':'f'}), TD(P, f='arctan2'), ), -'remainder' : +'remainder': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.remainder'), None, TD(intflt), TD(O, f='PyNumber_Remainder'), ), -'hypot' : +'hypot': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.hypot'), None, TD(flts, f='hypot', astype={'e':'f'}), TD(P, f='hypot'), ), -'isnan' : +'isnan': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.isnan'), None, TD(inexact, out='?'), ), -'isinf' : +'isinf': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.isinf'), None, TD(inexact, out='?'), ), -'isfinite' : +'isfinite': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.isfinite'), None, TD(inexact, out='?'), ), -'signbit' : +'signbit': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.signbit'), None, TD(flts, out='?'), ), -'copysign' : +'copysign': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.copysign'), None, TD(flts), ), -'nextafter' : +'nextafter': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.nextafter'), None, TD(flts), ), -'spacing' : +'spacing': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.spacing'), None, TD(flts), ), -'modf' : +'modf': Ufunc(1, 2, None, docstrings.get('numpy.core.umath.modf'), None, @@ -801,11 +801,11 @@ if sys.version_info[0] >= 3: # Will be aliased to true_divide in umathmodule.c.src:InitOtherOperators del defdict['divide'] -def indent(st,spaces): +def indent(st, spaces): indention = ' '*spaces - indented = indention + st.replace('\n','\n'+indention) + indented = indention + st.replace('\n', '\n'+indention) # trim off any trailing spaces - indented = re.sub(r' +$',r'',indented) + indented = re.sub(r' +$', r'', indented) return indented chartotype1 = {'e': 'e_e', @@ -899,7 +899,7 @@ def make_arrays(funcdict): % (name, datanames)) code1list.append("static char %s_signatures[] = { %s };" \ % (name, signames)) - return "\n".join(code1list),"\n".join(code2list) + return "\n".join(code1list), "\n".join(code2list) def make_ufuncs(funcdict): code3list = [] @@ -939,11 +939,11 @@ r"""f = PyUFunc_FromFuncAndData(%s_functions, %s_data, %s_signatures, %d, return '\n'.join(code3list) -def make_code(funcdict,filename): +def make_code(funcdict, filename): code1, code2 = make_arrays(funcdict) code3 = make_ufuncs(funcdict) - code2 = indent(code2,4) - code3 = indent(code3,4) + code2 = indent(code2, 4) + code3 = indent(code3, 4) code = r""" /** Warning this file is autogenerated!!! @@ -966,7 +966,7 @@ InitOperators(PyObject *dictionary) { if __name__ == "__main__": filename = __file__ - fid = open('__umath_generated.c','w') + fid = open('__umath_generated.c', 'w') code = make_code(defdict, filename) fid.write(code) fid.close() diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index 1af1fea16..ca18d64ea 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -40,7 +40,7 @@ def _wrapit(obj, method, *args, **kwds): wrap = obj.__array_wrap__ except AttributeError: wrap = None - result = getattr(asarray(obj),method)(*args, **kwds) + result = getattr(asarray(obj), method)(*args, **kwds) if wrap: if not isinstance(result, mu.ndarray): result = asarray(result) @@ -2239,7 +2239,7 @@ def alen(a): try: return len(a) except TypeError: - return len(array(a,ndmin=1)) + return len(array(a, ndmin=1)) def prod(a, axis=None, dtype=None, out=None, keepdims=False): diff --git a/numpy/core/function_base.py b/numpy/core/function_base.py index f198ab3b8..f2c895608 100644 --- a/numpy/core/function_base.py +++ b/numpy/core/function_base.py @@ -164,5 +164,5 @@ def logspace(start,stop,num=50,endpoint=True,base=10.0): >>> plt.show() """ - y = linspace(start,stop,num=num,endpoint=endpoint) - return _nx.power(base,y) + y = linspace(start, stop, num=num, endpoint=endpoint) + return _nx.power(base, y) diff --git a/numpy/core/getlimits.py b/numpy/core/getlimits.py index 93210a23b..165ea6860 100644 --- a/numpy/core/getlimits.py +++ b/numpy/core/getlimits.py @@ -3,7 +3,7 @@ """ from __future__ import division, absolute_import, print_function -__all__ = ['finfo','iinfo'] +__all__ = ['finfo', 'iinfo'] from .machar import MachAr from . import numeric @@ -97,7 +97,7 @@ class finfo(object): # In case a float instance was given dtype = numeric.dtype(type(dtype)) - obj = cls._finfo_cache.get(dtype,None) + obj = cls._finfo_cache.get(dtype, None) if obj is not None: return obj dtypes = [dtype] @@ -107,7 +107,7 @@ class finfo(object): dtype = newdtype if not issubclass(dtype, numeric.inexact): raise ValueError("data type %r not inexact" % (dtype)) - obj = cls._finfo_cache.get(dtype,None) + obj = cls._finfo_cache.get(dtype, None) if obj is not None: return obj if not issubclass(dtype, numeric.floating): @@ -115,7 +115,7 @@ class finfo(object): if newdtype is not dtype: dtypes.append(newdtype) dtype = newdtype - obj = cls._finfo_cache.get(dtype,None) + obj = cls._finfo_cache.get(dtype, None) if obj is not None: return obj obj = object.__new__(cls)._init(dtype) @@ -151,11 +151,11 @@ class finfo(object): 'numpy %s precision floating point number' % precname) for word in ['precision', 'iexp', - 'maxexp','minexp','negep', + 'maxexp', 'minexp', 'negep', 'machep']: - setattr(self,word,getattr(machar, word)) - for word in ['tiny','resolution','epsneg']: - setattr(self,word,getattr(machar, word).flat[0]) + setattr(self, word, getattr(machar, word)) + for word in ['tiny', 'resolution', 'epsneg']: + setattr(self, word, getattr(machar, word).flat[0]) self.max = machar.huge.flat[0] self.min = -self.max self.eps = machar.eps.flat[0] @@ -296,11 +296,11 @@ max = %(max)s if __name__ == '__main__': f = finfo(ntypes.single) - print('single epsilon:',f.eps) - print('single tiny:',f.tiny) + print('single epsilon:', f.eps) + print('single tiny:', f.tiny) f = finfo(ntypes.float) - print('float epsilon:',f.eps) - print('float tiny:',f.tiny) + print('float epsilon:', f.eps) + print('float tiny:', f.tiny) f = finfo(ntypes.longfloat) - print('longfloat epsilon:',f.eps) - print('longfloat tiny:',f.tiny) + print('longfloat epsilon:', f.eps) + print('longfloat tiny:', f.tiny) diff --git a/numpy/core/memmap.py b/numpy/core/memmap.py index 53662ce89..bd99a1374 100644 --- a/numpy/core/memmap.py +++ b/numpy/core/memmap.py @@ -11,7 +11,7 @@ from numpy.compat import long, basestring dtypedescr = dtype valid_filemodes = ["r", "c", "r+", "w+"] -writeable_filemodes = ["r+","w+"] +writeable_filemodes = ["r+", "w+"] mode_equivalents = { "readonly":"r", @@ -204,7 +204,7 @@ class memmap(ndarray): raise ValueError("mode must be one of %s" % (valid_filemodes + list(mode_equivalents.keys()))) - if hasattr(filename,'read'): + if hasattr(filename, 'read'): fid = filename own_file = False else: diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index e2c020ced..1b3d5d5a8 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -866,9 +866,9 @@ for NumPy 2.0. The new behavior fits the conventional definition of correlation: inputs are never swapped, and the second argument is conjugated for complex arrays.""", DeprecationWarning) - return multiarray.correlate(a,v,mode) + return multiarray.correlate(a, v, mode) else: - return multiarray.correlate2(a,v,mode) + return multiarray.correlate2(a, v, mode) def convolve(a,v,mode='full'): """ @@ -953,7 +953,7 @@ def convolve(a,v,mode='full'): array([ 2.5]) """ - a,v = array(a, ndmin=1),array(v, ndmin=1) + a, v = array(a, ndmin=1), array(v, ndmin=1) if (len(v) > len(a)): a, v = v, a if len(a) == 0 : @@ -963,7 +963,7 @@ def convolve(a,v,mode='full'): mode = _mode_from_name(mode) return multiarray.correlate(a, v[::-1], mode) -def outer(a,b): +def outer(a, b): """ Compute the outer product of two vectors. @@ -1037,7 +1037,7 @@ def outer(a,b): """ a = asarray(a) b = asarray(b) - return a.ravel()[:,newaxis]*b.ravel()[newaxis,:] + return a.ravel()[:, newaxis]*b.ravel()[newaxis,:] # try to import blas optimized dot if available try: @@ -1169,8 +1169,8 @@ def tensordot(a, b, axes=2): try: iter(axes) except: - axes_a = list(range(-axes,0)) - axes_b = list(range(0,axes)) + axes_a = list(range(-axes, 0)) + axes_b = list(range(0, axes)) else: axes_a, axes_b = axes try: @@ -1346,7 +1346,7 @@ def rollaxis(a, axis, start=0): start -= 1 if axis==start: return a - axes = list(range(0,n)) + axes = list(range(0, n)) axes.remove(axis) axes.insert(start, axis) return a.transpose(axes) @@ -1462,12 +1462,12 @@ def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): """ if axis is not None: - axisa,axisb,axisc=(axis,)*3 + axisa, axisb, axisc=(axis,)*3 a = asarray(a).swapaxes(axisa, 0) b = asarray(b).swapaxes(axisb, 0) msg = "incompatible dimensions for cross product\n"\ "(dimension must be 2 or 3)" - if (a.shape[0] not in [2,3]) or (b.shape[0] not in [2,3]): + if (a.shape[0] not in [2, 3]) or (b.shape[0] not in [2, 3]): raise ValueError(msg) if a.shape[0] == 2: if (b.shape[0] == 2): @@ -1489,11 +1489,11 @@ def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): x = -a[2]*b[1] y = a[2]*b[0] z = a[0]*b[1] - a[1]*b[0] - cp = array([x,y,z]) + cp = array([x, y, z]) if cp.ndim == 1: return cp else: - return cp.swapaxes(0,axisc) + return cp.swapaxes(0, axisc) #Use numarray's printing function @@ -1742,10 +1742,10 @@ def indices(dimensions, dtype=int): dimensions = tuple(dimensions) N = len(dimensions) if N == 0: - return array([],dtype=dtype) + return array([], dtype=dtype) res = empty((N,)+dimensions, dtype=dtype) for i, dim in enumerate(dimensions): - tmp = arange(dim,dtype=dtype) + tmp = arange(dim, dtype=dtype) tmp.shape = (1,)*i + (dim,)+(1,)*(N-i-1) newdim = dimensions[:i] + (1,)+ dimensions[i+1:] val = zeros(newdim, dtype) @@ -2019,7 +2019,7 @@ def _maketup(descr, val): if fields is None: return val else: - res = [_maketup(fields[name][0],val) for name in dt.names] + res = [_maketup(fields[name][0], val) for name in dt.names] return tuple(res) def identity(n, dtype=None): @@ -2699,7 +2699,7 @@ class errstate(object): # Note that we don't want to run the above doctests because they will fail # without a from __future__ import with_statement def __init__(self, **kwargs): - self.call = kwargs.pop('call',_Unspecified) + self.call = kwargs.pop('call', _Unspecified) self.kwargs = kwargs def __enter__(self): diff --git a/numpy/core/numerictypes.py b/numpy/core/numerictypes.py index 1a5f31e4e..8dc4ca75e 100644 --- a/numpy/core/numerictypes.py +++ b/numpy/core/numerictypes.py @@ -86,7 +86,7 @@ from __future__ import division, absolute_import, print_function __all__ = ['sctypeDict', 'sctypeNA', 'typeDict', 'typeNA', 'sctypes', 'ScalarType', 'obj2sctype', 'cast', 'nbytes', 'sctype2char', 'maximum_sctype', 'issctype', 'typecodes', 'find_common_type', - 'issubdtype', 'datetime_data','datetime_as_string', + 'issubdtype', 'datetime_data', 'datetime_as_string', 'busday_offset', 'busday_count', 'is_busday', 'busdaycalendar', ] @@ -436,7 +436,7 @@ def _construct_char_code_lookup(): for name in typeinfo.keys(): tup = typeinfo[name] if isinstance(tup, tuple): - if tup[0] not in ['p','P']: + if tup[0] not in ['p', 'P']: _sctype2char_dict[tup[-1]] = tup[0] _construct_char_code_lookup() @@ -445,7 +445,7 @@ sctypes = {'int': [], 'uint':[], 'float':[], 'complex':[], - 'others':[bool,object,str,unicode,void]} + 'others':[bool, object, str, unicode, void]} def _add_array_type(typename, bits): try: @@ -541,7 +541,7 @@ except AttributeError: # Py3K buffer_type = memoryview -_python_types = {int : 'int_', +_python_types = {int: 'int_', float: 'float_', complex: 'complex_', bool: 'bool_', @@ -871,7 +871,7 @@ for key in _sctype2char_dict.keys(): if issubclass(key, allTypes['flexible']): _typestr[key] = _sctype2char_dict[key] else: - _typestr[key] = empty((1,),key).dtype.str[1:] + _typestr[key] = empty((1,), key).dtype.str[1:] # Make sure all typestrings are in sctypeDict for key, val in _typestr.items(): @@ -942,7 +942,7 @@ def _find_common_coerce(a, b): thisind = __test_types.index(a.char) except ValueError: return None - return _can_coerce_all([a,b], start=thisind) + return _can_coerce_all([a, b], start=thisind) # Find a data-type that all data-types in a list can be coerced to def _can_coerce_all(dtypelist, start=0): @@ -1030,6 +1030,6 @@ def find_common_type(array_types, scalar_types): return None if index_sc > index_a: - return _find_common_coerce(maxsc,maxa) + return _find_common_coerce(maxsc, maxa) else: return maxa diff --git a/numpy/core/setup.py b/numpy/core/setup.py index 03d26c2b6..3937b2374 100644 --- a/numpy/core/setup.py +++ b/numpy/core/setup.py @@ -360,10 +360,10 @@ def check_types(config_cmd, ext, build_dir): def check_mathlib(config_cmd): # Testing the C math library mathlibs = [] - mathlibs_choices = [[],['m'],['cpml']] + mathlibs_choices = [[], ['m'], ['cpml']] mathlib = os.environ.get('MATHLIB') if mathlib: - mathlibs_choices.insert(0,mathlib.split(',')) + mathlibs_choices.insert(0, mathlib.split(',')) for libs in mathlibs_choices: if config_cmd.check_func("exp", libraries=libs, decl=True, call=True): mathlibs = libs @@ -383,12 +383,12 @@ def visibility_define(config): return '' def configuration(parent_package='',top_path=None): - from numpy.distutils.misc_util import Configuration,dot_join + from numpy.distutils.misc_util import Configuration, dot_join from numpy.distutils.system_info import get_info, default_lib_dirs - config = Configuration('core',parent_package,top_path) + config = Configuration('core', parent_package, top_path) local_dir = config.local_path - codegen_dir = join(local_dir,'code_generators') + codegen_dir = join(local_dir, 'code_generators') if is_released(config): warnings.simplefilter('error', MismatchCAPIWarning) @@ -397,32 +397,32 @@ def configuration(parent_package='',top_path=None): # actual C API VERSION check_api_version(C_API_VERSION, codegen_dir) - generate_umath_py = join(codegen_dir,'generate_umath.py') - n = dot_join(config.name,'generate_umath') + generate_umath_py = join(codegen_dir, 'generate_umath.py') + n = dot_join(config.name, 'generate_umath') generate_umath = imp.load_module('_'.join(n.split('.')), - open(generate_umath_py,'U'),generate_umath_py, - ('.py','U',1)) + open(generate_umath_py, 'U'), generate_umath_py, + ('.py', 'U', 1)) header_dir = 'include/numpy' # this is relative to config.path_in_package cocache = CallOnceOnly() def generate_config_h(ext, build_dir): - target = join(build_dir,header_dir,'config.h') + target = join(build_dir, header_dir, 'config.h') d = os.path.dirname(target) if not os.path.exists(d): os.makedirs(d) - if newer(__file__,target): + if newer(__file__, target): config_cmd = config.get_config_cmd() - log.info('Generating %s',target) + log.info('Generating %s', target) # Check sizeof moredefs, ignored = cocache.check_types(config_cmd, ext, build_dir) # Check math library and C99 math funcs availability mathlibs = check_mathlib(config_cmd) - moredefs.append(('MATHLIB',','.join(mathlibs))) + moredefs.append(('MATHLIB', ','.join(mathlibs))) check_math_capabilities(config_cmd, moredefs, mathlibs) moredefs.extend(cocache.check_ieee_macros(config_cmd)[0]) @@ -471,10 +471,10 @@ def configuration(parent_package='',top_path=None): # Generate the config.h file from moredefs target_f = open(target, 'w') for d in moredefs: - if isinstance(d,str): + if isinstance(d, str): target_f.write('#define %s\n' % (d)) else: - target_f.write('#define %s %s\n' % (d[0],d[1])) + target_f.write('#define %s %s\n' % (d[0], d[1])) # define inline to our keyword, or nothing target_f.write('#ifndef __cplusplus\n') @@ -493,7 +493,7 @@ def configuration(parent_package='',top_path=None): """) target_f.close() - print('File:',target) + print('File:', target) target_f = open(target) print(target_f.read()) target_f.close() @@ -523,13 +523,13 @@ def configuration(parent_package='',top_path=None): def generate_numpyconfig_h(ext, build_dir): """Depends on config.h: generate_config_h has to be called before !""" - target = join(build_dir,header_dir,'_numpyconfig.h') + target = join(build_dir, header_dir, '_numpyconfig.h') d = os.path.dirname(target) if not os.path.exists(d): os.makedirs(d) - if newer(__file__,target): + if newer(__file__, target): config_cmd = config.get_config_cmd() - log.info('Generating %s',target) + log.info('Generating %s', target) # Check sizeof ignored, moredefs = cocache.check_types(config_cmd, ext, build_dir) @@ -567,10 +567,10 @@ def configuration(parent_package='',top_path=None): # Add moredefs to header target_f = open(target, 'w') for d in moredefs: - if isinstance(d,str): + if isinstance(d, str): target_f.write('#define %s\n' % (d)) else: - target_f.write('#define %s %s\n' % (d[0],d[1])) + target_f.write('#define %s %s\n' % (d[0], d[1])) # Define __STDC_FORMAT_MACROS target_f.write(""" @@ -621,11 +621,11 @@ def configuration(parent_package='',top_path=None): config.numpy_include_dirs.extend(config.paths('include')) - deps = [join('src','npymath','_signbit.c'), - join('include','numpy','*object.h'), + deps = [join('src', 'npymath', '_signbit.c'), + join('include', 'numpy', '*object.h'), 'include/numpy/fenv/fenv.c', 'include/numpy/fenv/fenv.h', - join(codegen_dir,'genapi.py'), + join(codegen_dir, 'genapi.py'), ] # Don't install fenv unless we need them. @@ -643,7 +643,7 @@ def configuration(parent_package='',top_path=None): # generate_numpyconfig_h as sources *before* adding npymath. config.add_extension('_dummy', - sources = [join('src','dummymodule.c'), + sources = [join('src', 'dummymodule.c'), generate_config_h, generate_numpyconfig_h, generate_numpy_api] @@ -826,7 +826,7 @@ def configuration(parent_package='',top_path=None): [generate_config_h, generate_numpyconfig_h, generate_numpy_api, - join(codegen_dir,'generate_numpy_api.py'), + join(codegen_dir, 'generate_numpy_api.py'), join('*.py')], depends = deps + multiarray_deps, libraries = ['npymath', 'npysort']) @@ -857,13 +857,13 @@ def configuration(parent_package='',top_path=None): def generate_umath_c(ext, build_dir): - target = join(build_dir,header_dir,'__umath_generated.c') + target = join(build_dir, header_dir, '__umath_generated.c') dir = os.path.dirname(target) if not os.path.exists(dir): os.makedirs(dir) script = generate_umath_py - if newer(script,target): - f = open(target,'w') + if newer(script, target): + f = open(target, 'w') f.write(generate_umath.make_code(generate_umath.defdict, generate_umath.__file__)) f.close() @@ -881,7 +881,7 @@ def configuration(parent_package='',top_path=None): umath_deps = [ generate_umath_py, join('src', 'umath', 'simd.inc.src'), - join(codegen_dir,'generate_ufunc_api.py')] + join(codegen_dir, 'generate_ufunc_api.py')] if not ENABLE_SEPARATE_COMPILATION: umath_deps.extend(umath_src) @@ -905,7 +905,7 @@ def configuration(parent_package='',top_path=None): ####################################################################### config.add_extension('scalarmath', - sources = [join('src','scalarmathmodule.c.src'), + sources = [join('src', 'scalarmathmodule.c.src'), generate_config_h, generate_numpyconfig_h, generate_numpy_api, @@ -919,19 +919,19 @@ def configuration(parent_package='',top_path=None): ####################################################################### # Configure blasdot - blas_info = get_info('blas_opt',0) + blas_info = get_info('blas_opt', 0) #blas_info = {} def get_dotblas_sources(ext, build_dir): if blas_info: - if ('NO_ATLAS_INFO',1) in blas_info.get('define_macros',[]): + if ('NO_ATLAS_INFO', 1) in blas_info.get('define_macros', []): return None # dotblas needs ATLAS, Fortran compiled blas will not be sufficient. return ext.depends[:1] return None # no extension module will be built config.add_extension('_dotblas', sources = [get_dotblas_sources], - depends = [join('blasdot','_dotblas.c'), - join('blasdot','cblas.h'), + depends = [join('blasdot', '_dotblas.c'), + join('blasdot', 'cblas.h'), ], include_dirs = ['blasdot'], extra_info = blas_info @@ -942,21 +942,21 @@ def configuration(parent_package='',top_path=None): ####################################################################### config.add_extension('umath_tests', - sources = [join('src','umath', 'umath_tests.c.src')]) + sources = [join('src', 'umath', 'umath_tests.c.src')]) ####################################################################### # custom rational dtype module # ####################################################################### config.add_extension('test_rational', - sources = [join('src','umath', 'test_rational.c.src')]) + sources = [join('src', 'umath', 'test_rational.c.src')]) ####################################################################### # struct_ufunc_test module # ####################################################################### config.add_extension('struct_ufunc_test', - sources = [join('src','umath', 'struct_ufunc_test.c.src')]) + sources = [join('src', 'umath', 'struct_ufunc_test.c.src')]) ####################################################################### # multiarray_tests module # @@ -970,7 +970,7 @@ def configuration(parent_package='',top_path=None): ####################################################################### config.add_extension('operand_flag_tests', - sources = [join('src','umath', 'operand_flag_tests.c.src')]) + sources = [join('src', 'umath', 'operand_flag_tests.c.src')]) config.add_data_dir('tests') config.add_data_dir('tests/data') diff --git a/numpy/core/setup_common.py b/numpy/core/setup_common.py index 7f0ad8bfe..1f3e6b44e 100644 --- a/numpy/core/setup_common.py +++ b/numpy/core/setup_common.py @@ -236,9 +236,9 @@ def pyod(filename): else: return _pyod3() -_BEFORE_SEQ = ['000','000','000','000','000','000','000','000', - '001','043','105','147','211','253','315','357'] -_AFTER_SEQ = ['376', '334','272','230','166','124','062','020'] +_BEFORE_SEQ = ['000', '000', '000', '000', '000', '000', '000', '000', + '001', '043', '105', '147', '211', '253', '315', '357'] +_AFTER_SEQ = ['376', '334', '272', '230', '166', '124', '062', '020'] _IEEE_DOUBLE_BE = ['301', '235', '157', '064', '124', '000', '000', '000'] _IEEE_DOUBLE_LE = _IEEE_DOUBLE_BE[::-1] diff --git a/numpy/core/shape_base.py b/numpy/core/shape_base.py index 3671033e9..ae684fb42 100644 --- a/numpy/core/shape_base.py +++ b/numpy/core/shape_base.py @@ -1,6 +1,6 @@ from __future__ import division, absolute_import, print_function -__all__ = ['atleast_1d','atleast_2d','atleast_3d','vstack','hstack'] +__all__ = ['atleast_1d', 'atleast_2d', 'atleast_3d', 'vstack', 'hstack'] from . import numeric as _nx from .numeric import array, asanyarray, newaxis @@ -100,7 +100,7 @@ def atleast_2d(*arys): if len(ary.shape) == 0 : result = ary.reshape(1, 1) elif len(ary.shape) == 1 : - result = ary[newaxis, :] + result = ary[newaxis,:] else : result = ary res.append(result) @@ -162,11 +162,11 @@ def atleast_3d(*arys): for ary in arys: ary = asanyarray(ary) if len(ary.shape) == 0: - result = ary.reshape(1,1,1) + result = ary.reshape(1, 1, 1) elif len(ary.shape) == 1: - result = ary[newaxis,:,newaxis] + result = ary[newaxis,:, newaxis] elif len(ary.shape) == 2: - result = ary[:,:,newaxis] + result = ary[:,:, newaxis] else: result = ary res.append(result) diff --git a/numpy/core/src/multiarray/testcalcs.py b/numpy/core/src/multiarray/testcalcs.py index 9182ae2c3..e8b7b1734 100644 --- a/numpy/core/src/multiarray/testcalcs.py +++ b/numpy/core/src/multiarray/testcalcs.py @@ -33,7 +33,7 @@ def year_offset(year): else return_val = year*365 + (year-3)/4 - (year-99)/100 + (year-399)/400; """ - return weave.inline(code,['year']) + return weave.inline(code, ['year']) def days_from_ymd(year, month, day): diff --git a/numpy/core/tests/test_api.py b/numpy/core/tests/test_api.py index e8dacba2e..0bec38f22 100644 --- a/numpy/core/tests/test_api.py +++ b/numpy/core/tests/test_api.py @@ -167,19 +167,19 @@ def test_fastCopyAndTranspose(): assert_(b.flags.owndata) # 1D array - a = np.array([3,2,7,0]) + a = np.array([3, 2, 7, 0]) b = np.fastCopyAndTranspose(a) assert_equal(b, a.T) assert_(b.flags.owndata) # 2D array - a = np.arange(6).reshape(2,3) + a = np.arange(6).reshape(2, 3) b = np.fastCopyAndTranspose(a) assert_equal(b, a.T) assert_(b.flags.owndata) def test_array_astype(): - a = np.arange(6, dtype='f4').reshape(2,3) + a = np.arange(6, dtype='f4').reshape(2, 3) # Default behavior: allows unsafe casts, keeps memory layout, # always copies. b = a.astype('i4') @@ -221,7 +221,7 @@ def test_array_astype(): b = a.astype('f4', subok=0, copy=False) assert_(a is b) - a = np.matrix([[0,1,2],[3,4,5]], dtype='f4') + a = np.matrix([[0, 1, 2], [3, 4, 5]], dtype='f4') # subok=True passes through a matrix b = a.astype('f4', subok=True, copy=False) @@ -276,7 +276,7 @@ def test_array_astype(): def test_copyto_fromscalar(): - a = np.arange(6, dtype='f4').reshape(2,3) + a = np.arange(6, dtype='f4').reshape(2, 3) # Simple copy np.copyto(a, 1.5) @@ -285,23 +285,23 @@ def test_copyto_fromscalar(): assert_equal(a, 2.5) # Where-masked copy - mask = np.array([[0,1,0],[0,0,1]], dtype='?') + mask = np.array([[0, 1, 0], [0, 0, 1]], dtype='?') np.copyto(a, 3.5, where=mask) - assert_equal(a, [[2.5,3.5,2.5],[2.5,2.5,3.5]]) - mask = np.array([[0,1],[1,1],[1,0]], dtype='?') + assert_equal(a, [[2.5, 3.5, 2.5], [2.5, 2.5, 3.5]]) + mask = np.array([[0, 1], [1, 1], [1, 0]], dtype='?') np.copyto(a.T, 4.5, where=mask) - assert_equal(a, [[2.5,4.5,4.5],[4.5,4.5,3.5]]) + assert_equal(a, [[2.5, 4.5, 4.5], [4.5, 4.5, 3.5]]) def test_copyto(): - a = np.arange(6, dtype='i4').reshape(2,3) + a = np.arange(6, dtype='i4').reshape(2, 3) # Simple copy - np.copyto(a, [[3,1,5], [6,2,1]]) - assert_equal(a, [[3,1,5], [6,2,1]]) + np.copyto(a, [[3, 1, 5], [6, 2, 1]]) + assert_equal(a, [[3, 1, 5], [6, 2, 1]]) # Overlapping copy should work - np.copyto(a[:,:2], a[::-1, 1::-1]) - assert_equal(a, [[2,6,5], [1,3,1]]) + np.copyto(a[:, :2], a[::-1, 1::-1]) + assert_equal(a, [[2, 6, 5], [1, 3, 1]]) # Defaults to 'same_kind' casting assert_raises(TypeError, np.copyto, a, 1.5) @@ -311,27 +311,27 @@ def test_copyto(): assert_equal(a, 1) # Copying with a mask - np.copyto(a, 3, where=[True,False,True]) - assert_equal(a, [[3,1,3],[3,1,3]]) + np.copyto(a, 3, where=[True, False, True]) + assert_equal(a, [[3, 1, 3], [3, 1, 3]]) # Casting rule still applies with a mask - assert_raises(TypeError, np.copyto, a, 3.5, where=[True,False,True]) + assert_raises(TypeError, np.copyto, a, 3.5, where=[True, False, True]) # Lists of integer 0's and 1's is ok too - np.copyto(a, 4.0, casting='unsafe', where=[[0,1,1], [1,0,0]]) - assert_equal(a, [[3,4,4], [4,1,3]]) + np.copyto(a, 4.0, casting='unsafe', where=[[0, 1, 1], [1, 0, 0]]) + assert_equal(a, [[3, 4, 4], [4, 1, 3]]) # Overlapping copy with mask should work - np.copyto(a[:,:2], a[::-1, 1::-1], where=[[0,1],[1,1]]) - assert_equal(a, [[3,4,4], [4,3,3]]) + np.copyto(a[:, :2], a[::-1, 1::-1], where=[[0, 1], [1, 1]]) + assert_equal(a, [[3, 4, 4], [4, 3, 3]]) # 'dst' must be an array - assert_raises(TypeError, np.copyto, [1,2,3], [2,3,4]) + assert_raises(TypeError, np.copyto, [1, 2, 3], [2, 3, 4]) def test_copy_order(): - a = np.arange(24).reshape(2,1,3,4) + a = np.arange(24).reshape(2, 1, 3, 4) b = a.copy(order='F') - c = np.arange(24).reshape(2,1,4,3).swapaxes(2,3) + c = np.arange(24).reshape(2, 1, 4, 3).swapaxes(2, 3) def check_copy_result(x, y, ccontig, fcontig, strides=False): assert_(not (x is y)) @@ -397,10 +397,10 @@ def test_copy_order(): check_copy_result(res, c, ccontig=False, fcontig=False, strides=True) def test_contiguous_flags(): - a = np.ones((4,4,1))[::2,:,:] + a = np.ones((4, 4, 1))[::2,:,:] if NPY_RELAXED_STRIDES_CHECKING: a.strides = a.strides[:2] + (-123,) - b = np.ones((2,2,1,2,2)).swapaxes(3,4) + b = np.ones((2, 2, 1, 2, 2)).swapaxes(3, 4) def check_contig(a, ccontig, fcontig): assert_(a.flags.c_contiguous == ccontig) @@ -410,13 +410,13 @@ def test_contiguous_flags(): check_contig(a, False, False) check_contig(b, False, False) if NPY_RELAXED_STRIDES_CHECKING: - check_contig(np.empty((2,2,0,2,2)), True, True) - check_contig(np.array([[[1],[2]]], order='F'), True, True) + check_contig(np.empty((2, 2, 0, 2, 2)), True, True) + check_contig(np.array([[[1], [2]]], order='F'), True, True) else: - check_contig(np.empty((2,2,0,2,2)), True, False) - check_contig(np.array([[[1],[2]]], order='F'), False, True) - check_contig(np.empty((2,2)), True, False) - check_contig(np.empty((2,2), order='F'), False, True) + check_contig(np.empty((2, 2, 0, 2, 2)), True, False) + check_contig(np.array([[[1], [2]]], order='F'), False, True) + check_contig(np.empty((2, 2)), True, False) + check_contig(np.empty((2, 2), order='F'), False, True) # Check that np.array creates correct contiguous flags: check_contig(np.array(a, copy=False), False, False) @@ -426,27 +426,27 @@ def test_contiguous_flags(): if NPY_RELAXED_STRIDES_CHECKING: # Check slicing update of flags and : check_contig(a[0], True, True) - check_contig(a[None,::4,...,None], True, True) - check_contig(b[0,0,...], False, True) - check_contig(b[:,:,0:0,:,:], True, True) + check_contig(a[None, ::4, ..., None], True, True) + check_contig(b[0, 0, ...], False, True) + check_contig(b[:,:, 0:0,:,:], True, True) else: # Check slicing update of flags: check_contig(a[0], True, False) # Would be nice if this was C-Contiguous: - check_contig(a[None,0,...,None], False, False) - check_contig(b[0,0,0,...], False, True) + check_contig(a[None, 0, ..., None], False, False) + check_contig(b[0, 0, 0, ...], False, True) # Test ravel and squeeze. check_contig(a.ravel(), True, True) - check_contig(np.ones((1,3,1)).squeeze(), True, True) + check_contig(np.ones((1, 3, 1)).squeeze(), True, True) def test_broadcast_arrays(): # Test user defined dtypes - a = np.array([(1,2,3)], dtype='u4,u4,u4') - b = np.array([(1,2,3),(4,5,6),(7,8,9)], dtype='u4,u4,u4') + a = np.array([(1, 2, 3)], dtype='u4,u4,u4') + b = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype='u4,u4,u4') result = np.broadcast_arrays(a, b) - assert_equal(result[0], np.array([(1,2,3),(1,2,3),(1,2,3)], dtype='u4,u4,u4')) - assert_equal(result[1], np.array([(1,2,3),(4,5,6),(7,8,9)], dtype='u4,u4,u4')) + assert_equal(result[0], np.array([(1, 2, 3), (1, 2, 3), (1, 2, 3)], dtype='u4,u4,u4')) + assert_equal(result[1], np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype='u4,u4,u4')) if __name__ == "__main__": run_module_suite() diff --git a/numpy/core/tests/test_blasdot.py b/numpy/core/tests/test_blasdot.py index 2e99cf5b0..624c617d3 100644 --- a/numpy/core/tests/test_blasdot.py +++ b/numpy/core/tests/test_blasdot.py @@ -50,16 +50,16 @@ def test_dot_3args(): r = np.empty((1024, 32)) for i in range(12): - np.dot(f,v,r) + np.dot(f, v, r) assert_equal(sys.getrefcount(r), 2) - r2 = np.dot(f,v,out=None) + r2 = np.dot(f, v, out=None) assert_array_equal(r2, r) - assert_(r is np.dot(f,v,out=r)) + assert_(r is np.dot(f, v, out=r)) - v = v[:,0].copy() # v.shape == (16,) - r = r[:,0].copy() # r.shape == (1024,) - r2 = np.dot(f,v) - assert_(r is np.dot(f,v,r)) + v = v[:, 0].copy() # v.shape == (16,) + r = r[:, 0].copy() # r.shape == (1024,) + r2 = np.dot(f, v) + assert_(r is np.dot(f, v, r)) assert_array_equal(r2, r) def test_dot_3args_errors(): @@ -81,8 +81,8 @@ def test_dot_3args_errors(): assert_raises(ValueError, np.dot, f, v, r.T) r = np.empty((1024, 64)) - assert_raises(ValueError, np.dot, f, v, r[:,::2]) - assert_raises(ValueError, np.dot, f, v, r[:,:32]) + assert_raises(ValueError, np.dot, f, v, r[:, ::2]) + assert_raises(ValueError, np.dot, f, v, r[:, :32]) r = np.empty((1024, 32), dtype=np.float32) assert_raises(ValueError, np.dot, f, v, r) diff --git a/numpy/core/tests/test_datetime.py b/numpy/core/tests/test_datetime.py index 4ba0c048a..84efd87b3 100644 --- a/numpy/core/tests/test_datetime.py +++ b/numpy/core/tests/test_datetime.py @@ -159,26 +159,26 @@ class TestDateTime(TestCase): # Construction from datetime.date assert_equal(np.datetime64('1945-03-25'), - np.datetime64(datetime.date(1945,3,25))) + np.datetime64(datetime.date(1945, 3, 25))) assert_equal(np.datetime64('2045-03-25', 'D'), - np.datetime64(datetime.date(2045,3,25), 'D')) + np.datetime64(datetime.date(2045, 3, 25), 'D')) # Construction from datetime.datetime assert_equal(np.datetime64('1980-01-25T14:36:22.5Z'), - np.datetime64(datetime.datetime(1980,1,25, - 14,36,22,500000))) + np.datetime64(datetime.datetime(1980, 1, 25, + 14, 36, 22, 500000))) # Construction with time units from a date raises assert_raises(TypeError, np.datetime64, '1920-03-13', 'h') assert_raises(TypeError, np.datetime64, '1920-03', 'm') assert_raises(TypeError, np.datetime64, '1920', 's') - assert_raises(TypeError, np.datetime64, datetime.date(2045,3,25), 'ms') + assert_raises(TypeError, np.datetime64, datetime.date(2045, 3, 25), 'ms') # Construction with date units from a datetime raises assert_raises(TypeError, np.datetime64, '1920-03-13T18Z', 'D') assert_raises(TypeError, np.datetime64, '1920-03-13T18:33Z', 'W') assert_raises(TypeError, np.datetime64, '1920-03-13T18:33:12Z', 'M') assert_raises(TypeError, np.datetime64, '1920-03-13T18:33:12.5Z', 'Y') assert_raises(TypeError, np.datetime64, - datetime.datetime(1920,4,14,13,20), 'D') + datetime.datetime(1920, 4, 14, 13, 20), 'D') def test_datetime_array_find_type(self): dt = np.datetime64('1970-01-01', 'M') @@ -351,12 +351,12 @@ class TestDateTime(TestCase): np.dtype('M8[as]')) # Python date object - assert_equal(np.datetime64(datetime.date(2010,4,16)).dtype, + assert_equal(np.datetime64(datetime.date(2010, 4, 16)).dtype, np.dtype('M8[D]')) # Python datetime object assert_equal(np.datetime64( - datetime.datetime(2010,4,16,13,45,18)).dtype, + datetime.datetime(2010, 4, 16, 13, 45, 18)).dtype, np.dtype('M8[us]')) # 'today' special value @@ -592,7 +592,7 @@ class TestDateTime(TestCase): def test_pyobject_roundtrip(self): # All datetime types should be able to roundtrip through object - a = np.array([0,0,0,0,0,0,0,0,0, + a = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, -1020040340, -2942398, -1, 0, 1, 234523453, 1199164176], dtype=np.int64) # With date units @@ -878,11 +878,11 @@ class TestDateTime(TestCase): # M8 - M8 with different goes to higher precision assert_equal(np.subtract(dtc, dtd, casting='unsafe'), - np.timedelta64(0,'h')) + np.timedelta64(0, 'h')) assert_equal(np.subtract(dtc, dtd, casting='unsafe').dtype, np.dtype('m8[h]')) assert_equal(np.subtract(dtd, dtc, casting='unsafe'), - np.timedelta64(0,'h')) + np.timedelta64(0, 'h')) assert_equal(np.subtract(dtd, dtc, casting='unsafe').dtype, np.dtype('m8[h]')) @@ -1004,40 +1004,40 @@ class TestDateTime(TestCase): # of the operand metadata a = np.array('1999-03-12T13Z', dtype='M8[2m]') b = np.array('1999-03-12T12Z', dtype='M8[s]') - assert_equal(np.minimum(a,b), b) - assert_equal(np.minimum(a,b).dtype, np.dtype('M8[s]')) - assert_equal(np.fmin(a,b), b) - assert_equal(np.fmin(a,b).dtype, np.dtype('M8[s]')) - assert_equal(np.maximum(a,b), a) - assert_equal(np.maximum(a,b).dtype, np.dtype('M8[s]')) - assert_equal(np.fmax(a,b), a) - assert_equal(np.fmax(a,b).dtype, np.dtype('M8[s]')) + assert_equal(np.minimum(a, b), b) + assert_equal(np.minimum(a, b).dtype, np.dtype('M8[s]')) + assert_equal(np.fmin(a, b), b) + assert_equal(np.fmin(a, b).dtype, np.dtype('M8[s]')) + assert_equal(np.maximum(a, b), a) + assert_equal(np.maximum(a, b).dtype, np.dtype('M8[s]')) + assert_equal(np.fmax(a, b), a) + assert_equal(np.fmax(a, b).dtype, np.dtype('M8[s]')) # Viewed as integers, the comparison is opposite because # of the units chosen - assert_equal(np.minimum(a.view('i8'),b.view('i8')), a.view('i8')) + assert_equal(np.minimum(a.view('i8'), b.view('i8')), a.view('i8')) # Interaction with NaT a = np.array('1999-03-12T13Z', dtype='M8[2m]') dtnat = np.array('NaT', dtype='M8[h]') - assert_equal(np.minimum(a,dtnat), a) - assert_equal(np.minimum(dtnat,a), a) - assert_equal(np.maximum(a,dtnat), a) - assert_equal(np.maximum(dtnat,a), a) + assert_equal(np.minimum(a, dtnat), a) + assert_equal(np.minimum(dtnat, a), a) + assert_equal(np.maximum(a, dtnat), a) + assert_equal(np.maximum(dtnat, a), a) # Also do timedelta a = np.array(3, dtype='m8[h]') b = np.array(3*3600 - 3, dtype='m8[s]') - assert_equal(np.minimum(a,b), b) - assert_equal(np.minimum(a,b).dtype, np.dtype('m8[s]')) - assert_equal(np.fmin(a,b), b) - assert_equal(np.fmin(a,b).dtype, np.dtype('m8[s]')) - assert_equal(np.maximum(a,b), a) - assert_equal(np.maximum(a,b).dtype, np.dtype('m8[s]')) - assert_equal(np.fmax(a,b), a) - assert_equal(np.fmax(a,b).dtype, np.dtype('m8[s]')) + assert_equal(np.minimum(a, b), b) + assert_equal(np.minimum(a, b).dtype, np.dtype('m8[s]')) + assert_equal(np.fmin(a, b), b) + assert_equal(np.fmin(a, b).dtype, np.dtype('m8[s]')) + assert_equal(np.maximum(a, b), a) + assert_equal(np.maximum(a, b).dtype, np.dtype('m8[s]')) + assert_equal(np.fmax(a, b), a) + assert_equal(np.fmax(a, b).dtype, np.dtype('m8[s]')) # Viewed as integers, the comparison is opposite because # of the units chosen - assert_equal(np.minimum(a.view('i8'),b.view('i8')), a.view('i8')) + assert_equal(np.minimum(a.view('i8'), b.view('i8')), a.view('i8')) # should raise between datetime and timedelta # @@ -1394,18 +1394,18 @@ class TestDateTime(TestCase): assert_raises(ValueError, np.arange, np.datetime64('today'), np.datetime64('today') + 3, 0) # Promotion across nonlinear unit boundaries is disallowed - assert_raises(TypeError, np.arange, np.datetime64('2011-03-01','D'), - np.timedelta64(5,'M')) + assert_raises(TypeError, np.arange, np.datetime64('2011-03-01', 'D'), + np.timedelta64(5, 'M')) assert_raises(TypeError, np.arange, - np.datetime64('2012-02-03T14Z','s'), - np.timedelta64(5,'Y')) + np.datetime64('2012-02-03T14Z', 's'), + np.timedelta64(5, 'Y')) def test_timedelta_arange(self): a = np.arange(3, 10, dtype='m8') assert_equal(a.dtype, np.dtype('m8')) assert_equal(a, np.timedelta64(0) + np.arange(3, 10)) - a = np.arange(np.timedelta64(3,'s'), 10, 2, dtype='m8') + a = np.arange(np.timedelta64(3, 's'), 10, 2, dtype='m8') assert_equal(a.dtype, np.dtype('m8[s]')) assert_equal(a, np.timedelta64(0, 's') + np.arange(3, 10, 2)) @@ -1413,18 +1413,18 @@ class TestDateTime(TestCase): assert_raises(ValueError, np.arange, np.timedelta64(0), np.timedelta64(5), 0) # Promotion across nonlinear unit boundaries is disallowed - assert_raises(TypeError, np.arange, np.timedelta64(0,'D'), - np.timedelta64(5,'M')) - assert_raises(TypeError, np.arange, np.timedelta64(0,'Y'), - np.timedelta64(5,'D')) + assert_raises(TypeError, np.arange, np.timedelta64(0, 'D'), + np.timedelta64(5, 'M')) + assert_raises(TypeError, np.arange, np.timedelta64(0, 'Y'), + np.timedelta64(5, 'D')) def test_datetime_maximum_reduce(self): - a = np.array(['2010-01-02','1999-03-14','1833-03'], dtype='M8[D]') + a = np.array(['2010-01-02', '1999-03-14', '1833-03'], dtype='M8[D]') assert_equal(np.maximum.reduce(a).dtype, np.dtype('M8[D]')) assert_equal(np.maximum.reduce(a), np.datetime64('2010-01-02')) - a = np.array([1,4,0,7,2], dtype='m8[s]') + a = np.array([1, 4, 0, 7, 2], dtype='m8[s]') assert_equal(np.maximum.reduce(a).dtype, np.dtype('m8[s]')) assert_equal(np.maximum.reduce(a), np.timedelta64(7, 's')) @@ -1432,14 +1432,14 @@ class TestDateTime(TestCase): def test_datetime_busday_offset(self): # First Monday in June assert_equal( - np.busday_offset('2011-06',0,roll='forward',weekmask='Mon'), + np.busday_offset('2011-06', 0, roll='forward', weekmask='Mon'), np.datetime64('2011-06-06')) # Last Monday in June assert_equal( - np.busday_offset('2011-07',-1,roll='forward',weekmask='Mon'), + np.busday_offset('2011-07', -1, roll='forward', weekmask='Mon'), np.datetime64('2011-06-27')) assert_equal( - np.busday_offset('2011-07',-1,roll='forward',weekmask='Mon'), + np.busday_offset('2011-07', -1, roll='forward', weekmask='Mon'), np.datetime64('2011-06-27')) # Default M-F business days, different roll modes @@ -1481,26 +1481,26 @@ class TestDateTime(TestCase): # and sorts the result. bdd = np.busdaycalendar( holidays=['NaT', '2011-01-17', '2011-03-06', 'NaT', - '2011-12-26','2011-05-30','2011-01-17']) + '2011-12-26', '2011-05-30', '2011-01-17']) assert_equal(bdd.holidays, - np.array(['2011-01-17','2011-05-30','2011-12-26'], dtype='M8')) + np.array(['2011-01-17', '2011-05-30', '2011-12-26'], dtype='M8')) # Default M-F weekmask - assert_equal(bdd.weekmask, np.array([1,1,1,1,1,0,0], dtype='?')) + assert_equal(bdd.weekmask, np.array([1, 1, 1, 1, 1, 0, 0], dtype='?')) # Check string weekmask with varying whitespace. bdd = np.busdaycalendar(weekmask="Sun TueWed Thu\tFri") - assert_equal(bdd.weekmask, np.array([0,1,1,1,1,0,1], dtype='?')) + assert_equal(bdd.weekmask, np.array([0, 1, 1, 1, 1, 0, 1], dtype='?')) # Check length 7 0/1 string bdd = np.busdaycalendar(weekmask="0011001") - assert_equal(bdd.weekmask, np.array([0,0,1,1,0,0,1], dtype='?')) + assert_equal(bdd.weekmask, np.array([0, 0, 1, 1, 0, 0, 1], dtype='?')) # Check length 7 string weekmask. bdd = np.busdaycalendar(weekmask="Mon Tue") - assert_equal(bdd.weekmask, np.array([1,1,0,0,0,0,0], dtype='?')) + assert_equal(bdd.weekmask, np.array([1, 1, 0, 0, 0, 0, 0], dtype='?')) # All-zeros weekmask should raise - assert_raises(ValueError, np.busdaycalendar, weekmask=[0,0,0,0,0,0,0]) + assert_raises(ValueError, np.busdaycalendar, weekmask=[0, 0, 0, 0, 0, 0, 0]) # weekday names must be correct case assert_raises(ValueError, np.busdaycalendar, weekmask="satsun") # All-zeros weekmask should raise diff --git a/numpy/core/tests/test_defchararray.py b/numpy/core/tests/test_defchararray.py index 4656c842f..09fcff0d0 100644 --- a/numpy/core/tests/test_defchararray.py +++ b/numpy/core/tests/test_defchararray.py @@ -37,14 +37,14 @@ class TestBasic(TestCase): assert_array_equal(B, A) assert_equal(B.dtype, A.dtype) assert_equal(B.shape, A.shape) - B[0,0] = 'changed' - assert_(B[0,0] != A[0,0]) + B[0, 0] = 'changed' + assert_(B[0, 0] != A[0, 0]) C = np.char.asarray(A) assert_array_equal(C, A) assert_equal(C.dtype, A.dtype) - C[0,0] = 'changed again' - assert_(C[0,0] != B[0,0]) - assert_(C[0,0] == A[0,0]) + C[0, 0] = 'changed again' + assert_(C[0, 0] != B[0, 0]) + assert_(C[0, 0] == A[0, 0]) def test_from_unicode_array(self): A = np.array([['abc', sixu('Sigma \u03a3')], @@ -572,9 +572,9 @@ class TestOperations(TestCase): def test_mul(self): A = self.A - for r in (2,3,5,7,197): - Ar = np.array([[A[0,0]*r, A[0,1]*r], - [A[1,0]*r, A[1,1]*r]]).view(np.chararray) + for r in (2, 3, 5, 7, 197): + Ar = np.array([[A[0, 0]*r, A[0, 1]*r], + [A[1, 0]*r, A[1, 1]*r]]).view(np.chararray) assert_array_equal(Ar, (self.A * r)) @@ -588,9 +588,9 @@ class TestOperations(TestCase): def test_rmul(self): A = self.A - for r in (2,3,5,7,197): - Ar = np.array([[A[0,0]*r, A[0,1]*r], - [A[1,0]*r, A[1,1]*r]]).view(np.chararray) + for r in (2, 3, 5, 7, 197): + Ar = np.array([[A[0, 0]*r, A[0, 1]*r], + [A[1, 0]*r, A[1, 1]*r]]).view(np.chararray) assert_array_equal(Ar, (r * self.A)) for ob in [object(), 'qrs']: @@ -603,18 +603,18 @@ class TestOperations(TestCase): def test_mod(self): """Ticket #856""" - F = np.array([['%d', '%f'],['%s','%r']]).view(np.chararray) - C = np.array([[3,7],[19,1]]) + F = np.array([['%d', '%f'], ['%s', '%r']]).view(np.chararray) + C = np.array([[3, 7], [19, 1]]) FC = np.array([['3', '7.000000'], ['19', '1']]).view(np.chararray) assert_array_equal(FC, F % C) - A = np.array([['%.3f','%d'],['%s','%r']]).view(np.chararray) - A1 = np.array([['1.000','1'],['1','1']]).view(np.chararray) + A = np.array([['%.3f', '%d'], ['%s', '%r']]).view(np.chararray) + A1 = np.array([['1.000', '1'], ['1', '1']]).view(np.chararray) assert_array_equal(A1, (A % 1)) - A2 = np.array([['1.000','2'],['3','4']]).view(np.chararray) - assert_array_equal(A2, (A % [[1,2],[3,4]])) + A2 = np.array([['1.000', '2'], ['3', '4']]).view(np.chararray) + assert_array_equal(A2, (A % [[1, 2], [3, 4]])) def test_rmod(self): assert_(("%s" % self.A) == str(self.A)) diff --git a/numpy/core/tests/test_deprecations.py b/numpy/core/tests/test_deprecations.py index 2bedbca09..11e572ada 100644 --- a/numpy/core/tests/test_deprecations.py +++ b/numpy/core/tests/test_deprecations.py @@ -148,20 +148,20 @@ class TestFloatNonIntegerArgumentDeprecation(_DeprecationTestCase): assert_deprecated(lambda: a[0.0]) assert_deprecated(lambda: a[0, 0.0]) assert_deprecated(lambda: a[0.0, 0]) - assert_deprecated(lambda: a[0.0, :]) + assert_deprecated(lambda: a[0.0,:]) assert_deprecated(lambda: a[:, 0.0]) - assert_deprecated(lambda: a[:, 0.0, :]) - assert_deprecated(lambda: a[0.0, :, :], num=2) # [1] + assert_deprecated(lambda: a[:, 0.0,:]) + assert_deprecated(lambda: a[0.0,:,:], num=2) # [1] assert_deprecated(lambda: a[0, 0, 0.0]) assert_deprecated(lambda: a[0.0, 0, 0]) assert_deprecated(lambda: a[0, 0.0, 0]) assert_deprecated(lambda: a[-1.4]) assert_deprecated(lambda: a[0, -1.4]) assert_deprecated(lambda: a[-1.4, 0]) - assert_deprecated(lambda: a[-1.4, :]) + assert_deprecated(lambda: a[-1.4,:]) assert_deprecated(lambda: a[:, -1.4]) - assert_deprecated(lambda: a[:, -1.4, :]) - assert_deprecated(lambda: a[-1.4, :, :], num=2) # [1] + assert_deprecated(lambda: a[:, -1.4,:]) + assert_deprecated(lambda: a[-1.4,:,:], num=2) # [1] assert_deprecated(lambda: a[0, 0, -1.4]) assert_deprecated(lambda: a[-1.4, 0, 0]) assert_deprecated(lambda: a[0, -1.4, 0]) @@ -170,7 +170,7 @@ class TestFloatNonIntegerArgumentDeprecation(_DeprecationTestCase): # Test that the slice parameter deprecation warning doesn't mask # the scalar index warning. assert_deprecated(lambda: a[0.0:, 0.0], num=2) - assert_deprecated(lambda: a[0.0:, 0.0, :], num=2) + assert_deprecated(lambda: a[0.0:, 0.0,:], num=2) def test_valid_indexing(self): @@ -180,8 +180,8 @@ class TestFloatNonIntegerArgumentDeprecation(_DeprecationTestCase): assert_not_deprecated(lambda: a[np.array([0])]) assert_not_deprecated(lambda: a[[0, 0]]) assert_not_deprecated(lambda: a[:, [0, 0]]) - assert_not_deprecated(lambda: a[:, 0, :]) - assert_not_deprecated(lambda: a[:, :, :]) + assert_not_deprecated(lambda: a[:, 0,:]) + assert_not_deprecated(lambda: a[:,:,:]) def test_slicing(self): @@ -193,26 +193,26 @@ class TestFloatNonIntegerArgumentDeprecation(_DeprecationTestCase): assert_deprecated(lambda: a[0.0:]) assert_deprecated(lambda: a[0:, 0.0:2]) assert_deprecated(lambda: a[0.0::2, :0]) - assert_deprecated(lambda: a[0.0:1:2, :]) + assert_deprecated(lambda: a[0.0:1:2,:]) assert_deprecated(lambda: a[:, 0.0:]) # stop as float. assert_deprecated(lambda: a[:0.0]) assert_deprecated(lambda: a[:0, 1:2.0]) assert_deprecated(lambda: a[:0.0:2, :0]) - assert_deprecated(lambda: a[:0.0, :]) + assert_deprecated(lambda: a[:0.0,:]) assert_deprecated(lambda: a[:, 0:4.0:2]) # step as float. assert_deprecated(lambda: a[::1.0]) assert_deprecated(lambda: a[0:, :2:2.0]) assert_deprecated(lambda: a[1::4.0, :0]) - assert_deprecated(lambda: a[::5.0, :]) + assert_deprecated(lambda: a[::5.0,:]) assert_deprecated(lambda: a[:, 0:4:2.0]) # mixed. assert_deprecated(lambda: a[1.0:2:2.0], num=2) assert_deprecated(lambda: a[1.0::2.0], num=2) assert_deprecated(lambda: a[0:, :2.0:2.0], num=2) assert_deprecated(lambda: a[1.0:1:4.0, :0], num=2) - assert_deprecated(lambda: a[1.0:5.0:5.0, :], num=3) + assert_deprecated(lambda: a[1.0:5.0:5.0,:], num=3) assert_deprecated(lambda: a[:, 0.4:4.0:2.0], num=3) # should still get the DeprecationWarning if step = 0. assert_deprecated(lambda: a[::0.0], function_fails=True) @@ -261,8 +261,8 @@ class TestBooleanArgumentDeprecation(_DeprecationTestCase): assert_raises(TypeError, operator.index, np.array(True)) self.assert_deprecated(np.take, args=(a, [0], False)) self.assert_deprecated(lambda: a[False:True:True], exceptions=IndexError, num=3) - self.assert_deprecated(lambda: a[False,0], exceptions=IndexError) - self.assert_deprecated(lambda: a[False,0,0], exceptions=IndexError) + self.assert_deprecated(lambda: a[False, 0], exceptions=IndexError) + self.assert_deprecated(lambda: a[False, 0, 0], exceptions=IndexError) class TestArrayToIndexDeprecation(_DeprecationTestCase): diff --git a/numpy/core/tests/test_dtype.py b/numpy/core/tests/test_dtype.py index fed7375b7..83017ea6a 100644 --- a/numpy/core/tests/test_dtype.py +++ b/numpy/core/tests/test_dtype.py @@ -85,21 +85,21 @@ class TestBuiltin(TestCase): def test_bad_param(self): # Can't give a size that's too small assert_raises(ValueError, np.dtype, - {'names':['f0','f1'], + {'names':['f0', 'f1'], 'formats':['i4', 'i1'], - 'offsets':[0,4], + 'offsets':[0, 4], 'itemsize':4}) # If alignment is enabled, the alignment (4) must divide the itemsize assert_raises(ValueError, np.dtype, - {'names':['f0','f1'], + {'names':['f0', 'f1'], 'formats':['i4', 'i1'], - 'offsets':[0,4], + 'offsets':[0, 4], 'itemsize':9}, align=True) # If alignment is enabled, the individual fields must be aligned assert_raises(ValueError, np.dtype, - {'names':['f0','f1'], - 'formats':['i1','f4'], - 'offsets':[0,2]}, align=True) + {'names':['f0', 'f1'], + 'formats':['i1', 'f4'], + 'offsets':[0, 2]}, align=True) class TestRecord(TestCase): def test_equivalent_record(self): @@ -116,10 +116,10 @@ class TestRecord(TestCase): def test_different_titles(self): # In theory, they may hash the same (collision) ? - a = np.dtype({'names': ['r','b'], + a = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'], 'titles': ['Red pixel', 'Blue pixel']}) - b = np.dtype({'names': ['r','b'], + b = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'], 'titles': ['RRed pixel', 'Blue pixel']}) assert_dtype_not_equal(a, b) @@ -139,9 +139,9 @@ class TestRecord(TestCase): assert_equal(dt.itemsize, 8) dt = np.dtype([('f0', 'i4'), ('f1', 'i1')], align=True) assert_equal(dt.itemsize, 8) - dt = np.dtype({'names':['f0','f1'], + dt = np.dtype({'names':['f0', 'f1'], 'formats':['i4', 'u1'], - 'offsets':[0,4]}, align=True) + 'offsets':[0, 4]}, align=True) assert_equal(dt.itemsize, 8) dt = np.dtype({'f0': ('i4', 0), 'f1':('u1', 4)}, align=True) assert_equal(dt.itemsize, 8) @@ -150,7 +150,7 @@ class TestRecord(TestCase): ('f1', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')]), ('f2', 'i1')], align=True) assert_equal(dt1.itemsize, 20) - dt2 = np.dtype({'names':['f0','f1','f2'], + dt2 = np.dtype({'names':['f0', 'f1', 'f2'], 'formats':['i4', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], 'i1'], @@ -167,7 +167,7 @@ class TestRecord(TestCase): ('f1', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')]), ('f2', 'i1')], align=False) assert_equal(dt1.itemsize, 11) - dt2 = np.dtype({'names':['f0','f1','f2'], + dt2 = np.dtype({'names':['f0', 'f1', 'f2'], 'formats':['i4', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], 'i1'], @@ -182,22 +182,22 @@ class TestRecord(TestCase): def test_union_struct(self): # Should be able to create union dtypes - dt = np.dtype({'names':['f0','f1','f2'], 'formats':['<u4', '<u2','<u2'], - 'offsets':[0,0,2]}, align=True) + dt = np.dtype({'names':['f0', 'f1', 'f2'], 'formats':['<u4', '<u2', '<u2'], + 'offsets':[0, 0, 2]}, align=True) assert_equal(dt.itemsize, 4) a = np.array([3], dtype='<u4').view(dt) a['f1'] = 10 a['f2'] = 36 assert_equal(a['f0'], 10 + 36*256*256) # Should be able to specify fields out of order - dt = np.dtype({'names':['f0','f1','f2'], 'formats':['<u4', '<u2','<u2'], - 'offsets':[4,0,2]}, align=True) + dt = np.dtype({'names':['f0', 'f1', 'f2'], 'formats':['<u4', '<u2', '<u2'], + 'offsets':[4, 0, 2]}, align=True) assert_equal(dt.itemsize, 8) - dt2 = np.dtype({'names':['f2','f0','f1'], - 'formats':['<u2', '<u4','<u2'], - 'offsets':[2,4,0]}, align=True) - vals = [(0,1,2), (3,-1,4)] - vals2 = [(2,0,1), (4,3,-1)] + dt2 = np.dtype({'names':['f2', 'f0', 'f1'], + 'formats':['<u2', '<u4', '<u2'], + 'offsets':[2, 4, 0]}, align=True) + vals = [(0, 1, 2), (3, -1, 4)] + vals2 = [(2, 0, 1), (4, 3, -1)] a = np.array(vals, dt) b = np.array(vals2, dt2) assert_equal(a.astype(dt2), b) @@ -206,23 +206,23 @@ class TestRecord(TestCase): assert_equal(b.view(dt), a) # Should not be able to overlap objects with other types assert_raises(TypeError, np.dtype, - {'names':['f0','f1'], + {'names':['f0', 'f1'], 'formats':['O', 'i1'], - 'offsets':[0,2]}) + 'offsets':[0, 2]}) assert_raises(TypeError, np.dtype, - {'names':['f0','f1'], + {'names':['f0', 'f1'], 'formats':['i4', 'O'], - 'offsets':[0,3]}) + 'offsets':[0, 3]}) assert_raises(TypeError, np.dtype, - {'names':['f0','f1'], - 'formats':[[('a','O')], 'i1'], - 'offsets':[0,2]}) + {'names':['f0', 'f1'], + 'formats':[[('a', 'O')], 'i1'], + 'offsets':[0, 2]}) assert_raises(TypeError, np.dtype, - {'names':['f0','f1'], - 'formats':['i4', [('a','O')]], - 'offsets':[0,3]}) + {'names':['f0', 'f1'], + 'formats':['i4', [('a', 'O')]], + 'offsets':[0, 3]}) # Out of order should still be ok, however - dt = np.dtype({'names':['f0','f1'], + dt = np.dtype({'names':['f0', 'f1'], 'formats':['i1', 'O'], 'offsets':[np.dtype('intp').itemsize, 0]}) @@ -263,38 +263,38 @@ class TestSubarray(TestCase): def test_shape_equal(self): """Test some data types that are equal""" - assert_dtype_equal(np.dtype('f8'), np.dtype(('f8',tuple()))) - assert_dtype_equal(np.dtype('f8'), np.dtype(('f8',1))) - assert_dtype_equal(np.dtype((np.int,2)), np.dtype((np.int,(2,)))) - assert_dtype_equal(np.dtype(('<f4',(3,2))), np.dtype(('<f4',(3,2)))) - d = ([('a','f4',(1,2)),('b','f8',(3,1))],(3,2)) + assert_dtype_equal(np.dtype('f8'), np.dtype(('f8', tuple()))) + assert_dtype_equal(np.dtype('f8'), np.dtype(('f8', 1))) + assert_dtype_equal(np.dtype((np.int, 2)), np.dtype((np.int, (2,)))) + assert_dtype_equal(np.dtype(('<f4', (3, 2))), np.dtype(('<f4', (3, 2)))) + d = ([('a', 'f4', (1, 2)), ('b', 'f8', (3, 1))], (3, 2)) assert_dtype_equal(np.dtype(d), np.dtype(d)) def test_shape_simple(self): """Test some simple cases that shouldn't be equal""" - assert_dtype_not_equal(np.dtype('f8'), np.dtype(('f8',(1,)))) - assert_dtype_not_equal(np.dtype(('f8',(1,))), np.dtype(('f8',(1,1)))) - assert_dtype_not_equal(np.dtype(('f4',(3,2))), np.dtype(('f4',(2,3)))) + assert_dtype_not_equal(np.dtype('f8'), np.dtype(('f8', (1,)))) + assert_dtype_not_equal(np.dtype(('f8', (1,))), np.dtype(('f8', (1, 1)))) + assert_dtype_not_equal(np.dtype(('f4', (3, 2))), np.dtype(('f4', (2, 3)))) def test_shape_monster(self): """Test some more complicated cases that shouldn't be equal""" assert_dtype_not_equal( - np.dtype(([('a','f4',(2,1)), ('b','f8',(1,3))],(2,2))), - np.dtype(([('a','f4',(1,2)), ('b','f8',(1,3))],(2,2)))) + np.dtype(([('a', 'f4', (2, 1)), ('b', 'f8', (1, 3))], (2, 2))), + np.dtype(([('a', 'f4', (1, 2)), ('b', 'f8', (1, 3))], (2, 2)))) assert_dtype_not_equal( - np.dtype(([('a','f4',(2,1)), ('b','f8',(1,3))],(2,2))), - np.dtype(([('a','f4',(2,1)), ('b','i8',(1,3))],(2,2)))) + np.dtype(([('a', 'f4', (2, 1)), ('b', 'f8', (1, 3))], (2, 2))), + np.dtype(([('a', 'f4', (2, 1)), ('b', 'i8', (1, 3))], (2, 2)))) assert_dtype_not_equal( - np.dtype(([('a','f4',(2,1)), ('b','f8',(1,3))],(2,2))), - np.dtype(([('e','f8',(1,3)), ('d','f4',(2,1))],(2,2)))) + np.dtype(([('a', 'f4', (2, 1)), ('b', 'f8', (1, 3))], (2, 2))), + np.dtype(([('e', 'f8', (1, 3)), ('d', 'f4', (2, 1))], (2, 2)))) assert_dtype_not_equal( - np.dtype(([('a',[('a','i4',6)],(2,1)), ('b','f8',(1,3))],(2,2))), - np.dtype(([('a',[('a','u4',6)],(2,1)), ('b','f8',(1,3))],(2,2)))) + np.dtype(([('a', [('a', 'i4', 6)], (2, 1)), ('b', 'f8', (1, 3))], (2, 2))), + np.dtype(([('a', [('a', 'u4', 6)], (2, 1)), ('b', 'f8', (1, 3))], (2, 2)))) class TestMonsterType(TestCase): """Test deeply nested subtypes.""" def test1(self): - simple1 = np.dtype({'names': ['r','b'], 'formats': ['u1', 'u1'], + simple1 = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'], 'titles': ['Red pixel', 'Blue pixel']}) a = np.dtype([('yo', np.int), ('ye', simple1), ('yi', np.dtype((np.int, (3, 2))))]) @@ -357,7 +357,7 @@ class TestString(TestCase): "'aligned':True}") assert_equal(np.dtype(eval(str(dt))), dt) - dt = np.dtype({'names': ['r','g','b'], 'formats': ['u1', 'u1', 'u1'], + dt = np.dtype({'names': ['r', 'g', 'b'], 'formats': ['u1', 'u1', 'u1'], 'offsets': [0, 1, 2], 'titles': ['Red pixel', 'Green pixel', 'Blue pixel']}) assert_equal(str(dt), @@ -365,7 +365,7 @@ class TestString(TestCase): "(('Green pixel', 'g'), 'u1'), " "(('Blue pixel', 'b'), 'u1')]") - dt = np.dtype({'names': ['rgba', 'r','g','b'], + dt = np.dtype({'names': ['rgba', 'r', 'g', 'b'], 'formats': ['<u4', 'u1', 'u1', 'u1'], 'offsets': [0, 0, 1, 2], 'titles': ['Color', 'Red pixel', @@ -378,7 +378,7 @@ class TestString(TestCase): "'Green pixel','Blue pixel']," " 'itemsize':4}") - dt = np.dtype({'names': ['r','b'], 'formats': ['u1', 'u1'], + dt = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'], 'offsets': [0, 2], 'titles': ['Red pixel', 'Blue pixel']}) assert_equal(str(dt), @@ -403,7 +403,7 @@ class TestString(TestCase): "('bottom', [('bleft', ('>f4', (8, 64)), (1,)), " "('bright', '>f4', (8, 36))])])") - dt = np.dtype({'names': ['r','g','b'], 'formats': ['u1', 'u1', 'u1'], + dt = np.dtype({'names': ['r', 'g', 'b'], 'formats': ['u1', 'u1', 'u1'], 'offsets': [0, 1, 2], 'titles': ['Red pixel', 'Green pixel', 'Blue pixel']}, align=True) @@ -412,7 +412,7 @@ class TestString(TestCase): "(('Green pixel', 'g'), 'u1'), " "(('Blue pixel', 'b'), 'u1')], align=True)") - dt = np.dtype({'names': ['rgba', 'r','g','b'], + dt = np.dtype({'names': ['rgba', 'r', 'g', 'b'], 'formats': ['<u4', 'u1', 'u1', 'u1'], 'offsets': [0, 0, 1, 2], 'titles': ['Color', 'Red pixel', @@ -425,7 +425,7 @@ class TestString(TestCase): "'Green pixel','Blue pixel']," " 'itemsize':4}, align=True)") - dt = np.dtype({'names': ['r','b'], 'formats': ['u1', 'u1'], + dt = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'], 'offsets': [0, 2], 'titles': ['Red pixel', 'Blue pixel'], 'itemsize': 4}) diff --git a/numpy/core/tests/test_einsum.py b/numpy/core/tests/test_einsum.py index e7480a269..31f94bf07 100644 --- a/numpy/core/tests/test_einsum.py +++ b/numpy/core/tests/test_einsum.py @@ -38,42 +38,42 @@ class TestEinSum(TestCase): # can't have more subscripts than dimensions in the operand assert_raises(ValueError, np.einsum, "i", 0) - assert_raises(ValueError, np.einsum, "ij", [0,0]) + assert_raises(ValueError, np.einsum, "ij", [0, 0]) assert_raises(ValueError, np.einsum, "...i", 0) - assert_raises(ValueError, np.einsum, "i...j", [0,0]) + assert_raises(ValueError, np.einsum, "i...j", [0, 0]) assert_raises(ValueError, np.einsum, "i...", 0) - assert_raises(ValueError, np.einsum, "ij...", [0,0]) + assert_raises(ValueError, np.einsum, "ij...", [0, 0]) # invalid ellipsis - assert_raises(ValueError, np.einsum, "i..", [0,0]) - assert_raises(ValueError, np.einsum, ".i...", [0,0]) - assert_raises(ValueError, np.einsum, "j->..j", [0,0]) - assert_raises(ValueError, np.einsum, "j->.j...", [0,0]) + assert_raises(ValueError, np.einsum, "i..", [0, 0]) + assert_raises(ValueError, np.einsum, ".i...", [0, 0]) + assert_raises(ValueError, np.einsum, "j->..j", [0, 0]) + assert_raises(ValueError, np.einsum, "j->.j...", [0, 0]) # invalid subscript character - assert_raises(ValueError, np.einsum, "i%...", [0,0]) - assert_raises(ValueError, np.einsum, "...j$", [0,0]) - assert_raises(ValueError, np.einsum, "i->&", [0,0]) + assert_raises(ValueError, np.einsum, "i%...", [0, 0]) + assert_raises(ValueError, np.einsum, "...j$", [0, 0]) + assert_raises(ValueError, np.einsum, "i->&", [0, 0]) # output subscripts must appear in input - assert_raises(ValueError, np.einsum, "i->ij", [0,0]) + assert_raises(ValueError, np.einsum, "i->ij", [0, 0]) # output subscripts may only be specified once - assert_raises(ValueError, np.einsum, "ij->jij", [[0,0],[0,0]]) + assert_raises(ValueError, np.einsum, "ij->jij", [[0, 0], [0, 0]]) # dimensions much match when being collapsed - assert_raises(ValueError, np.einsum, "ii", np.arange(6).reshape(2,3)) - assert_raises(ValueError, np.einsum, "ii->i", np.arange(6).reshape(2,3)) + assert_raises(ValueError, np.einsum, "ii", np.arange(6).reshape(2, 3)) + assert_raises(ValueError, np.einsum, "ii->i", np.arange(6).reshape(2, 3)) # broadcasting to new dimensions must be enabled explicitly - assert_raises(ValueError, np.einsum, "i", np.arange(6).reshape(2,3)) - assert_raises(ValueError, np.einsum, "i->i", [[0,1],[0,1]], - out=np.arange(4).reshape(2,2)) + assert_raises(ValueError, np.einsum, "i", np.arange(6).reshape(2, 3)) + assert_raises(ValueError, np.einsum, "i->i", [[0, 1], [0, 1]], + out=np.arange(4).reshape(2, 2)) def test_einsum_views(self): # pass-through a = np.arange(6) - a.shape = (2,3) + a.shape = (2, 3) b = np.einsum("...", a) assert_(b.base is a) @@ -85,186 +85,186 @@ class TestEinSum(TestCase): assert_(b.base is a) assert_equal(b, a) - b = np.einsum(a, [0,1]) + b = np.einsum(a, [0, 1]) assert_(b.base is a) assert_equal(b, a) # transpose a = np.arange(6) - a.shape = (2,3) + a.shape = (2, 3) b = np.einsum("ji", a) assert_(b.base is a) assert_equal(b, a.T) - b = np.einsum(a, [1,0]) + b = np.einsum(a, [1, 0]) assert_(b.base is a) assert_equal(b, a.T) # diagonal a = np.arange(9) - a.shape = (3,3) + a.shape = (3, 3) b = np.einsum("ii->i", a) assert_(b.base is a) - assert_equal(b, [a[i,i] for i in range(3)]) + assert_equal(b, [a[i, i] for i in range(3)]) - b = np.einsum(a, [0,0], [0]) + b = np.einsum(a, [0, 0], [0]) assert_(b.base is a) - assert_equal(b, [a[i,i] for i in range(3)]) + assert_equal(b, [a[i, i] for i in range(3)]) # diagonal with various ways of broadcasting an additional dimension a = np.arange(27) - a.shape = (3,3,3) + a.shape = (3, 3, 3) b = np.einsum("...ii->...i", a) assert_(b.base is a) - assert_equal(b, [[x[i,i] for i in range(3)] for x in a]) + assert_equal(b, [[x[i, i] for i in range(3)] for x in a]) - b = np.einsum(a, [Ellipsis,0,0], [Ellipsis,0]) + b = np.einsum(a, [Ellipsis, 0, 0], [Ellipsis, 0]) assert_(b.base is a) - assert_equal(b, [[x[i,i] for i in range(3)] for x in a]) + assert_equal(b, [[x[i, i] for i in range(3)] for x in a]) b = np.einsum("ii...->...i", a) assert_(b.base is a) - assert_equal(b, [[x[i,i] for i in range(3)] - for x in a.transpose(2,0,1)]) + assert_equal(b, [[x[i, i] for i in range(3)] + for x in a.transpose(2, 0, 1)]) - b = np.einsum(a, [0,0,Ellipsis], [Ellipsis,0]) + b = np.einsum(a, [0, 0, Ellipsis], [Ellipsis, 0]) assert_(b.base is a) - assert_equal(b, [[x[i,i] for i in range(3)] - for x in a.transpose(2,0,1)]) + assert_equal(b, [[x[i, i] for i in range(3)] + for x in a.transpose(2, 0, 1)]) b = np.einsum("...ii->i...", a) assert_(b.base is a) - assert_equal(b, [a[:,i,i] for i in range(3)]) + assert_equal(b, [a[:, i, i] for i in range(3)]) - b = np.einsum(a, [Ellipsis,0,0], [0,Ellipsis]) + b = np.einsum(a, [Ellipsis, 0, 0], [0, Ellipsis]) assert_(b.base is a) - assert_equal(b, [a[:,i,i] for i in range(3)]) + assert_equal(b, [a[:, i, i] for i in range(3)]) b = np.einsum("jii->ij", a) assert_(b.base is a) - assert_equal(b, [a[:,i,i] for i in range(3)]) + assert_equal(b, [a[:, i, i] for i in range(3)]) - b = np.einsum(a, [1,0,0], [0,1]) + b = np.einsum(a, [1, 0, 0], [0, 1]) assert_(b.base is a) - assert_equal(b, [a[:,i,i] for i in range(3)]) + assert_equal(b, [a[:, i, i] for i in range(3)]) b = np.einsum("ii...->i...", a) assert_(b.base is a) - assert_equal(b, [a.transpose(2,0,1)[:,i,i] for i in range(3)]) + assert_equal(b, [a.transpose(2, 0, 1)[:, i, i] for i in range(3)]) - b = np.einsum(a, [0,0,Ellipsis], [0,Ellipsis]) + b = np.einsum(a, [0, 0, Ellipsis], [0, Ellipsis]) assert_(b.base is a) - assert_equal(b, [a.transpose(2,0,1)[:,i,i] for i in range(3)]) + assert_equal(b, [a.transpose(2, 0, 1)[:, i, i] for i in range(3)]) b = np.einsum("i...i->i...", a) assert_(b.base is a) - assert_equal(b, [a.transpose(1,0,2)[:,i,i] for i in range(3)]) + assert_equal(b, [a.transpose(1, 0, 2)[:, i, i] for i in range(3)]) - b = np.einsum(a, [0,Ellipsis,0], [0,Ellipsis]) + b = np.einsum(a, [0, Ellipsis, 0], [0, Ellipsis]) assert_(b.base is a) - assert_equal(b, [a.transpose(1,0,2)[:,i,i] for i in range(3)]) + assert_equal(b, [a.transpose(1, 0, 2)[:, i, i] for i in range(3)]) b = np.einsum("i...i->...i", a) assert_(b.base is a) - assert_equal(b, [[x[i,i] for i in range(3)] - for x in a.transpose(1,0,2)]) + assert_equal(b, [[x[i, i] for i in range(3)] + for x in a.transpose(1, 0, 2)]) - b = np.einsum(a, [0,Ellipsis,0], [Ellipsis,0]) + b = np.einsum(a, [0, Ellipsis, 0], [Ellipsis, 0]) assert_(b.base is a) - assert_equal(b, [[x[i,i] for i in range(3)] - for x in a.transpose(1,0,2)]) + assert_equal(b, [[x[i, i] for i in range(3)] + for x in a.transpose(1, 0, 2)]) # triple diagonal a = np.arange(27) - a.shape = (3,3,3) + a.shape = (3, 3, 3) b = np.einsum("iii->i", a) assert_(b.base is a) - assert_equal(b, [a[i,i,i] for i in range(3)]) + assert_equal(b, [a[i, i, i] for i in range(3)]) - b = np.einsum(a, [0,0,0], [0]) + b = np.einsum(a, [0, 0, 0], [0]) assert_(b.base is a) - assert_equal(b, [a[i,i,i] for i in range(3)]) + assert_equal(b, [a[i, i, i] for i in range(3)]) # swap axes a = np.arange(24) - a.shape = (2,3,4) + a.shape = (2, 3, 4) b = np.einsum("ijk->jik", a) assert_(b.base is a) - assert_equal(b, a.swapaxes(0,1)) + assert_equal(b, a.swapaxes(0, 1)) - b = np.einsum(a, [0,1,2], [1,0,2]) + b = np.einsum(a, [0, 1, 2], [1, 0, 2]) assert_(b.base is a) - assert_equal(b, a.swapaxes(0,1)) + assert_equal(b, a.swapaxes(0, 1)) def check_einsum_sums(self, dtype): # Check various sums. Does many sizes to exercise unrolled loops. # sum(a, axis=-1) - for n in range(1,17): + for n in range(1, 17): a = np.arange(n, dtype=dtype) assert_equal(np.einsum("i->", a), np.sum(a, axis=-1).astype(dtype)) assert_equal(np.einsum(a, [0], []), np.sum(a, axis=-1).astype(dtype)) - for n in range(1,17): - a = np.arange(2*3*n, dtype=dtype).reshape(2,3,n) + for n in range(1, 17): + a = np.arange(2*3*n, dtype=dtype).reshape(2, 3, n) assert_equal(np.einsum("...i->...", a), np.sum(a, axis=-1).astype(dtype)) - assert_equal(np.einsum(a, [Ellipsis,0], [Ellipsis]), + assert_equal(np.einsum(a, [Ellipsis, 0], [Ellipsis]), np.sum(a, axis=-1).astype(dtype)) # sum(a, axis=0) - for n in range(1,17): - a = np.arange(2*n, dtype=dtype).reshape(2,n) + for n in range(1, 17): + a = np.arange(2*n, dtype=dtype).reshape(2, n) assert_equal(np.einsum("i...->...", a), np.sum(a, axis=0).astype(dtype)) - assert_equal(np.einsum(a, [0,Ellipsis], [Ellipsis]), + assert_equal(np.einsum(a, [0, Ellipsis], [Ellipsis]), np.sum(a, axis=0).astype(dtype)) - for n in range(1,17): - a = np.arange(2*3*n, dtype=dtype).reshape(2,3,n) + for n in range(1, 17): + a = np.arange(2*3*n, dtype=dtype).reshape(2, 3, n) assert_equal(np.einsum("i...->...", a), np.sum(a, axis=0).astype(dtype)) - assert_equal(np.einsum(a, [0,Ellipsis], [Ellipsis]), + assert_equal(np.einsum(a, [0, Ellipsis], [Ellipsis]), np.sum(a, axis=0).astype(dtype)) # trace(a) - for n in range(1,17): - a = np.arange(n*n, dtype=dtype).reshape(n,n) + for n in range(1, 17): + a = np.arange(n*n, dtype=dtype).reshape(n, n) assert_equal(np.einsum("ii", a), np.trace(a).astype(dtype)) - assert_equal(np.einsum(a, [0,0]), np.trace(a).astype(dtype)) + assert_equal(np.einsum(a, [0, 0]), np.trace(a).astype(dtype)) # multiply(a, b) assert_equal(np.einsum("..., ...", 3, 4), 12) # scalar case - for n in range(1,17): - a = np.arange(3*n, dtype=dtype).reshape(3,n) - b = np.arange(2*3*n, dtype=dtype).reshape(2,3,n) + for n in range(1, 17): + a = np.arange(3*n, dtype=dtype).reshape(3, n) + b = np.arange(2*3*n, dtype=dtype).reshape(2, 3, n) assert_equal(np.einsum("..., ...", a, b), np.multiply(a, b)) assert_equal(np.einsum(a, [Ellipsis], b, [Ellipsis]), np.multiply(a, b)) # inner(a,b) - for n in range(1,17): - a = np.arange(2*3*n, dtype=dtype).reshape(2,3,n) + for n in range(1, 17): + a = np.arange(2*3*n, dtype=dtype).reshape(2, 3, n) b = np.arange(n, dtype=dtype) assert_equal(np.einsum("...i, ...i", a, b), np.inner(a, b)) - assert_equal(np.einsum(a, [Ellipsis,0], b, [Ellipsis,0]), + assert_equal(np.einsum(a, [Ellipsis, 0], b, [Ellipsis, 0]), np.inner(a, b)) - for n in range(1,11): - a = np.arange(n*3*2, dtype=dtype).reshape(n,3,2) + for n in range(1, 11): + a = np.arange(n*3*2, dtype=dtype).reshape(n, 3, 2) b = np.arange(n, dtype=dtype) assert_equal(np.einsum("i..., i...", a, b), np.inner(a.T, b.T).T) - assert_equal(np.einsum(a, [0,Ellipsis], b, [0,Ellipsis]), + assert_equal(np.einsum(a, [0, Ellipsis], b, [0, Ellipsis]), np.inner(a.T, b.T).T) # outer(a,b) - for n in range(1,17): + for n in range(1, 17): a = np.arange(3, dtype=dtype)+1 b = np.arange(n, dtype=dtype)+1 assert_equal(np.einsum("i,j", a, b), np.outer(a, b)) @@ -275,11 +275,11 @@ class TestEinSum(TestCase): warnings.simplefilter('ignore', np.ComplexWarning) # matvec(a,b) / a.dot(b) where a is matrix, b is vector - for n in range(1,17): - a = np.arange(4*n, dtype=dtype).reshape(4,n) + for n in range(1, 17): + a = np.arange(4*n, dtype=dtype).reshape(4, n) b = np.arange(n, dtype=dtype) assert_equal(np.einsum("ij, j", a, b), np.dot(a, b)) - assert_equal(np.einsum(a, [0,1], b, [1]), np.dot(a, b)) + assert_equal(np.einsum(a, [0, 1], b, [1]), np.dot(a, b)) c = np.arange(4, dtype=dtype) np.einsum("ij,j", a, b, out=c, @@ -288,17 +288,17 @@ class TestEinSum(TestCase): np.dot(a.astype('f8'), b.astype('f8')).astype(dtype)) c[...] = 0 - np.einsum(a, [0,1], b, [1], out=c, + np.einsum(a, [0, 1], b, [1], out=c, dtype='f8', casting='unsafe') assert_equal(c, np.dot(a.astype('f8'), b.astype('f8')).astype(dtype)) - for n in range(1,17): - a = np.arange(4*n, dtype=dtype).reshape(4,n) + for n in range(1, 17): + a = np.arange(4*n, dtype=dtype).reshape(4, n) b = np.arange(n, dtype=dtype) assert_equal(np.einsum("ji,j", a.T, b.T), np.dot(b.T, a.T)) - assert_equal(np.einsum(a.T, [1,0], b.T, [1]), np.dot(b.T, a.T)) + assert_equal(np.einsum(a.T, [1, 0], b.T, [1]), np.dot(b.T, a.T)) c = np.arange(4, dtype=dtype) np.einsum("ji,j", a.T, b.T, out=c, dtype='f8', casting='unsafe') @@ -306,30 +306,30 @@ class TestEinSum(TestCase): np.dot(b.T.astype('f8'), a.T.astype('f8')).astype(dtype)) c[...] = 0 - np.einsum(a.T, [1,0], b.T, [1], out=c, + np.einsum(a.T, [1, 0], b.T, [1], out=c, dtype='f8', casting='unsafe') assert_equal(c, np.dot(b.T.astype('f8'), a.T.astype('f8')).astype(dtype)) # matmat(a,b) / a.dot(b) where a is matrix, b is matrix - for n in range(1,17): + for n in range(1, 17): if n < 8 or dtype != 'f2': - a = np.arange(4*n, dtype=dtype).reshape(4,n) - b = np.arange(n*6, dtype=dtype).reshape(n,6) + a = np.arange(4*n, dtype=dtype).reshape(4, n) + b = np.arange(n*6, dtype=dtype).reshape(n, 6) assert_equal(np.einsum("ij,jk", a, b), np.dot(a, b)) - assert_equal(np.einsum(a, [0,1], b, [1,2]), np.dot(a, b)) + assert_equal(np.einsum(a, [0, 1], b, [1, 2]), np.dot(a, b)) - for n in range(1,17): - a = np.arange(4*n, dtype=dtype).reshape(4,n) - b = np.arange(n*6, dtype=dtype).reshape(n,6) - c = np.arange(24, dtype=dtype).reshape(4,6) + for n in range(1, 17): + a = np.arange(4*n, dtype=dtype).reshape(4, n) + b = np.arange(n*6, dtype=dtype).reshape(n, 6) + c = np.arange(24, dtype=dtype).reshape(4, 6) np.einsum("ij,jk", a, b, out=c, dtype='f8', casting='unsafe') assert_equal(c, np.dot(a.astype('f8'), b.astype('f8')).astype(dtype)) c[...] = 0 - np.einsum(a, [0,1], b, [1,2], out=c, + np.einsum(a, [0, 1], b, [1, 2], out=c, dtype='f8', casting='unsafe') assert_equal(c, np.dot(a.astype('f8'), @@ -337,50 +337,50 @@ class TestEinSum(TestCase): # matrix triple product (note this is not currently an efficient # way to multiply 3 matrices) - a = np.arange(12, dtype=dtype).reshape(3,4) - b = np.arange(20, dtype=dtype).reshape(4,5) - c = np.arange(30, dtype=dtype).reshape(5,6) + a = np.arange(12, dtype=dtype).reshape(3, 4) + b = np.arange(20, dtype=dtype).reshape(4, 5) + c = np.arange(30, dtype=dtype).reshape(5, 6) if dtype != 'f2': assert_equal(np.einsum("ij,jk,kl", a, b, c), a.dot(b).dot(c)) - assert_equal(np.einsum(a, [0,1], b, [1,2], c, [2,3]), + assert_equal(np.einsum(a, [0, 1], b, [1, 2], c, [2, 3]), a.dot(b).dot(c)) - d = np.arange(18, dtype=dtype).reshape(3,6) + d = np.arange(18, dtype=dtype).reshape(3, 6) np.einsum("ij,jk,kl", a, b, c, out=d, dtype='f8', casting='unsafe') assert_equal(d, a.astype('f8').dot(b.astype('f8') ).dot(c.astype('f8')).astype(dtype)) d[...] = 0 - np.einsum(a, [0,1], b, [1,2], c, [2,3], out=d, + np.einsum(a, [0, 1], b, [1, 2], c, [2, 3], out=d, dtype='f8', casting='unsafe') assert_equal(d, a.astype('f8').dot(b.astype('f8') ).dot(c.astype('f8')).astype(dtype)) # tensordot(a, b) if np.dtype(dtype) != np.dtype('f2'): - a = np.arange(60, dtype=dtype).reshape(3,4,5) - b = np.arange(24, dtype=dtype).reshape(4,3,2) + a = np.arange(60, dtype=dtype).reshape(3, 4, 5) + b = np.arange(24, dtype=dtype).reshape(4, 3, 2) assert_equal(np.einsum("ijk, jil -> kl", a, b), - np.tensordot(a,b, axes=([1,0],[0,1]))) - assert_equal(np.einsum(a, [0,1,2], b, [1,0,3], [2,3]), - np.tensordot(a,b, axes=([1,0],[0,1]))) + np.tensordot(a, b, axes=([1, 0], [0, 1]))) + assert_equal(np.einsum(a, [0, 1, 2], b, [1, 0, 3], [2, 3]), + np.tensordot(a, b, axes=([1, 0], [0, 1]))) - c = np.arange(10, dtype=dtype).reshape(5,2) + c = np.arange(10, dtype=dtype).reshape(5, 2) np.einsum("ijk,jil->kl", a, b, out=c, dtype='f8', casting='unsafe') assert_equal(c, np.tensordot(a.astype('f8'), b.astype('f8'), - axes=([1,0],[0,1])).astype(dtype)) + axes=([1, 0], [0, 1])).astype(dtype)) c[...] = 0 - np.einsum(a, [0,1,2], b, [1,0,3], [2,3], out=c, + np.einsum(a, [0, 1, 2], b, [1, 0, 3], [2, 3], out=c, dtype='f8', casting='unsafe') assert_equal(c, np.tensordot(a.astype('f8'), b.astype('f8'), - axes=([1,0],[0,1])).astype(dtype)) + axes=([1, 0], [0, 1])).astype(dtype)) # logical_and(logical_and(a!=0, b!=0), c!=0) a = np.array([1, 3, -2, 0, 12, 13, 0, 1], dtype=dtype) b = np.array([0, 3.5, 0., -2, 0, 1, 3, 12], dtype=dtype) - c = np.array([True,True,False,True,True,False,True,True]) + c = np.array([True, True, False, True, True, False, True, True]) assert_equal(np.einsum("i,i,i->i", a, b, c, dtype='?', casting='unsafe'), np.logical_and(np.logical_and(a!=0, b!=0), c!=0)) @@ -395,20 +395,20 @@ class TestEinSum(TestCase): assert_equal(np.einsum(a, [0], 3, [], []), 3*np.sum(a)) # Various stride0, contiguous, and SSE aligned variants - for n in range(1,25): + for n in range(1, 25): a = np.arange(n, dtype=dtype) if np.dtype(dtype).itemsize > 1: - assert_equal(np.einsum("...,...",a,a), np.multiply(a,a)) - assert_equal(np.einsum("i,i", a, a), np.dot(a,a)) + assert_equal(np.einsum("...,...", a, a), np.multiply(a, a)) + assert_equal(np.einsum("i,i", a, a), np.dot(a, a)) assert_equal(np.einsum("i,->i", a, 2), 2*a) assert_equal(np.einsum(",i->i", 2, a), 2*a) assert_equal(np.einsum("i,->", a, 2), 2*np.sum(a)) assert_equal(np.einsum(",i->", 2, a), 2*np.sum(a)) - assert_equal(np.einsum("...,...",a[1:],a[:-1]), - np.multiply(a[1:],a[:-1])) + assert_equal(np.einsum("...,...", a[1:], a[:-1]), + np.multiply(a[1:], a[:-1])) assert_equal(np.einsum("i,i", a[1:], a[:-1]), - np.dot(a[1:],a[:-1])) + np.dot(a[1:], a[:-1])) assert_equal(np.einsum("i,->i", a[1:], 2), 2*a[1:]) assert_equal(np.einsum(",i->i", 2, a[1:]), 2*a[1:]) assert_equal(np.einsum("i,->", a[1:], 2), 2*np.sum(a[1:])) @@ -427,8 +427,8 @@ class TestEinSum(TestCase): # A case which was failing (ticket #1885) p = np.arange(2) + 1 - q = np.arange(4).reshape(2,2) + 3 - r = np.arange(4).reshape(2,2) + 7 + q = np.arange(4).reshape(2, 2) + 3 + r = np.arange(4).reshape(2, 2) + 7 assert_equal(np.einsum('z,mz,zm->', p, q, r), 253) def test_einsum_sums_int8(self): @@ -479,15 +479,15 @@ class TestEinSum(TestCase): def test_einsum_misc(self): # This call used to crash because of a bug in # PyArray_AssignZero - a = np.ones((1,2)) - b = np.ones((2,2,1)) - assert_equal(np.einsum('ij...,j...->i...',a,b), [[[2],[2]]]) + a = np.ones((1, 2)) + b = np.ones((2, 2, 1)) + assert_equal(np.einsum('ij...,j...->i...', a, b), [[[2], [2]]]) # The iterator had an issue with buffering this reduction a = np.ones((5, 12, 4, 2, 3), np.int64) b = np.ones((5, 12, 11), np.int64) - assert_equal(np.einsum('ijklm,ijn,ijn->',a,b,b), - np.einsum('ijklm,ijn->',a,b)) + assert_equal(np.einsum('ijklm,ijn,ijn->', a, b, b), + np.einsum('ijklm,ijn->', a, b)) # Issue #2027, was a problem in the contiguous 3-argument # inner loop implementation diff --git a/numpy/core/tests/test_function_base.py b/numpy/core/tests/test_function_base.py index 6f239a979..efca9ef8a 100644 --- a/numpy/core/tests/test_function_base.py +++ b/numpy/core/tests/test_function_base.py @@ -5,33 +5,33 @@ from numpy import logspace, linspace class TestLogspace(TestCase): def test_basic(self): - y = logspace(0,6) + y = logspace(0, 6) assert_(len(y)==50) - y = logspace(0,6,num=100) + y = logspace(0, 6, num=100) assert_(y[-1] == 10**6) - y = logspace(0,6,endpoint=0) + y = logspace(0, 6, endpoint=0) assert_(y[-1] < 10**6) - y = logspace(0,6,num=7) - assert_array_equal(y,[1,10,100,1e3,1e4,1e5,1e6]) + y = logspace(0, 6, num=7) + assert_array_equal(y, [1, 10, 100, 1e3, 1e4, 1e5, 1e6]) class TestLinspace(TestCase): def test_basic(self): - y = linspace(0,10) + y = linspace(0, 10) assert_(len(y)==50) - y = linspace(2,10,num=100) + y = linspace(2, 10, num=100) assert_(y[-1] == 10) - y = linspace(2,10,endpoint=0) + y = linspace(2, 10, endpoint=0) assert_(y[-1] < 10) def test_corner(self): - y = list(linspace(0,1,1)) + y = list(linspace(0, 1, 1)) assert_(y == [0.0], y) - y = list(linspace(0,1,2.5)) + y = list(linspace(0, 1, 2.5)) assert_(y == [0.0, 1.0]) def test_type(self): - t1 = linspace(0,1,0).dtype - t2 = linspace(0,1,1).dtype - t3 = linspace(0,1,2).dtype + t1 = linspace(0, 1, 0).dtype + t2 = linspace(0, 1, 1).dtype + t3 = linspace(0, 1, 2).dtype assert_equal(t1, t2) assert_equal(t2, t3) diff --git a/numpy/core/tests/test_getlimits.py b/numpy/core/tests/test_getlimits.py index 96ca66b10..6ccdbd5de 100644 --- a/numpy/core/tests/test_getlimits.py +++ b/numpy/core/tests/test_getlimits.py @@ -15,31 +15,31 @@ class TestPythonFloat(TestCase): def test_singleton(self): ftype = finfo(float) ftype2 = finfo(float) - assert_equal(id(ftype),id(ftype2)) + assert_equal(id(ftype), id(ftype2)) class TestHalf(TestCase): def test_singleton(self): ftype = finfo(half) ftype2 = finfo(half) - assert_equal(id(ftype),id(ftype2)) + assert_equal(id(ftype), id(ftype2)) class TestSingle(TestCase): def test_singleton(self): ftype = finfo(single) ftype2 = finfo(single) - assert_equal(id(ftype),id(ftype2)) + assert_equal(id(ftype), id(ftype2)) class TestDouble(TestCase): def test_singleton(self): ftype = finfo(double) ftype2 = finfo(double) - assert_equal(id(ftype),id(ftype2)) + assert_equal(id(ftype), id(ftype2)) class TestLongdouble(TestCase): def test_singleton(self,level=2): ftype = finfo(longdouble) ftype2 = finfo(longdouble) - assert_equal(id(ftype),id(ftype2)) + assert_equal(id(ftype), id(ftype2)) class TestIinfo(TestCase): def test_basic(self): diff --git a/numpy/core/tests/test_half.py b/numpy/core/tests/test_half.py index e5f2eaf9b..928db48b7 100644 --- a/numpy/core/tests/test_half.py +++ b/numpy/core/tests/test_half.py @@ -28,8 +28,8 @@ class TestHalf(TestCase): # An array of all non-NaN float16 values, in sorted order self.nonan_f16 = np.concatenate( - (np.arange(0xfc00,0x7fff,-1, dtype=uint16), - np.arange(0x0000,0x7c01,1, dtype=uint16)) + (np.arange(0xfc00, 0x7fff, -1, dtype=uint16), + np.arange(0x0000, 0x7c01, 1, dtype=uint16)) ) self.nonan_f16.dtype = float16 self.nonan_f32 = np.array(self.nonan_f16, dtype=float32) @@ -65,10 +65,10 @@ class TestHalf(TestCase): b.view(dtype=uint16)) # Check the range for which all integers can be represented - i_int = np.arange(-2048,2049) + i_int = np.arange(-2048, 2049) i_f16 = np.array(i_int, dtype=float16) j = np.array(i_f16, dtype=np.int) - assert_equal(i_int,j) + assert_equal(i_int, j) def test_nans_infs(self): with np.errstate(all='ignore'): @@ -223,17 +223,17 @@ class TestHalf(TestCase): assert_equal(a, np.ones((5,), dtype=float16)) # nonzero and copyswap - a = np.array([0,0,-1,-1/1e20,0,2.0**-24, 7.629e-6], dtype=float16) + a = np.array([0, 0, -1, -1/1e20, 0, 2.0**-24, 7.629e-6], dtype=float16) assert_equal(a.nonzero()[0], - [2,5,6]) + [2, 5, 6]) a = a.byteswap().newbyteorder() assert_equal(a.nonzero()[0], - [2,5,6]) + [2, 5, 6]) # dot a = np.arange(0, 10, 0.5, dtype=float16) b = np.ones((20,), dtype=float16) - assert_equal(np.dot(a,b), + assert_equal(np.dot(a, b), 95) # argmax @@ -247,7 +247,7 @@ class TestHalf(TestCase): # getitem a = np.arange(10, dtype=float16) for i in range(10): - assert_equal(a.item(i),i) + assert_equal(a.item(i), i) def test_spacing_nextafter(self): """Test np.spacing and np.nextafter""" @@ -276,127 +276,127 @@ class TestHalf(TestCase): def test_half_ufuncs(self): """Test the various ufuncs""" - a = np.array([0,1,2,4,2], dtype=float16) - b = np.array([-2,5,1,4,3], dtype=float16) - c = np.array([0,-1,-np.inf,np.nan,6], dtype=float16) - - assert_equal(np.add(a,b), [-2,6,3,8,5]) - assert_equal(np.subtract(a,b), [2,-4,1,0,-1]) - assert_equal(np.multiply(a,b), [0,5,2,16,6]) - assert_equal(np.divide(a,b), [0,0.199951171875,2,1,0.66650390625]) - - assert_equal(np.equal(a,b), [False,False,False,True,False]) - assert_equal(np.not_equal(a,b), [True,True,True,False,True]) - assert_equal(np.less(a,b), [False,True,False,False,True]) - assert_equal(np.less_equal(a,b), [False,True,False,True,True]) - assert_equal(np.greater(a,b), [True,False,True,False,False]) - assert_equal(np.greater_equal(a,b), [True,False,True,True,False]) - assert_equal(np.logical_and(a,b), [False,True,True,True,True]) - assert_equal(np.logical_or(a,b), [True,True,True,True,True]) - assert_equal(np.logical_xor(a,b), [True,False,False,False,False]) - assert_equal(np.logical_not(a), [True,False,False,False,False]) - - assert_equal(np.isnan(c), [False,False,False,True,False]) - assert_equal(np.isinf(c), [False,False,True,False,False]) - assert_equal(np.isfinite(c), [True,True,False,False,True]) - assert_equal(np.signbit(b), [True,False,False,False,False]) - - assert_equal(np.copysign(b,a), [2,5,1,4,3]) - - assert_equal(np.maximum(a,b), [0,5,2,4,3]) - x = np.maximum(b,c) + a = np.array([0, 1, 2, 4, 2], dtype=float16) + b = np.array([-2, 5, 1, 4, 3], dtype=float16) + c = np.array([0, -1, -np.inf, np.nan, 6], dtype=float16) + + assert_equal(np.add(a, b), [-2, 6, 3, 8, 5]) + assert_equal(np.subtract(a, b), [2, -4, 1, 0, -1]) + assert_equal(np.multiply(a, b), [0, 5, 2, 16, 6]) + assert_equal(np.divide(a, b), [0, 0.199951171875, 2, 1, 0.66650390625]) + + assert_equal(np.equal(a, b), [False, False, False, True, False]) + assert_equal(np.not_equal(a, b), [True, True, True, False, True]) + assert_equal(np.less(a, b), [False, True, False, False, True]) + assert_equal(np.less_equal(a, b), [False, True, False, True, True]) + assert_equal(np.greater(a, b), [True, False, True, False, False]) + assert_equal(np.greater_equal(a, b), [True, False, True, True, False]) + assert_equal(np.logical_and(a, b), [False, True, True, True, True]) + assert_equal(np.logical_or(a, b), [True, True, True, True, True]) + assert_equal(np.logical_xor(a, b), [True, False, False, False, False]) + assert_equal(np.logical_not(a), [True, False, False, False, False]) + + assert_equal(np.isnan(c), [False, False, False, True, False]) + assert_equal(np.isinf(c), [False, False, True, False, False]) + assert_equal(np.isfinite(c), [True, True, False, False, True]) + assert_equal(np.signbit(b), [True, False, False, False, False]) + + assert_equal(np.copysign(b, a), [2, 5, 1, 4, 3]) + + assert_equal(np.maximum(a, b), [0, 5, 2, 4, 3]) + x = np.maximum(b, c) assert_(np.isnan(x[3])) x[3] = 0 - assert_equal(x, [0,5,1,0,6]) - assert_equal(np.minimum(a,b), [-2,1,1,4,2]) - x = np.minimum(b,c) + assert_equal(x, [0, 5, 1, 0, 6]) + assert_equal(np.minimum(a, b), [-2, 1, 1, 4, 2]) + x = np.minimum(b, c) assert_(np.isnan(x[3])) x[3] = 0 - assert_equal(x, [-2,-1,-np.inf,0,3]) - assert_equal(np.fmax(a,b), [0,5,2,4,3]) - assert_equal(np.fmax(b,c), [0,5,1,4,6]) - assert_equal(np.fmin(a,b), [-2,1,1,4,2]) - assert_equal(np.fmin(b,c), [-2,-1,-np.inf,4,3]) - - assert_equal(np.floor_divide(a,b), [0,0,2,1,0]) - assert_equal(np.remainder(a,b), [0,1,0,0,2]) - assert_equal(np.square(b), [4,25,1,16,9]) - assert_equal(np.reciprocal(b), [-0.5,0.199951171875,1,0.25,0.333251953125]) - assert_equal(np.ones_like(b), [1,1,1,1,1]) + assert_equal(x, [-2, -1, -np.inf, 0, 3]) + assert_equal(np.fmax(a, b), [0, 5, 2, 4, 3]) + assert_equal(np.fmax(b, c), [0, 5, 1, 4, 6]) + assert_equal(np.fmin(a, b), [-2, 1, 1, 4, 2]) + assert_equal(np.fmin(b, c), [-2, -1, -np.inf, 4, 3]) + + assert_equal(np.floor_divide(a, b), [0, 0, 2, 1, 0]) + assert_equal(np.remainder(a, b), [0, 1, 0, 0, 2]) + assert_equal(np.square(b), [4, 25, 1, 16, 9]) + assert_equal(np.reciprocal(b), [-0.5, 0.199951171875, 1, 0.25, 0.333251953125]) + assert_equal(np.ones_like(b), [1, 1, 1, 1, 1]) assert_equal(np.conjugate(b), b) - assert_equal(np.absolute(b), [2,5,1,4,3]) - assert_equal(np.negative(b), [2,-5,-1,-4,-3]) - assert_equal(np.sign(b), [-1,1,1,1,1]) - assert_equal(np.modf(b), ([0,0,0,0,0],b)) - assert_equal(np.frexp(b), ([-0.5,0.625,0.5,0.5,0.75],[2,3,1,3,2])) - assert_equal(np.ldexp(b,[0,1,2,4,2]), [-2,10,4,64,12]) + assert_equal(np.absolute(b), [2, 5, 1, 4, 3]) + assert_equal(np.negative(b), [2, -5, -1, -4, -3]) + assert_equal(np.sign(b), [-1, 1, 1, 1, 1]) + assert_equal(np.modf(b), ([0, 0, 0, 0, 0], b)) + assert_equal(np.frexp(b), ([-0.5, 0.625, 0.5, 0.5, 0.75], [2, 3, 1, 3, 2])) + assert_equal(np.ldexp(b, [0, 1, 2, 4, 2]), [-2, 10, 4, 64, 12]) def test_half_coercion(self): """Test that half gets coerced properly with the other types""" - a16 = np.array((1,),dtype=float16) - a32 = np.array((1,),dtype=float32) + a16 = np.array((1,), dtype=float16) + a32 = np.array((1,), dtype=float32) b16 = float16(1) b32 = float32(1) - assert_equal(np.power(a16,2).dtype, float16) - assert_equal(np.power(a16,2.0).dtype, float16) - assert_equal(np.power(a16,b16).dtype, float16) - assert_equal(np.power(a16,b32).dtype, float16) - assert_equal(np.power(a16,a16).dtype, float16) - assert_equal(np.power(a16,a32).dtype, float32) - - assert_equal(np.power(b16,2).dtype, float64) - assert_equal(np.power(b16,2.0).dtype, float64) - assert_equal(np.power(b16,b16).dtype, float16) - assert_equal(np.power(b16,b32).dtype, float32) - assert_equal(np.power(b16,a16).dtype, float16) - assert_equal(np.power(b16,a32).dtype, float32) - - assert_equal(np.power(a32,a16).dtype, float32) - assert_equal(np.power(a32,b16).dtype, float32) - assert_equal(np.power(b32,a16).dtype, float16) - assert_equal(np.power(b32,b16).dtype, float32) + assert_equal(np.power(a16, 2).dtype, float16) + assert_equal(np.power(a16, 2.0).dtype, float16) + assert_equal(np.power(a16, b16).dtype, float16) + assert_equal(np.power(a16, b32).dtype, float16) + assert_equal(np.power(a16, a16).dtype, float16) + assert_equal(np.power(a16, a32).dtype, float32) + + assert_equal(np.power(b16, 2).dtype, float64) + assert_equal(np.power(b16, 2.0).dtype, float64) + assert_equal(np.power(b16, b16).dtype, float16) + assert_equal(np.power(b16, b32).dtype, float32) + assert_equal(np.power(b16, a16).dtype, float16) + assert_equal(np.power(b16, a32).dtype, float32) + + assert_equal(np.power(a32, a16).dtype, float32) + assert_equal(np.power(a32, b16).dtype, float32) + assert_equal(np.power(b32, a16).dtype, float16) + assert_equal(np.power(b32, b16).dtype, float32) @dec.skipif(platform.machine() == "armv5tel", "See gh-413.") def test_half_fpe(self): with np.errstate(all='raise'): - sx16 = np.array((1e-4,),dtype=float16) - bx16 = np.array((1e4,),dtype=float16) + sx16 = np.array((1e-4,), dtype=float16) + bx16 = np.array((1e4,), dtype=float16) sy16 = float16(1e-4) by16 = float16(1e4) # Underflow errors - assert_raises_fpe('underflow', lambda a,b:a*b, sx16, sx16) - assert_raises_fpe('underflow', lambda a,b:a*b, sx16, sy16) - assert_raises_fpe('underflow', lambda a,b:a*b, sy16, sx16) - assert_raises_fpe('underflow', lambda a,b:a*b, sy16, sy16) - assert_raises_fpe('underflow', lambda a,b:a/b, sx16, bx16) - assert_raises_fpe('underflow', lambda a,b:a/b, sx16, by16) - assert_raises_fpe('underflow', lambda a,b:a/b, sy16, bx16) - assert_raises_fpe('underflow', lambda a,b:a/b, sy16, by16) - assert_raises_fpe('underflow', lambda a,b:a/b, + assert_raises_fpe('underflow', lambda a, b:a*b, sx16, sx16) + assert_raises_fpe('underflow', lambda a, b:a*b, sx16, sy16) + assert_raises_fpe('underflow', lambda a, b:a*b, sy16, sx16) + assert_raises_fpe('underflow', lambda a, b:a*b, sy16, sy16) + assert_raises_fpe('underflow', lambda a, b:a/b, sx16, bx16) + assert_raises_fpe('underflow', lambda a, b:a/b, sx16, by16) + assert_raises_fpe('underflow', lambda a, b:a/b, sy16, bx16) + assert_raises_fpe('underflow', lambda a, b:a/b, sy16, by16) + assert_raises_fpe('underflow', lambda a, b:a/b, float16(2.**-14), float16(2**11)) - assert_raises_fpe('underflow', lambda a,b:a/b, + assert_raises_fpe('underflow', lambda a, b:a/b, float16(-2.**-14), float16(2**11)) - assert_raises_fpe('underflow', lambda a,b:a/b, + assert_raises_fpe('underflow', lambda a, b:a/b, float16(2.**-14+2**-24), float16(2)) - assert_raises_fpe('underflow', lambda a,b:a/b, + assert_raises_fpe('underflow', lambda a, b:a/b, float16(-2.**-14-2**-24), float16(2)) - assert_raises_fpe('underflow', lambda a,b:a/b, + assert_raises_fpe('underflow', lambda a, b:a/b, float16(2.**-14+2**-23), float16(4)) # Overflow errors - assert_raises_fpe('overflow', lambda a,b:a*b, bx16, bx16) - assert_raises_fpe('overflow', lambda a,b:a*b, bx16, by16) - assert_raises_fpe('overflow', lambda a,b:a*b, by16, bx16) - assert_raises_fpe('overflow', lambda a,b:a*b, by16, by16) - assert_raises_fpe('overflow', lambda a,b:a/b, bx16, sx16) - assert_raises_fpe('overflow', lambda a,b:a/b, bx16, sy16) - assert_raises_fpe('overflow', lambda a,b:a/b, by16, sx16) - assert_raises_fpe('overflow', lambda a,b:a/b, by16, sy16) - assert_raises_fpe('overflow', lambda a,b:a+b, + assert_raises_fpe('overflow', lambda a, b:a*b, bx16, bx16) + assert_raises_fpe('overflow', lambda a, b:a*b, bx16, by16) + assert_raises_fpe('overflow', lambda a, b:a*b, by16, bx16) + assert_raises_fpe('overflow', lambda a, b:a*b, by16, by16) + assert_raises_fpe('overflow', lambda a, b:a/b, bx16, sx16) + assert_raises_fpe('overflow', lambda a, b:a/b, bx16, sy16) + assert_raises_fpe('overflow', lambda a, b:a/b, by16, sx16) + assert_raises_fpe('overflow', lambda a, b:a/b, by16, sy16) + assert_raises_fpe('overflow', lambda a, b:a+b, float16(65504), float16(17)) - assert_raises_fpe('overflow', lambda a,b:a-b, + assert_raises_fpe('overflow', lambda a, b:a-b, float16(-65504), float16(17)) assert_raises_fpe('overflow', np.nextafter, float16(65504), float16(np.inf)) assert_raises_fpe('overflow', np.nextafter, float16(-65504), float16(-np.inf)) diff --git a/numpy/core/tests/test_indexerrors.py b/numpy/core/tests/test_indexerrors.py index 263c505de..e5dc9dbab 100644 --- a/numpy/core/tests/test_indexerrors.py +++ b/numpy/core/tests/test_indexerrors.py @@ -54,34 +54,34 @@ class TestIndexErrors(TestCase): def assign(obj, ind, val): obj[ind] = val - a = np.zeros([1,2,3]) - assert_raises(IndexError, lambda: a[0,5,None,2]) - assert_raises(IndexError, lambda: a[0,5,0,2]) - assert_raises(IndexError, lambda: assign(a, (0,5,None,2), 1)) - assert_raises(IndexError, lambda: assign(a, (0,5,0,2), 1)) + a = np.zeros([1, 2, 3]) + assert_raises(IndexError, lambda: a[0, 5, None, 2]) + assert_raises(IndexError, lambda: a[0, 5, 0, 2]) + assert_raises(IndexError, lambda: assign(a, (0, 5, None, 2), 1)) + assert_raises(IndexError, lambda: assign(a, (0, 5, 0, 2), 1)) - a = np.zeros([1,0,3]) - assert_raises(IndexError, lambda: a[0,0,None,2]) - assert_raises(IndexError, lambda: assign(a, (0,0,None,2), 1)) + a = np.zeros([1, 0, 3]) + assert_raises(IndexError, lambda: a[0, 0, None, 2]) + assert_raises(IndexError, lambda: assign(a, (0, 0, None, 2), 1)) - a = np.zeros([1,2,3]) + a = np.zeros([1, 2, 3]) assert_raises(IndexError, lambda: a.flat[10]) assert_raises(IndexError, lambda: assign(a.flat, 10, 5)) - a = np.zeros([1,0,3]) + a = np.zeros([1, 0, 3]) assert_raises(IndexError, lambda: a.flat[10]) assert_raises(IndexError, lambda: assign(a.flat, 10, 5)) - a = np.zeros([1,2,3]) + a = np.zeros([1, 2, 3]) assert_raises(IndexError, lambda: a.flat[np.array(10)]) assert_raises(IndexError, lambda: assign(a.flat, np.array(10), 5)) - a = np.zeros([1,0,3]) + a = np.zeros([1, 0, 3]) assert_raises(IndexError, lambda: a.flat[np.array(10)]) assert_raises(IndexError, lambda: assign(a.flat, np.array(10), 5)) - a = np.zeros([1,2,3]) + a = np.zeros([1, 2, 3]) assert_raises(IndexError, lambda: a.flat[np.array([10])]) assert_raises(IndexError, lambda: assign(a.flat, np.array([10]), 5)) - a = np.zeros([1,0,3]) + a = np.zeros([1, 0, 3]) assert_raises(IndexError, lambda: a.flat[np.array([10])]) assert_raises(IndexError, lambda: assign(a.flat, np.array([10]), 5)) @@ -94,10 +94,10 @@ class TestIndexErrors(TestCase): a = np.zeros((0, 10)) assert_raises(IndexError, lambda: a[12]) - a = np.zeros((3,5)) + a = np.zeros((3, 5)) assert_raises(IndexError, lambda: a[(10, 20)]) assert_raises(IndexError, lambda: assign(a, (10, 20), 1)) - a = np.zeros((3,0)) + a = np.zeros((3, 0)) assert_raises(IndexError, lambda: a[(1, 0)]) assert_raises(IndexError, lambda: assign(a, (1, 0), 1)) @@ -106,10 +106,10 @@ class TestIndexErrors(TestCase): a = np.zeros((0,)) assert_raises(IndexError, lambda: assign(a, 10, 1)) - a = np.zeros((3,5)) + a = np.zeros((3, 5)) assert_raises(IndexError, lambda: a[(1, [1, 20])]) assert_raises(IndexError, lambda: assign(a, (1, [1, 20]), 1)) - a = np.zeros((3,0)) + a = np.zeros((3, 0)) assert_raises(IndexError, lambda: a[(1, [0, 1])]) assert_raises(IndexError, lambda: assign(a, (1, [0, 1]), 1)) diff --git a/numpy/core/tests/test_indexing.py b/numpy/core/tests/test_indexing.py index ecd93ec71..89e28af78 100644 --- a/numpy/core/tests/test_indexing.py +++ b/numpy/core/tests/test_indexing.py @@ -39,7 +39,7 @@ class TestIndexing(TestCase): def test_ellipsis_index(self): # Ellipsis index does not create a view a = np.array([[1, 2, 3], - [4 ,5, 6], + [4, 5, 6], [7, 8, 9]]) assert_equal(a[...], a) assert_(a[...] is a) @@ -47,7 +47,7 @@ class TestIndexing(TestCase): # Slicing with ellipsis can skip an # arbitrary number of dimensions assert_equal(a[0, ...], a[0]) - assert_equal(a[0, ...], a[0, :]) + assert_equal(a[0, ...], a[0,:]) assert_equal(a[..., 0], a[:, 0]) # Slicing with ellipsis always results @@ -57,7 +57,7 @@ class TestIndexing(TestCase): def test_single_int_index(self): # Single integer index selects one row a = np.array([[1, 2, 3], - [4 ,5, 6], + [4, 5, 6], [7, 8, 9]]) assert_equal(a[0], [1, 2, 3]) @@ -71,7 +71,7 @@ class TestIndexing(TestCase): def test_single_bool_index(self): # Single boolean index a = np.array([[1, 2, 3], - [4 ,5, 6], + [4, 5, 6], [7, 8, 9]]) # Python boolean converts to integer @@ -108,7 +108,7 @@ class TestIndexing(TestCase): # Indexing a 2-dimensional array with # 2-dimensional boolean array a = np.array([[1, 2, 3], - [4 ,5, 6], + [4, 5, 6], [7, 8, 9]]) b = np.array([[ True, False, True], [False, True, False], @@ -140,8 +140,8 @@ class TestMultiIndexingAutomated(TestCase): will usually not be the same one. They are *not* tested. """ def setUp(self): - self.a = np.arange(np.prod([3,1,5,6])).reshape(3,1,5,6) - self.b = np.empty((3,0,5,6)) + self.a = np.arange(np.prod([3, 1, 5, 6])).reshape(3, 1, 5, 6) + self.b = np.empty((3, 0, 5, 6)) self.complex_indices = ['skip', Ellipsis, 0, # Boolean indices, up to 3-d for some special cases of eating up @@ -154,19 +154,19 @@ class TestMultiIndexingAutomated(TestCase): slice(-5, 5, 2), slice(1, 1, 100), slice(4, -1, -2), - slice(None,None,-3), + slice(None, None, -3), # Some Fancy indexes: - np.empty((0,1,1), dtype=np.intp), # empty broadcastable - np.array([0,1,-2]), - np.array([[2],[0],[1]]), - np.array([[0,-1], [0,1]]), - np.array([2,-1]), + np.empty((0, 1, 1), dtype=np.intp), # empty broadcastable + np.array([0, 1, -2]), + np.array([[2], [0], [1]]), + np.array([[0, -1], [0, 1]]), + np.array([2, -1]), np.zeros([1]*31, dtype=int), # trigger too large array. np.array([0., 1.])] # invalid datatype # Some simpler indices that still cover a bit more self.simple_indices = [Ellipsis, None, -1, [1], np.array([True]), 'skip'] # Very simple ones to fill the rest: - self.fill_indices = [slice(None,None), 0] + self.fill_indices = [slice(None, None), 0] def _get_multi_index(self, arr, indices): @@ -226,7 +226,7 @@ class TestMultiIndexingAutomated(TestCase): if ellipsis_pos is None: ellipsis_pos = i continue # do not increment ndim counter - in_indices[i] = slice(None,None) + in_indices[i] = slice(None, None) ndim += 1 continue if isinstance(indx, slice): @@ -258,7 +258,7 @@ class TestMultiIndexingAutomated(TestCase): return arr.copy(), no_copy if ellipsis_pos is not None: - in_indices[ellipsis_pos:ellipsis_pos+1] = [slice(None,None)] * (arr.ndim - ndim) + in_indices[ellipsis_pos:ellipsis_pos+1] = [slice(None, None)] * (arr.ndim - ndim) for ax, indx in enumerate(in_indices): if isinstance(indx, slice): @@ -481,8 +481,8 @@ class TestMultiIndexingAutomated(TestCase): # consistency with arr[boolean_array,] also no broadcasting # is done at all self._check_multi_index(self.a, (np.zeros_like(self.a, dtype=bool),)) - self._check_multi_index(self.a, (np.zeros_like(self.a, dtype=bool)[...,0],)) - self._check_multi_index(self.a, (np.zeros_like(self.a, dtype=bool)[None,...],)) + self._check_multi_index(self.a, (np.zeros_like(self.a, dtype=bool)[..., 0],)) + self._check_multi_index(self.a, (np.zeros_like(self.a, dtype=bool)[None, ...],)) def test_multidim(self): @@ -492,7 +492,7 @@ class TestMultiIndexingAutomated(TestCase): # This is so that np.array(True) is not accepted in a full integer # index, when running the file seperatly. warnings.filterwarnings('error', '', DeprecationWarning) - for simple_pos in [0,2,3]: + for simple_pos in [0, 2, 3]: tocheck = [self.fill_indices, self.complex_indices, self.fill_indices, self.fill_indices] tocheck[simple_pos] = self.simple_indices @@ -502,13 +502,13 @@ class TestMultiIndexingAutomated(TestCase): self._check_multi_index(self.b, index) # Check very simple item getting: - self._check_multi_index(self.a, (0,0,0,0)) - self._check_multi_index(self.b, (0,0,0,0)) + self._check_multi_index(self.a, (0, 0, 0, 0)) + self._check_multi_index(self.b, (0, 0, 0, 0)) # Also check (simple cases of) too many indices: - assert_raises(IndexError, self.a.__getitem__, (0,0,0,0,0)) - assert_raises(IndexError, self.a.__setitem__, (0,0,0,0,0), 0) - assert_raises(IndexError, self.a.__getitem__, (0,0,[1],0,0)) - assert_raises(IndexError, self.a.__setitem__, (0,0,[1],0,0), 0) + assert_raises(IndexError, self.a.__getitem__, (0, 0, 0, 0, 0)) + assert_raises(IndexError, self.a.__setitem__, (0, 0, 0, 0, 0), 0) + assert_raises(IndexError, self.a.__getitem__, (0, 0, [1], 0, 0)) + assert_raises(IndexError, self.a.__setitem__, (0, 0, [1], 0, 0), 0) def test_1d(self): diff --git a/numpy/core/tests/test_item_selection.py b/numpy/core/tests/test_item_selection.py index 9954e1e0f..e501588c9 100644 --- a/numpy/core/tests/test_item_selection.py +++ b/numpy/core/tests/test_item_selection.py @@ -8,12 +8,12 @@ import sys, warnings class TestTake(TestCase): def test_simple(self): a = [[1, 2], [3, 4]] - a_str = [[b'1', b'2'],[b'3', b'4']] + a_str = [[b'1', b'2'], [b'3', b'4']] modes = ['raise', 'wrap', 'clip'] indices = [-1, 4] index_arrays = [np.empty(0, dtype=np.intp), np.empty(tuple(), dtype=np.intp), - np.empty((1,1), dtype=np.intp)] + np.empty((1, 1), dtype=np.intp)] real_indices = {} real_indices['raise'] = {-1:1, 4:IndexError} real_indices['wrap'] = {-1:1, 4:0} diff --git a/numpy/core/tests/test_memmap.py b/numpy/core/tests/test_memmap.py index 97afb68a2..6de6319ef 100644 --- a/numpy/core/tests/test_memmap.py +++ b/numpy/core/tests/test_memmap.py @@ -11,7 +11,7 @@ from numpy.testing import * class TestMemmap(TestCase): def setUp(self): self.tmpfp = NamedTemporaryFile(prefix='mmap') - self.shape = (3,4) + self.shape = (3, 4) self.dtype = 'float32' self.data = arange(12, dtype=self.dtype) self.data.resize(self.shape) @@ -33,7 +33,7 @@ class TestMemmap(TestCase): assert_array_equal(self.data, newfp) def test_open_with_filename(self): - tmpname = mktemp('','mmap') + tmpname = mktemp('', 'mmap') fp = memmap(tmpname, dtype=self.dtype, mode='w+', shape=self.shape) fp[:] = self.data[:] @@ -55,7 +55,7 @@ class TestMemmap(TestCase): del fp def test_filename(self): - tmpname = mktemp('','mmap') + tmpname = mktemp('', 'mmap') fp = memmap(tmpname, dtype=self.dtype, mode='w+', shape=self.shape) abspath = os.path.abspath(tmpname) diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py index 40847aab8..12d1e8ea9 100644 --- a/numpy/core/tests/test_multiarray.py +++ b/numpy/core/tests/test_multiarray.py @@ -63,16 +63,16 @@ class TestFlags(TestCase): class TestAttributes(TestCase): def setUp(self): self.one = arange(10) - self.two = arange(20).reshape(4,5) - self.three = arange(60,dtype=float64).reshape(2,5,6) + self.two = arange(20).reshape(4, 5) + self.three = arange(60, dtype=float64).reshape(2, 5, 6) def test_attributes(self): assert_equal(self.one.shape, (10,)) - assert_equal(self.two.shape, (4,5)) - assert_equal(self.three.shape, (2,5,6)) - self.three.shape = (10,3,2) - assert_equal(self.three.shape, (10,3,2)) - self.three.shape = (2,5,6) + assert_equal(self.two.shape, (4, 5)) + assert_equal(self.three.shape, (2, 5, 6)) + self.three.shape = (10, 3, 2) + assert_equal(self.three.shape, (10, 3, 2)) + self.three.shape = (2, 5, 6) assert_equal(self.one.strides, (self.one.itemsize,)) num = self.two.itemsize assert_equal(self.two.strides, (5*num, num)) @@ -137,13 +137,13 @@ class TestAttributes(TestCase): r.strides = strides=strides*x.itemsize return r assert_equal(make_array(4, 4, -1), array([4, 3, 2, 1])) - assert_equal(make_array(7,3,1), array([3, 4, 5, 6, 7, 8, 9])) + assert_equal(make_array(7, 3, 1), array([3, 4, 5, 6, 7, 8, 9])) self.assertRaises(ValueError, make_array, 4, 4, -2) self.assertRaises(ValueError, make_array, 4, 2, -1) self.assertRaises(RuntimeError, make_array, 8, 3, 1) # Check that the true extent of the array is used. # Test relies on as_strided base not exposing a buffer. - x = np.lib.stride_tricks.as_strided(arange(1), (10,10), (0,0)) + x = np.lib.stride_tricks.as_strided(arange(1), (10, 10), (0, 0)) def set_strides(arr, strides): arr.strides = strides self.assertRaises(ValueError, set_strides, x, (10*x.itemsize, x.itemsize)) @@ -158,15 +158,15 @@ class TestAttributes(TestCase): def test_fill(self): for t in "?bhilqpBHILQPfdgFDGO": - x = empty((3,2,1), t) - y = empty((3,2,1), t) + x = empty((3, 2, 1), t) + y = empty((3, 2, 1), t) x.fill(1) y[...] = 1 - assert_equal(x,y) + assert_equal(x, y) def test_fill_struct_array(self): # Filling from a scalar - x = array([(0,0.0), (1,1.0)], dtype='i4,f8') + x = array([(0, 0.0), (1, 1.0)], dtype='i4,f8') x.fill(x[0]) assert_equal(x['f1'][1], x['f1'][0]) # Filling from a tuple that can be converted @@ -178,13 +178,13 @@ class TestAttributes(TestCase): class TestAssignment(TestCase): def test_assignment_broadcasting(self): - a = np.arange(6).reshape(2,3) + a = np.arange(6).reshape(2, 3) # Broadcasting the input to the output a[...] = np.arange(3) - assert_equal(a, [[0,1,2],[0,1,2]]) - a[...] = np.arange(2).reshape(2,1) - assert_equal(a, [[0,0,0],[1,1,1]]) + assert_equal(a, [[0, 1, 2], [0, 1, 2]]) + a[...] = np.arange(2).reshape(2, 1) + assert_equal(a, [[0, 0, 0], [1, 1, 1]]) # For compatibility with <= 1.5, a limited version of broadcasting # the output to the input. @@ -194,12 +194,12 @@ class TestAssignment(TestCase): # rules (adding a new "1" dimension to the left of the shape), # applied to the output instead of an input. In NumPy 2.0, this kind # of broadcasting assignment will likely be disallowed. - a[...] = np.arange(6)[::-1].reshape(1,2,3) - assert_equal(a, [[5,4,3],[2,1,0]]) + a[...] = np.arange(6)[::-1].reshape(1, 2, 3) + assert_equal(a, [[5, 4, 3], [2, 1, 0]]) # The other type of broadcasting would require a reduction operation. - def assign(a,b): + def assign(a, b): a[...] = b - assert_raises(ValueError, assign, a, np.arange(12).reshape(2,2,3)) + assert_raises(ValueError, assign, a, np.arange(12).reshape(2, 2, 3)) class TestDtypedescr(TestCase): def test_construction(self): @@ -213,42 +213,42 @@ class TestZeroRank(TestCase): self.d = array(0), array('x', object) def test_ellipsis_subscript(self): - a,b = self.d + a, b = self.d self.assertEqual(a[...], 0) self.assertEqual(b[...], 'x') self.assertTrue(a[...] is a) self.assertTrue(b[...] is b) def test_empty_subscript(self): - a,b = self.d + a, b = self.d self.assertEqual(a[()], 0) self.assertEqual(b[()], 'x') self.assertTrue(type(a[()]) is a.dtype.type) self.assertTrue(type(b[()]) is str) def test_invalid_subscript(self): - a,b = self.d + a, b = self.d self.assertRaises(IndexError, lambda x: x[0], a) self.assertRaises(IndexError, lambda x: x[0], b) self.assertRaises(IndexError, lambda x: x[array([], int)], a) self.assertRaises(IndexError, lambda x: x[array([], int)], b) def test_ellipsis_subscript_assignment(self): - a,b = self.d + a, b = self.d a[...] = 42 self.assertEqual(a, 42) b[...] = '' self.assertEqual(b.item(), '') def test_empty_subscript_assignment(self): - a,b = self.d + a, b = self.d a[()] = 42 self.assertEqual(a, 42) b[()] = '' self.assertEqual(b.item(), '') def test_invalid_subscript_assignment(self): - a,b = self.d + a, b = self.d def assign(x, i, v): x[i] = v self.assertRaises(IndexError, assign, a, 0, 42) @@ -256,18 +256,18 @@ class TestZeroRank(TestCase): self.assertRaises(ValueError, assign, a, (), '') def test_newaxis(self): - a,b = self.d + a, b = self.d self.assertEqual(a[newaxis].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) self.assertEqual(a[newaxis, ...].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) - self.assertEqual(a[newaxis, ..., newaxis].shape, (1,1)) - self.assertEqual(a[..., newaxis, newaxis].shape, (1,1)) - self.assertEqual(a[newaxis, newaxis, ...].shape, (1,1)) + self.assertEqual(a[newaxis, ..., newaxis].shape, (1, 1)) + self.assertEqual(a[..., newaxis, newaxis].shape, (1, 1)) + self.assertEqual(a[newaxis, newaxis, ...].shape, (1, 1)) self.assertEqual(a[(newaxis,)*10].shape, (1,)*10) def test_invalid_newaxis(self): - a,b = self.d + a, b = self.d def subscript(x, i): x[i] self.assertRaises(IndexError, subscript, a, (newaxis, 0)) self.assertRaises(IndexError, subscript, a, (newaxis,)*50) @@ -276,7 +276,7 @@ class TestZeroRank(TestCase): x = ndarray(()) x[()] = 5 self.assertEqual(x[()], 5) - y = ndarray((),buffer=x) + y = ndarray((), buffer=x) y[()] = 6 self.assertEqual(x[()], 6) @@ -287,17 +287,17 @@ class TestZeroRank(TestCase): class TestScalarIndexing(TestCase): def setUp(self): - self.d = array([0,1])[0] + self.d = array([0, 1])[0] def test_ellipsis_subscript(self): a = self.d self.assertEqual(a[...], 0) - self.assertEqual(a[...].shape,()) + self.assertEqual(a[...].shape, ()) def test_empty_subscript(self): a = self.d self.assertEqual(a[()], 0) - self.assertEqual(a[()].shape,()) + self.assertEqual(a[()].shape, ()) def test_invalid_subscript(self): a = self.d @@ -316,9 +316,9 @@ class TestScalarIndexing(TestCase): self.assertEqual(a[..., newaxis].shape, (1,)) self.assertEqual(a[newaxis, ...].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) - self.assertEqual(a[newaxis, ..., newaxis].shape, (1,1)) - self.assertEqual(a[..., newaxis, newaxis].shape, (1,1)) - self.assertEqual(a[newaxis, newaxis, ...].shape, (1,1)) + self.assertEqual(a[newaxis, ..., newaxis].shape, (1, 1)) + self.assertEqual(a[..., newaxis, newaxis].shape, (1, 1)) + self.assertEqual(a[newaxis, newaxis, ...].shape, (1, 1)) self.assertEqual(a[(newaxis,)*10].shape, (1,)*10) def test_invalid_newaxis(self): @@ -331,49 +331,49 @@ class TestScalarIndexing(TestCase): # With positive strides a = np.arange(4) a[:-1] = a[1:] - assert_equal(a, [1,2,3,3]) + assert_equal(a, [1, 2, 3, 3]) a = np.arange(4) a[1:] = a[:-1] - assert_equal(a, [0,0,1,2]) + assert_equal(a, [0, 0, 1, 2]) # With positive and negative strides a = np.arange(4) a[:] = a[::-1] - assert_equal(a, [3,2,1,0]) + assert_equal(a, [3, 2, 1, 0]) - a = np.arange(6).reshape(2,3) - a[::-1,:] = a[:,::-1] - assert_equal(a, [[5,4,3],[2,1,0]]) + a = np.arange(6).reshape(2, 3) + a[::-1,:] = a[:, ::-1] + assert_equal(a, [[5, 4, 3], [2, 1, 0]]) - a = np.arange(6).reshape(2,3) - a[::-1,::-1] = a[:,::-1] - assert_equal(a, [[3,4,5],[0,1,2]]) + a = np.arange(6).reshape(2, 3) + a[::-1, ::-1] = a[:, ::-1] + assert_equal(a, [[3, 4, 5], [0, 1, 2]]) # With just one element overlapping a = np.arange(5) a[:3] = a[2:] - assert_equal(a, [2,3,4,3,4]) + assert_equal(a, [2, 3, 4, 3, 4]) a = np.arange(5) a[2:] = a[:3] - assert_equal(a, [0,1,0,1,2]) + assert_equal(a, [0, 1, 0, 1, 2]) a = np.arange(5) a[2::-1] = a[2:] - assert_equal(a, [4,3,2,3,4]) + assert_equal(a, [4, 3, 2, 3, 4]) a = np.arange(5) a[2:] = a[2::-1] - assert_equal(a, [0,1,2,1,0]) + assert_equal(a, [0, 1, 2, 1, 0]) a = np.arange(5) a[2::-1] = a[:1:-1] - assert_equal(a, [2,3,4,3,4]) + assert_equal(a, [2, 3, 4, 3, 4]) a = np.arange(5) a[:1:-1] = a[2::-1] - assert_equal(a, [0,1,0,1,2]) + assert_equal(a, [0, 1, 0, 1, 2]) class TestCreation(TestCase): def test_from_attribute(self): @@ -384,7 +384,7 @@ class TestCreation(TestCase): def test_from_string(self) : types = np.typecodes['AllInteger'] + np.typecodes['Float'] - nstr = ['123','123'] + nstr = ['123', '123'] result = array([123, 123], dtype=int) for type in types : msg = 'String conversion for %s' % type @@ -459,52 +459,52 @@ class TestStructured(TestCase): # Check that comparisons between record arrays with # multi-dimensional field types work properly a = np.rec.fromrecords( - [([1,2,3],'a', [[1,2],[3,4]]),([3,3,3],'b',[[0,0],[0,0]])], - dtype=[('a', ('f4',3)), ('b', np.object), ('c', ('i4',(2,2)))]) + [([1, 2, 3], 'a', [[1, 2], [3, 4]]), ([3, 3, 3], 'b', [[0, 0], [0, 0]])], + dtype=[('a', ('f4', 3)), ('b', np.object), ('c', ('i4', (2, 2)))]) b = a.copy() - assert_equal(a==b, [True,True]) - assert_equal(a!=b, [False,False]) + assert_equal(a==b, [True, True]) + assert_equal(a!=b, [False, False]) b[1].b = 'c' - assert_equal(a==b, [True,False]) - assert_equal(a!=b, [False,True]) + assert_equal(a==b, [True, False]) + assert_equal(a!=b, [False, True]) for i in range(3): b[0].a = a[0].a b[0].a[i] = 5 - assert_equal(a==b, [False,False]) - assert_equal(a!=b, [True,True]) + assert_equal(a==b, [False, False]) + assert_equal(a!=b, [True, True]) for i in range(2): for j in range(2): b = a.copy() - b[0].c[i,j] = 10 - assert_equal(a==b, [False,True]) - assert_equal(a!=b, [True,False]) + b[0].c[i, j] = 10 + assert_equal(a==b, [False, True]) + assert_equal(a!=b, [True, False]) # Check that broadcasting with a subarray works - a = np.array([[(0,)],[(1,)]],dtype=[('a','f8')]) - b = np.array([(0,),(0,),(1,)],dtype=[('a','f8')]) + a = np.array([[(0,)], [(1,)]], dtype=[('a', 'f8')]) + b = np.array([(0,), (0,), (1,)], dtype=[('a', 'f8')]) assert_equal(a==b, [[True, True, False], [False, False, True]]) assert_equal(b==a, [[True, True, False], [False, False, True]]) - a = np.array([[(0,)],[(1,)]],dtype=[('a','f8',(1,))]) - b = np.array([(0,),(0,),(1,)],dtype=[('a','f8',(1,))]) + a = np.array([[(0,)], [(1,)]], dtype=[('a', 'f8', (1,))]) + b = np.array([(0,), (0,), (1,)], dtype=[('a', 'f8', (1,))]) assert_equal(a==b, [[True, True, False], [False, False, True]]) assert_equal(b==a, [[True, True, False], [False, False, True]]) - a = np.array([[([0,0],)],[([1,1],)]],dtype=[('a','f8',(2,))]) - b = np.array([([0,0],),([0,1],),([1,1],)],dtype=[('a','f8',(2,))]) + a = np.array([[([0, 0],)], [([1, 1],)]], dtype=[('a', 'f8', (2,))]) + b = np.array([([0, 0],), ([0, 1],), ([1, 1],)], dtype=[('a', 'f8', (2,))]) assert_equal(a==b, [[True, False, False], [False, False, True]]) assert_equal(b==a, [[True, False, False], [False, False, True]]) # Check that broadcasting Fortran-style arrays with a subarray work - a = np.array([[([0,0],)],[([1,1],)]],dtype=[('a','f8',(2,))], order='F') - b = np.array([([0,0],),([0,1],),([1,1],)],dtype=[('a','f8',(2,))]) + a = np.array([[([0, 0],)], [([1, 1],)]], dtype=[('a', 'f8', (2,))], order='F') + b = np.array([([0, 0],), ([0, 1],), ([1, 1],)], dtype=[('a', 'f8', (2,))]) assert_equal(a==b, [[True, False, False], [False, False, True]]) assert_equal(b==a, [[True, False, False], [False, False, True]]) # Check that incompatible sub-array shapes don't result to broadcasting - x = np.zeros((1,), dtype=[('a', ('f4', (1,2))), ('b', 'i1')]) + x = np.zeros((1,), dtype=[('a', ('f4', (1, 2))), ('b', 'i1')]) y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')]) assert_equal(x == y, False) - x = np.zeros((1,), dtype=[('a', ('f4', (2,1))), ('b', 'i1')]) + x = np.zeros((1,), dtype=[('a', ('f4', (2, 1))), ('b', 'i1')]) y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')]) assert_equal(x == y, False) @@ -523,17 +523,17 @@ class TestBool(TestCase): class TestMethods(TestCase): def test_test_round(self): - assert_equal(array([1.2,1.5]).round(), [1,2]) + assert_equal(array([1.2, 1.5]).round(), [1, 2]) assert_equal(array(1.5).round(), 2) - assert_equal(array([12.2,15.5]).round(-1), [10,20]) - assert_equal(array([12.15,15.51]).round(1), [12.2,15.5]) + assert_equal(array([12.2, 15.5]).round(-1), [10, 20]) + assert_equal(array([12.15, 15.51]).round(1), [12.2, 15.5]) def test_transpose(self): - a = array([[1,2],[3,4]]) - assert_equal(a.transpose(), [[1,3],[2,4]]) + a = array([[1, 2], [3, 4]]) + assert_equal(a.transpose(), [[1, 3], [2, 4]]) self.assertRaises(ValueError, lambda: a.transpose(0)) - self.assertRaises(ValueError, lambda: a.transpose(0,0)) - self.assertRaises(ValueError, lambda: a.transpose(0,1,2)) + self.assertRaises(ValueError, lambda: a.transpose(0, 0)) + self.assertRaises(ValueError, lambda: a.transpose(0, 1, 2)) def test_sort(self): # test ordering for floats and complex containing nans. It is only @@ -561,7 +561,7 @@ class TestMethods(TestCase): # sort for small arrays. a = np.arange(101) b = a[::-1].copy() - for kind in ['q','m','h'] : + for kind in ['q', 'm', 'h'] : msg = "scalar sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) @@ -574,7 +574,7 @@ class TestMethods(TestCase): # but the compare fuction differs. ai = a*1j + 1 bi = b*1j + 1 - for kind in ['q','m','h'] : + for kind in ['q', 'm', 'h'] : msg = "complex sort, real part == 1, kind=%s" % kind c = ai.copy(); c.sort(kind=kind) @@ -584,7 +584,7 @@ class TestMethods(TestCase): assert_equal(c, ai, msg) ai = a + 1j bi = b + 1j - for kind in ['q','m','h'] : + for kind in ['q', 'm', 'h'] : msg = "complex sort, imag part == 1, kind=%s" % kind c = ai.copy(); c.sort(kind=kind) @@ -633,8 +633,8 @@ class TestMethods(TestCase): assert_equal(c, a, msg) # test record array sorts. - dt = np.dtype([('f',float),('i',int)]) - a = array([(i,i) for i in range(101)], dtype = dt) + dt = np.dtype([('f', float), ('i', int)]) + a = array([(i, i) for i in range(101)], dtype = dt) b = a[::-1] for kind in ['q', 'h', 'm'] : msg = "object sort, kind=%s" % kind @@ -671,9 +671,9 @@ class TestMethods(TestCase): # check axis handling. This should be the same for all type # specific sorts, so we only check it for one type and one kind - a = np.array([[3,2],[1,0]]) - b = np.array([[1,0],[3,2]]) - c = np.array([[2,3],[0,1]]) + a = np.array([[3, 2], [1, 0]]) + b = np.array([[1, 0], [3, 2]]) + c = np.array([[2, 3], [0, 1]]) d = a.copy() d.sort(axis=0) assert_equal(d, b, "test sort with axis=0") @@ -711,32 +711,32 @@ class TestMethods(TestCase): def test_sort_order(self): # Test sorting an array with fields - x1=np.array([21,32,14]) - x2=np.array(['my','first','name']) - x3=np.array([3.1,4.5,6.2]) - r=np.rec.fromarrays([x1,x2,x3],names='id,word,number') + x1=np.array([21, 32, 14]) + x2=np.array(['my', 'first', 'name']) + x3=np.array([3.1, 4.5, 6.2]) + r=np.rec.fromarrays([x1, x2, x3], names='id,word,number') r.sort(order=['id']) - assert_equal(r.id, array([14,21,32])) - assert_equal(r.word, array(['name','my','first'])) - assert_equal(r.number, array([6.2,3.1,4.5])) + assert_equal(r.id, array([14, 21, 32])) + assert_equal(r.word, array(['name', 'my', 'first'])) + assert_equal(r.number, array([6.2, 3.1, 4.5])) r.sort(order=['word']) - assert_equal(r.id, array([32,21,14])) - assert_equal(r.word, array(['first','my','name'])) - assert_equal(r.number, array([4.5,3.1,6.2])) + assert_equal(r.id, array([32, 21, 14])) + assert_equal(r.word, array(['first', 'my', 'name'])) + assert_equal(r.number, array([4.5, 3.1, 6.2])) r.sort(order=['number']) - assert_equal(r.id, array([21,32,14])) - assert_equal(r.word, array(['my','first','name'])) - assert_equal(r.number, array([3.1,4.5,6.2])) + assert_equal(r.id, array([21, 32, 14])) + assert_equal(r.word, array(['my', 'first', 'name'])) + assert_equal(r.number, array([3.1, 4.5, 6.2])) if sys.byteorder == 'little': strtype = '>i2' else: strtype = '<i2' - mydtype = [('name', strchar + '5'),('col2',strtype)] - r = np.array([('a', 1),('b', 255), ('c', 3), ('d', 258)], + mydtype = [('name', strchar + '5'), ('col2', strtype)] + r = np.array([('a', 1), ('b', 255), ('c', 3), ('d', 258)], dtype= mydtype) r.sort(order='col2') assert_equal(r['col2'], [1, 3, 255, 258]) @@ -751,7 +751,7 @@ class TestMethods(TestCase): # sort for small arrays. a = np.arange(101) b = a[::-1].copy() - for kind in ['q','m','h'] : + for kind in ['q', 'm', 'h'] : msg = "scalar argsort, kind=%s" % kind assert_equal(a.copy().argsort(kind=kind), a, msg) assert_equal(b.copy().argsort(kind=kind), b, msg) @@ -760,13 +760,13 @@ class TestMethods(TestCase): # but the compare fuction differs. ai = a*1j + 1 bi = b*1j + 1 - for kind in ['q','m','h'] : + for kind in ['q', 'm', 'h'] : msg = "complex argsort, kind=%s" % kind assert_equal(ai.copy().argsort(kind=kind), a, msg) assert_equal(bi.copy().argsort(kind=kind), b, msg) ai = a + 1j bi = b + 1j - for kind in ['q','m','h'] : + for kind in ['q', 'm', 'h'] : msg = "complex argsort, kind=%s" % kind assert_equal(ai.copy().argsort(kind=kind), a, msg) assert_equal(bi.copy().argsort(kind=kind), b, msg) @@ -805,8 +805,8 @@ class TestMethods(TestCase): assert_equal(b.copy().argsort(kind=kind), rr, msg) # test structured array argsorts. - dt = np.dtype([('f',float),('i',int)]) - a = array([(i,i) for i in range(101)], dtype = dt) + dt = np.dtype([('f', float), ('i', int)]) + a = array([(i, i) for i in range(101)], dtype = dt) b = a[::-1] r = np.arange(101) rr = r[::-1] @@ -838,9 +838,9 @@ class TestMethods(TestCase): # check axis handling. This should be the same for all type # specific argsorts, so we only check it for one type and one kind - a = np.array([[3,2],[1,0]]) - b = np.array([[1,1],[0,0]]) - c = np.array([[1,0],[1,0]]) + a = np.array([[3, 2], [1, 0]]) + b = np.array([[1, 1], [0, 0]]) + c = np.array([[1, 0], [1, 0]]) assert_equal(a.copy().argsort(axis=0), b) assert_equal(a.copy().argsort(axis=1), c) assert_equal(a.copy().argsort(), c) @@ -876,7 +876,7 @@ class TestMethods(TestCase): assert_equal(b, np.arange(3), msg) msg = "Test real searchsorted with nans, side='r'" b = a.searchsorted(a, side='r') - assert_equal(b, np.arange(1,4), msg) + assert_equal(b, np.arange(1, 4), msg) # check double complex a = np.zeros(9, dtype=np.complex128) a.real += [0, 0, 1, 1, 0, 1, np.nan, np.nan, np.nan] @@ -886,14 +886,14 @@ class TestMethods(TestCase): assert_equal(b, np.arange(9), msg) msg = "Test complex searchsorted with nans, side='r'" b = a.searchsorted(a, side='r') - assert_equal(b, np.arange(1,10), msg) + assert_equal(b, np.arange(1, 10), msg) msg = "Test searchsorted with little endian, side='l'" - a = np.array([0,128],dtype='<i4') - b = a.searchsorted(np.array(128,dtype='<i4')) + a = np.array([0, 128], dtype='<i4') + b = a.searchsorted(np.array(128, dtype='<i4')) assert_equal(b, 1, msg) msg = "Test searchsorted with big endian, side='l'" - a = np.array([0,128],dtype='>i4') - b = a.searchsorted(np.array(128,dtype='>i4')) + a = np.array([0, 128], dtype='>i4') + b = a.searchsorted(np.array(128, dtype='>i4')) assert_equal(b, 1, msg) # Check 0 elements @@ -959,17 +959,17 @@ class TestMethods(TestCase): assert_equal([a.searchsorted(a[i], 'right') for i in ind], ind + 1) def test_searchsorted_with_sorter(self): - a = np.array([5,2,1,3,4]) + a = np.array([5, 2, 1, 3, 4]) s = np.argsort(a) - assert_raises(TypeError, np.searchsorted, a, 0, sorter=(1,(2,3))) + assert_raises(TypeError, np.searchsorted, a, 0, sorter=(1, (2, 3))) assert_raises(TypeError, np.searchsorted, a, 0, sorter=[1.1]) - assert_raises(ValueError, np.searchsorted, a, 0, sorter=[1,2,3,4]) - assert_raises(ValueError, np.searchsorted, a, 0, sorter=[1,2,3,4,5,6]) + assert_raises(ValueError, np.searchsorted, a, 0, sorter=[1, 2, 3, 4]) + assert_raises(ValueError, np.searchsorted, a, 0, sorter=[1, 2, 3, 4, 5, 6]) # bounds check - assert_raises(ValueError, np.searchsorted, a, 4, sorter=[0,1,2,3,5]) - assert_raises(ValueError, np.searchsorted, a, 0, sorter=[-1,0,1,2,3]) - assert_raises(ValueError, np.searchsorted, a, 0, sorter=[4,0,-1,2,3]) + assert_raises(ValueError, np.searchsorted, a, 4, sorter=[0, 1, 2, 3, 5]) + assert_raises(ValueError, np.searchsorted, a, 0, sorter=[-1, 0, 1, 2, 3]) + assert_raises(ValueError, np.searchsorted, a, 0, sorter=[4, 0, -1, 2, 3]) a = np.random.rand(300) s = a.argsort() @@ -1156,23 +1156,23 @@ class TestMethods(TestCase): aae(p, d[np.argpartition(d, i, kind=k)]) p = np.partition(d1, i, axis=1, kind=k) - aae(p[:,i], np.array([i] * d1.shape[0], dtype=dt)) + aae(p[:, i], np.array([i] * d1.shape[0], dtype=dt)) # array_less does not seem to work right at((p[:, :i].T <= p[:, i]).all(), msg="%d: %r <= %r" % (i, p[:, i], p[:, :i].T)) at((p[:, i + 1:].T > p[:, i]).all(), msg="%d: %r < %r" % (i, p[:, i], p[:, i + 1:].T)) - aae(p, d1[np.arange(d1.shape[0])[:,None], + aae(p, d1[np.arange(d1.shape[0])[:, None], np.argpartition(d1, i, axis=1, kind=k)]) p = np.partition(d0, i, axis=0, kind=k) - aae(p[i, :], np.array([i] * d1.shape[0], + aae(p[i,:], np.array([i] * d1.shape[0], dtype=dt)) # array_less does not seem to work right - at((p[:i, :] <= p[i, :]).all(), - msg="%d: %r <= %r" % (i, p[i, :], p[:i, :])) - at((p[i + 1:, :] > p[i, :]).all(), - msg="%d: %r < %r" % (i, p[i, :], p[:, i + 1:])) + at((p[:i,:] <= p[i,:]).all(), + msg="%d: %r <= %r" % (i, p[i,:], p[:i,:])) + at((p[i + 1:,:] > p[i,:]).all(), + msg="%d: %r < %r" % (i, p[i,:], p[:, i + 1:])) aae(p, d0[np.argpartition(d0, i, axis=0, kind=k), np.arange(d0.shape[1])[None,:]]) @@ -1253,11 +1253,11 @@ class TestMethods(TestCase): kth = (1, 6, 7, -1) p = np.partition(d1, kth, axis=1) - pa = d1[np.arange(d1.shape[0])[:,None], + pa = d1[np.arange(d1.shape[0])[:, None], d1.argpartition(kth, axis=1)] assert_array_equal(p, pa) for i in range(d1.shape[0]): - self.assert_partitioned(p[i, :], kth) + self.assert_partitioned(p[i,:], kth) p = np.partition(d0, kth, axis=0) pa = d0[np.argpartition(d0, kth, axis=0), np.arange(d0.shape[1])[None,:]] @@ -1293,12 +1293,12 @@ class TestMethods(TestCase): def test_flatten(self): - x0 = np.array([[1,2,3],[4,5,6]], np.int32) - x1 = np.array([[[1,2],[3,4]],[[5,6],[7,8]]], np.int32) - y0 = np.array([1,2,3,4,5,6], np.int32) - y0f = np.array([1,4,2,5,3,6], np.int32) - y1 = np.array([1,2,3,4,5,6,7,8], np.int32) - y1f = np.array([1,5,3,7,2,6,4,8], np.int32) + x0 = np.array([[1, 2, 3], [4, 5, 6]], np.int32) + x1 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], np.int32) + y0 = np.array([1, 2, 3, 4, 5, 6], np.int32) + y0f = np.array([1, 4, 2, 5, 3, 6], np.int32) + y1 = np.array([1, 2, 3, 4, 5, 6, 7, 8], np.int32) + y1f = np.array([1, 5, 3, 7, 2, 6, 4, 8], np.int32) assert_equal(x0.flatten(), y0) assert_equal(x0.flatten('F'), y0f) assert_equal(x0.flatten('F'), x0.T.flatten()) @@ -1316,13 +1316,13 @@ class TestMethods(TestCase): # test passing in an output array c = np.zeros_like(a) - a.dot(b,c) - assert_equal(c, np.dot(a,b)) + a.dot(b, c) + assert_equal(c, np.dot(a, b)) # test keyword args c = np.zeros_like(a) - a.dot(b=b,out=c) - assert_equal(c, np.dot(a,b)) + a.dot(b=b, out=c) + assert_equal(c, np.dot(a, b)) def test_diagonal(self): a = np.arange(12).reshape((3, 4)) @@ -1470,39 +1470,39 @@ class TestMethods(TestCase): assert_(sys.getrefcount(a) < 50) def test_ravel(self): - a = np.array([[0,1],[2,3]]) - assert_equal(a.ravel(), [0,1,2,3]) + a = np.array([[0, 1], [2, 3]]) + assert_equal(a.ravel(), [0, 1, 2, 3]) assert_(not a.ravel().flags.owndata) - assert_equal(a.ravel('F'), [0,2,1,3]) - assert_equal(a.ravel(order='C'), [0,1,2,3]) - assert_equal(a.ravel(order='F'), [0,2,1,3]) - assert_equal(a.ravel(order='A'), [0,1,2,3]) + assert_equal(a.ravel('F'), [0, 2, 1, 3]) + assert_equal(a.ravel(order='C'), [0, 1, 2, 3]) + assert_equal(a.ravel(order='F'), [0, 2, 1, 3]) + assert_equal(a.ravel(order='A'), [0, 1, 2, 3]) assert_(not a.ravel(order='A').flags.owndata) - assert_equal(a.ravel(order='K'), [0,1,2,3]) + assert_equal(a.ravel(order='K'), [0, 1, 2, 3]) assert_(not a.ravel(order='K').flags.owndata) assert_equal(a.ravel(), a.reshape(-1)) - a = np.array([[0,1],[2,3]], order='F') - assert_equal(a.ravel(), [0,1,2,3]) - assert_equal(a.ravel(order='A'), [0,2,1,3]) - assert_equal(a.ravel(order='K'), [0,2,1,3]) + a = np.array([[0, 1], [2, 3]], order='F') + assert_equal(a.ravel(), [0, 1, 2, 3]) + assert_equal(a.ravel(order='A'), [0, 2, 1, 3]) + assert_equal(a.ravel(order='K'), [0, 2, 1, 3]) assert_(not a.ravel(order='A').flags.owndata) assert_(not a.ravel(order='K').flags.owndata) assert_equal(a.ravel(), a.reshape(-1)) assert_equal(a.ravel(order='A'), a.reshape(-1, order='A')) - a = np.array([[0,1],[2,3]])[::-1,:] - assert_equal(a.ravel(), [2,3,0,1]) - assert_equal(a.ravel(order='C'), [2,3,0,1]) - assert_equal(a.ravel(order='F'), [2,0,3,1]) - assert_equal(a.ravel(order='A'), [2,3,0,1]) + a = np.array([[0, 1], [2, 3]])[::-1,:] + assert_equal(a.ravel(), [2, 3, 0, 1]) + assert_equal(a.ravel(order='C'), [2, 3, 0, 1]) + assert_equal(a.ravel(order='F'), [2, 0, 3, 1]) + assert_equal(a.ravel(order='A'), [2, 3, 0, 1]) # 'K' doesn't reverse the axes of negative strides - assert_equal(a.ravel(order='K'), [2,3,0,1]) + assert_equal(a.ravel(order='K'), [2, 3, 0, 1]) assert_(a.ravel(order='K').flags.owndata) class TestSubscripting(TestCase): def test_test_zero_rank(self): - x = array([1,2,3]) + x = array([1, 2, 3]) self.assertTrue(isinstance(x[0], np.int_)) if sys.version_info[0] < 3: self.assertTrue(isinstance(x[0], int)) @@ -1512,11 +1512,11 @@ class TestSubscripting(TestCase): class TestPickling(TestCase): def test_roundtrip(self): import pickle - carray = array([[2,9],[7,0],[3,8]]) + carray = array([[2, 9], [7, 0], [3, 8]]) DATA = [ carray, transpose(carray), - array([('xxx', 1, 2.0)], dtype=[('a', (str,3)), ('b', int), + array([('xxx', 1, 2.0)], dtype=[('a', (str, 3)), ('b', int), ('c', float)]) ] @@ -1533,7 +1533,7 @@ class TestPickling(TestCase): # version 0 doesn't have a version field def test_version0_int8(self): s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02i1K\x00K\x01\x87Rq\x05(U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x04\x01\x02\x03\x04tb.' - a = array([1,2,3,4], dtype=int8) + a = array([1, 2, 3, 4], dtype=int8) p = self._loads(asbytes(s)) assert_equal(a, p) @@ -1552,7 +1552,7 @@ class TestPickling(TestCase): # version 1 pickles, using protocol=2 to pickle def test_version1_int8(self): s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01K\x04\x85cnumpy\ndtype\nq\x04U\x02i1K\x00K\x01\x87Rq\x05(K\x01U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x04\x01\x02\x03\x04tb.' - a = array([1,2,3,4], dtype=int8) + a = array([1, 2, 3, 4], dtype=int8) p = self._loads(asbytes(s)) assert_equal(a, p) @@ -1570,78 +1570,78 @@ class TestPickling(TestCase): def test_subarray_int_shape(self): s = "cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n(S'V6'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nN(S'a'\np12\ng3\ntp13\n(dp14\ng12\n(g7\n(S'V4'\np15\nI0\nI1\ntp16\nRp17\n(I3\nS'|'\np18\n(g7\n(S'i1'\np19\nI0\nI1\ntp20\nRp21\n(I3\nS'|'\np22\nNNNI-1\nI-1\nI0\ntp23\nb(I2\nI2\ntp24\ntp25\nNNI4\nI1\nI0\ntp26\nbI0\ntp27\nsg3\n(g7\n(S'V2'\np28\nI0\nI1\ntp29\nRp30\n(I3\nS'|'\np31\n(g21\nI2\ntp32\nNNI2\nI1\nI0\ntp33\nbI4\ntp34\nsI6\nI1\nI0\ntp35\nbI00\nS'\\x01\\x01\\x01\\x01\\x01\\x02'\np36\ntp37\nb." - a = np.array([(1,(1,2))], dtype=[('a', 'i1', (2,2)), ('b', 'i1', 2)]) + a = np.array([(1, (1, 2))], dtype=[('a', 'i1', (2, 2)), ('b', 'i1', 2)]) p = self._loads(asbytes(s)) assert_equal(a, p) class TestFancyIndexing(TestCase): def test_list(self): - x = ones((1,1)) - x[:,[0]] = 2.0 + x = ones((1, 1)) + x[:, [0]] = 2.0 assert_array_equal(x, array([[2.0]])) - x = ones((1,1,1)) - x[:,:,[0]] = 2.0 + x = ones((1, 1, 1)) + x[:,:, [0]] = 2.0 assert_array_equal(x, array([[[2.0]]])) def test_tuple(self): - x = ones((1,1)) - x[:,(0,)] = 2.0 + x = ones((1, 1)) + x[:, (0,)] = 2.0 assert_array_equal(x, array([[2.0]])) - x = ones((1,1,1)) - x[:,:,(0,)] = 2.0 + x = ones((1, 1, 1)) + x[:,:, (0,)] = 2.0 assert_array_equal(x, array([[[2.0]]])) def test_mask(self): - x = array([1,2,3,4]) - m = array([0,1],bool) + x = array([1, 2, 3, 4]) + m = array([0, 1], bool) assert_array_equal(x[m], array([2])) def test_mask2(self): - x = array([[1,2,3,4],[5,6,7,8]]) - m = array([0,1],bool) - m2 = array([[0,1],[1,0]], bool) - m3 = array([[0,1]], bool) - assert_array_equal(x[m], array([[5,6,7,8]])) - assert_array_equal(x[m2], array([2,5])) + x = array([[1, 2, 3, 4], [5, 6, 7, 8]]) + m = array([0, 1], bool) + m2 = array([[0, 1], [1, 0]], bool) + m3 = array([[0, 1]], bool) + assert_array_equal(x[m], array([[5, 6, 7, 8]])) + assert_array_equal(x[m2], array([2, 5])) assert_array_equal(x[m3], array([2])) def test_assign_mask(self): - x = array([1,2,3,4]) - m = array([0,1],bool) + x = array([1, 2, 3, 4]) + m = array([0, 1], bool) x[m] = 5 - assert_array_equal(x, array([1,5,3,4])) + assert_array_equal(x, array([1, 5, 3, 4])) def test_assign_mask2(self): - xorig = array([[1,2,3,4],[5,6,7,8]]) - m = array([0,1],bool) - m2 = array([[0,1],[1,0]],bool) - m3 = array([[0,1]], bool) + xorig = array([[1, 2, 3, 4], [5, 6, 7, 8]]) + m = array([0, 1], bool) + m2 = array([[0, 1], [1, 0]], bool) + m3 = array([[0, 1]], bool) x = xorig.copy() x[m] = 10 - assert_array_equal(x, array([[1,2,3,4],[10,10,10,10]])) + assert_array_equal(x, array([[1, 2, 3, 4], [10, 10, 10, 10]])) x = xorig.copy() x[m2] = 10 - assert_array_equal(x, array([[1,10,3,4],[10,6,7,8]])) + assert_array_equal(x, array([[1, 10, 3, 4], [10, 6, 7, 8]])) x = xorig.copy() x[m3] = 10 - assert_array_equal(x, array([[1,10,3,4],[5,6,7,8]])) + assert_array_equal(x, array([[1, 10, 3, 4], [5, 6, 7, 8]])) class TestStringCompare(TestCase): def test_string(self): - g1 = array(["This","is","example"]) - g2 = array(["This","was","example"]) - assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0,1,2]]) - assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0,1,2]]) - assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0,1,2]]) - assert_array_equal(g1 >= g2, [g1[i] >= g2[i] for i in [0,1,2]]) - assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0,1,2]]) - assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0,1,2]]) + g1 = array(["This", "is", "example"]) + g2 = array(["This", "was", "example"]) + assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0, 1, 2]]) + assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0, 1, 2]]) + assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0, 1, 2]]) + assert_array_equal(g1 >= g2, [g1[i] >= g2[i] for i in [0, 1, 2]]) + assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0, 1, 2]]) + assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0, 1, 2]]) def test_mixed(self): - g1 = array(["spam","spa","spammer","and eggs"]) + g1 = array(["spam", "spa", "spammer", "and eggs"]) g2 = "spam" assert_array_equal(g1 == g2, [x == g2 for x in g1]) assert_array_equal(g1 != g2, [x != g2 for x in g1]) @@ -1652,14 +1652,14 @@ class TestStringCompare(TestCase): def test_unicode(self): - g1 = array([sixu("This"),sixu("is"),sixu("example")]) - g2 = array([sixu("This"),sixu("was"),sixu("example")]) - assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0,1,2]]) - assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0,1,2]]) - assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0,1,2]]) - assert_array_equal(g1 >= g2, [g1[i] >= g2[i] for i in [0,1,2]]) - assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0,1,2]]) - assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0,1,2]]) + g1 = array([sixu("This"), sixu("is"), sixu("example")]) + g2 = array([sixu("This"), sixu("was"), sixu("example")]) + assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0, 1, 2]]) + assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0, 1, 2]]) + assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0, 1, 2]]) + assert_array_equal(g1 >= g2, [g1[i] >= g2[i] for i in [0, 1, 2]]) + assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0, 1, 2]]) + assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0, 1, 2]]) class TestArgmax(TestCase): @@ -1669,11 +1669,11 @@ class TestArgmax(TestCase): ([0, 1, 2, np.nan, 3], 3), ([np.nan, 0, 1, 2, 3], 0), ([np.nan, 0, np.nan, 2, 3], 0), - ([0, 1, 2, 3, complex(0,np.nan)], 4), - ([0, 1, 2, 3, complex(np.nan,0)], 4), - ([0, 1, 2, complex(np.nan,0), 3], 3), - ([0, 1, 2, complex(0,np.nan), 3], 3), - ([complex(0,np.nan), 0, 1, 2, 3], 0), + ([0, 1, 2, 3, complex(0, np.nan)], 4), + ([0, 1, 2, 3, complex(np.nan, 0)], 4), + ([0, 1, 2, complex(np.nan, 0), 3], 3), + ([0, 1, 2, complex(0, np.nan), 3], 3), + ([complex(0, np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, 1)], 0), ([complex(np.nan, np.nan), complex(np.nan, 2), complex(np.nan, 1)], 0), @@ -1716,7 +1716,7 @@ class TestArgmax(TestCase): ] def test_all(self): - a = np.random.normal(0,1,(4,5,6,7,8)) + a = np.random.normal(0, 1, (4, 5, 6, 7, 8)) for i in range(a.ndim): amax = a.max(i) aargmax = a.argmax(i) @@ -1737,11 +1737,11 @@ class TestArgmin(TestCase): ([0, 1, 2, np.nan, 3], 3), ([np.nan, 0, 1, 2, 3], 0), ([np.nan, 0, np.nan, 2, 3], 0), - ([0, 1, 2, 3, complex(0,np.nan)], 4), - ([0, 1, 2, 3, complex(np.nan,0)], 4), - ([0, 1, 2, complex(np.nan,0), 3], 3), - ([0, 1, 2, complex(0,np.nan), 3], 3), - ([complex(0,np.nan), 0, 1, 2, 3], 0), + ([0, 1, 2, 3, complex(0, np.nan)], 4), + ([0, 1, 2, 3, complex(np.nan, 0)], 4), + ([0, 1, 2, complex(np.nan, 0), 3], 3), + ([0, 1, 2, complex(0, np.nan), 3], 3), + ([complex(0, np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, 1)], 0), ([complex(np.nan, np.nan), complex(np.nan, 2), complex(np.nan, 1)], 0), @@ -1784,7 +1784,7 @@ class TestArgmin(TestCase): ] def test_all(self): - a = np.random.normal(0,1,(4,5,6,7,8)) + a = np.random.normal(0, 1, (4, 5, 6, 7, 8)) for i in range(a.ndim): amin = a.min(i) aargmin = a.argmin(i) @@ -1823,18 +1823,18 @@ class TestMinMax(TestCase): assert_equal(np.amin(1, axis=None), 1) def test_axis(self): - assert_raises(ValueError, np.amax, [1,2,3], 1000) - assert_equal(np.amax([[1,2,3]], axis=1), 3) + assert_raises(ValueError, np.amax, [1, 2, 3], 1000) + assert_equal(np.amax([[1, 2, 3]], axis=1), 3) class TestNewaxis(TestCase): def test_basic(self): - sk = array([0,-0.1,0.1]) - res = 250*sk[:,newaxis] - assert_almost_equal(res.ravel(),250*sk) + sk = array([0, -0.1, 0.1]) + res = 250*sk[:, newaxis] + assert_almost_equal(res.ravel(), 250*sk) class TestClip(TestCase): - def _check_range(self,x,cmin,cmax): + def _check_range(self, x, cmin, cmax): assert_(np.all(x >= cmin)) assert_(np.all(x <= cmax)) @@ -1848,45 +1848,45 @@ class TestClip(TestCase): for T in np.sctypes[type_group]: if sys.byteorder == 'little': - byte_orders = ['=','>'] + byte_orders = ['=', '>'] else: - byte_orders = ['<','='] + byte_orders = ['<', '='] for byteorder in byte_orders: dtype = np.dtype(T).newbyteorder(byteorder) x = (np.random.random(1000) * array_max).astype(dtype) if inplace: - x.clip(clip_min,clip_max,x) + x.clip(clip_min, clip_max, x) else: - x = x.clip(clip_min,clip_max) + x = x.clip(clip_min, clip_max) byteorder = '=' if x.dtype.byteorder == '|': byteorder = '|' - assert_equal(x.dtype.byteorder,byteorder) - self._check_range(x,expected_min,expected_max) + assert_equal(x.dtype.byteorder, byteorder) + self._check_range(x, expected_min, expected_max) return x def test_basic(self): for inplace in [False, True]: - self._clip_type('float',1024,-12.8,100.2, inplace=inplace) - self._clip_type('float',1024,0,0, inplace=inplace) + self._clip_type('float', 1024, -12.8, 100.2, inplace=inplace) + self._clip_type('float', 1024, 0, 0, inplace=inplace) - self._clip_type('int',1024,-120,100.5, inplace=inplace) - self._clip_type('int',1024,0,0, inplace=inplace) + self._clip_type('int', 1024, -120, 100.5, inplace=inplace) + self._clip_type('int', 1024, 0, 0, inplace=inplace) - x = self._clip_type('uint',1024,-120,100,expected_min=0, + x = self._clip_type('uint', 1024, -120, 100, expected_min=0, inplace=inplace) - x = self._clip_type('uint',1024,0,0, inplace=inplace) + x = self._clip_type('uint', 1024, 0, 0, inplace=inplace) def test_record_array(self): rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)], dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')]) - y = rec['x'].clip(-0.3,0.5) - self._check_range(y,-0.3,0.5) + y = rec['x'].clip(-0.3, 0.5) + self._check_range(y, -0.3, 0.5) def test_max_or_min(self): - val = np.array([0,1,2,3,4,5,6,7]) + val = np.array([0, 1, 2, 3, 4, 5, 6, 7]) x = val.clip(3) assert_(np.all(x >= 3)) x = val.clip(min=3) @@ -1907,36 +1907,36 @@ class TestPutmask(object): x = np.random.random(1000)*100 mask = x < 40 - for val in [-100,0,15]: + for val in [-100, 0, 15]: for types in np.sctypes.values(): for T in types: if T not in unchecked_types: - yield self.tst_basic,x.copy().astype(T),T,mask,val + yield self.tst_basic, x.copy().astype(T), T, mask, val def test_mask_size(self): - assert_raises(ValueError, np.putmask, np.array([1,2,3]), [True], 5) + assert_raises(ValueError, np.putmask, np.array([1, 2, 3]), [True], 5) - def tst_byteorder(self,dtype): - x = np.array([1,2,3],dtype) - np.putmask(x,[True,False,True],-1) - assert_array_equal(x,[-1,2,-1]) + def tst_byteorder(self, dtype): + x = np.array([1, 2, 3], dtype) + np.putmask(x, [True, False, True], -1) + assert_array_equal(x, [-1, 2, -1]) def test_ip_byteorder(self): - for dtype in ('>i4','<i4'): - yield self.tst_byteorder,dtype + for dtype in ('>i4', '<i4'): + yield self.tst_byteorder, dtype def test_record_array(self): # Note mixed byteorder. rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)], dtype=[('x', '<f8'), ('y', '>f8'), ('z', '<f8')]) - np.putmask(rec['x'],[True,False],10) - assert_array_equal(rec['x'],[10,5]) - assert_array_equal(rec['y'],[2,4]) - assert_array_equal(rec['z'],[3,3]) - np.putmask(rec['y'],[True,False],11) - assert_array_equal(rec['x'],[10,5]) - assert_array_equal(rec['y'],[11,4]) - assert_array_equal(rec['z'],[3,3]) + np.putmask(rec['x'], [True, False], 10) + assert_array_equal(rec['x'], [10, 5]) + assert_array_equal(rec['y'], [2, 4]) + assert_array_equal(rec['z'], [3, 3]) + np.putmask(rec['y'], [True, False], 11) + assert_array_equal(rec['x'], [10, 5]) + assert_array_equal(rec['y'], [11, 4]) + assert_array_equal(rec['z'], [3, 3]) def test_masked_array(self): ## x = np.array([1,2,3]) @@ -1946,7 +1946,7 @@ class TestPutmask(object): class TestTake(object): - def tst_basic(self,x): + def tst_basic(self, x): ind = list(range(x.shape[0])) assert_array_equal(x.take(ind, axis=0), x) @@ -1954,39 +1954,39 @@ class TestTake(object): unchecked_types = [str, unicode, np.void, object] x = np.random.random(24)*100 - x.shape = 2,3,4 + x.shape = 2, 3, 4 for types in np.sctypes.values(): for T in types: if T not in unchecked_types: - yield self.tst_basic,x.copy().astype(T) + yield self.tst_basic, x.copy().astype(T) def test_raise(self): x = np.random.random(24)*100 - x.shape = 2,3,4 - assert_raises(IndexError, x.take, [0,1,2], axis=0) + x.shape = 2, 3, 4 + assert_raises(IndexError, x.take, [0, 1, 2], axis=0) assert_raises(IndexError, x.take, [-3], axis=0) assert_array_equal(x.take([-1], axis=0)[0], x[1]) def test_clip(self): x = np.random.random(24)*100 - x.shape = 2,3,4 + x.shape = 2, 3, 4 assert_array_equal(x.take([-1], axis=0, mode='clip')[0], x[0]) assert_array_equal(x.take([2], axis=0, mode='clip')[0], x[1]) def test_wrap(self): x = np.random.random(24)*100 - x.shape = 2,3,4 + x.shape = 2, 3, 4 assert_array_equal(x.take([-1], axis=0, mode='wrap')[0], x[1]) assert_array_equal(x.take([2], axis=0, mode='wrap')[0], x[0]) assert_array_equal(x.take([3], axis=0, mode='wrap')[0], x[1]) - def tst_byteorder(self,dtype): - x = np.array([1,2,3],dtype) - assert_array_equal(x.take([0,2,1]),[1,3,2]) + def tst_byteorder(self, dtype): + x = np.array([1, 2, 3], dtype) + assert_array_equal(x.take([0, 2, 1]), [1, 3, 2]) def test_ip_byteorder(self): - for dtype in ('>i4','<i4'): - yield self.tst_byteorder,dtype + for dtype in ('>i4', '<i4'): + yield self.tst_byteorder, dtype def test_record_array(self): # Note mixed byteorder. @@ -1998,27 +1998,27 @@ class TestTake(object): class TestLexsort(TestCase): def test_basic(self): - a = [1,2,1,3,1,5] - b = [0,4,5,6,2,3] - idx = np.lexsort((b,a)) - expected_idx = np.array([0,4,2,1,3,5]) - assert_array_equal(idx,expected_idx) + a = [1, 2, 1, 3, 1, 5] + b = [0, 4, 5, 6, 2, 3] + idx = np.lexsort((b, a)) + expected_idx = np.array([0, 4, 2, 1, 3, 5]) + assert_array_equal(idx, expected_idx) - x = np.vstack((b,a)) + x = np.vstack((b, a)) idx = np.lexsort(x) - assert_array_equal(idx,expected_idx) + assert_array_equal(idx, expected_idx) - assert_array_equal(x[1][idx],np.sort(x[1])) + assert_array_equal(x[1][idx], np.sort(x[1])) class TestIO(object): """Test tofile, fromfile, tostring, and fromstring""" def setUp(self): - shape = (2,4,3) + shape = (2, 4, 3) rand = np.random.random self.x = rand(shape) + rand(shape).astype(np.complex)*1j - self.x[0,:,1] = [nan, inf, -inf, nan] + self.x[0,:, 1] = [nan, inf, -inf, nan] self.dtype = self.x.dtype self.filename = tempfile.mktemp() @@ -2028,7 +2028,7 @@ class TestIO(object): #tmp_file.close() def test_bool_fromstring(self): - v = np.array([True,False,True,False], dtype=np.bool_) + v = np.array([True, False, True, False], dtype=np.bool_) y = np.fromstring('1 0 -2.3 0.0', sep=' ', dtype=np.bool_) assert_array_equal(v, y) @@ -2109,7 +2109,7 @@ class TestIO(object): def test_binary(self): self._check_from('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', - array([1,2,3,4]), + array([1, 2, 3, 4]), dtype='<f4') @dec.slow # takes > 1 minute on mechanical hard drive @@ -2149,21 +2149,21 @@ class TestIO(object): self._check_from('1 2 3 4 ', [1, 2, 3, 4], dtype=int, sep=' ') def test_counted_string_with_ws(self): - self._check_from('1 2 3 4 ', [1,2,3], count=3, dtype=int, + self._check_from('1 2 3 4 ', [1, 2, 3], count=3, dtype=int, sep=' ') def test_ascii(self): - self._check_from('1 , 2 , 3 , 4', [1.,2.,3.,4.], sep=',') - self._check_from('1,2,3,4', [1.,2.,3.,4.], dtype=float, sep=',') + self._check_from('1 , 2 , 3 , 4', [1., 2., 3., 4.], sep=',') + self._check_from('1,2,3,4', [1., 2., 3., 4.], dtype=float, sep=',') def test_malformed(self): self._check_from('1.234 1,234', [1.234, 1.], sep=' ') def test_long_sep(self): - self._check_from('1_x_3_x_4_x_5', [1,3,4,5], sep='_x_') + self._check_from('1_x_3_x_4_x_5', [1, 3, 4, 5], sep='_x_') def test_dtype(self): - v = np.array([1,2,3,4], dtype=np.int_) + v = np.array([1, 2, 3, 4], dtype=np.int_) self._check_from('1,2,3,4', v, sep=',', dtype=np.int_) def test_dtype_bool(self): @@ -2210,14 +2210,14 @@ class TestIO(object): class TestFromBuffer(object): - def tst_basic(self,buffer,expected,kwargs): - assert_array_equal(np.frombuffer(buffer,**kwargs),expected) + def tst_basic(self, buffer, expected, kwargs): + assert_array_equal(np.frombuffer(buffer,**kwargs), expected) def test_ip_basic(self): - for byteorder in ['<','>']: - for dtype in [float,int,np.complex]: + for byteorder in ['<', '>']: + for dtype in [float, int, np.complex]: dt = np.dtype(dtype).newbyteorder(byteorder) - x = (np.random.random((4,7))*5).astype(dt) + x = (np.random.random((4, 7))*5).astype(dt) buf = x.tostring() yield self.tst_basic, buf, x.flat, {'dtype':dt} @@ -2228,13 +2228,13 @@ class TestFromBuffer(object): class TestFlat(TestCase): def setUp(self): a0 = arange(20.0) - a = a0.reshape(4,5) - a0.shape = (4,5) + a = a0.reshape(4, 5) + a0.shape = (4, 5) a.flags.writeable = False self.a = a - self.b = a[::2,::2] + self.b = a[::2, ::2] self.a0 = a0 - self.b0 = a0[::2,::2] + self.b0 = a0[::2, ::2] def test_contiguous(self): testpassed = False @@ -2274,15 +2274,15 @@ class TestFlat(TestCase): class TestResize(TestCase): def test_basic(self): x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) - x.resize((5,5)) + x.resize((5, 5)) assert_array_equal(x.flat[:9], np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).flat) - assert_array_equal(x[9:].flat,0) + assert_array_equal(x[9:].flat, 0) def test_check_reference(self): x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) y = x - self.assertRaises(ValueError,x.resize,(5,1)) + self.assertRaises(ValueError, x.resize, (5, 1)) def test_int_shape(self): x = np.eye(3) @@ -2304,21 +2304,21 @@ class TestResize(TestCase): def test_freeform_shape(self): x = np.eye(3) - x.resize(3,2,1) - assert_(x.shape == (3,2,1)) + x.resize(3, 2, 1) + assert_(x.shape == (3, 2, 1)) def test_zeros_appended(self): x = np.eye(3) - x.resize(2,3,3) + x.resize(2, 3, 3) assert_array_equal(x[0], np.eye(3)) - assert_array_equal(x[1], np.zeros((3,3))) + assert_array_equal(x[1], np.zeros((3, 3))) class TestRecord(TestCase): def test_field_rename(self): - dt = np.dtype([('f',float),('i',int)]) - dt.names = ['p','q'] - assert_equal(dt.names,['p','q']) + dt = np.dtype([('f', float), ('i', int)]) + dt.names = ['p', 'q'] + assert_equal(dt.names, ['p', 'q']) if sys.version_info[0] >= 3: def test_bytes_fields(self): @@ -2393,14 +2393,14 @@ class TestRecord(TestCase): # multiple Subfields fn2 = func('f2') b[fn2] = 3 - assert_equal(b[['f1','f2']][0].tolist(), (2, 3)) - assert_equal(b[['f2','f1']][0].tolist(), (3, 2)) - assert_equal(b[['f1','f3']][0].tolist(), (2, (1,))) + assert_equal(b[['f1', 'f2']][0].tolist(), (2, 3)) + assert_equal(b[['f2', 'f1']][0].tolist(), (3, 2)) + assert_equal(b[['f1', 'f3']][0].tolist(), (2, (1,))) # view of subfield view/copy - assert_equal(b[['f1','f2']][0].view(('i4',2)).tolist(), (2, 3)) - assert_equal(b[['f2','f1']][0].view(('i4',2)).tolist(), (3, 2)) - view_dtype=[('f1', 'i4'),('f3', [('', 'i4')])] - assert_equal(b[['f1','f3']][0].view(view_dtype).tolist(), (2, (1,))) + assert_equal(b[['f1', 'f2']][0].view(('i4', 2)).tolist(), (2, 3)) + assert_equal(b[['f2', 'f1']][0].view(('i4', 2)).tolist(), (3, 2)) + view_dtype=[('f1', 'i4'), ('f3', [('', 'i4')])] + assert_equal(b[['f1', 'f3']][0].view(view_dtype).tolist(), (2, (1,))) # non-ascii unicode field indexing is well behaved if not is_py3: raise SkipTest('non ascii unicode field indexing skipped; ' @@ -2432,11 +2432,11 @@ class TestRecord(TestCase): # All the different functions raise a warning, but not an error, and # 'a' is not modified: - assert_equal(collect_warning_types(a[['f1','f2']].__setitem__, 0, (10,20)), + assert_equal(collect_warning_types(a[['f1', 'f2']].__setitem__, 0, (10, 20)), [FutureWarning]) assert_equal(a, b) # Views also warn - subset = a[['f1','f2']] + subset = a[['f1', 'f2']] subset_view = subset.view() assert_equal(collect_warning_types(subset_view['f1'].__setitem__, 0, 10), [FutureWarning]) @@ -2448,11 +2448,11 @@ class TestRecord(TestCase): []) def test_record_hash(self): - a = np.array([(1,2),(1,2)], dtype='i1,i2') + a = np.array([(1, 2), (1, 2)], dtype='i1,i2') a.flags.writeable = False - b = np.array([(1,2),(3,4)], dtype=[('num1', 'i1'), ('num2', 'i2')]) + b = np.array([(1, 2), (3, 4)], dtype=[('num1', 'i1'), ('num2', 'i2')]) b.flags.writeable = False - c = np.array([(1,2),(3,4)], dtype='i1,i2') + c = np.array([(1, 2), (3, 4)], dtype='i1,i2') c.flags.writeable = False self.assertTrue(hash(a[0]) == hash(a[1])) self.assertTrue(hash(a[0]) == hash(b[0])) @@ -2460,13 +2460,13 @@ class TestRecord(TestCase): self.assertTrue(hash(c[0]) == hash(a[0]) and c[0] == a[0]) def test_record_no_hash(self): - a = np.array([(1,2),(1,2)], dtype='i1,i2') + a = np.array([(1, 2), (1, 2)], dtype='i1,i2') self.assertRaises(TypeError, hash, a[0]) class TestView(TestCase): def test_basic(self): - x = np.array([(1,2,3,4),(5,6,7,8)],dtype=[('r',np.int8),('g',np.int8), - ('b',np.int8),('a',np.int8)]) + x = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype=[('r', np.int8), ('g', np.int8), + ('b', np.int8), ('a', np.int8)]) # We must be specific about the endianness here: y = x.view(dtype='<i4') # ... and again without the keyword. @@ -2605,7 +2605,7 @@ class TestStats(TestCase): assert_(issubclass(w[0].category, RuntimeWarning)) def test_empty(self): - A = np.zeros((0,3)) + A = np.zeros((0, 3)) for f in self.funcs: for axis in [0, None]: with warnings.catch_warnings(record=True) as w: @@ -2656,7 +2656,7 @@ class TestStats(TestCase): def __array_finalize__(self, obj): self.info = getattr(obj, "info", '') - dat = TestArray([[1,2,3,4],[5,6,7,8]], 'jubba') + dat = TestArray([[1, 2, 3, 4], [5, 6, 7, 8]], 'jubba') res = dat.mean(1) assert_(res.info == dat.info) res = dat.std(1) @@ -2684,16 +2684,16 @@ class TestDot(TestCase): r = np.empty((1024, 32)) for i in range(12): - dot(f,v,r) + dot(f, v, r) assert_equal(sys.getrefcount(r), 2) - r2 = dot(f,v,out=None) + r2 = dot(f, v, out=None) assert_array_equal(r2, r) - assert_(r is dot(f,v,out=r)) + assert_(r is dot(f, v, out=r)) - v = v[:,0].copy() # v.shape == (16,) - r = r[:,0].copy() # r.shape == (1024,) - r2 = dot(f,v) - assert_(r is dot(f,v,r)) + v = v[:, 0].copy() # v.shape == (16,) + r = r[:, 0].copy() # r.shape == (1024,) + r2 = dot(f, v) + assert_(r is dot(f, v, r)) assert_array_equal(r2, r) def test_dot_3args_errors(self): @@ -2717,8 +2717,8 @@ class TestDot(TestCase): assert_raises(ValueError, dot, f, v, r.T) r = np.empty((1024, 64)) - assert_raises(ValueError, dot, f, v, r[:,::2]) - assert_raises(ValueError, dot, f, v, r[:,:32]) + assert_raises(ValueError, dot, f, v, r[:, ::2]) + assert_raises(ValueError, dot, f, v, r[:, :32]) r = np.empty((1024, 32), dtype=np.float32) assert_raises(ValueError, dot, f, v, r) @@ -2737,7 +2737,7 @@ class TestSummarization(TestCase): assert_(repr(A) == reprA) def test_2d(self): - A = np.arange(1002).reshape(2,501) + A = np.arange(1002).reshape(2, 501) strA = '[[ 0 1 2 ..., 498 499 500]\n' \ ' [ 501 502 503 ..., 999 1000 1001]]' assert_(str(A) == strA) @@ -2749,23 +2749,23 @@ class TestSummarization(TestCase): class TestChoose(TestCase): def setUp(self): - self.x = 2*ones((3,),dtype=int) - self.y = 3*ones((3,),dtype=int) - self.x2 = 2*ones((2,3), dtype=int) - self.y2 = 3*ones((2,3), dtype=int) - self.ind = [0,0,1] + self.x = 2*ones((3,), dtype=int) + self.y = 3*ones((3,), dtype=int) + self.x2 = 2*ones((2, 3), dtype=int) + self.y2 = 3*ones((2, 3), dtype=int) + self.ind = [0, 0, 1] def test_basic(self): A = np.choose(self.ind, (self.x, self.y)) - assert_equal(A, [2,2,3]) + assert_equal(A, [2, 2, 3]) def test_broadcast1(self): A = np.choose(self.ind, (self.x2, self.y2)) - assert_equal(A, [[2,2,3],[2,2,3]]) + assert_equal(A, [[2, 2, 3], [2, 2, 3]]) def test_broadcast2(self): A = np.choose(self.ind, (self.x, self.y2)) - assert_equal(A, [[2,2,3],[2,2,3]]) + assert_equal(A, [[2, 2, 3], [2, 2, 3]]) def can_use_decimal(): try: @@ -3052,13 +3052,13 @@ class TestStackedNeighborhoodIter(TestCase): class TestWarnings(object): def test_complex_warning(self): - x = np.array([1,2]) - y = np.array([1-2j,1+2j]) + x = np.array([1, 2]) + y = np.array([1-2j, 1+2j]) with warnings.catch_warnings(): warnings.simplefilter("error", np.ComplexWarning) assert_raises(np.ComplexWarning, x.__setitem__, slice(None), y) - assert_equal(x, [1,2]) + assert_equal(x, [1, 2]) class TestMinScalarType(object): @@ -3187,13 +3187,13 @@ class TestNewBufferProtocol(object): assert_array_equal(obj, y2) def test_roundtrip(self): - x = np.array([1,2,3,4,5], dtype='i4') + x = np.array([1, 2, 3, 4, 5], dtype='i4') self._check_roundtrip(x) - x = np.array([[1,2],[3,4]], dtype=np.float64) + x = np.array([[1, 2], [3, 4]], dtype=np.float64) self._check_roundtrip(x) - x = np.zeros((3,3,3), dtype=np.float32)[:,0,:] + x = np.zeros((3, 3, 3), dtype=np.float32)[:, 0,:] self._check_roundtrip(x) dt = [('a', 'b'), @@ -3224,32 +3224,32 @@ class TestNewBufferProtocol(object): dtype=dt) self._check_roundtrip(x) - x = np.array(([[1,2],[3,4]],), dtype=[('a', (int, (2,2)))]) + x = np.array(([[1, 2], [3, 4]],), dtype=[('a', (int, (2, 2)))]) self._check_roundtrip(x) - x = np.array([1,2,3], dtype='>i2') + x = np.array([1, 2, 3], dtype='>i2') self._check_roundtrip(x) - x = np.array([1,2,3], dtype='<i2') + x = np.array([1, 2, 3], dtype='<i2') self._check_roundtrip(x) - x = np.array([1,2,3], dtype='>i4') + x = np.array([1, 2, 3], dtype='>i4') self._check_roundtrip(x) - x = np.array([1,2,3], dtype='<i4') + x = np.array([1, 2, 3], dtype='<i4') self._check_roundtrip(x) # Native-only data types can be passed through the buffer interface # only in native byte order if sys.byteorder == 'little': - x = np.array([1,2,3], dtype='>q') + x = np.array([1, 2, 3], dtype='>q') assert_raises(ValueError, self._check_roundtrip, x) - x = np.array([1,2,3], dtype='<q') + x = np.array([1, 2, 3], dtype='<q') self._check_roundtrip(x) else: - x = np.array([1,2,3], dtype='>q') + x = np.array([1, 2, 3], dtype='>q') self._check_roundtrip(x) - x = np.array([1,2,3], dtype='<q') + x = np.array([1, 2, 3], dtype='<q') assert_raises(ValueError, self._check_roundtrip, x) def test_roundtrip_half(self): @@ -3272,7 +3272,7 @@ class TestNewBufferProtocol(object): self._check_roundtrip(x) def test_export_simple_1d(self): - x = np.array([1,2,3,4,5], dtype='i') + x = np.array([1, 2, 3, 4, 5], dtype='i') y = memoryview(x) assert_equal(y.format, 'i') assert_equal(y.shape, (5,)) @@ -3282,7 +3282,7 @@ class TestNewBufferProtocol(object): assert_equal(y.itemsize, 4) def test_export_simple_nd(self): - x = np.array([[1,2],[3,4]], dtype=np.float64) + x = np.array([[1, 2], [3, 4]], dtype=np.float64) y = memoryview(x) assert_equal(y.format, 'd') assert_equal(y.shape, (2, 2)) @@ -3292,7 +3292,7 @@ class TestNewBufferProtocol(object): assert_equal(y.itemsize, 8) def test_export_discontiguous(self): - x = np.zeros((3,3,3), dtype=np.float32)[:,0,:] + x = np.zeros((3, 3, 3), dtype=np.float32)[:, 0,:] y = memoryview(x) assert_equal(y.format, 'f') assert_equal(y.shape, (3, 3)) @@ -3344,7 +3344,7 @@ class TestNewBufferProtocol(object): assert_equal(y.itemsize, sz) def test_export_subarray(self): - x = np.array(([[1,2],[3,4]],), dtype=[('a', ('i', (2,2)))]) + x = np.array(([[1, 2], [3, 4]],), dtype=[('a', ('i', (2, 2)))]) y = memoryview(x) assert_equal(y.format, 'T{(2,2)i:a:}') assert_equal(y.shape, EMPTY) @@ -3354,14 +3354,14 @@ class TestNewBufferProtocol(object): assert_equal(y.itemsize, 16) def test_export_endian(self): - x = np.array([1,2,3], dtype='>i') + x = np.array([1, 2, 3], dtype='>i') y = memoryview(x) if sys.byteorder == 'little': assert_equal(y.format, '>i') else: assert_equal(y.format, 'i') - x = np.array([1,2,3], dtype='<i') + x = np.array([1, 2, 3], dtype='<i') y = memoryview(x) if sys.byteorder == 'little': assert_equal(y.format, 'i') @@ -3374,7 +3374,7 @@ class TestNewBufferProtocol(object): def test_padding(self): for j in range(8): - x = np.array([(1,),(2,)], dtype={'f0': (int, j)}) + x = np.array([(1,), (2,)], dtype={'f0': (int, j)}) self._check_roundtrip(x) def test_reference_leak(self): @@ -3460,7 +3460,7 @@ def test_array_interface(): assert_equal(np.array(f), 0.5) f.iface['shape'] = None assert_raises(TypeError, np.array, f) - f.iface['shape'] = (1,1) + f.iface['shape'] = (1, 1) assert_equal(np.array(f), [[0.5]]) f.iface['shape'] = (2,) assert_raises(ValueError, np.array, f) @@ -3497,19 +3497,19 @@ class TestMapIter(TestCase): # The actual tests are within the C code in # multiarray/multiarray_tests.c.src - a = arange(12).reshape((3,4)).astype(float) - index = ([1,1,2,0], - [0,0,2,3]) - vals = [50,50, 30,16] + a = arange(12).reshape((3, 4)).astype(float) + index = ([1, 1, 2, 0], + [0, 0, 2, 3]) + vals = [50, 50, 30, 16] test_inplace_increment(a, index, vals) - assert_equal(a, [[ 0. , 1., 2., 19.,], + assert_equal(a, [[ 0., 1., 2., 19.,], [ 104., 5., 6., 7.,], [ 8., 9., 40., 11.,]]) b = arange(6).astype(float) - index = (array([1,2,0]),) - vals = [50,4,100.1] + index = (array([1, 2, 0]),) + vals = [50, 4, 100.1] test_inplace_increment(b, index, vals) assert_equal(b, [ 100.1, 51., 6., 3., 4., 5. ]) diff --git a/numpy/core/tests/test_nditer.py b/numpy/core/tests/test_nditer.py index 76d85618f..bc20b900e 100644 --- a/numpy/core/tests/test_nditer.py +++ b/numpy/core/tests/test_nditer.py @@ -39,7 +39,7 @@ def test_iter_refcount(): rc_a = sys.getrefcount(a) rc_dt = sys.getrefcount(dt) it = nditer(a, [], - [['readwrite','updateifcopy']], + [['readwrite', 'updateifcopy']], casting='unsafe', op_dtypes=[dt]) assert_(not it.iterationneedsapi) @@ -74,14 +74,14 @@ def test_iter_best_order(): # with increasing memory addresses # Test the ordering for 1-D to 5-D shapes - for shape in [(5,), (3,4), (2,3,4), (2,3,4,3), (2,3,2,2,3)]: + for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: a = arange(np.prod(shape)) # Test each combination of positive and negative strides for dirs in range(2**len(shape)): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit)&dirs): - dirs_index[bit] = slice(None,None,-1) + dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] @@ -93,21 +93,21 @@ def test_iter_best_order(): assert_equal([x for x in i], a) # Other order if len(shape) > 2: - i = nditer(aview.swapaxes(0,1), [], [['readonly']]) + i = nditer(aview.swapaxes(0, 1), [], [['readonly']]) assert_equal([x for x in i], a) def test_iter_c_order(): # Test forcing C order # Test the ordering for 1-D to 5-D shapes - for shape in [(5,), (3,4), (2,3,4), (2,3,4,3), (2,3,2,2,3)]: + for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: a = arange(np.prod(shape)) # Test each combination of positive and negative strides for dirs in range(2**len(shape)): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit)&dirs): - dirs_index[bit] = slice(None,None,-1) + dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] @@ -119,22 +119,22 @@ def test_iter_c_order(): assert_equal([x for x in i], aview.T.ravel(order='C')) # Other order if len(shape) > 2: - i = nditer(aview.swapaxes(0,1), order='C') + i = nditer(aview.swapaxes(0, 1), order='C') assert_equal([x for x in i], - aview.swapaxes(0,1).ravel(order='C')) + aview.swapaxes(0, 1).ravel(order='C')) def test_iter_f_order(): # Test forcing F order # Test the ordering for 1-D to 5-D shapes - for shape in [(5,), (3,4), (2,3,4), (2,3,4,3), (2,3,2,2,3)]: + for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: a = arange(np.prod(shape)) # Test each combination of positive and negative strides for dirs in range(2**len(shape)): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit)&dirs): - dirs_index[bit] = slice(None,None,-1) + dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] @@ -146,22 +146,22 @@ def test_iter_f_order(): assert_equal([x for x in i], aview.T.ravel(order='F')) # Other order if len(shape) > 2: - i = nditer(aview.swapaxes(0,1), order='F') + i = nditer(aview.swapaxes(0, 1), order='F') assert_equal([x for x in i], - aview.swapaxes(0,1).ravel(order='F')) + aview.swapaxes(0, 1).ravel(order='F')) def test_iter_c_or_f_order(): # Test forcing any contiguous (C or F) order # Test the ordering for 1-D to 5-D shapes - for shape in [(5,), (3,4), (2,3,4), (2,3,4,3), (2,3,2,2,3)]: + for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: a = arange(np.prod(shape)) # Test each combination of positive and negative strides for dirs in range(2**len(shape)): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit)&dirs): - dirs_index[bit] = slice(None,None,-1) + dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] @@ -173,250 +173,250 @@ def test_iter_c_or_f_order(): assert_equal([x for x in i], aview.T.ravel(order='A')) # Other order if len(shape) > 2: - i = nditer(aview.swapaxes(0,1), order='A') + i = nditer(aview.swapaxes(0, 1), order='A') assert_equal([x for x in i], - aview.swapaxes(0,1).ravel(order='A')) + aview.swapaxes(0, 1).ravel(order='A')) def test_iter_best_order_multi_index_1d(): # The multi-indices should be correct with any reordering a = arange(4) # 1D order - i = nditer(a,['multi_index'],[['readonly']]) - assert_equal(iter_multi_index(i), [(0,),(1,),(2,),(3,)]) + i = nditer(a, ['multi_index'], [['readonly']]) + assert_equal(iter_multi_index(i), [(0,), (1,), (2,), (3,)]) # 1D reversed order - i = nditer(a[::-1],['multi_index'],[['readonly']]) - assert_equal(iter_multi_index(i), [(3,),(2,),(1,),(0,)]) + i = nditer(a[::-1], ['multi_index'], [['readonly']]) + assert_equal(iter_multi_index(i), [(3,), (2,), (1,), (0,)]) def test_iter_best_order_multi_index_2d(): # The multi-indices should be correct with any reordering a = arange(6) # 2D C-order - i = nditer(a.reshape(2,3),['multi_index'],[['readonly']]) - assert_equal(iter_multi_index(i), [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2)]) + i = nditer(a.reshape(2, 3), ['multi_index'], [['readonly']]) + assert_equal(iter_multi_index(i), [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]) # 2D Fortran-order - i = nditer(a.reshape(2,3).copy(order='F'),['multi_index'],[['readonly']]) - assert_equal(iter_multi_index(i), [(0,0),(1,0),(0,1),(1,1),(0,2),(1,2)]) + i = nditer(a.reshape(2, 3).copy(order='F'), ['multi_index'], [['readonly']]) + assert_equal(iter_multi_index(i), [(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2)]) # 2D reversed C-order - i = nditer(a.reshape(2,3)[::-1],['multi_index'],[['readonly']]) - assert_equal(iter_multi_index(i), [(1,0),(1,1),(1,2),(0,0),(0,1),(0,2)]) - i = nditer(a.reshape(2,3)[:,::-1],['multi_index'],[['readonly']]) - assert_equal(iter_multi_index(i), [(0,2),(0,1),(0,0),(1,2),(1,1),(1,0)]) - i = nditer(a.reshape(2,3)[::-1,::-1],['multi_index'],[['readonly']]) - assert_equal(iter_multi_index(i), [(1,2),(1,1),(1,0),(0,2),(0,1),(0,0)]) + i = nditer(a.reshape(2, 3)[::-1], ['multi_index'], [['readonly']]) + assert_equal(iter_multi_index(i), [(1, 0), (1, 1), (1, 2), (0, 0), (0, 1), (0, 2)]) + i = nditer(a.reshape(2, 3)[:, ::-1], ['multi_index'], [['readonly']]) + assert_equal(iter_multi_index(i), [(0, 2), (0, 1), (0, 0), (1, 2), (1, 1), (1, 0)]) + i = nditer(a.reshape(2, 3)[::-1, ::-1], ['multi_index'], [['readonly']]) + assert_equal(iter_multi_index(i), [(1, 2), (1, 1), (1, 0), (0, 2), (0, 1), (0, 0)]) # 2D reversed Fortran-order - i = nditer(a.reshape(2,3).copy(order='F')[::-1],['multi_index'],[['readonly']]) - assert_equal(iter_multi_index(i), [(1,0),(0,0),(1,1),(0,1),(1,2),(0,2)]) - i = nditer(a.reshape(2,3).copy(order='F')[:,::-1], - ['multi_index'],[['readonly']]) - assert_equal(iter_multi_index(i), [(0,2),(1,2),(0,1),(1,1),(0,0),(1,0)]) - i = nditer(a.reshape(2,3).copy(order='F')[::-1,::-1], - ['multi_index'],[['readonly']]) - assert_equal(iter_multi_index(i), [(1,2),(0,2),(1,1),(0,1),(1,0),(0,0)]) + i = nditer(a.reshape(2, 3).copy(order='F')[::-1], ['multi_index'], [['readonly']]) + assert_equal(iter_multi_index(i), [(1, 0), (0, 0), (1, 1), (0, 1), (1, 2), (0, 2)]) + i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1], + ['multi_index'], [['readonly']]) + assert_equal(iter_multi_index(i), [(0, 2), (1, 2), (0, 1), (1, 1), (0, 0), (1, 0)]) + i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1], + ['multi_index'], [['readonly']]) + assert_equal(iter_multi_index(i), [(1, 2), (0, 2), (1, 1), (0, 1), (1, 0), (0, 0)]) def test_iter_best_order_multi_index_3d(): # The multi-indices should be correct with any reordering a = arange(12) # 3D C-order - i = nditer(a.reshape(2,3,2),['multi_index'],[['readonly']]) + i = nditer(a.reshape(2, 3, 2), ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), - [(0,0,0),(0,0,1),(0,1,0),(0,1,1),(0,2,0),(0,2,1), - (1,0,0),(1,0,1),(1,1,0),(1,1,1),(1,2,0),(1,2,1)]) + [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (0, 2, 0), (0, 2, 1), + (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1), (1, 2, 0), (1, 2, 1)]) # 3D Fortran-order - i = nditer(a.reshape(2,3,2).copy(order='F'),['multi_index'],[['readonly']]) + i = nditer(a.reshape(2, 3, 2).copy(order='F'), ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), - [(0,0,0),(1,0,0),(0,1,0),(1,1,0),(0,2,0),(1,2,0), - (0,0,1),(1,0,1),(0,1,1),(1,1,1),(0,2,1),(1,2,1)]) + [(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 2, 0), (1, 2, 0), + (0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1), (0, 2, 1), (1, 2, 1)]) # 3D reversed C-order - i = nditer(a.reshape(2,3,2)[::-1],['multi_index'],[['readonly']]) + i = nditer(a.reshape(2, 3, 2)[::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), - [(1,0,0),(1,0,1),(1,1,0),(1,1,1),(1,2,0),(1,2,1), - (0,0,0),(0,0,1),(0,1,0),(0,1,1),(0,2,0),(0,2,1)]) - i = nditer(a.reshape(2,3,2)[:,::-1],['multi_index'],[['readonly']]) + [(1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1), (1, 2, 0), (1, 2, 1), + (0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (0, 2, 0), (0, 2, 1)]) + i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), - [(0,2,0),(0,2,1),(0,1,0),(0,1,1),(0,0,0),(0,0,1), - (1,2,0),(1,2,1),(1,1,0),(1,1,1),(1,0,0),(1,0,1)]) - i = nditer(a.reshape(2,3,2)[:,:,::-1],['multi_index'],[['readonly']]) + [(0, 2, 0), (0, 2, 1), (0, 1, 0), (0, 1, 1), (0, 0, 0), (0, 0, 1), + (1, 2, 0), (1, 2, 1), (1, 1, 0), (1, 1, 1), (1, 0, 0), (1, 0, 1)]) + i = nditer(a.reshape(2, 3, 2)[:,:, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), - [(0,0,1),(0,0,0),(0,1,1),(0,1,0),(0,2,1),(0,2,0), - (1,0,1),(1,0,0),(1,1,1),(1,1,0),(1,2,1),(1,2,0)]) + [(0, 0, 1), (0, 0, 0), (0, 1, 1), (0, 1, 0), (0, 2, 1), (0, 2, 0), + (1, 0, 1), (1, 0, 0), (1, 1, 1), (1, 1, 0), (1, 2, 1), (1, 2, 0)]) # 3D reversed Fortran-order - i = nditer(a.reshape(2,3,2).copy(order='F')[::-1], - ['multi_index'],[['readonly']]) + i = nditer(a.reshape(2, 3, 2).copy(order='F')[::-1], + ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), - [(1,0,0),(0,0,0),(1,1,0),(0,1,0),(1,2,0),(0,2,0), - (1,0,1),(0,0,1),(1,1,1),(0,1,1),(1,2,1),(0,2,1)]) - i = nditer(a.reshape(2,3,2).copy(order='F')[:,::-1], - ['multi_index'],[['readonly']]) + [(1, 0, 0), (0, 0, 0), (1, 1, 0), (0, 1, 0), (1, 2, 0), (0, 2, 0), + (1, 0, 1), (0, 0, 1), (1, 1, 1), (0, 1, 1), (1, 2, 1), (0, 2, 1)]) + i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, ::-1], + ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), - [(0,2,0),(1,2,0),(0,1,0),(1,1,0),(0,0,0),(1,0,0), - (0,2,1),(1,2,1),(0,1,1),(1,1,1),(0,0,1),(1,0,1)]) - i = nditer(a.reshape(2,3,2).copy(order='F')[:,:,::-1], - ['multi_index'],[['readonly']]) + [(0, 2, 0), (1, 2, 0), (0, 1, 0), (1, 1, 0), (0, 0, 0), (1, 0, 0), + (0, 2, 1), (1, 2, 1), (0, 1, 1), (1, 1, 1), (0, 0, 1), (1, 0, 1)]) + i = nditer(a.reshape(2, 3, 2).copy(order='F')[:,:, ::-1], + ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), - [(0,0,1),(1,0,1),(0,1,1),(1,1,1),(0,2,1),(1,2,1), - (0,0,0),(1,0,0),(0,1,0),(1,1,0),(0,2,0),(1,2,0)]) + [(0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1), (0, 2, 1), (1, 2, 1), + (0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 2, 0), (1, 2, 0)]) def test_iter_best_order_c_index_1d(): # The C index should be correct with any reordering a = arange(4) # 1D order - i = nditer(a,['c_index'],[['readonly']]) - assert_equal(iter_indices(i), [0,1,2,3]) + i = nditer(a, ['c_index'], [['readonly']]) + assert_equal(iter_indices(i), [0, 1, 2, 3]) # 1D reversed order - i = nditer(a[::-1],['c_index'],[['readonly']]) - assert_equal(iter_indices(i), [3,2,1,0]) + i = nditer(a[::-1], ['c_index'], [['readonly']]) + assert_equal(iter_indices(i), [3, 2, 1, 0]) def test_iter_best_order_c_index_2d(): # The C index should be correct with any reordering a = arange(6) # 2D C-order - i = nditer(a.reshape(2,3),['c_index'],[['readonly']]) - assert_equal(iter_indices(i), [0,1,2,3,4,5]) + i = nditer(a.reshape(2, 3), ['c_index'], [['readonly']]) + assert_equal(iter_indices(i), [0, 1, 2, 3, 4, 5]) # 2D Fortran-order - i = nditer(a.reshape(2,3).copy(order='F'), - ['c_index'],[['readonly']]) - assert_equal(iter_indices(i), [0,3,1,4,2,5]) + i = nditer(a.reshape(2, 3).copy(order='F'), + ['c_index'], [['readonly']]) + assert_equal(iter_indices(i), [0, 3, 1, 4, 2, 5]) # 2D reversed C-order - i = nditer(a.reshape(2,3)[::-1],['c_index'],[['readonly']]) - assert_equal(iter_indices(i), [3,4,5,0,1,2]) - i = nditer(a.reshape(2,3)[:,::-1],['c_index'],[['readonly']]) - assert_equal(iter_indices(i), [2,1,0,5,4,3]) - i = nditer(a.reshape(2,3)[::-1,::-1],['c_index'],[['readonly']]) - assert_equal(iter_indices(i), [5,4,3,2,1,0]) + i = nditer(a.reshape(2, 3)[::-1], ['c_index'], [['readonly']]) + assert_equal(iter_indices(i), [3, 4, 5, 0, 1, 2]) + i = nditer(a.reshape(2, 3)[:, ::-1], ['c_index'], [['readonly']]) + assert_equal(iter_indices(i), [2, 1, 0, 5, 4, 3]) + i = nditer(a.reshape(2, 3)[::-1, ::-1], ['c_index'], [['readonly']]) + assert_equal(iter_indices(i), [5, 4, 3, 2, 1, 0]) # 2D reversed Fortran-order - i = nditer(a.reshape(2,3).copy(order='F')[::-1], - ['c_index'],[['readonly']]) - assert_equal(iter_indices(i), [3,0,4,1,5,2]) - i = nditer(a.reshape(2,3).copy(order='F')[:,::-1], - ['c_index'],[['readonly']]) - assert_equal(iter_indices(i), [2,5,1,4,0,3]) - i = nditer(a.reshape(2,3).copy(order='F')[::-1,::-1], - ['c_index'],[['readonly']]) - assert_equal(iter_indices(i), [5,2,4,1,3,0]) + i = nditer(a.reshape(2, 3).copy(order='F')[::-1], + ['c_index'], [['readonly']]) + assert_equal(iter_indices(i), [3, 0, 4, 1, 5, 2]) + i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1], + ['c_index'], [['readonly']]) + assert_equal(iter_indices(i), [2, 5, 1, 4, 0, 3]) + i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1], + ['c_index'], [['readonly']]) + assert_equal(iter_indices(i), [5, 2, 4, 1, 3, 0]) def test_iter_best_order_c_index_3d(): # The C index should be correct with any reordering a = arange(12) # 3D C-order - i = nditer(a.reshape(2,3,2),['c_index'],[['readonly']]) + i = nditer(a.reshape(2, 3, 2), ['c_index'], [['readonly']]) assert_equal(iter_indices(i), - [0,1,2,3,4,5,6,7,8,9,10,11]) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) # 3D Fortran-order - i = nditer(a.reshape(2,3,2).copy(order='F'), - ['c_index'],[['readonly']]) + i = nditer(a.reshape(2, 3, 2).copy(order='F'), + ['c_index'], [['readonly']]) assert_equal(iter_indices(i), - [0,6,2,8,4,10,1,7,3,9,5,11]) + [0, 6, 2, 8, 4, 10, 1, 7, 3, 9, 5, 11]) # 3D reversed C-order - i = nditer(a.reshape(2,3,2)[::-1],['c_index'],[['readonly']]) + i = nditer(a.reshape(2, 3, 2)[::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), - [6,7,8,9,10,11,0,1,2,3,4,5]) - i = nditer(a.reshape(2,3,2)[:,::-1],['c_index'],[['readonly']]) + [6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5]) + i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), - [4,5,2,3,0,1,10,11,8,9,6,7]) - i = nditer(a.reshape(2,3,2)[:,:,::-1],['c_index'],[['readonly']]) + [4, 5, 2, 3, 0, 1, 10, 11, 8, 9, 6, 7]) + i = nditer(a.reshape(2, 3, 2)[:,:, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), - [1,0,3,2,5,4,7,6,9,8,11,10]) + [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10]) # 3D reversed Fortran-order - i = nditer(a.reshape(2,3,2).copy(order='F')[::-1], - ['c_index'],[['readonly']]) + i = nditer(a.reshape(2, 3, 2).copy(order='F')[::-1], + ['c_index'], [['readonly']]) assert_equal(iter_indices(i), - [6,0,8,2,10,4,7,1,9,3,11,5]) - i = nditer(a.reshape(2,3,2).copy(order='F')[:,::-1], - ['c_index'],[['readonly']]) + [6, 0, 8, 2, 10, 4, 7, 1, 9, 3, 11, 5]) + i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, ::-1], + ['c_index'], [['readonly']]) assert_equal(iter_indices(i), - [4,10,2,8,0,6,5,11,3,9,1,7]) - i = nditer(a.reshape(2,3,2).copy(order='F')[:,:,::-1], - ['c_index'],[['readonly']]) + [4, 10, 2, 8, 0, 6, 5, 11, 3, 9, 1, 7]) + i = nditer(a.reshape(2, 3, 2).copy(order='F')[:,:, ::-1], + ['c_index'], [['readonly']]) assert_equal(iter_indices(i), - [1,7,3,9,5,11,0,6,2,8,4,10]) + [1, 7, 3, 9, 5, 11, 0, 6, 2, 8, 4, 10]) def test_iter_best_order_f_index_1d(): # The Fortran index should be correct with any reordering a = arange(4) # 1D order - i = nditer(a,['f_index'],[['readonly']]) - assert_equal(iter_indices(i), [0,1,2,3]) + i = nditer(a, ['f_index'], [['readonly']]) + assert_equal(iter_indices(i), [0, 1, 2, 3]) # 1D reversed order - i = nditer(a[::-1],['f_index'],[['readonly']]) - assert_equal(iter_indices(i), [3,2,1,0]) + i = nditer(a[::-1], ['f_index'], [['readonly']]) + assert_equal(iter_indices(i), [3, 2, 1, 0]) def test_iter_best_order_f_index_2d(): # The Fortran index should be correct with any reordering a = arange(6) # 2D C-order - i = nditer(a.reshape(2,3),['f_index'],[['readonly']]) - assert_equal(iter_indices(i), [0,2,4,1,3,5]) + i = nditer(a.reshape(2, 3), ['f_index'], [['readonly']]) + assert_equal(iter_indices(i), [0, 2, 4, 1, 3, 5]) # 2D Fortran-order - i = nditer(a.reshape(2,3).copy(order='F'), - ['f_index'],[['readonly']]) - assert_equal(iter_indices(i), [0,1,2,3,4,5]) + i = nditer(a.reshape(2, 3).copy(order='F'), + ['f_index'], [['readonly']]) + assert_equal(iter_indices(i), [0, 1, 2, 3, 4, 5]) # 2D reversed C-order - i = nditer(a.reshape(2,3)[::-1],['f_index'],[['readonly']]) - assert_equal(iter_indices(i), [1,3,5,0,2,4]) - i = nditer(a.reshape(2,3)[:,::-1],['f_index'],[['readonly']]) - assert_equal(iter_indices(i), [4,2,0,5,3,1]) - i = nditer(a.reshape(2,3)[::-1,::-1],['f_index'],[['readonly']]) - assert_equal(iter_indices(i), [5,3,1,4,2,0]) + i = nditer(a.reshape(2, 3)[::-1], ['f_index'], [['readonly']]) + assert_equal(iter_indices(i), [1, 3, 5, 0, 2, 4]) + i = nditer(a.reshape(2, 3)[:, ::-1], ['f_index'], [['readonly']]) + assert_equal(iter_indices(i), [4, 2, 0, 5, 3, 1]) + i = nditer(a.reshape(2, 3)[::-1, ::-1], ['f_index'], [['readonly']]) + assert_equal(iter_indices(i), [5, 3, 1, 4, 2, 0]) # 2D reversed Fortran-order - i = nditer(a.reshape(2,3).copy(order='F')[::-1], - ['f_index'],[['readonly']]) - assert_equal(iter_indices(i), [1,0,3,2,5,4]) - i = nditer(a.reshape(2,3).copy(order='F')[:,::-1], - ['f_index'],[['readonly']]) - assert_equal(iter_indices(i), [4,5,2,3,0,1]) - i = nditer(a.reshape(2,3).copy(order='F')[::-1,::-1], - ['f_index'],[['readonly']]) - assert_equal(iter_indices(i), [5,4,3,2,1,0]) + i = nditer(a.reshape(2, 3).copy(order='F')[::-1], + ['f_index'], [['readonly']]) + assert_equal(iter_indices(i), [1, 0, 3, 2, 5, 4]) + i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1], + ['f_index'], [['readonly']]) + assert_equal(iter_indices(i), [4, 5, 2, 3, 0, 1]) + i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1], + ['f_index'], [['readonly']]) + assert_equal(iter_indices(i), [5, 4, 3, 2, 1, 0]) def test_iter_best_order_f_index_3d(): # The Fortran index should be correct with any reordering a = arange(12) # 3D C-order - i = nditer(a.reshape(2,3,2),['f_index'],[['readonly']]) + i = nditer(a.reshape(2, 3, 2), ['f_index'], [['readonly']]) assert_equal(iter_indices(i), - [0,6,2,8,4,10,1,7,3,9,5,11]) + [0, 6, 2, 8, 4, 10, 1, 7, 3, 9, 5, 11]) # 3D Fortran-order - i = nditer(a.reshape(2,3,2).copy(order='F'), - ['f_index'],[['readonly']]) + i = nditer(a.reshape(2, 3, 2).copy(order='F'), + ['f_index'], [['readonly']]) assert_equal(iter_indices(i), - [0,1,2,3,4,5,6,7,8,9,10,11]) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) # 3D reversed C-order - i = nditer(a.reshape(2,3,2)[::-1],['f_index'],[['readonly']]) + i = nditer(a.reshape(2, 3, 2)[::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), - [1,7,3,9,5,11,0,6,2,8,4,10]) - i = nditer(a.reshape(2,3,2)[:,::-1],['f_index'],[['readonly']]) + [1, 7, 3, 9, 5, 11, 0, 6, 2, 8, 4, 10]) + i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), - [4,10,2,8,0,6,5,11,3,9,1,7]) - i = nditer(a.reshape(2,3,2)[:,:,::-1],['f_index'],[['readonly']]) + [4, 10, 2, 8, 0, 6, 5, 11, 3, 9, 1, 7]) + i = nditer(a.reshape(2, 3, 2)[:,:, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), - [6,0,8,2,10,4,7,1,9,3,11,5]) + [6, 0, 8, 2, 10, 4, 7, 1, 9, 3, 11, 5]) # 3D reversed Fortran-order - i = nditer(a.reshape(2,3,2).copy(order='F')[::-1], - ['f_index'],[['readonly']]) + i = nditer(a.reshape(2, 3, 2).copy(order='F')[::-1], + ['f_index'], [['readonly']]) assert_equal(iter_indices(i), - [1,0,3,2,5,4,7,6,9,8,11,10]) - i = nditer(a.reshape(2,3,2).copy(order='F')[:,::-1], - ['f_index'],[['readonly']]) + [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10]) + i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, ::-1], + ['f_index'], [['readonly']]) assert_equal(iter_indices(i), - [4,5,2,3,0,1,10,11,8,9,6,7]) - i = nditer(a.reshape(2,3,2).copy(order='F')[:,:,::-1], - ['f_index'],[['readonly']]) + [4, 5, 2, 3, 0, 1, 10, 11, 8, 9, 6, 7]) + i = nditer(a.reshape(2, 3, 2).copy(order='F')[:,:, ::-1], + ['f_index'], [['readonly']]) assert_equal(iter_indices(i), - [6,7,8,9,10,11,0,1,2,3,4,5]) + [6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5]) def test_iter_no_inner_full_coalesce(): # Check no_inner iterators which coalesce into a single inner loop - for shape in [(5,), (3,4), (2,3,4), (2,3,4,3), (2,3,2,2,3)]: + for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: size = np.prod(shape) a = arange(size) # Test each combination of forward and backwards indexing @@ -424,7 +424,7 @@ def test_iter_no_inner_full_coalesce(): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit)&dirs): - dirs_index[bit] = slice(None,None,-1) + dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] @@ -438,7 +438,7 @@ def test_iter_no_inner_full_coalesce(): assert_equal(i[0].shape, (size,)) # Other order if len(shape) > 2: - i = nditer(aview.swapaxes(0,1), + i = nditer(aview.swapaxes(0, 1), ['external_loop'], [['readonly']]) assert_equal(i.ndim, 1) assert_equal(i[0].shape, (size,)) @@ -448,21 +448,21 @@ def test_iter_no_inner_dim_coalescing(): # Skipping the last element in a dimension prevents coalescing # with the next-bigger dimension - a = arange(24).reshape(2,3,4)[:,:,:-1] + a = arange(24).reshape(2, 3, 4)[:,:, :-1] i = nditer(a, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 2) assert_equal(i[0].shape, (3,)) - a = arange(24).reshape(2,3,4)[:,:-1,:] + a = arange(24).reshape(2, 3, 4)[:, :-1,:] i = nditer(a, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 2) assert_equal(i[0].shape, (8,)) - a = arange(24).reshape(2,3,4)[:-1,:,:] + a = arange(24).reshape(2, 3, 4)[:-1,:,:] i = nditer(a, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 1) assert_equal(i[0].shape, (12,)) # Even with lots of 1-sized dimensions, should still coalesce - a = arange(24).reshape(1,1,2,1,1,3,1,1,4,1,1) + a = arange(24).reshape(1, 1, 2, 1, 1, 3, 1, 1, 4, 1, 1) i = nditer(a, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 1) assert_equal(i[0].shape, (24,)) @@ -471,25 +471,25 @@ def test_iter_dim_coalescing(): # Check that the correct number of dimensions are coalesced # Tracking a multi-index disables coalescing - a = arange(24).reshape(2,3,4) + a = arange(24).reshape(2, 3, 4) i = nditer(a, ['multi_index'], [['readonly']]) assert_equal(i.ndim, 3) # A tracked index can allow coalescing if it's compatible with the array - a3d = arange(24).reshape(2,3,4) + a3d = arange(24).reshape(2, 3, 4) i = nditer(a3d, ['c_index'], [['readonly']]) assert_equal(i.ndim, 1) - i = nditer(a3d.swapaxes(0,1), ['c_index'], [['readonly']]) + i = nditer(a3d.swapaxes(0, 1), ['c_index'], [['readonly']]) assert_equal(i.ndim, 3) i = nditer(a3d.T, ['c_index'], [['readonly']]) assert_equal(i.ndim, 3) i = nditer(a3d.T, ['f_index'], [['readonly']]) assert_equal(i.ndim, 1) - i = nditer(a3d.T.swapaxes(0,1), ['f_index'], [['readonly']]) + i = nditer(a3d.T.swapaxes(0, 1), ['f_index'], [['readonly']]) assert_equal(i.ndim, 3) # When C or F order is forced, coalescing may still occur - a3d = arange(24).reshape(2,3,4) + a3d = arange(24).reshape(2, 3, 4) i = nditer(a3d, order='C') assert_equal(i.ndim, 1) i = nditer(a3d.T, order='C') @@ -512,95 +512,95 @@ def test_iter_broadcasting(): assert_equal(i.shape, (6,)) # 2D with scalar - i = nditer([arange(6).reshape(2,3), np.int32(2)], + i = nditer([arange(6).reshape(2, 3), np.int32(2)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 6) - assert_equal(i.shape, (2,3)) + assert_equal(i.shape, (2, 3)) # 2D with 1D - i = nditer([arange(6).reshape(2,3), arange(3)], + i = nditer([arange(6).reshape(2, 3), arange(3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 6) - assert_equal(i.shape, (2,3)) - i = nditer([arange(2).reshape(2,1), arange(3)], + assert_equal(i.shape, (2, 3)) + i = nditer([arange(2).reshape(2, 1), arange(3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 6) - assert_equal(i.shape, (2,3)) + assert_equal(i.shape, (2, 3)) # 2D with 2D - i = nditer([arange(2).reshape(2,1), arange(3).reshape(1,3)], + i = nditer([arange(2).reshape(2, 1), arange(3).reshape(1, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 6) - assert_equal(i.shape, (2,3)) + assert_equal(i.shape, (2, 3)) # 3D with scalar - i = nditer([np.int32(2), arange(24).reshape(4,2,3)], + i = nditer([np.int32(2), arange(24).reshape(4, 2, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) - assert_equal(i.shape, (4,2,3)) + assert_equal(i.shape, (4, 2, 3)) # 3D with 1D - i = nditer([arange(3), arange(24).reshape(4,2,3)], + i = nditer([arange(3), arange(24).reshape(4, 2, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) - assert_equal(i.shape, (4,2,3)) - i = nditer([arange(3), arange(8).reshape(4,2,1)], + assert_equal(i.shape, (4, 2, 3)) + i = nditer([arange(3), arange(8).reshape(4, 2, 1)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) - assert_equal(i.shape, (4,2,3)) + assert_equal(i.shape, (4, 2, 3)) # 3D with 2D - i = nditer([arange(6).reshape(2,3), arange(24).reshape(4,2,3)], + i = nditer([arange(6).reshape(2, 3), arange(24).reshape(4, 2, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) - assert_equal(i.shape, (4,2,3)) - i = nditer([arange(2).reshape(2,1), arange(24).reshape(4,2,3)], + assert_equal(i.shape, (4, 2, 3)) + i = nditer([arange(2).reshape(2, 1), arange(24).reshape(4, 2, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) - assert_equal(i.shape, (4,2,3)) - i = nditer([arange(3).reshape(1,3), arange(8).reshape(4,2,1)], + assert_equal(i.shape, (4, 2, 3)) + i = nditer([arange(3).reshape(1, 3), arange(8).reshape(4, 2, 1)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) - assert_equal(i.shape, (4,2,3)) + assert_equal(i.shape, (4, 2, 3)) # 3D with 3D - i = nditer([arange(2).reshape(1,2,1), arange(3).reshape(1,1,3), - arange(4).reshape(4,1,1)], + i = nditer([arange(2).reshape(1, 2, 1), arange(3).reshape(1, 1, 3), + arange(4).reshape(4, 1, 1)], ['multi_index'], [['readonly']]*3) assert_equal(i.itersize, 24) - assert_equal(i.shape, (4,2,3)) - i = nditer([arange(6).reshape(1,2,3), arange(4).reshape(4,1,1)], + assert_equal(i.shape, (4, 2, 3)) + i = nditer([arange(6).reshape(1, 2, 3), arange(4).reshape(4, 1, 1)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) - assert_equal(i.shape, (4,2,3)) - i = nditer([arange(24).reshape(4,2,3), arange(12).reshape(4,1,3)], + assert_equal(i.shape, (4, 2, 3)) + i = nditer([arange(24).reshape(4, 2, 3), arange(12).reshape(4, 1, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) - assert_equal(i.shape, (4,2,3)) + assert_equal(i.shape, (4, 2, 3)) def test_iter_itershape(): # Check that allocated outputs work with a specified shape - a = np.arange(6, dtype='i2').reshape(2,3) - i = nditer([a, None], [], [['readonly'], ['writeonly','allocate']], - op_axes=[[0,1,None], None], - itershape=(-1,-1,4)) - assert_equal(i.operands[1].shape, (2,3,4)) - assert_equal(i.operands[1].strides, (24,8,2)) - - i = nditer([a.T, None], [], [['readonly'], ['writeonly','allocate']], - op_axes=[[0,1,None], None], - itershape=(-1,-1,4)) - assert_equal(i.operands[1].shape, (3,2,4)) - assert_equal(i.operands[1].strides, (8,24,2)) - - i = nditer([a.T, None], [], [['readonly'], ['writeonly','allocate']], + a = np.arange(6, dtype='i2').reshape(2, 3) + i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']], + op_axes=[[0, 1, None], None], + itershape=(-1, -1, 4)) + assert_equal(i.operands[1].shape, (2, 3, 4)) + assert_equal(i.operands[1].strides, (24, 8, 2)) + + i = nditer([a.T, None], [], [['readonly'], ['writeonly', 'allocate']], + op_axes=[[0, 1, None], None], + itershape=(-1, -1, 4)) + assert_equal(i.operands[1].shape, (3, 2, 4)) + assert_equal(i.operands[1].strides, (8, 24, 2)) + + i = nditer([a.T, None], [], [['readonly'], ['writeonly', 'allocate']], order='F', - op_axes=[[0,1,None], None], - itershape=(-1,-1,4)) - assert_equal(i.operands[1].shape, (3,2,4)) - assert_equal(i.operands[1].strides, (2,6,12)) + op_axes=[[0, 1, None], None], + itershape=(-1, -1, 4)) + assert_equal(i.operands[1].shape, (3, 2, 4)) + assert_equal(i.operands[1].strides, (2, 6, 12)) # If we specify 1 in the itershape, it shouldn't allow broadcasting # of that dimension to a bigger value assert_raises(ValueError, nditer, [a, None], [], - [['readonly'], ['writeonly','allocate']], - op_axes=[[0,1,None], None], - itershape=(-1,1,4)) + [['readonly'], ['writeonly', 'allocate']], + op_axes=[[0, 1, None], None], + itershape=(-1, 1, 4)) # Test bug that for no op_axes but itershape, they are NULLed correctly i = np.nditer([np.ones(2), None, None], itershape=(2,)) @@ -612,30 +612,30 @@ def test_iter_broadcasting_errors(): [], [['readonly']]*2) # 2D with 1D assert_raises(ValueError, nditer, - [arange(6).reshape(2,3), arange(2)], + [arange(6).reshape(2, 3), arange(2)], [], [['readonly']]*2) # 2D with 2D assert_raises(ValueError, nditer, - [arange(6).reshape(2,3), arange(9).reshape(3,3)], + [arange(6).reshape(2, 3), arange(9).reshape(3, 3)], [], [['readonly']]*2) assert_raises(ValueError, nditer, - [arange(6).reshape(2,3), arange(4).reshape(2,2)], + [arange(6).reshape(2, 3), arange(4).reshape(2, 2)], [], [['readonly']]*2) # 3D with 3D assert_raises(ValueError, nditer, - [arange(36).reshape(3,3,4), arange(24).reshape(2,3,4)], + [arange(36).reshape(3, 3, 4), arange(24).reshape(2, 3, 4)], [], [['readonly']]*2) assert_raises(ValueError, nditer, - [arange(8).reshape(2,4,1), arange(24).reshape(2,3,4)], + [arange(8).reshape(2, 4, 1), arange(24).reshape(2, 3, 4)], [], [['readonly']]*2) # Verify that the error message mentions the right shapes try: - i = nditer([arange(2).reshape(1,2,1), - arange(3).reshape(1,3), - arange(6).reshape(2,3)], + i = nditer([arange(2).reshape(1, 2, 1), + arange(3).reshape(1, 3), + arange(6).reshape(2, 3)], [], - [['readonly'], ['readonly'], ['writeonly','no_broadcast']]) + [['readonly'], ['readonly'], ['writeonly', 'no_broadcast']]) assert_(False, 'Should have raised a broadcast error') except ValueError as e: msg = str(e) @@ -647,10 +647,10 @@ def test_iter_broadcasting_errors(): 'Message "%s" doesn\'t contain broadcast shape (1,2,3)' % msg) try: - i = nditer([arange(6).reshape(2,3), arange(2)], [], - [['readonly'],['readonly']], - op_axes=[[0,1], [0,np.newaxis]], - itershape=(4,3)) + i = nditer([arange(6).reshape(2, 3), arange(2)], [], + [['readonly'], ['readonly']], + op_axes=[[0, 1], [0, np.newaxis]], + itershape=(4, 3)) assert_(False, 'Should have raised a broadcast error') except ValueError as e: msg = str(e) @@ -665,9 +665,9 @@ def test_iter_broadcasting_errors(): 'Message "%s" doesn\'t contain itershape parameter (4,3)' % msg) try: - i = nditer([np.zeros((2,1,1)), np.zeros((2,))], + i = nditer([np.zeros((2, 1, 1)), np.zeros((2,))], [], - [['writeonly','no_broadcast'], ['readonly']]) + [['writeonly', 'no_broadcast'], ['readonly']]) assert_(False, 'Should have raised a broadcast error') except ValueError as e: msg = str(e) @@ -690,7 +690,7 @@ def test_iter_flags_errors(): # Bad global flag assert_raises(ValueError, nditer, [a], ['bad flag'], [['readonly']]) # Bad op flag - assert_raises(ValueError, nditer, [a], [], [['readonly','bad flag']]) + assert_raises(ValueError, nditer, [a], [], [['readonly', 'bad flag']]) # Bad order parameter assert_raises(ValueError, nditer, [a], [], [['readonly']], order='G') # Bad casting parameter @@ -699,21 +699,21 @@ def test_iter_flags_errors(): assert_raises(ValueError, nditer, [a]*3, [], [['readonly']]*2) # Cannot track both a C and an F index assert_raises(ValueError, nditer, a, - ['c_index','f_index'], [['readonly']]) + ['c_index', 'f_index'], [['readonly']]) # Inner iteration and multi-indices/indices are incompatible assert_raises(ValueError, nditer, a, - ['external_loop','multi_index'], [['readonly']]) + ['external_loop', 'multi_index'], [['readonly']]) assert_raises(ValueError, nditer, a, - ['external_loop','c_index'], [['readonly']]) + ['external_loop', 'c_index'], [['readonly']]) assert_raises(ValueError, nditer, a, - ['external_loop','f_index'], [['readonly']]) + ['external_loop', 'f_index'], [['readonly']]) # Must specify exactly one of readwrite/readonly/writeonly per operand assert_raises(ValueError, nditer, a, [], [[]]) - assert_raises(ValueError, nditer, a, [], [['readonly','writeonly']]) - assert_raises(ValueError, nditer, a, [], [['readonly','readwrite']]) - assert_raises(ValueError, nditer, a, [], [['writeonly','readwrite']]) + assert_raises(ValueError, nditer, a, [], [['readonly', 'writeonly']]) + assert_raises(ValueError, nditer, a, [], [['readonly', 'readwrite']]) + assert_raises(ValueError, nditer, a, [], [['writeonly', 'readwrite']]) assert_raises(ValueError, nditer, a, - [], [['readonly','writeonly','readwrite']]) + [], [['readonly', 'writeonly', 'readwrite']]) # Python scalars are always readonly assert_raises(TypeError, nditer, 1.5, [], [['writeonly']]) assert_raises(TypeError, nditer, 1.5, [], [['readwrite']]) @@ -738,7 +738,7 @@ def test_iter_flags_errors(): def assign_iterindex(i): i.iterindex = 0; def assign_iterrange(i): - i.iterrange = (0,1); + i.iterrange = (0, 1); i = nditer(arange(6), ['external_loop']) assert_raises(ValueError, assign_multi_index, i) assert_raises(ValueError, assign_index, i) @@ -753,13 +753,13 @@ def test_iter_flags_errors(): def test_iter_slice(): a, b, c = np.arange(3), np.arange(3), np.arange(3.) - i = nditer([a,b,c], [], ['readwrite']) - i[0:2] = (3,3) - assert_equal(a, [3,1,2]) - assert_equal(b, [3,1,2]) - assert_equal(c, [0,1,2]) + i = nditer([a, b, c], [], ['readwrite']) + i[0:2] = (3, 3) + assert_equal(a, [3, 1, 2]) + assert_equal(b, [3, 1, 2]) + assert_equal(c, [0, 1, 2]) i[1] = 12 - assert_equal(i[0:2], [3,12]) + assert_equal(i[0:2], [3, 12]) def test_iter_nbo_align_contig(): # Check that byte order, alignment, and contig changes work @@ -768,7 +768,7 @@ def test_iter_nbo_align_contig(): a = np.arange(6, dtype='f4') au = a.byteswap().newbyteorder() assert_(a.dtype.byteorder != au.dtype.byteorder) - i = nditer(au, [], [['readwrite','updateifcopy']], + i = nditer(au, [], [['readwrite', 'updateifcopy']], casting='equiv', op_dtypes=[np.dtype('f4')]) assert_equal(i.dtypes[0].byteorder, a.dtype.byteorder) @@ -782,7 +782,7 @@ def test_iter_nbo_align_contig(): a = np.arange(6, dtype='f4') au = a.byteswap().newbyteorder() assert_(a.dtype.byteorder != au.dtype.byteorder) - i = nditer(au, [], [['readwrite','updateifcopy','nbo']], casting='equiv') + i = nditer(au, [], [['readwrite', 'updateifcopy', 'nbo']], casting='equiv') assert_equal(i.dtypes[0].byteorder, a.dtype.byteorder) assert_equal(i.operands[0].dtype.byteorder, a.dtype.byteorder) assert_equal(i.operands[0], a) @@ -800,7 +800,7 @@ def test_iter_nbo_align_contig(): assert_(not i.operands[0].flags.aligned) assert_equal(i.operands[0], a); # With 'aligned', should make a copy - i = nditer(a, [], [['readwrite','updateifcopy','aligned']]) + i = nditer(a, [], [['readwrite', 'updateifcopy', 'aligned']]) assert_(i.operands[0].flags.aligned) assert_equal(i.operands[0], a); i.operands[0][:] = 3 @@ -814,8 +814,8 @@ def test_iter_nbo_align_contig(): assert_(i.operands[0].flags.contiguous) assert_equal(i.operands[0], a[:6]); # If it isn't contiguous, should buffer - i = nditer(a[::2], ['buffered','external_loop'], - [['readonly','contig']], + i = nditer(a[::2], ['buffered', 'external_loop'], + [['readonly', 'contig']], buffersize=10) assert_(i[0].flags.contiguous) assert_equal(i[0], a[::2]) @@ -824,106 +824,106 @@ def test_iter_array_cast(): # Check that arrays are cast as requested # No cast 'f4' -> 'f4' - a = np.arange(6, dtype='f4').reshape(2,3) + a = np.arange(6, dtype='f4').reshape(2, 3) i = nditer(a, [], [['readwrite']], op_dtypes=[np.dtype('f4')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('f4')) # Byte-order cast '<f4' -> '>f4' - a = np.arange(6, dtype='<f4').reshape(2,3) - i = nditer(a, [], [['readwrite','updateifcopy']], + a = np.arange(6, dtype='<f4').reshape(2, 3) + i = nditer(a, [], [['readwrite', 'updateifcopy']], casting='equiv', op_dtypes=[np.dtype('>f4')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('>f4')) # Safe case 'f4' -> 'f8' - a = np.arange(24, dtype='f4').reshape(2,3,4).swapaxes(1,2) - i = nditer(a, [], [['readonly','copy']], + a = np.arange(24, dtype='f4').reshape(2, 3, 4).swapaxes(1, 2) + i = nditer(a, [], [['readonly', 'copy']], casting='safe', op_dtypes=[np.dtype('f8')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('f8')) # The memory layout of the temporary should match a (a is (48,4,16)) # except negative strides get flipped to positive strides. - assert_equal(i.operands[0].strides, (96,8,32)) - a = a[::-1,:,::-1] - i = nditer(a, [], [['readonly','copy']], + assert_equal(i.operands[0].strides, (96, 8, 32)) + a = a[::-1,:, ::-1] + i = nditer(a, [], [['readonly', 'copy']], casting='safe', op_dtypes=[np.dtype('f8')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('f8')) - assert_equal(i.operands[0].strides, (96,8,32)) + assert_equal(i.operands[0].strides, (96, 8, 32)) # Same-kind cast 'f8' -> 'f4' -> 'f8' - a = np.arange(24, dtype='f8').reshape(2,3,4).T + a = np.arange(24, dtype='f8').reshape(2, 3, 4).T i = nditer(a, [], - [['readwrite','updateifcopy']], + [['readwrite', 'updateifcopy']], casting='same_kind', op_dtypes=[np.dtype('f4')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('f4')) assert_equal(i.operands[0].strides, (4, 16, 48)) # Check that UPDATEIFCOPY is activated - i.operands[0][2,1,1] = -12.5 - assert_(a[2,1,1] != -12.5) + i.operands[0][2, 1, 1] = -12.5 + assert_(a[2, 1, 1] != -12.5) i = None - assert_equal(a[2,1,1], -12.5) + assert_equal(a[2, 1, 1], -12.5) a = np.arange(6, dtype='i4')[::-2] i = nditer(a, [], - [['writeonly','updateifcopy']], + [['writeonly', 'updateifcopy']], casting='unsafe', op_dtypes=[np.dtype('f4')]) assert_equal(i.operands[0].dtype, np.dtype('f4')) # Even though the stride was negative in 'a', it # becomes positive in the temporary assert_equal(i.operands[0].strides, (4,)) - i.operands[0][:] = [1,2,3] + i.operands[0][:] = [1, 2, 3] i = None - assert_equal(a, [1,2,3]) + assert_equal(a, [1, 2, 3]) def test_iter_array_cast_errors(): # Check that invalid casts are caught # Need to enable copying for casts to occur - assert_raises(TypeError, nditer, arange(2,dtype='f4'), [], + assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], [['readonly']], op_dtypes=[np.dtype('f8')]) # Also need to allow casting for casts to occur - assert_raises(TypeError, nditer, arange(2,dtype='f4'), [], - [['readonly','copy']], casting='no', + assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], + [['readonly', 'copy']], casting='no', op_dtypes=[np.dtype('f8')]) - assert_raises(TypeError, nditer, arange(2,dtype='f4'), [], - [['readonly','copy']], casting='equiv', + assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], + [['readonly', 'copy']], casting='equiv', op_dtypes=[np.dtype('f8')]) - assert_raises(TypeError, nditer, arange(2,dtype='f8'), [], - [['writeonly','updateifcopy']], + assert_raises(TypeError, nditer, arange(2, dtype='f8'), [], + [['writeonly', 'updateifcopy']], casting='no', op_dtypes=[np.dtype('f4')]) - assert_raises(TypeError, nditer, arange(2,dtype='f8'), [], - [['writeonly','updateifcopy']], + assert_raises(TypeError, nditer, arange(2, dtype='f8'), [], + [['writeonly', 'updateifcopy']], casting='equiv', op_dtypes=[np.dtype('f4')]) # '<f4' -> '>f4' should not work with casting='no' - assert_raises(TypeError, nditer, arange(2,dtype='<f4'), [], - [['readonly','copy']], casting='no', + assert_raises(TypeError, nditer, arange(2, dtype='<f4'), [], + [['readonly', 'copy']], casting='no', op_dtypes=[np.dtype('>f4')]) # 'f4' -> 'f8' is a safe cast, but 'f8' -> 'f4' isn't - assert_raises(TypeError, nditer, arange(2,dtype='f4'), [], - [['readwrite','updateifcopy']], + assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], + [['readwrite', 'updateifcopy']], casting='safe', op_dtypes=[np.dtype('f8')]) - assert_raises(TypeError, nditer, arange(2,dtype='f8'), [], - [['readwrite','updateifcopy']], + assert_raises(TypeError, nditer, arange(2, dtype='f8'), [], + [['readwrite', 'updateifcopy']], casting='safe', op_dtypes=[np.dtype('f4')]) # 'f4' -> 'i4' is neither a safe nor a same-kind cast - assert_raises(TypeError, nditer, arange(2,dtype='f4'), [], - [['readonly','copy']], + assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], + [['readonly', 'copy']], casting='same_kind', op_dtypes=[np.dtype('i4')]) - assert_raises(TypeError, nditer, arange(2,dtype='i4'), [], - [['writeonly','updateifcopy']], + assert_raises(TypeError, nditer, arange(2, dtype='i4'), [], + [['writeonly', 'updateifcopy']], casting='same_kind', op_dtypes=[np.dtype('f4')]) @@ -938,7 +938,7 @@ def test_iter_scalar_cast(): assert_equal(i.value, 2.5) # Safe cast 'f4' -> 'f8' i = nditer(np.float32(2.5), [], - [['readonly','copy']], + [['readonly', 'copy']], casting='safe', op_dtypes=[np.dtype('f8')]) assert_equal(i.dtypes[0], np.dtype('f8')) @@ -946,7 +946,7 @@ def test_iter_scalar_cast(): assert_equal(i.value, 2.5) # Same-kind cast 'f8' -> 'f4' i = nditer(np.float64(2.5), [], - [['readonly','copy']], + [['readonly', 'copy']], casting='same_kind', op_dtypes=[np.dtype('f4')]) assert_equal(i.dtypes[0], np.dtype('f4')) @@ -954,7 +954,7 @@ def test_iter_scalar_cast(): assert_equal(i.value, 2.5) # Unsafe cast 'f8' -> 'i4' i = nditer(np.float64(3.0), [], - [['readonly','copy']], + [['readonly', 'copy']], casting='unsafe', op_dtypes=[np.dtype('i4')]) assert_equal(i.dtypes[0], np.dtype('i4')) @@ -988,7 +988,7 @@ def test_iter_object_arrays_basic(): # Check that object arrays work obj = {'a':3,'b':'d'} - a = np.array([[1,2,3], None, obj, None], dtype='O') + a = np.array([[1, 2, 3], None, obj, None], dtype='O') rc = sys.getrefcount(obj) # Need to allow references for object arrays @@ -1001,15 +1001,15 @@ def test_iter_object_arrays_basic(): vals, i, x = [None]*3 assert_equal(sys.getrefcount(obj), rc) - i = nditer(a.reshape(2,2).T, ['refs_ok','buffered'], + i = nditer(a.reshape(2, 2).T, ['refs_ok', 'buffered'], ['readonly'], order='C') assert_(i.iterationneedsapi) vals = [x[()] for x in i] - assert_equal(np.array(vals, dtype='O'), a.reshape(2,2).ravel(order='F')) + assert_equal(np.array(vals, dtype='O'), a.reshape(2, 2).ravel(order='F')) vals, i, x = [None]*3 assert_equal(sys.getrefcount(obj), rc) - i = nditer(a.reshape(2,2).T, ['refs_ok','buffered'], + i = nditer(a.reshape(2, 2).T, ['refs_ok', 'buffered'], ['readwrite'], order='C') for x in i: x[...] = None @@ -1020,34 +1020,34 @@ def test_iter_object_arrays_basic(): def test_iter_object_arrays_conversions(): # Conversions to/from objects a = np.arange(6, dtype='O') - i = nditer(a, ['refs_ok','buffered'], ['readwrite'], + i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'], casting='unsafe', op_dtypes='i4') for x in i: x[...] += 1 assert_equal(a, np.arange(6)+1) a = np.arange(6, dtype='i4') - i = nditer(a, ['refs_ok','buffered'], ['readwrite'], + i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'], casting='unsafe', op_dtypes='O') for x in i: x[...] += 1 assert_equal(a, np.arange(6)+1) # Non-contiguous object array - a = np.zeros((6,), dtype=[('p','i1'),('a','O')]) + a = np.zeros((6,), dtype=[('p', 'i1'), ('a', 'O')]) a = a['a'] a[:] = np.arange(6) - i = nditer(a, ['refs_ok','buffered'], ['readwrite'], + i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'], casting='unsafe', op_dtypes='i4') for x in i: x[...] += 1 assert_equal(a, np.arange(6)+1) #Non-contiguous value array - a = np.zeros((6,), dtype=[('p','i1'),('a','i4')]) + a = np.zeros((6,), dtype=[('p', 'i1'), ('a', 'i4')]) a = a['a'] a[:] = np.arange(6) + 98172488 - i = nditer(a, ['refs_ok','buffered'], ['readwrite'], + i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'], casting='unsafe', op_dtypes='O') ob = i[0][()] rc = sys.getrefcount(ob) @@ -1059,61 +1059,61 @@ def test_iter_object_arrays_conversions(): def test_iter_common_dtype(): # Check that the iterator finds a common data type correctly - i = nditer([array([3],dtype='f4'),array([0],dtype='f8')], + i = nditer([array([3], dtype='f4'), array([0], dtype='f8')], ['common_dtype'], - [['readonly','copy']]*2, + [['readonly', 'copy']]*2, casting='safe') assert_equal(i.dtypes[0], np.dtype('f8')); assert_equal(i.dtypes[1], np.dtype('f8')); - i = nditer([array([3],dtype='i4'),array([0],dtype='f4')], + i = nditer([array([3], dtype='i4'), array([0], dtype='f4')], ['common_dtype'], - [['readonly','copy']]*2, + [['readonly', 'copy']]*2, casting='safe') assert_equal(i.dtypes[0], np.dtype('f8')); assert_equal(i.dtypes[1], np.dtype('f8')); - i = nditer([array([3],dtype='f4'),array(0,dtype='f8')], + i = nditer([array([3], dtype='f4'), array(0, dtype='f8')], ['common_dtype'], - [['readonly','copy']]*2, + [['readonly', 'copy']]*2, casting='same_kind') assert_equal(i.dtypes[0], np.dtype('f4')); assert_equal(i.dtypes[1], np.dtype('f4')); - i = nditer([array([3],dtype='u4'),array(0,dtype='i4')], + i = nditer([array([3], dtype='u4'), array(0, dtype='i4')], ['common_dtype'], - [['readonly','copy']]*2, + [['readonly', 'copy']]*2, casting='safe') assert_equal(i.dtypes[0], np.dtype('u4')); assert_equal(i.dtypes[1], np.dtype('u4')); - i = nditer([array([3],dtype='u4'),array(-12,dtype='i4')], + i = nditer([array([3], dtype='u4'), array(-12, dtype='i4')], ['common_dtype'], - [['readonly','copy']]*2, + [['readonly', 'copy']]*2, casting='safe') assert_equal(i.dtypes[0], np.dtype('i8')); assert_equal(i.dtypes[1], np.dtype('i8')); - i = nditer([array([3],dtype='u4'),array(-12,dtype='i4'), - array([2j],dtype='c8'),array([9],dtype='f8')], + i = nditer([array([3], dtype='u4'), array(-12, dtype='i4'), + array([2j], dtype='c8'), array([9], dtype='f8')], ['common_dtype'], - [['readonly','copy']]*4, + [['readonly', 'copy']]*4, casting='safe') assert_equal(i.dtypes[0], np.dtype('c16')); assert_equal(i.dtypes[1], np.dtype('c16')); assert_equal(i.dtypes[2], np.dtype('c16')); assert_equal(i.dtypes[3], np.dtype('c16')); - assert_equal(i.value, (3,-12,2j,9)) + assert_equal(i.value, (3, -12, 2j, 9)) # When allocating outputs, other outputs aren't factored in - i = nditer([array([3],dtype='i4'),None,array([2j],dtype='c16')], [], - [['readonly','copy'], - ['writeonly','allocate'], + i = nditer([array([3], dtype='i4'), None, array([2j], dtype='c16')], [], + [['readonly', 'copy'], + ['writeonly', 'allocate'], ['writeonly']], casting='safe') assert_equal(i.dtypes[0], np.dtype('i4')); assert_equal(i.dtypes[1], np.dtype('i4')); assert_equal(i.dtypes[2], np.dtype('c16')); # But, if common data types are requested, they are - i = nditer([array([3],dtype='i4'),None,array([2j],dtype='c16')], + i = nditer([array([3], dtype='i4'), None, array([2j], dtype='c16')], ['common_dtype'], - [['readonly','copy'], - ['writeonly','allocate'], + [['readonly', 'copy'], + ['writeonly', 'allocate'], ['writeonly']], casting='safe') assert_equal(i.dtypes[0], np.dtype('c16')); @@ -1124,69 +1124,69 @@ def test_iter_op_axes(): # Check that custom axes work # Reverse the axes - a = arange(6).reshape(2,3) - i = nditer([a,a.T], [], [['readonly']]*2, op_axes=[[0,1],[1,0]]) - assert_(all([x==y for (x,y) in i])) - a = arange(24).reshape(2,3,4) - i = nditer([a.T,a], [], [['readonly']]*2, op_axes=[[2,1,0],None]) - assert_(all([x==y for (x,y) in i])) + a = arange(6).reshape(2, 3) + i = nditer([a, a.T], [], [['readonly']]*2, op_axes=[[0, 1], [1, 0]]) + assert_(all([x==y for (x, y) in i])) + a = arange(24).reshape(2, 3, 4) + i = nditer([a.T, a], [], [['readonly']]*2, op_axes=[[2, 1, 0], None]) + assert_(all([x==y for (x, y) in i])) # Broadcast 1D to any dimension - a = arange(1,31).reshape(2,3,5) - b = arange(1,3) - i = nditer([a,b], [], [['readonly']]*2, op_axes=[None,[0,-1,-1]]) - assert_equal([x*y for (x,y) in i], (a*b.reshape(2,1,1)).ravel()) - b = arange(1,4) - i = nditer([a,b], [], [['readonly']]*2, op_axes=[None,[-1,0,-1]]) - assert_equal([x*y for (x,y) in i], (a*b.reshape(1,3,1)).ravel()) - b = arange(1,6) - i = nditer([a,b], [], [['readonly']]*2, - op_axes=[None,[np.newaxis,np.newaxis,0]]) - assert_equal([x*y for (x,y) in i], (a*b.reshape(1,1,5)).ravel()) + a = arange(1, 31).reshape(2, 3, 5) + b = arange(1, 3) + i = nditer([a, b], [], [['readonly']]*2, op_axes=[None, [0, -1, -1]]) + assert_equal([x*y for (x, y) in i], (a*b.reshape(2, 1, 1)).ravel()) + b = arange(1, 4) + i = nditer([a, b], [], [['readonly']]*2, op_axes=[None, [-1, 0, -1]]) + assert_equal([x*y for (x, y) in i], (a*b.reshape(1, 3, 1)).ravel()) + b = arange(1, 6) + i = nditer([a, b], [], [['readonly']]*2, + op_axes=[None, [np.newaxis, np.newaxis, 0]]) + assert_equal([x*y for (x, y) in i], (a*b.reshape(1, 1, 5)).ravel()) # Inner product-style broadcasting - a = arange(24).reshape(2,3,4) - b = arange(40).reshape(5,2,4) - i = nditer([a,b], ['multi_index'], [['readonly']]*2, - op_axes=[[0,1,-1,-1],[-1,-1,0,1]]) - assert_equal(i.shape, (2,3,5,2)) + a = arange(24).reshape(2, 3, 4) + b = arange(40).reshape(5, 2, 4) + i = nditer([a, b], ['multi_index'], [['readonly']]*2, + op_axes=[[0, 1, -1, -1], [-1, -1, 0, 1]]) + assert_equal(i.shape, (2, 3, 5, 2)) # Matrix product-style broadcasting - a = arange(12).reshape(3,4) - b = arange(20).reshape(4,5) - i = nditer([a,b], ['multi_index'], [['readonly']]*2, - op_axes=[[0,-1],[-1,1]]) - assert_equal(i.shape, (3,5)) + a = arange(12).reshape(3, 4) + b = arange(20).reshape(4, 5) + i = nditer([a, b], ['multi_index'], [['readonly']]*2, + op_axes=[[0, -1], [-1, 1]]) + assert_equal(i.shape, (3, 5)) def test_iter_op_axes_errors(): # Check that custom axes throws errors for bad inputs # Wrong number of items in op_axes - a = arange(6).reshape(2,3) - assert_raises(ValueError, nditer, [a,a], [], [['readonly']]*2, - op_axes=[[0],[1],[0]]) + a = arange(6).reshape(2, 3) + assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, + op_axes=[[0], [1], [0]]) # Out of bounds items in op_axes - assert_raises(ValueError, nditer, [a,a], [], [['readonly']]*2, - op_axes=[[2,1],[0,1]]) - assert_raises(ValueError, nditer, [a,a], [], [['readonly']]*2, - op_axes=[[0,1],[2,-1]]) + assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, + op_axes=[[2, 1], [0, 1]]) + assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, + op_axes=[[0, 1], [2, -1]]) # Duplicate items in op_axes - assert_raises(ValueError, nditer, [a,a], [], [['readonly']]*2, - op_axes=[[0,0],[0,1]]) - assert_raises(ValueError, nditer, [a,a], [], [['readonly']]*2, - op_axes=[[0,1],[1,1]]) + assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, + op_axes=[[0, 0], [0, 1]]) + assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, + op_axes=[[0, 1], [1, 1]]) # Different sized arrays in op_axes - assert_raises(ValueError, nditer, [a,a], [], [['readonly']]*2, - op_axes=[[0,1],[0,1,0]]) + assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, + op_axes=[[0, 1], [0, 1, 0]]) # Non-broadcastable dimensions in the result - assert_raises(ValueError, nditer, [a,a], [], [['readonly']]*2, - op_axes=[[0,1],[1,0]]) + assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, + op_axes=[[0, 1], [1, 0]]) def test_iter_copy(): # Check that copying the iterator works correctly - a = arange(24).reshape(2,3,4) + a = arange(24).reshape(2, 3, 4) # Simple iterator i = nditer(a) @@ -1198,7 +1198,7 @@ def test_iter_copy(): assert_equal([x[()] for x in i], [x[()] for x in j]) # Buffered iterator - i = nditer(a, ['buffered','ranged'], order='F', buffersize=3) + i = nditer(a, ['buffered', 'ranged'], order='F', buffersize=3) j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) @@ -1206,11 +1206,11 @@ def test_iter_copy(): j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) - i.iterrange = (3,9) + i.iterrange = (3, 9) j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) - i.iterrange = (2,18) + i.iterrange = (2, 18) next(i) next(i) j = i.copy() @@ -1223,7 +1223,7 @@ def test_iter_copy(): i = None assert_equal([x[()] for x in j], a.ravel(order='F')) - a = arange(24, dtype='<i4').reshape(2,3,4) + a = arange(24, dtype='<i4').reshape(2, 3, 4) i = nditer(a, ['buffered'], order='F', casting='unsafe', op_dtypes='>f8', buffersize=5) j = i.copy() @@ -1235,8 +1235,8 @@ def test_iter_allocate_output_simple(): # Simple case a = arange(6) - i = nditer([a,None], [], [['readonly'],['writeonly','allocate']], - op_dtypes=[None,np.dtype('f4')]) + i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']], + op_dtypes=[None, np.dtype('f4')]) assert_equal(i.operands[1].shape, a.shape) assert_equal(i.operands[1].dtype, np.dtype('f4')) @@ -1244,8 +1244,8 @@ def test_iter_allocate_output_buffered_readwrite(): # Allocated output with buffering + delay_bufalloc a = arange(6) - i = nditer([a,None], ['buffered','delay_bufalloc'], - [['readonly'],['allocate','readwrite']]) + i = nditer([a, None], ['buffered', 'delay_bufalloc'], + [['readonly'], ['allocate', 'readwrite']]) i.operands[1][:] = 1 i.reset() for x in i: @@ -1256,78 +1256,78 @@ def test_iter_allocate_output_itorder(): # The allocated output should match the iteration order # C-order input, best iteration order - a = arange(6, dtype='i4').reshape(2,3) - i = nditer([a,None], [], [['readonly'],['writeonly','allocate']], - op_dtypes=[None,np.dtype('f4')]) + a = arange(6, dtype='i4').reshape(2, 3) + i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']], + op_dtypes=[None, np.dtype('f4')]) assert_equal(i.operands[1].shape, a.shape) assert_equal(i.operands[1].strides, a.strides) assert_equal(i.operands[1].dtype, np.dtype('f4')) # F-order input, best iteration order - a = arange(24, dtype='i4').reshape(2,3,4).T - i = nditer([a,None], [], [['readonly'],['writeonly','allocate']], - op_dtypes=[None,np.dtype('f4')]) + a = arange(24, dtype='i4').reshape(2, 3, 4).T + i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']], + op_dtypes=[None, np.dtype('f4')]) assert_equal(i.operands[1].shape, a.shape) assert_equal(i.operands[1].strides, a.strides) assert_equal(i.operands[1].dtype, np.dtype('f4')) # Non-contiguous input, C iteration order - a = arange(24, dtype='i4').reshape(2,3,4).swapaxes(0,1) - i = nditer([a,None], [], - [['readonly'],['writeonly','allocate']], + a = arange(24, dtype='i4').reshape(2, 3, 4).swapaxes(0, 1) + i = nditer([a, None], [], + [['readonly'], ['writeonly', 'allocate']], order='C', - op_dtypes=[None,np.dtype('f4')]) + op_dtypes=[None, np.dtype('f4')]) assert_equal(i.operands[1].shape, a.shape) - assert_equal(i.operands[1].strides, (32,16,4)) + assert_equal(i.operands[1].strides, (32, 16, 4)) assert_equal(i.operands[1].dtype, np.dtype('f4')) def test_iter_allocate_output_opaxes(): # Specifing op_axes should work - a = arange(24, dtype='i4').reshape(2,3,4) - i = nditer([None,a], [], [['writeonly','allocate'],['readonly']], - op_dtypes=[np.dtype('u4'),None], - op_axes=[[1,2,0],None]); - assert_equal(i.operands[0].shape, (4,2,3)) - assert_equal(i.operands[0].strides, (4,48,16)) + a = arange(24, dtype='i4').reshape(2, 3, 4) + i = nditer([None, a], [], [['writeonly', 'allocate'], ['readonly']], + op_dtypes=[np.dtype('u4'), None], + op_axes=[[1, 2, 0], None]); + assert_equal(i.operands[0].shape, (4, 2, 3)) + assert_equal(i.operands[0].strides, (4, 48, 16)) assert_equal(i.operands[0].dtype, np.dtype('u4')) def test_iter_allocate_output_types_promotion(): # Check type promotion of automatic outputs - i = nditer([array([3],dtype='f4'),array([0],dtype='f8'),None], [], - [['readonly']]*2+[['writeonly','allocate']]) + i = nditer([array([3], dtype='f4'), array([0], dtype='f8'), None], [], + [['readonly']]*2+[['writeonly', 'allocate']]) assert_equal(i.dtypes[2], np.dtype('f8')); - i = nditer([array([3],dtype='i4'),array([0],dtype='f4'),None], [], - [['readonly']]*2+[['writeonly','allocate']]) + i = nditer([array([3], dtype='i4'), array([0], dtype='f4'), None], [], + [['readonly']]*2+[['writeonly', 'allocate']]) assert_equal(i.dtypes[2], np.dtype('f8')); - i = nditer([array([3],dtype='f4'),array(0,dtype='f8'),None], [], - [['readonly']]*2+[['writeonly','allocate']]) + i = nditer([array([3], dtype='f4'), array(0, dtype='f8'), None], [], + [['readonly']]*2+[['writeonly', 'allocate']]) assert_equal(i.dtypes[2], np.dtype('f4')); - i = nditer([array([3],dtype='u4'),array(0,dtype='i4'),None], [], - [['readonly']]*2+[['writeonly','allocate']]) + i = nditer([array([3], dtype='u4'), array(0, dtype='i4'), None], [], + [['readonly']]*2+[['writeonly', 'allocate']]) assert_equal(i.dtypes[2], np.dtype('u4')); - i = nditer([array([3],dtype='u4'),array(-12,dtype='i4'),None], [], - [['readonly']]*2+[['writeonly','allocate']]) + i = nditer([array([3], dtype='u4'), array(-12, dtype='i4'), None], [], + [['readonly']]*2+[['writeonly', 'allocate']]) assert_equal(i.dtypes[2], np.dtype('i8')); def test_iter_allocate_output_types_byte_order(): # Verify the rules for byte order changes # When there's just one input, the output type exactly matches - a = array([3],dtype='u4').newbyteorder() - i = nditer([a,None], [], - [['readonly'],['writeonly','allocate']]) + a = array([3], dtype='u4').newbyteorder() + i = nditer([a, None], [], + [['readonly'], ['writeonly', 'allocate']]) assert_equal(i.dtypes[0], i.dtypes[1]); # With two or more inputs, the output type is in native byte order - i = nditer([a,a,None], [], - [['readonly'],['readonly'],['writeonly','allocate']]) + i = nditer([a, a, None], [], + [['readonly'], ['readonly'], ['writeonly', 'allocate']]) assert_(i.dtypes[0] != i.dtypes[2]); assert_equal(i.dtypes[0].newbyteorder('='), i.dtypes[2]) def test_iter_allocate_output_types_scalar(): # If the inputs are all scalars, the output should be a scalar - i = nditer([None,1,2.3,np.float32(12),np.complex128(3)],[], - [['writeonly','allocate']] + [['readonly']]*4) + i = nditer([None, 1, 2.3, np.float32(12), np.complex128(3)], [], + [['writeonly', 'allocate']] + [['readonly']]*4) assert_equal(i.operands[0].dtype, np.dtype('complex128')) assert_equal(i.operands[0].ndim, 0) @@ -1335,81 +1335,81 @@ def test_iter_allocate_output_subtype(): # Make sure that the subtype with priority wins # matrix vs ndarray - a = np.matrix([[1,2], [3,4]]) - b = np.arange(4).reshape(2,2).T - i = nditer([a,b,None], [], - [['readonly'],['readonly'],['writeonly','allocate']]) + a = np.matrix([[1, 2], [3, 4]]) + b = np.arange(4).reshape(2, 2).T + i = nditer([a, b, None], [], + [['readonly'], ['readonly'], ['writeonly', 'allocate']]) assert_equal(type(a), type(i.operands[2])) assert_(type(b) != type(i.operands[2])) - assert_equal(i.operands[2].shape, (2,2)) + assert_equal(i.operands[2].shape, (2, 2)) # matrix always wants things to be 2D - b = np.arange(4).reshape(1,2,2) - assert_raises(RuntimeError, nditer, [a,b,None], [], - [['readonly'],['readonly'],['writeonly','allocate']]) + b = np.arange(4).reshape(1, 2, 2) + assert_raises(RuntimeError, nditer, [a, b, None], [], + [['readonly'], ['readonly'], ['writeonly', 'allocate']]) # but if subtypes are disabled, the result can still work - i = nditer([a,b,None], [], - [['readonly'],['readonly'],['writeonly','allocate','no_subtype']]) + i = nditer([a, b, None], [], + [['readonly'], ['readonly'], ['writeonly', 'allocate', 'no_subtype']]) assert_equal(type(b), type(i.operands[2])) assert_(type(a) != type(i.operands[2])) - assert_equal(i.operands[2].shape, (1,2,2)) + assert_equal(i.operands[2].shape, (1, 2, 2)) def test_iter_allocate_output_errors(): # Check that the iterator will throw errors for bad output allocations # Need an input if no output data type is specified a = arange(6) - assert_raises(TypeError, nditer, [a,None], [], - [['writeonly'],['writeonly','allocate']]) + assert_raises(TypeError, nditer, [a, None], [], + [['writeonly'], ['writeonly', 'allocate']]) # Allocated output should be flagged for writing - assert_raises(ValueError, nditer, [a,None], [], - [['readonly'],['allocate','readonly']]) + assert_raises(ValueError, nditer, [a, None], [], + [['readonly'], ['allocate', 'readonly']]) # Allocated output can't have buffering without delayed bufalloc - assert_raises(ValueError, nditer, [a,None], ['buffered'], - ['allocate','readwrite']) + assert_raises(ValueError, nditer, [a, None], ['buffered'], + ['allocate', 'readwrite']) # Must specify at least one input - assert_raises(ValueError, nditer, [None,None], [], - [['writeonly','allocate'], - ['writeonly','allocate']], - op_dtypes=[np.dtype('f4'),np.dtype('f4')]) + assert_raises(ValueError, nditer, [None, None], [], + [['writeonly', 'allocate'], + ['writeonly', 'allocate']], + op_dtypes=[np.dtype('f4'), np.dtype('f4')]) # If using op_axes, must specify all the axes - a = arange(24, dtype='i4').reshape(2,3,4) - assert_raises(ValueError, nditer, [a,None], [], - [['readonly'],['writeonly','allocate']], - op_dtypes=[None,np.dtype('f4')], - op_axes=[None,[0,np.newaxis,1]]) + a = arange(24, dtype='i4').reshape(2, 3, 4) + assert_raises(ValueError, nditer, [a, None], [], + [['readonly'], ['writeonly', 'allocate']], + op_dtypes=[None, np.dtype('f4')], + op_axes=[None, [0, np.newaxis, 1]]) # If using op_axes, the axes must be within bounds - assert_raises(ValueError, nditer, [a,None], [], - [['readonly'],['writeonly','allocate']], - op_dtypes=[None,np.dtype('f4')], - op_axes=[None,[0,3,1]]) + assert_raises(ValueError, nditer, [a, None], [], + [['readonly'], ['writeonly', 'allocate']], + op_dtypes=[None, np.dtype('f4')], + op_axes=[None, [0, 3, 1]]) # If using op_axes, there can't be duplicates - assert_raises(ValueError, nditer, [a,None], [], - [['readonly'],['writeonly','allocate']], - op_dtypes=[None,np.dtype('f4')], - op_axes=[None,[0,2,1,0]]) + assert_raises(ValueError, nditer, [a, None], [], + [['readonly'], ['writeonly', 'allocate']], + op_dtypes=[None, np.dtype('f4')], + op_axes=[None, [0, 2, 1, 0]]) def test_iter_remove_axis(): - a = arange(24).reshape(2,3,4) + a = arange(24).reshape(2, 3, 4) - i = nditer(a,['multi_index']) + i = nditer(a, ['multi_index']) i.remove_axis(1) - assert_equal([x for x in i], a[:,0,:].ravel()) + assert_equal([x for x in i], a[:, 0,:].ravel()) a = a[::-1,:,:] - i = nditer(a,['multi_index']) + i = nditer(a, ['multi_index']) i.remove_axis(0) assert_equal([x for x in i], a[0,:,:].ravel()) def test_iter_remove_multi_index_inner_loop(): # Check that removing multi-index support works - a = arange(24).reshape(2,3,4) + a = arange(24).reshape(2, 3, 4) - i = nditer(a,['multi_index']) + i = nditer(a, ['multi_index']) assert_equal(i.ndim, 3) - assert_equal(i.shape, (2,3,4)) - assert_equal(i.itviews[0].shape, (2,3,4)) + assert_equal(i.shape, (2, 3, 4)) + assert_equal(i.itviews[0].shape, (2, 3, 4)) # Removing the multi-index tracking causes all dimensions to coalesce before = [x for x in i] @@ -1434,57 +1434,57 @@ def test_iter_iterindex(): # Make sure iterindex works buffersize = 5 - a = arange(24).reshape(4,3,2) + a = arange(24).reshape(4, 3, 2) for flags in ([], ['buffered']): i = nditer(a, flags, buffersize=buffersize) assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 2 - assert_equal(iter_iterindices(i), list(range(2,24))) + assert_equal(iter_iterindices(i), list(range(2, 24))) i = nditer(a, flags, order='F', buffersize=buffersize) assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 5 - assert_equal(iter_iterindices(i), list(range(5,24))) + assert_equal(iter_iterindices(i), list(range(5, 24))) i = nditer(a[::-1], flags, order='F', buffersize=buffersize) assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 9 - assert_equal(iter_iterindices(i), list(range(9,24))) + assert_equal(iter_iterindices(i), list(range(9, 24))) - i = nditer(a[::-1,::-1], flags, order='C', buffersize=buffersize) + i = nditer(a[::-1, ::-1], flags, order='C', buffersize=buffersize) assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 13 - assert_equal(iter_iterindices(i), list(range(13,24))) + assert_equal(iter_iterindices(i), list(range(13, 24))) - i = nditer(a[::1,::-1], flags, buffersize=buffersize) + i = nditer(a[::1, ::-1], flags, buffersize=buffersize) assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 23 - assert_equal(iter_iterindices(i), list(range(23,24))) + assert_equal(iter_iterindices(i), list(range(23, 24))) i.reset() i.iterindex = 2 - assert_equal(iter_iterindices(i), list(range(2,24))) + assert_equal(iter_iterindices(i), list(range(2, 24))) def test_iter_iterrange(): # Make sure getting and resetting the iterrange works buffersize = 5 - a = arange(24, dtype='i4').reshape(4,3,2) + a = arange(24, dtype='i4').reshape(4, 3, 2) a_fort = a.ravel(order='F') i = nditer(a, ['ranged'], ['readonly'], order='F', buffersize=buffersize) - assert_equal(i.iterrange, (0,24)) + assert_equal(i.iterrange, (0, 24)) assert_equal([x[()] for x in i], a_fort) - for r in [(0,24), (1,2), (3,24), (5,5), (0,20), (23,24)]: + for r in [(0, 24), (1, 2), (3, 24), (5, 5), (0, 20), (23, 24)]: i.iterrange = r assert_equal(i.iterrange, r) assert_equal([x[()] for x in i], a_fort[r[0]:r[1]]) - i = nditer(a, ['ranged','buffered'], ['readonly'], order='F', + i = nditer(a, ['ranged', 'buffered'], ['readonly'], order='F', op_dtypes='f8', buffersize=buffersize) - assert_equal(i.iterrange, (0,24)) + assert_equal(i.iterrange, (0, 24)) assert_equal([x[()] for x in i], a_fort) - for r in [(0,24), (1,2), (3,24), (5,5), (0,20), (23,24)]: + for r in [(0, 24), (1, 2), (3, 24), (5, 5), (0, 20), (23, 24)]: i.iterrange = r assert_equal(i.iterrange, r) assert_equal([x[()] for x in i], a_fort[r[0]:r[1]]) @@ -1495,12 +1495,12 @@ def test_iter_iterrange(): val = np.concatenate((val, x)) return val - i = nditer(a, ['ranged','buffered','external_loop'], + i = nditer(a, ['ranged', 'buffered', 'external_loop'], ['readonly'], order='F', op_dtypes='f8', buffersize=buffersize) - assert_equal(i.iterrange, (0,24)) + assert_equal(i.iterrange, (0, 24)) assert_equal(get_array(i), a_fort) - for r in [(0,24), (1,2), (3,24), (5,5), (0,20), (23,24)]: + for r in [(0, 24), (1, 2), (3, 24), (5, 5), (0, 20), (23, 24)]: i.iterrange = r assert_equal(i.iterrange, r) assert_equal(get_array(i), a_fort[r[0]:r[1]]) @@ -1510,21 +1510,21 @@ def test_iter_buffering(): arrays = [] # F-order swapped array arrays.append(np.arange(24, - dtype='c16').reshape(2,3,4).T.newbyteorder().byteswap()) + dtype='c16').reshape(2, 3, 4).T.newbyteorder().byteswap()) # Contiguous 1-dimensional array arrays.append(np.arange(10, dtype='f4')) # Unaligned array a = np.zeros((4*16+1,), dtype='i1')[1:] a.dtype = 'i4' - a[:] = np.arange(16,dtype='i4') + a[:] = np.arange(16, dtype='i4') arrays.append(a) # 4-D F-order array - arrays.append(np.arange(120,dtype='i4').reshape(5,3,2,4).T) + arrays.append(np.arange(120, dtype='i4').reshape(5, 3, 2, 4).T) for a in arrays: - for buffersize in (1,2,3,5,8,11,16,1024): + for buffersize in (1, 2, 3, 5, 8, 11, 16, 1024): vals = [] - i = nditer(a, ['buffered','external_loop'], - [['readonly','nbo','aligned']], + i = nditer(a, ['buffered', 'external_loop'], + [['readonly', 'nbo', 'aligned']], order='C', casting='equiv', buffersize=buffersize) @@ -1538,9 +1538,9 @@ def test_iter_write_buffering(): # Test that buffering of writes is working # F-order swapped array - a = np.arange(24).reshape(2,3,4).T.newbyteorder().byteswap() + a = np.arange(24).reshape(2, 3, 4).T.newbyteorder().byteswap() i = nditer(a, ['buffered'], - [['readwrite','nbo','aligned']], + [['readwrite', 'nbo', 'aligned']], casting='equiv', order='C', buffersize=16) @@ -1556,7 +1556,7 @@ def test_iter_buffering_delayed_alloc(): a = np.arange(6) b = np.arange(1, dtype='f4') - i = nditer([a,b], ['buffered','delay_bufalloc','multi_index','reduce_ok'], + i = nditer([a, b], ['buffered', 'delay_bufalloc', 'multi_index', 'reduce_ok'], ['readwrite'], casting='unsafe', op_dtypes='f4') @@ -1573,15 +1573,15 @@ def test_iter_buffering_delayed_alloc(): assert_equal(i.multi_index, (0,)) assert_equal(i[0], 0) i[1] = 1 - assert_equal(i[0:2], [0,1]) - assert_equal([[x[0][()],x[1][()]] for x in i], list(zip(range(6), [1]*6))) + assert_equal(i[0:2], [0, 1]) + assert_equal([[x[0][()], x[1][()]] for x in i], list(zip(range(6), [1]*6))) def test_iter_buffered_cast_simple(): # Test that buffering can handle a simple cast a = np.arange(10, dtype='f4') - i = nditer(a, ['buffered','external_loop'], - [['readwrite','nbo','aligned']], + i = nditer(a, ['buffered', 'external_loop'], + [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('f8')], buffersize=3) @@ -1594,8 +1594,8 @@ def test_iter_buffered_cast_byteswapped(): # Test that buffering can handle a cast which requires swap->cast->swap a = np.arange(10, dtype='f4').newbyteorder().byteswap() - i = nditer(a, ['buffered','external_loop'], - [['readwrite','nbo','aligned']], + i = nditer(a, ['buffered', 'external_loop'], + [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('f8').newbyteorder()], buffersize=3) @@ -1608,8 +1608,8 @@ def test_iter_buffered_cast_byteswapped(): warnings.simplefilter("ignore", np.ComplexWarning) a = np.arange(10, dtype='f8').newbyteorder().byteswap() - i = nditer(a, ['buffered','external_loop'], - [['readwrite','nbo','aligned']], + i = nditer(a, ['buffered', 'external_loop'], + [['readwrite', 'nbo', 'aligned']], casting='unsafe', op_dtypes=[np.dtype('c8').newbyteorder()], buffersize=3) @@ -1625,8 +1625,8 @@ def test_iter_buffered_cast_byteswapped_complex(): a = np.arange(10, dtype='c8').newbyteorder().byteswap() a += 2j - i = nditer(a, ['buffered','external_loop'], - [['readwrite','nbo','aligned']], + i = nditer(a, ['buffered', 'external_loop'], + [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('c16')], buffersize=3) @@ -1636,8 +1636,8 @@ def test_iter_buffered_cast_byteswapped_complex(): a = np.arange(10, dtype='c8') a += 2j - i = nditer(a, ['buffered','external_loop'], - [['readwrite','nbo','aligned']], + i = nditer(a, ['buffered', 'external_loop'], + [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('c16').newbyteorder()], buffersize=3) @@ -1647,8 +1647,8 @@ def test_iter_buffered_cast_byteswapped_complex(): a = np.arange(10, dtype=np.clongdouble).newbyteorder().byteswap() a += 2j - i = nditer(a, ['buffered','external_loop'], - [['readwrite','nbo','aligned']], + i = nditer(a, ['buffered', 'external_loop'], + [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('c16')], buffersize=3) @@ -1657,8 +1657,8 @@ def test_iter_buffered_cast_byteswapped_complex(): assert_equal(a, 2*np.arange(10, dtype=np.clongdouble) + 4j) a = np.arange(10, dtype=np.longdouble).newbyteorder().byteswap() - i = nditer(a, ['buffered','external_loop'], - [['readwrite','nbo','aligned']], + i = nditer(a, ['buffered', 'external_loop'], + [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('f4')], buffersize=7) @@ -1670,9 +1670,9 @@ def test_iter_buffered_cast_structured_type(): # Tests buffering of structured types # simple -> struct type (duplicates the value) - sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2,3)), ('d', 'O')] + sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')] a = np.arange(3, dtype='f4') + 0.5 - i = nditer(a, ['buffered','refs_ok'], ['readonly'], + i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt) vals = [np.array(x) for x in i] @@ -1687,13 +1687,13 @@ def test_iter_buffered_cast_structured_type(): assert_equal(vals[0].dtype, np.dtype(sdt)) # object -> struct type - sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2,3)), ('d', 'O')] + sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')] a = np.zeros((3,), dtype='O') - a[0] = (0.5,0.5,[[0.5,0.5,0.5],[0.5,0.5,0.5]],0.5) - a[1] = (1.5,1.5,[[1.5,1.5,1.5],[1.5,1.5,1.5]],1.5) - a[2] = (2.5,2.5,[[2.5,2.5,2.5],[2.5,2.5,2.5]],2.5) + a[0] = (0.5, 0.5, [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5]], 0.5) + a[1] = (1.5, 1.5, [[1.5, 1.5, 1.5], [1.5, 1.5, 1.5]], 1.5) + a[2] = (2.5, 2.5, [[2.5, 2.5, 2.5], [2.5, 2.5, 2.5]], 2.5) rc = sys.getrefcount(a[0]) - i = nditer(a, ['buffered','refs_ok'], ['readonly'], + i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt) vals = [x.copy() for x in i] @@ -1711,8 +1711,8 @@ def test_iter_buffered_cast_structured_type(): # struct type -> simple (takes the first value) sdt = [('a', 'f4'), ('b', 'i8'), ('d', 'O')] - a = np.array([(5.5,7,'test'),(8,10,11)], dtype=sdt) - i = nditer(a, ['buffered','refs_ok'], ['readonly'], + a = np.array([(5.5, 7, 'test'), (8, 10, 11)], dtype=sdt) + i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes='i4') assert_equal([x[()] for x in i], [5, 8]) @@ -1720,20 +1720,20 @@ def test_iter_buffered_cast_structured_type(): # struct type -> struct type (field-wise copy) sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', 'O')] sdt2 = [('d', 'u2'), ('a', 'O'), ('b', 'f8')] - a = np.array([(1,2,3),(4,5,6)], dtype=sdt1) - i = nditer(a, ['buffered','refs_ok'], ['readonly'], + a = np.array([(1, 2, 3), (4, 5, 6)], dtype=sdt1) + i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) assert_equal([np.array(x) for x in i], - [np.array((3,1,2), dtype=sdt2), - np.array((6,4,5), dtype=sdt2)]) + [np.array((3, 1, 2), dtype=sdt2), + np.array((6, 4, 5), dtype=sdt2)]) # struct type -> struct type (field gets discarded) sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', 'O')] sdt2 = [('b', 'O'), ('a', 'f8')] - a = np.array([(1,2,3),(4,5,6)], dtype=sdt1) - i = nditer(a, ['buffered','refs_ok'], ['readwrite'], + a = np.array([(1, 2, 3), (4, 5, 6)], dtype=sdt1) + i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) @@ -1741,15 +1741,15 @@ def test_iter_buffered_cast_structured_type(): for x in i: vals.append(np.array(x)) x['a'] = x['b']+3 - assert_equal(vals, [np.array((2,1), dtype=sdt2), - np.array((5,4), dtype=sdt2)]) - assert_equal(a, np.array([(5,2,None),(8,5,None)], dtype=sdt1)) + assert_equal(vals, [np.array((2, 1), dtype=sdt2), + np.array((5, 4), dtype=sdt2)]) + assert_equal(a, np.array([(5, 2, None), (8, 5, None)], dtype=sdt1)) # struct type -> struct type (structured field gets discarded) - sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', [('a', 'i2'),('b','i4')])] + sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', [('a', 'i2'), ('b', 'i4')])] sdt2 = [('b', 'O'), ('a', 'f8')] - a = np.array([(1,2,(0,9)),(4,5,(20,21))], dtype=sdt1) - i = nditer(a, ['buffered','refs_ok'], ['readwrite'], + a = np.array([(1, 2, (0, 9)), (4, 5, (20, 21))], dtype=sdt1) + i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) @@ -1757,15 +1757,15 @@ def test_iter_buffered_cast_structured_type(): for x in i: vals.append(np.array(x)) x['a'] = x['b']+3 - assert_equal(vals, [np.array((2,1), dtype=sdt2), - np.array((5,4), dtype=sdt2)]) - assert_equal(a, np.array([(5,2,(0,0)),(8,5,(0,0))], dtype=sdt1)) + assert_equal(vals, [np.array((2, 1), dtype=sdt2), + np.array((5, 4), dtype=sdt2)]) + assert_equal(a, np.array([(5, 2, (0, 0)), (8, 5, (0, 0))], dtype=sdt1)) # struct type -> struct type (structured field w/ ref gets discarded) - sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', [('a', 'i2'),('b','O')])] + sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', [('a', 'i2'), ('b', 'O')])] sdt2 = [('b', 'O'), ('a', 'f8')] - a = np.array([(1,2,(0,9)),(4,5,(20,21))], dtype=sdt1) - i = nditer(a, ['buffered','refs_ok'], ['readwrite'], + a = np.array([(1, 2, (0, 9)), (4, 5, (20, 21))], dtype=sdt1) + i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) @@ -1773,36 +1773,36 @@ def test_iter_buffered_cast_structured_type(): for x in i: vals.append(np.array(x)) x['a'] = x['b']+3 - assert_equal(vals, [np.array((2,1), dtype=sdt2), - np.array((5,4), dtype=sdt2)]) - assert_equal(a, np.array([(5,2,(0,None)),(8,5,(0,None))], dtype=sdt1)) + assert_equal(vals, [np.array((2, 1), dtype=sdt2), + np.array((5, 4), dtype=sdt2)]) + assert_equal(a, np.array([(5, 2, (0, None)), (8, 5, (0, None))], dtype=sdt1)) # struct type -> struct type back (structured field w/ ref gets discarded) sdt1 = [('b', 'O'), ('a', 'f8')] - sdt2 = [('a', 'f4'), ('b', 'i8'), ('d', [('a', 'i2'),('b','O')])] - a = np.array([(1,2),(4,5)], dtype=sdt1) - i = nditer(a, ['buffered','refs_ok'], ['readwrite'], + sdt2 = [('a', 'f4'), ('b', 'i8'), ('d', [('a', 'i2'), ('b', 'O')])] + a = np.array([(1, 2), (4, 5)], dtype=sdt1) + i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) vals = [] for x in i: vals.append(np.array(x)) - assert_equal(x['d'], np.array((0, None), dtype=[('a','i2'),('b','O')])) + assert_equal(x['d'], np.array((0, None), dtype=[('a', 'i2'), ('b', 'O')])) x['a'] = x['b']+3 - assert_equal(vals, [np.array((2,1,(0,None)), dtype=sdt2), - np.array((5,4,(0,None)), dtype=sdt2)]) - assert_equal(a, np.array([(1,4),(4,7)], dtype=sdt1)) + assert_equal(vals, [np.array((2, 1, (0, None)), dtype=sdt2), + np.array((5, 4, (0, None)), dtype=sdt2)]) + assert_equal(a, np.array([(1, 4), (4, 7)], dtype=sdt1)) def test_iter_buffered_cast_subarray(): # Tests buffering of subarrays # one element -> many (copies it to all) sdt1 = [('a', 'f4')] - sdt2 = [('a', 'f8', (3,2,2))] + sdt2 = [('a', 'f8', (3, 2, 2))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6) - i = nditer(a, ['buffered','refs_ok'], ['readonly'], + i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) @@ -1810,11 +1810,11 @@ def test_iter_buffered_cast_subarray(): assert_(np.all(x['a'] == count)) # one element -> many -> back (copies it to all) - sdt1 = [('a', 'O', (1,1))] - sdt2 = [('a', 'O', (3,2,2))] + sdt1 = [('a', 'O', (1, 1))] + sdt2 = [('a', 'O', (3, 2, 2))] a = np.zeros((6,), dtype=sdt1) - a['a'][:,0,0] = np.arange(6) - i = nditer(a, ['buffered','refs_ok'], ['readwrite'], + a['a'][:, 0, 0] = np.arange(6) + i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) @@ -1823,14 +1823,14 @@ def test_iter_buffered_cast_subarray(): assert_(np.all(x['a'] == count)) x['a'][0] += 2 count += 1 - assert_equal(a['a'], np.arange(6).reshape(6,1,1)+2) + assert_equal(a['a'], np.arange(6).reshape(6, 1, 1)+2) # many -> one element -> back (copies just element 0) - sdt1 = [('a', 'O', (3,2,2))] + sdt1 = [('a', 'O', (3, 2, 2))] sdt2 = [('a', 'O', (1,))] a = np.zeros((6,), dtype=sdt1) - a['a'][:,0,0,0] = np.arange(6) - i = nditer(a, ['buffered','refs_ok'], ['readwrite'], + a['a'][:, 0, 0, 0] = np.arange(6) + i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) @@ -1839,14 +1839,14 @@ def test_iter_buffered_cast_subarray(): assert_equal(x['a'], count) x['a'] += 2 count += 1 - assert_equal(a['a'], np.arange(6).reshape(6,1,1,1)*np.ones((1,3,2,2))+2) + assert_equal(a['a'], np.arange(6).reshape(6, 1, 1, 1)*np.ones((1, 3, 2, 2))+2) # many -> one element -> back (copies just element 0) - sdt1 = [('a', 'f8', (3,2,2))] + sdt1 = [('a', 'f8', (3, 2, 2))] sdt2 = [('a', 'O', (1,))] a = np.zeros((6,), dtype=sdt1) - a['a'][:,0,0,0] = np.arange(6) - i = nditer(a, ['buffered','refs_ok'], ['readonly'], + a['a'][:, 0, 0, 0] = np.arange(6) + i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) @@ -1856,11 +1856,11 @@ def test_iter_buffered_cast_subarray(): count += 1 # many -> one element (copies just element 0) - sdt1 = [('a', 'O', (3,2,2))] + sdt1 = [('a', 'O', (3, 2, 2))] sdt2 = [('a', 'f4', (1,))] a = np.zeros((6,), dtype=sdt1) - a['a'][:,0,0,0] = np.arange(6) - i = nditer(a, ['buffered','refs_ok'], ['readonly'], + a['a'][:, 0, 0, 0] = np.arange(6) + i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) @@ -1870,11 +1870,11 @@ def test_iter_buffered_cast_subarray(): count += 1 # many -> matching shape (straightforward copy) - sdt1 = [('a', 'O', (3,2,2))] - sdt2 = [('a', 'f4', (3,2,2))] + sdt1 = [('a', 'O', (3, 2, 2))] + sdt2 = [('a', 'f4', (3, 2, 2))] a = np.zeros((6,), dtype=sdt1) - a['a'] = np.arange(6*3*2*2).reshape(6,3,2,2) - i = nditer(a, ['buffered','refs_ok'], ['readonly'], + a['a'] = np.arange(6*3*2*2).reshape(6, 3, 2, 2) + i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) @@ -1887,8 +1887,8 @@ def test_iter_buffered_cast_subarray(): sdt1 = [('a', 'f8', (6,))] sdt2 = [('a', 'f4', (2,))] a = np.zeros((6,), dtype=sdt1) - a['a'] = np.arange(6*6).reshape(6,6) - i = nditer(a, ['buffered','refs_ok'], ['readonly'], + a['a'] = np.arange(6*6).reshape(6, 6) + i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) @@ -1901,23 +1901,23 @@ def test_iter_buffered_cast_subarray(): sdt1 = [('a', 'f8', (2,))] sdt2 = [('a', 'f4', (6,))] a = np.zeros((6,), dtype=sdt1) - a['a'] = np.arange(6*2).reshape(6,2) - i = nditer(a, ['buffered','refs_ok'], ['readonly'], + a['a'] = np.arange(6*2).reshape(6, 2) + i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'][:2], a[count]['a']) - assert_equal(x['a'][2:], [0,0,0,0]) + assert_equal(x['a'][2:], [0, 0, 0, 0]) count += 1 # vector -> matrix (broadcasts) sdt1 = [('a', 'f8', (2,))] - sdt2 = [('a', 'f4', (2,2))] + sdt2 = [('a', 'f4', (2, 2))] a = np.zeros((6,), dtype=sdt1) - a['a'] = np.arange(6*2).reshape(6,2) - i = nditer(a, ['buffered','refs_ok'], ['readonly'], + a['a'] = np.arange(6*2).reshape(6, 2) + i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) @@ -1928,76 +1928,76 @@ def test_iter_buffered_cast_subarray(): count += 1 # vector -> matrix (broadcasts and zero-pads) - sdt1 = [('a', 'f8', (2,1))] - sdt2 = [('a', 'f4', (3,2))] + sdt1 = [('a', 'f8', (2, 1))] + sdt2 = [('a', 'f4', (3, 2))] a = np.zeros((6,), dtype=sdt1) - a['a'] = np.arange(6*2).reshape(6,2,1) - i = nditer(a, ['buffered','refs_ok'], ['readonly'], + a['a'] = np.arange(6*2).reshape(6, 2, 1) + i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: - assert_equal(x['a'][:2,0], a[count]['a'][:,0]) - assert_equal(x['a'][:2,1], a[count]['a'][:,0]) - assert_equal(x['a'][2,:], [0,0]) + assert_equal(x['a'][:2, 0], a[count]['a'][:, 0]) + assert_equal(x['a'][:2, 1], a[count]['a'][:, 0]) + assert_equal(x['a'][2,:], [0, 0]) count += 1 # matrix -> matrix (truncates and zero-pads) - sdt1 = [('a', 'f8', (2,3))] - sdt2 = [('a', 'f4', (3,2))] + sdt1 = [('a', 'f8', (2, 3))] + sdt2 = [('a', 'f4', (3, 2))] a = np.zeros((6,), dtype=sdt1) - a['a'] = np.arange(6*2*3).reshape(6,2,3) - i = nditer(a, ['buffered','refs_ok'], ['readonly'], + a['a'] = np.arange(6*2*3).reshape(6, 2, 3) + i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: - assert_equal(x['a'][:2,0], a[count]['a'][:,0]) - assert_equal(x['a'][:2,1], a[count]['a'][:,1]) - assert_equal(x['a'][2,:], [0,0]) + assert_equal(x['a'][:2, 0], a[count]['a'][:, 0]) + assert_equal(x['a'][:2, 1], a[count]['a'][:, 1]) + assert_equal(x['a'][2,:], [0, 0]) count += 1 def test_iter_buffering_badwriteback(): # Writing back from a buffer cannot combine elements # a needs write buffering, but had a broadcast dimension - a = np.arange(6).reshape(2,3,1) - b = np.arange(12).reshape(2,3,2) - assert_raises(ValueError,nditer,[a,b], - ['buffered','external_loop'], - [['readwrite'],['writeonly']], + a = np.arange(6).reshape(2, 3, 1) + b = np.arange(12).reshape(2, 3, 2) + assert_raises(ValueError, nditer, [a, b], + ['buffered', 'external_loop'], + [['readwrite'], ['writeonly']], order='C') # But if a is readonly, it's fine - i = nditer([a,b],['buffered','external_loop'], - [['readonly'],['writeonly']], + i = nditer([a, b], ['buffered', 'external_loop'], + [['readonly'], ['writeonly']], order='C') # If a has just one element, it's fine too (constant 0 stride, a reduction) - a = np.arange(1).reshape(1,1,1) - i = nditer([a,b],['buffered','external_loop','reduce_ok'], - [['readwrite'],['writeonly']], + a = np.arange(1).reshape(1, 1, 1) + i = nditer([a, b], ['buffered', 'external_loop', 'reduce_ok'], + [['readwrite'], ['writeonly']], order='C') # check that it fails on other dimensions too - a = np.arange(6).reshape(1,3,2) - assert_raises(ValueError,nditer,[a,b], - ['buffered','external_loop'], - [['readwrite'],['writeonly']], + a = np.arange(6).reshape(1, 3, 2) + assert_raises(ValueError, nditer, [a, b], + ['buffered', 'external_loop'], + [['readwrite'], ['writeonly']], order='C') - a = np.arange(4).reshape(2,1,2) - assert_raises(ValueError,nditer,[a,b], - ['buffered','external_loop'], - [['readwrite'],['writeonly']], + a = np.arange(4).reshape(2, 1, 2) + assert_raises(ValueError, nditer, [a, b], + ['buffered', 'external_loop'], + [['readwrite'], ['writeonly']], order='C') def test_iter_buffering_string(): # Safe casting disallows shrinking strings a = np.array(['abc', 'a', 'abcd'], dtype=np.bytes_) assert_equal(a.dtype, np.dtype('S4')); - assert_raises(TypeError,nditer,a,['buffered'],['readonly'], + assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'], op_dtypes='S2') i = nditer(a, ['buffered'], ['readonly'], op_dtypes='S6') assert_equal(i[0], asbytes('abc')) @@ -2005,7 +2005,7 @@ def test_iter_buffering_string(): a = np.array(['abc', 'a', 'abcd'], dtype=np.unicode) assert_equal(a.dtype, np.dtype('U4')); - assert_raises(TypeError,nditer,a,['buffered'],['readonly'], + assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'], op_dtypes='U2') i = nditer(a, ['buffered'], ['readonly'], op_dtypes='U6') assert_equal(i[0], sixu('abc')) @@ -2014,7 +2014,7 @@ def test_iter_buffering_string(): def test_iter_buffering_growinner(): # Test that the inner loop grows when no buffering is needed a = np.arange(30) - i = nditer(a, ['buffered','growinner','external_loop'], + i = nditer(a, ['buffered', 'growinner', 'external_loop'], buffersize=5) # Should end up with just one inner loop here assert_equal(i[0].size, a.size) @@ -2025,8 +2025,8 @@ def test_iter_buffered_reduce_reuse(): # large enough array for all views, including negative strides. a = np.arange(2*3**5)[3**5:3**5+1] flags = ['buffered', 'delay_bufalloc', 'multi_index', 'reduce_ok', 'refs_ok'] - op_flags = [('readonly',), ('readwrite','allocate')] - op_axes_list = [[(0,1,2), (0,1,-1)], [(0,1,2), (0,-1,-1)]] + op_flags = [('readonly',), ('readwrite', 'allocate')] + op_axes_list = [[(0, 1, 2), (0, 1, -1)], [(0, 1, 2), (0, -1, -1)]] # wrong dtype to force buffering op_dtypes = [np.float, a.dtype] @@ -2037,7 +2037,7 @@ def test_iter_buffered_reduce_reuse(): # last stride is reduced and because of that not # important for this test, as it is the inner stride. strides = (xs * a.itemsize, ys * a.itemsize, a.itemsize) - arr = np.lib.stride_tricks.as_strided(a, (3,3,3), strides) + arr = np.lib.stride_tricks.as_strided(a, (3, 3, 3), strides) for skip in [0, 1]: yield arr, op_axes, skip @@ -2072,174 +2072,174 @@ def test_iter_buffered_reduce_reuse(): def test_iter_no_broadcast(): # Test that the no_broadcast flag works - a = np.arange(24).reshape(2,3,4) - b = np.arange(6).reshape(2,3,1) - c = np.arange(12).reshape(3,4) + a = np.arange(24).reshape(2, 3, 4) + b = np.arange(6).reshape(2, 3, 1) + c = np.arange(12).reshape(3, 4) - i = nditer([a,b,c], [], - [['readonly','no_broadcast'],['readonly'],['readonly']]) - assert_raises(ValueError, nditer, [a,b,c], [], - [['readonly'],['readonly','no_broadcast'],['readonly']]) - assert_raises(ValueError, nditer, [a,b,c], [], - [['readonly'],['readonly'],['readonly','no_broadcast']]) + i = nditer([a, b, c], [], + [['readonly', 'no_broadcast'], ['readonly'], ['readonly']]) + assert_raises(ValueError, nditer, [a, b, c], [], + [['readonly'], ['readonly', 'no_broadcast'], ['readonly']]) + assert_raises(ValueError, nditer, [a, b, c], [], + [['readonly'], ['readonly'], ['readonly', 'no_broadcast']]) def test_iter_nested_iters_basic(): # Test nested iteration basic usage - a = arange(12).reshape(2,3,2) + a = arange(12).reshape(2, 3, 2) - i, j = np.nested_iters(a, [[0],[1,2]]) + i, j = np.nested_iters(a, [[0], [1, 2]]) vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0,1,2,3,4,5],[6,7,8,9,10,11]]) + assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]) - i, j = np.nested_iters(a, [[0,1],[2]]) + i, j = np.nested_iters(a, [[0, 1], [2]]) vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0,1],[2,3],[4,5],[6,7],[8,9],[10,11]]) + assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]) - i, j = np.nested_iters(a, [[0,2],[1]]) + i, j = np.nested_iters(a, [[0, 2], [1]]) vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0,2,4],[1,3,5],[6,8,10],[7,9,11]]) + assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]]) def test_iter_nested_iters_reorder(): # Test nested iteration basic usage - a = arange(12).reshape(2,3,2) + a = arange(12).reshape(2, 3, 2) # In 'K' order (default), it gets reordered - i, j = np.nested_iters(a, [[0],[2,1]]) + i, j = np.nested_iters(a, [[0], [2, 1]]) vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0,1,2,3,4,5],[6,7,8,9,10,11]]) + assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]) - i, j = np.nested_iters(a, [[1,0],[2]]) + i, j = np.nested_iters(a, [[1, 0], [2]]) vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0,1],[2,3],[4,5],[6,7],[8,9],[10,11]]) + assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]) - i, j = np.nested_iters(a, [[2,0],[1]]) + i, j = np.nested_iters(a, [[2, 0], [1]]) vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0,2,4],[1,3,5],[6,8,10],[7,9,11]]) + assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]]) # In 'C' order, it doesn't - i, j = np.nested_iters(a, [[0],[2,1]], order='C') + i, j = np.nested_iters(a, [[0], [2, 1]], order='C') vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0,2,4,1,3,5],[6,8,10,7,9,11]]) + assert_equal(vals, [[0, 2, 4, 1, 3, 5], [6, 8, 10, 7, 9, 11]]) - i, j = np.nested_iters(a, [[1,0],[2]], order='C') + i, j = np.nested_iters(a, [[1, 0], [2]], order='C') vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0,1],[6,7],[2,3],[8,9],[4,5],[10,11]]) + assert_equal(vals, [[0, 1], [6, 7], [2, 3], [8, 9], [4, 5], [10, 11]]) - i, j = np.nested_iters(a, [[2,0],[1]], order='C') + i, j = np.nested_iters(a, [[2, 0], [1]], order='C') vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0,2,4],[6,8,10],[1,3,5],[7,9,11]]) + assert_equal(vals, [[0, 2, 4], [6, 8, 10], [1, 3, 5], [7, 9, 11]]) def test_iter_nested_iters_flip_axes(): # Test nested iteration with negative axes - a = arange(12).reshape(2,3,2)[::-1,::-1,::-1] + a = arange(12).reshape(2, 3, 2)[::-1, ::-1, ::-1] # In 'K' order (default), the axes all get flipped - i, j = np.nested_iters(a, [[0],[1,2]]) + i, j = np.nested_iters(a, [[0], [1, 2]]) vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0,1,2,3,4,5],[6,7,8,9,10,11]]) + assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]) - i, j = np.nested_iters(a, [[0,1],[2]]) + i, j = np.nested_iters(a, [[0, 1], [2]]) vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0,1],[2,3],[4,5],[6,7],[8,9],[10,11]]) + assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]) - i, j = np.nested_iters(a, [[0,2],[1]]) + i, j = np.nested_iters(a, [[0, 2], [1]]) vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0,2,4],[1,3,5],[6,8,10],[7,9,11]]) + assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]]) # In 'C' order, flipping axes is disabled - i, j = np.nested_iters(a, [[0],[1,2]], order='C') + i, j = np.nested_iters(a, [[0], [1, 2]], order='C') vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[11,10,9,8,7,6],[5,4,3,2,1,0]]) + assert_equal(vals, [[11, 10, 9, 8, 7, 6], [5, 4, 3, 2, 1, 0]]) - i, j = np.nested_iters(a, [[0,1],[2]], order='C') + i, j = np.nested_iters(a, [[0, 1], [2]], order='C') vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[11,10],[9,8],[7,6],[5,4],[3,2],[1,0]]) + assert_equal(vals, [[11, 10], [9, 8], [7, 6], [5, 4], [3, 2], [1, 0]]) - i, j = np.nested_iters(a, [[0,2],[1]], order='C') + i, j = np.nested_iters(a, [[0, 2], [1]], order='C') vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[11,9,7],[10,8,6],[5,3,1],[4,2,0]]) + assert_equal(vals, [[11, 9, 7], [10, 8, 6], [5, 3, 1], [4, 2, 0]]) def test_iter_nested_iters_broadcast(): # Test nested iteration with broadcasting - a = arange(2).reshape(2,1) - b = arange(3).reshape(1,3) + a = arange(2).reshape(2, 1) + b = arange(3).reshape(1, 3) - i, j = np.nested_iters([a,b], [[0],[1]]) + i, j = np.nested_iters([a, b], [[0], [1]]) vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[[0,0],[0,1],[0,2]],[[1,0],[1,1],[1,2]]]) + assert_equal(vals, [[[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]]]) - i, j = np.nested_iters([a,b], [[1],[0]]) + i, j = np.nested_iters([a, b], [[1], [0]]) vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[[0,0],[1,0]],[[0,1],[1,1]],[[0,2],[1,2]]]) + assert_equal(vals, [[[0, 0], [1, 0]], [[0, 1], [1, 1]], [[0, 2], [1, 2]]]) def test_iter_nested_iters_dtype_copy(): # Test nested iteration with a copy to change dtype # copy - a = arange(6, dtype='i4').reshape(2,3) - i, j = np.nested_iters(a, [[0],[1]], - op_flags=['readonly','copy'], + a = arange(6, dtype='i4').reshape(2, 3) + i, j = np.nested_iters(a, [[0], [1]], + op_flags=['readonly', 'copy'], op_dtypes='f8') assert_equal(j[0].dtype, np.dtype('f8')) vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0,1,2],[3,4,5]]) + assert_equal(vals, [[0, 1, 2], [3, 4, 5]]) vals = None # updateifcopy - a = arange(6, dtype='f4').reshape(2,3) - i, j = np.nested_iters(a, [[0],[1]], - op_flags=['readwrite','updateifcopy'], + a = arange(6, dtype='f4').reshape(2, 3) + i, j = np.nested_iters(a, [[0], [1]], + op_flags=['readwrite', 'updateifcopy'], casting='same_kind', op_dtypes='f8') assert_equal(j[0].dtype, np.dtype('f8')) for x in i: for y in j: y[...] += 1 - assert_equal(a, [[0,1,2],[3,4,5]]) + assert_equal(a, [[0, 1, 2], [3, 4, 5]]) i, j, x, y = (None,)*4 # force the updateifcopy - assert_equal(a, [[1,2,3],[4,5,6]]) + assert_equal(a, [[1, 2, 3], [4, 5, 6]]) def test_iter_nested_iters_dtype_buffered(): # Test nested iteration with buffering to change dtype - a = arange(6, dtype='f4').reshape(2,3) - i, j = np.nested_iters(a, [[0],[1]], + a = arange(6, dtype='f4').reshape(2, 3) + i, j = np.nested_iters(a, [[0], [1]], flags=['buffered'], op_flags=['readwrite'], casting='same_kind', @@ -2248,27 +2248,27 @@ def test_iter_nested_iters_dtype_buffered(): for x in i: for y in j: y[...] += 1 - assert_equal(a, [[1,2,3],[4,5,6]]) + assert_equal(a, [[1, 2, 3], [4, 5, 6]]) def test_iter_reduction_error(): a = np.arange(6) - assert_raises(ValueError, nditer, [a,None], [], - [['readonly'], ['readwrite','allocate']], - op_axes=[[0],[-1]]) + assert_raises(ValueError, nditer, [a, None], [], + [['readonly'], ['readwrite', 'allocate']], + op_axes=[[0], [-1]]) - a = np.arange(6).reshape(2,3) - assert_raises(ValueError, nditer, [a,None], ['external_loop'], - [['readonly'], ['readwrite','allocate']], - op_axes=[[0,1],[-1,-1]]) + a = np.arange(6).reshape(2, 3) + assert_raises(ValueError, nditer, [a, None], ['external_loop'], + [['readonly'], ['readwrite', 'allocate']], + op_axes=[[0, 1], [-1, -1]]) def test_iter_reduction(): # Test doing reductions with the iterator a = np.arange(6) - i = nditer([a,None], ['reduce_ok'], - [['readonly'], ['readwrite','allocate']], - op_axes=[[0],[-1]]) + i = nditer([a, None], ['reduce_ok'], + [['readonly'], ['readwrite', 'allocate']], + op_axes=[[0], [-1]]) # Need to initialize the output operand to the addition unit i.operands[1][...] = 0 # Do the reduction @@ -2278,10 +2278,10 @@ def test_iter_reduction(): assert_equal(i.operands[1].ndim, 0) assert_equal(i.operands[1], np.sum(a)) - a = np.arange(6).reshape(2,3) - i = nditer([a,None], ['reduce_ok','external_loop'], - [['readonly'], ['readwrite','allocate']], - op_axes=[[0,1],[-1,-1]]) + a = np.arange(6).reshape(2, 3) + i = nditer([a, None], ['reduce_ok', 'external_loop'], + [['readonly'], ['readwrite', 'allocate']], + op_axes=[[0, 1], [-1, -1]]) # Need to initialize the output operand to the addition unit i.operands[1][...] = 0 # Reduction shape/strides for the output @@ -2296,14 +2296,14 @@ def test_iter_reduction(): # This is a tricky reduction case for the buffering double loop # to handle - a = np.ones((2,3,5)) - it1 = nditer([a,None], ['reduce_ok','external_loop'], - [['readonly'], ['readwrite','allocate']], - op_axes=[None,[0,-1,1]]) - it2 = nditer([a,None], ['reduce_ok','external_loop', - 'buffered','delay_bufalloc'], - [['readonly'], ['readwrite','allocate']], - op_axes=[None,[0,-1,1]], buffersize=10) + a = np.ones((2, 3, 5)) + it1 = nditer([a, None], ['reduce_ok', 'external_loop'], + [['readonly'], ['readwrite', 'allocate']], + op_axes=[None, [0, -1, 1]]) + it2 = nditer([a, None], ['reduce_ok', 'external_loop', + 'buffered', 'delay_bufalloc'], + [['readonly'], ['readwrite', 'allocate']], + op_axes=[None, [0, -1, 1]], buffersize=10) it1.operands[1].fill(0) it2.operands[1].fill(0) it2.reset() @@ -2319,9 +2319,9 @@ def test_iter_buffering_reduction(): a = np.arange(6) b = np.array(0., dtype='f8').byteswap().newbyteorder() - i = nditer([a,b], ['reduce_ok', 'buffered'], - [['readonly'], ['readwrite','nbo']], - op_axes=[[0],[-1]]) + i = nditer([a, b], ['reduce_ok', 'buffered'], + [['readonly'], ['readwrite', 'nbo']], + op_axes=[[0], [-1]]) assert_equal(i[1].dtype, np.dtype('f8')) assert_(i[1].dtype != b.dtype) # Do the reduction @@ -2330,11 +2330,11 @@ def test_iter_buffering_reduction(): # Since no axes were specified, should have allocated a scalar assert_equal(b, np.sum(a)) - a = np.arange(6).reshape(2,3) - b = np.array([0,0], dtype='f8').byteswap().newbyteorder() - i = nditer([a,b], ['reduce_ok','external_loop', 'buffered'], - [['readonly'], ['readwrite','nbo']], - op_axes=[[0,1],[0,-1]]) + a = np.arange(6).reshape(2, 3) + b = np.array([0, 0], dtype='f8').byteswap().newbyteorder() + i = nditer([a, b], ['reduce_ok', 'external_loop', 'buffered'], + [['readonly'], ['readwrite', 'nbo']], + op_axes=[[0, 1], [0, -1]]) # Reduction shape/strides for the output assert_equal(i[1].shape, (3,)) assert_equal(i[1].strides, (0,)) @@ -2345,135 +2345,135 @@ def test_iter_buffering_reduction(): # Iterator inner double loop was wrong on this one p = np.arange(2) + 1 - it = np.nditer([p,None], - ['delay_bufalloc','reduce_ok','buffered','external_loop'], - [['readonly'],['readwrite','allocate']], - op_axes=[[-1,0],[-1,-1]], - itershape=(2,2)) + it = np.nditer([p, None], + ['delay_bufalloc', 'reduce_ok', 'buffered', 'external_loop'], + [['readonly'], ['readwrite', 'allocate']], + op_axes=[[-1, 0], [-1, -1]], + itershape=(2, 2)) it.operands[1].fill(0) it.reset() - assert_equal(it[0], [1,2,1,2]) + assert_equal(it[0], [1, 2, 1, 2]) def test_iter_buffering_reduction_reuse_reduce_loops(): # There was a bug triggering reuse of the reduce loop inappropriately, # which caused processing to happen in unnecessarily small chunks # and overran the buffer. - a = np.zeros((2,7)) - b = np.zeros((1,7)) - it = np.nditer([a,b], flags=['reduce_ok', 'external_loop', 'buffered'], + a = np.zeros((2, 7)) + b = np.zeros((1, 7)) + it = np.nditer([a, b], flags=['reduce_ok', 'external_loop', 'buffered'], op_flags=[['readonly'], ['readwrite']], buffersize = 5) bufsizes = [] for x, y in it: bufsizes.append(x.shape[0]) - assert_equal(bufsizes, [5,2,5,2]) + assert_equal(bufsizes, [5, 2, 5, 2]) assert_equal(sum(bufsizes), a.size) def test_iter_writemasked_badinput(): - a = np.zeros((2,3)) + a = np.zeros((2, 3)) b = np.zeros((3,)) - m = np.array([[True,True,False],[False,True,False]]) - m2 = np.array([True,True,False]) - m3 = np.array([0,1,1], dtype='u1') - mbad1 = np.array([0,1,1], dtype='i1') - mbad2 = np.array([0,1,1], dtype='f4') + m = np.array([[True, True, False], [False, True, False]]) + m2 = np.array([True, True, False]) + m3 = np.array([0, 1, 1], dtype='u1') + mbad1 = np.array([0, 1, 1], dtype='i1') + mbad2 = np.array([0, 1, 1], dtype='f4') # Need an 'arraymask' if any operand is 'writemasked' - assert_raises(ValueError, nditer, [a,m], [], - [['readwrite','writemasked'],['readonly']]) + assert_raises(ValueError, nditer, [a, m], [], + [['readwrite', 'writemasked'], ['readonly']]) # A 'writemasked' operand must not be readonly - assert_raises(ValueError, nditer, [a,m], [], - [['readonly','writemasked'],['readonly','arraymask']]) + assert_raises(ValueError, nditer, [a, m], [], + [['readonly', 'writemasked'], ['readonly', 'arraymask']]) # 'writemasked' and 'arraymask' may not be used together - assert_raises(ValueError, nditer, [a,m], [], - [['readonly'],['readwrite','arraymask','writemasked']]) + assert_raises(ValueError, nditer, [a, m], [], + [['readonly'], ['readwrite', 'arraymask', 'writemasked']]) # 'arraymask' may only be specified once - assert_raises(ValueError, nditer, [a,m, m2], [], - [['readwrite','writemasked'], - ['readonly','arraymask'], - ['readonly','arraymask']]) + assert_raises(ValueError, nditer, [a, m, m2], [], + [['readwrite', 'writemasked'], + ['readonly', 'arraymask'], + ['readonly', 'arraymask']]) # An 'arraymask' with nothing 'writemasked' also doesn't make sense - assert_raises(ValueError, nditer, [a,m], [], - [['readwrite'],['readonly','arraymask']]) + assert_raises(ValueError, nditer, [a, m], [], + [['readwrite'], ['readonly', 'arraymask']]) # A writemasked reduction requires a similarly smaller mask - assert_raises(ValueError, nditer, [a,b,m], ['reduce_ok'], + assert_raises(ValueError, nditer, [a, b, m], ['reduce_ok'], [['readonly'], - ['readwrite','writemasked'], - ['readonly','arraymask']]) + ['readwrite', 'writemasked'], + ['readonly', 'arraymask']]) # But this should work with a smaller/equal mask to the reduction operand - np.nditer([a,b,m2], ['reduce_ok'], + np.nditer([a, b, m2], ['reduce_ok'], [['readonly'], - ['readwrite','writemasked'], - ['readonly','arraymask']]) + ['readwrite', 'writemasked'], + ['readonly', 'arraymask']]) # The arraymask itself cannot be a reduction - assert_raises(ValueError, nditer, [a,b,m2], ['reduce_ok'], + assert_raises(ValueError, nditer, [a, b, m2], ['reduce_ok'], [['readonly'], - ['readwrite','writemasked'], - ['readwrite','arraymask']]) + ['readwrite', 'writemasked'], + ['readwrite', 'arraymask']]) # A uint8 mask is ok too - np.nditer([a,m3], ['buffered'], - [['readwrite','writemasked'], - ['readonly','arraymask']], - op_dtypes=['f4',None], + np.nditer([a, m3], ['buffered'], + [['readwrite', 'writemasked'], + ['readonly', 'arraymask']], + op_dtypes=['f4', None], casting='same_kind') # An int8 mask isn't ok - assert_raises(TypeError, np.nditer, [a,mbad1], ['buffered'], - [['readwrite','writemasked'], - ['readonly','arraymask']], - op_dtypes=['f4',None], + assert_raises(TypeError, np.nditer, [a, mbad1], ['buffered'], + [['readwrite', 'writemasked'], + ['readonly', 'arraymask']], + op_dtypes=['f4', None], casting='same_kind') # A float32 mask isn't ok - assert_raises(TypeError, np.nditer, [a,mbad2], ['buffered'], - [['readwrite','writemasked'], - ['readonly','arraymask']], - op_dtypes=['f4',None], + assert_raises(TypeError, np.nditer, [a, mbad2], ['buffered'], + [['readwrite', 'writemasked'], + ['readonly', 'arraymask']], + op_dtypes=['f4', None], casting='same_kind') def test_iter_writemasked(): a = np.zeros((3,), dtype='f8') - msk = np.array([True,True,False]) + msk = np.array([True, True, False]) # When buffering is unused, 'writemasked' effectively does nothing. # It's up to the user of the iterator to obey the requested semantics. - it = np.nditer([a,msk], [], - [['readwrite','writemasked'], - ['readonly','arraymask']]) + it = np.nditer([a, msk], [], + [['readwrite', 'writemasked'], + ['readonly', 'arraymask']]) for x, m in it: x[...] = 1 # Because we violated the semantics, all the values became 1 - assert_equal(a, [1,1,1]) + assert_equal(a, [1, 1, 1]) # Even if buffering is enabled, we still may be accessing the array # directly. - it = np.nditer([a,msk], ['buffered'], - [['readwrite','writemasked'], - ['readonly','arraymask']]) + it = np.nditer([a, msk], ['buffered'], + [['readwrite', 'writemasked'], + ['readonly', 'arraymask']]) for x, m in it: x[...] = 2.5 # Because we violated the semantics, all the values became 2.5 - assert_equal(a, [2.5,2.5,2.5]) + assert_equal(a, [2.5, 2.5, 2.5]) # If buffering will definitely happening, for instance because of # a cast, only the items selected by the mask will be copied back from # the buffer. - it = np.nditer([a,msk], ['buffered'], - [['readwrite','writemasked'], - ['readonly','arraymask']], - op_dtypes=['i8',None], + it = np.nditer([a, msk], ['buffered'], + [['readwrite', 'writemasked'], + ['readonly', 'arraymask']], + op_dtypes=['i8', None], casting='unsafe') for x, m in it: x[...] = 3 # Even though we violated the semantics, only the selected values # were copied back - assert_equal(a, [3,3,2.5]) + assert_equal(a, [3, 3, 2.5]) def test_iter_non_writable_attribute_deletion(): it = np.nditer(np.ones(2)) @@ -2514,15 +2514,15 @@ def test_iter_allocated_array_dtypes(): for a, b in it: b[0] = a - 1 b[1] = a + 1 - assert_equal(it.operands[1], [[0,2], [2,4], [19,21]]) + assert_equal(it.operands[1], [[0, 2], [2, 4], [19, 21]]) # Make sure this works for scalars too - it = np.nditer((10, 2, None), op_dtypes=[None, None, ('i4', (2,2))]) + it = np.nditer((10, 2, None), op_dtypes=[None, None, ('i4', (2, 2))]) for a, b, c in it: - c[0,0] = a - b - c[0,1] = a + b - c[1,0] = a * b - c[1,1] = a / b + c[0, 0] = a - b + c[0, 1] = a + b + c[1, 0] = a * b + c[1, 1] = a / b assert_equal(it.operands[2], [[8, 12], [20, 5]]) @@ -2546,9 +2546,9 @@ def test_0d_iter(): # note that itershape=(), still behaves like None due to the conversions # Test a more complex buffered casting case (same as another test above) - sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2,3)), ('d', 'O')] + sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')] a = np.array(0.5, dtype='f4') - i = nditer(a, ['buffered','refs_ok'], ['readonly'], + i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt) vals = next(i) assert_equal(vals['a'], 0.5) @@ -2558,25 +2558,25 @@ def test_0d_iter(): def test_0d_nested_iter(): - a = np.arange(12).reshape(2,3,2) - i, j = np.nested_iters(a, [[],[1,0,2]]) + a = np.arange(12).reshape(2, 3, 2) + i, j = np.nested_iters(a, [[], [1, 0, 2]]) vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0,1,2,3,4,5,6,7,8,9,10,11]]) + assert_equal(vals, [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]) - i, j = np.nested_iters(a, [[1,0,2],[]]) + i, j = np.nested_iters(a, [[1, 0, 2], []]) vals = [] for x in i: vals.append([y for y in j]) - assert_equal(vals, [[0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11]]) + assert_equal(vals, [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]]) - i, j, k = np.nested_iters(a, [[2,0], [] ,[1]]) + i, j, k = np.nested_iters(a, [[2, 0], [], [1]]) vals = [] for x in i: for y in j: vals.append([z for z in k]) - assert_equal(vals, [[0,2,4],[1,3,5],[6,8,10],[7,9,11]]) + assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]]) if __name__ == "__main__": diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py index fdf1c1ac1..6202bd125 100644 --- a/numpy/core/tests/test_numeric.py +++ b/numpy/core/tests/test_numeric.py @@ -17,28 +17,28 @@ class Vec(object): if sequence is None: sequence=[] self.array=array(sequence) - def __add__(self,other): + def __add__(self, other): out=Vec() out.array=self.array+other.array return out - def __sub__(self,other): + def __sub__(self, other): out=Vec() out.array=self.array-other.array return out - def __mul__(self,other): # with scalar + def __mul__(self, other): # with scalar out=Vec(self.array.copy()) out.array*=other return out - def __rmul__(self,other): + def __rmul__(self, other): return self*other class TestDot(TestCase): def setUp(self): - self.A = rand(10,8) - self.b1 = rand(8,1) + self.A = rand(10, 8) + self.b1 = rand(8, 1) self.b2 = rand(8) - self.b3 = rand(1,8) + self.b3 = rand(1, 8) self.b4 = rand(10) self.N = 14 @@ -74,8 +74,8 @@ class TestDot(TestCase): def test_vecmat3(self): A, b4 = self.A, self.b4 - c1 = dot(A.transpose(),b4) - c2 = dot_(A.transpose(),b4) + c1 = dot(A.transpose(), b4) + c2 = dot_(A.transpose(), b4) assert_almost_equal(c1, c2, decimal=self.N) def test_vecvecouter(self): @@ -91,35 +91,35 @@ class TestDot(TestCase): assert_almost_equal(c1, c2, decimal=self.N) def test_columnvect1(self): - b1 = ones((3,1)) + b1 = ones((3, 1)) b2 = [5.3] - c1 = dot(b1,b2) - c2 = dot_(b1,b2) + c1 = dot(b1, b2) + c2 = dot_(b1, b2) assert_almost_equal(c1, c2, decimal=self.N) def test_columnvect2(self): - b1 = ones((3,1)).transpose() + b1 = ones((3, 1)).transpose() b2 = [6.2] - c1 = dot(b2,b1) - c2 = dot_(b2,b1) + c1 = dot(b2, b1) + c2 = dot_(b2, b1) assert_almost_equal(c1, c2, decimal=self.N) def test_vecscalar(self): - b1 = rand(1,1) - b2 = rand(1,8) - c1 = dot(b1,b2) - c2 = dot_(b1,b2) + b1 = rand(1, 1) + b2 = rand(1, 8) + c1 = dot(b1, b2) + c2 = dot_(b1, b2) assert_almost_equal(c1, c2, decimal=self.N) def test_vecscalar2(self): - b1 = rand(8,1) - b2 = rand(1,1) - c1 = dot(b1,b2) - c2 = dot_(b1,b2) + b1 = rand(8, 1) + b2 = rand(1, 1) + c1 = dot(b1, b2) + c2 = dot_(b1, b2) assert_almost_equal(c1, c2, decimal=self.N) def test_all(self): - dims = [(),(1,),(1,1)] + dims = [(), (1,), (1, 1)] for dim1 in dims: for dim2 in dims: arg1 = rand(*dim1) @@ -130,53 +130,53 @@ class TestDot(TestCase): assert_almost_equal(c1, c2, decimal=self.N) def test_vecobject(self): - U_non_cont = transpose([[1.,1.],[1.,2.]]) + U_non_cont = transpose([[1., 1.], [1., 2.]]) U_cont = ascontiguousarray(U_non_cont) - x = array([Vec([1.,0.]),Vec([0.,1.])]) - zeros = array([Vec([0.,0.]),Vec([0.,0.])]) - zeros_test = dot(U_cont,x) - dot(U_non_cont,x) + x = array([Vec([1., 0.]), Vec([0., 1.])]) + zeros = array([Vec([0., 0.]), Vec([0., 0.])]) + zeros_test = dot(U_cont, x) - dot(U_non_cont, x) assert_equal(zeros[0].array, zeros_test[0].array) assert_equal(zeros[1].array, zeros_test[1].array) class TestResize(TestCase): def test_copies(self): - A = array([[1,2],[3,4]]) - Ar1 = array([[1,2,3,4],[1,2,3,4]]) - assert_equal(resize(A, (2,4)), Ar1) + A = array([[1, 2], [3, 4]]) + Ar1 = array([[1, 2, 3, 4], [1, 2, 3, 4]]) + assert_equal(resize(A, (2, 4)), Ar1) - Ar2 = array([[1,2],[3,4],[1,2],[3,4]]) - assert_equal(resize(A, (4,2)), Ar2) + Ar2 = array([[1, 2], [3, 4], [1, 2], [3, 4]]) + assert_equal(resize(A, (4, 2)), Ar2) - Ar3 = array([[1,2,3],[4,1,2],[3,4,1],[2,3,4]]) - assert_equal(resize(A, (4,3)), Ar3) + Ar3 = array([[1, 2, 3], [4, 1, 2], [3, 4, 1], [2, 3, 4]]) + assert_equal(resize(A, (4, 3)), Ar3) def test_zeroresize(self): - A = array([[1,2],[3,4]]) + A = array([[1, 2], [3, 4]]) Ar = resize(A, (0,)) assert_equal(Ar, array([])) class TestNonarrayArgs(TestCase): # check that non-array arguments to functions wrap them in arrays def test_squeeze(self): - A = [[[1,1,1],[2,2,2],[3,3,3]]] - assert_(squeeze(A).shape == (3,3)) + A = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]]] + assert_(squeeze(A).shape == (3, 3)) def test_cumproduct(self): - A = [[1,2,3],[4,5,6]] - assert_(all(cumproduct(A) == array([1,2,6,24,120,720]))) + A = [[1, 2, 3], [4, 5, 6]] + assert_(all(cumproduct(A) == array([1, 2, 6, 24, 120, 720]))) def test_size(self): - A = [[1,2,3],[4,5,6]] + A = [[1, 2, 3], [4, 5, 6]] assert_(size(A) == 6) - assert_(size(A,0) == 2) - assert_(size(A,1) == 3) + assert_(size(A, 0) == 2) + assert_(size(A, 1) == 3) def test_mean(self): - A = [[1,2,3],[4,5,6]] + A = [[1, 2, 3], [4, 5, 6]] assert_(mean(A) == 3.5) - assert_(all(mean(A,0) == array([2.5,3.5,4.5]))) - assert_(all(mean(A,1) == array([2.,5.]))) + assert_(all(mean(A, 0) == array([2.5, 3.5, 4.5]))) + assert_(all(mean(A, 1) == array([2., 5.]))) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', RuntimeWarning) @@ -184,10 +184,10 @@ class TestNonarrayArgs(TestCase): assert_(w[0].category is RuntimeWarning) def test_std(self): - A = [[1,2,3],[4,5,6]] + A = [[1, 2, 3], [4, 5, 6]] assert_almost_equal(std(A), 1.707825127659933) - assert_almost_equal(std(A,0), array([1.5, 1.5, 1.5])) - assert_almost_equal(std(A,1), array([0.81649658, 0.81649658])) + assert_almost_equal(std(A, 0), array([1.5, 1.5, 1.5])) + assert_almost_equal(std(A, 1), array([0.81649658, 0.81649658])) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', RuntimeWarning) @@ -195,10 +195,10 @@ class TestNonarrayArgs(TestCase): assert_(w[0].category is RuntimeWarning) def test_var(self): - A = [[1,2,3],[4,5,6]] + A = [[1, 2, 3], [4, 5, 6]] assert_almost_equal(var(A), 2.9166666666666665) - assert_almost_equal(var(A,0), array([2.25, 2.25, 2.25])) - assert_almost_equal(var(A,1), array([0.66666667, 0.66666667])) + assert_almost_equal(var(A, 0), array([2.25, 2.25, 2.25])) + assert_almost_equal(var(A, 1), array([0.66666667, 0.66666667])) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', RuntimeWarning) @@ -461,31 +461,31 @@ class TestFloatExceptions(TestCase): invalid = 'invalid' self.assert_raises_fpe(underflow, - lambda a,b:a/b, ft_tiny, ft_max) + lambda a, b:a/b, ft_tiny, ft_max) self.assert_raises_fpe(underflow, - lambda a,b:a*b, ft_tiny, ft_tiny) + lambda a, b:a*b, ft_tiny, ft_tiny) self.assert_raises_fpe(overflow, - lambda a,b:a*b, ft_max, ftype(2)) + lambda a, b:a*b, ft_max, ftype(2)) self.assert_raises_fpe(overflow, - lambda a,b:a/b, ft_max, ftype(0.5)) + lambda a, b:a/b, ft_max, ftype(0.5)) self.assert_raises_fpe(overflow, - lambda a,b:a+b, ft_max, ft_max*ft_eps) + lambda a, b:a+b, ft_max, ft_max*ft_eps) self.assert_raises_fpe(overflow, - lambda a,b:a-b, -ft_max, ft_max*ft_eps) + lambda a, b:a-b, -ft_max, ft_max*ft_eps) self.assert_raises_fpe(overflow, np.power, ftype(2), ftype(2**fi.nexp)) self.assert_raises_fpe(divbyzero, - lambda a,b:a/b, ftype(1), ftype(0)) + lambda a, b:a/b, ftype(1), ftype(0)) self.assert_raises_fpe(invalid, - lambda a,b:a/b, ftype(np.inf), ftype(np.inf)) + lambda a, b:a/b, ftype(np.inf), ftype(np.inf)) self.assert_raises_fpe(invalid, - lambda a,b:a/b, ftype(0), ftype(0)) + lambda a, b:a/b, ftype(0), ftype(0)) self.assert_raises_fpe(invalid, - lambda a,b:a-b, ftype(np.inf), ftype(np.inf)) + lambda a, b:a-b, ftype(np.inf), ftype(np.inf)) self.assert_raises_fpe(invalid, - lambda a,b:a+b, ftype(np.inf), ftype(-np.inf)) + lambda a, b:a+b, ftype(np.inf), ftype(-np.inf)) self.assert_raises_fpe(invalid, - lambda a,b:a*b, ftype(0), ftype(np.inf)) + lambda a, b:a*b, ftype(0), ftype(np.inf)) class TestTypes(TestCase): def check_promotion_cases(self, promote_func): @@ -497,56 +497,56 @@ class TestTypes(TestCase): c64, c128, cld = complex64(0), complex128(0), clongdouble(0) # coercion within the same kind - assert_equal(promote_func(i8,i16), np.dtype(int16)) - assert_equal(promote_func(i32,i8), np.dtype(int32)) - assert_equal(promote_func(i16,i64), np.dtype(int64)) - assert_equal(promote_func(u8,u32), np.dtype(uint32)) - assert_equal(promote_func(f32,f64), np.dtype(float64)) - assert_equal(promote_func(fld,f32), np.dtype(longdouble)) - assert_equal(promote_func(f64,fld), np.dtype(longdouble)) - assert_equal(promote_func(c128,c64), np.dtype(complex128)) - assert_equal(promote_func(cld,c128), np.dtype(clongdouble)) - assert_equal(promote_func(c64,fld), np.dtype(clongdouble)) + assert_equal(promote_func(i8, i16), np.dtype(int16)) + assert_equal(promote_func(i32, i8), np.dtype(int32)) + assert_equal(promote_func(i16, i64), np.dtype(int64)) + assert_equal(promote_func(u8, u32), np.dtype(uint32)) + assert_equal(promote_func(f32, f64), np.dtype(float64)) + assert_equal(promote_func(fld, f32), np.dtype(longdouble)) + assert_equal(promote_func(f64, fld), np.dtype(longdouble)) + assert_equal(promote_func(c128, c64), np.dtype(complex128)) + assert_equal(promote_func(cld, c128), np.dtype(clongdouble)) + assert_equal(promote_func(c64, fld), np.dtype(clongdouble)) # coercion between kinds - assert_equal(promote_func(b,i32), np.dtype(int32)) - assert_equal(promote_func(b,u8), np.dtype(uint8)) - assert_equal(promote_func(i8,u8), np.dtype(int16)) - assert_equal(promote_func(u8,i32), np.dtype(int32)) - assert_equal(promote_func(i64,u32), np.dtype(int64)) - assert_equal(promote_func(u64,i32), np.dtype(float64)) - assert_equal(promote_func(i32,f32), np.dtype(float64)) - assert_equal(promote_func(i64,f32), np.dtype(float64)) - assert_equal(promote_func(f32,i16), np.dtype(float32)) - assert_equal(promote_func(f32,u32), np.dtype(float64)) - assert_equal(promote_func(f32,c64), np.dtype(complex64)) - assert_equal(promote_func(c128,f32), np.dtype(complex128)) - assert_equal(promote_func(cld,f64), np.dtype(clongdouble)) + assert_equal(promote_func(b, i32), np.dtype(int32)) + assert_equal(promote_func(b, u8), np.dtype(uint8)) + assert_equal(promote_func(i8, u8), np.dtype(int16)) + assert_equal(promote_func(u8, i32), np.dtype(int32)) + assert_equal(promote_func(i64, u32), np.dtype(int64)) + assert_equal(promote_func(u64, i32), np.dtype(float64)) + assert_equal(promote_func(i32, f32), np.dtype(float64)) + assert_equal(promote_func(i64, f32), np.dtype(float64)) + assert_equal(promote_func(f32, i16), np.dtype(float32)) + assert_equal(promote_func(f32, u32), np.dtype(float64)) + assert_equal(promote_func(f32, c64), np.dtype(complex64)) + assert_equal(promote_func(c128, f32), np.dtype(complex128)) + assert_equal(promote_func(cld, f64), np.dtype(clongdouble)) # coercion between scalars and 1-D arrays - assert_equal(promote_func(array([b]),i8), np.dtype(int8)) - assert_equal(promote_func(array([b]),u8), np.dtype(uint8)) - assert_equal(promote_func(array([b]),i32), np.dtype(int32)) - assert_equal(promote_func(array([b]),u32), np.dtype(uint32)) - assert_equal(promote_func(array([i8]),i64), np.dtype(int8)) - assert_equal(promote_func(u64,array([i32])), np.dtype(int32)) - assert_equal(promote_func(i64,array([u32])), np.dtype(uint32)) - assert_equal(promote_func(int32(-1),array([u64])), np.dtype(float64)) - assert_equal(promote_func(f64,array([f32])), np.dtype(float32)) - assert_equal(promote_func(fld,array([f32])), np.dtype(float32)) - assert_equal(promote_func(array([f64]),fld), np.dtype(float64)) - assert_equal(promote_func(fld,array([c64])), np.dtype(complex64)) - assert_equal(promote_func(c64,array([f64])), np.dtype(complex128)) - assert_equal(promote_func(complex64(3j),array([f64])), + assert_equal(promote_func(array([b]), i8), np.dtype(int8)) + assert_equal(promote_func(array([b]), u8), np.dtype(uint8)) + assert_equal(promote_func(array([b]), i32), np.dtype(int32)) + assert_equal(promote_func(array([b]), u32), np.dtype(uint32)) + assert_equal(promote_func(array([i8]), i64), np.dtype(int8)) + assert_equal(promote_func(u64, array([i32])), np.dtype(int32)) + assert_equal(promote_func(i64, array([u32])), np.dtype(uint32)) + assert_equal(promote_func(int32(-1), array([u64])), np.dtype(float64)) + assert_equal(promote_func(f64, array([f32])), np.dtype(float32)) + assert_equal(promote_func(fld, array([f32])), np.dtype(float32)) + assert_equal(promote_func(array([f64]), fld), np.dtype(float64)) + assert_equal(promote_func(fld, array([c64])), np.dtype(complex64)) + assert_equal(promote_func(c64, array([f64])), np.dtype(complex128)) + assert_equal(promote_func(complex64(3j), array([f64])), np.dtype(complex128)) # coercion between scalars and 1-D arrays, where # the scalar has greater kind than the array - assert_equal(promote_func(array([b]),f64), np.dtype(float64)) - assert_equal(promote_func(array([b]),i64), np.dtype(int64)) - assert_equal(promote_func(array([b]),u64), np.dtype(uint64)) - assert_equal(promote_func(array([i8]),f64), np.dtype(float64)) - assert_equal(promote_func(array([u16]),f64), np.dtype(float64)) + assert_equal(promote_func(array([b]), f64), np.dtype(float64)) + assert_equal(promote_func(array([b]), i64), np.dtype(int64)) + assert_equal(promote_func(array([b]), u64), np.dtype(uint64)) + assert_equal(promote_func(array([i8]), f64), np.dtype(float64)) + assert_equal(promote_func(array([u16]), f64), np.dtype(float64)) # uint and int are treated as the same "kind" for # the purposes of array-scalar promotion. @@ -556,7 +556,7 @@ class TestTypes(TestCase): # the purposes of array-scalar promotion, so that you can do # (0j + float32array) to get a complex64 array instead of # a complex128 array. - assert_equal(promote_func(array([f32]),c128), np.dtype(complex64)) + assert_equal(promote_func(array([f32]), c128), np.dtype(complex64)) def test_coercion(self): def res_type(a, b): @@ -565,7 +565,7 @@ class TestTypes(TestCase): # Use-case: float/complex scalar * bool/int8 array # shouldn't narrow the float/complex type - for a in [np.array([True,False]), np.array([-3,12], dtype=np.int8)]: + for a in [np.array([True, False]), np.array([-3, 12], dtype=np.int8)]: b = 1.234 * a assert_equal(b.dtype, np.dtype('f8'), "array type %s" % a.dtype) b = np.longdouble(1.234) * a @@ -692,8 +692,8 @@ class TestFromiter(TestCase): expected = array(list(self.makegen())) a = fromiter(self.makegen(), int) a20 = fromiter(self.makegen(), int, 20) - self.assertTrue(alltrue(a == expected,axis=0)) - self.assertTrue(alltrue(a20 == expected[:20],axis=0)) + self.assertTrue(alltrue(a == expected, axis=0)) + self.assertTrue(alltrue(a20 == expected[:20], axis=0)) def load_data(self, n, eindex): # Utility method for the issue 2592 tests. @@ -731,48 +731,48 @@ class TestNonzero(TestCase): assert_equal(np.nonzero(array(1)), ([0],)) def test_nonzero_onedim(self): - x = array([1,0,2,-1,0,0,8]) + x = array([1, 0, 2, -1, 0, 0, 8]) assert_equal(np.count_nonzero(x), 4) assert_equal(np.count_nonzero(x), 4) assert_equal(np.nonzero(x), ([0, 2, 3, 6],)) - x = array([(1,2),(0,0),(1,1),(-1,3),(0,7)], - dtype=[('a','i4'),('b','i2')]) + x = array([(1, 2), (0, 0), (1, 1), (-1, 3), (0, 7)], + dtype=[('a', 'i4'), ('b', 'i2')]) assert_equal(np.count_nonzero(x['a']), 3) assert_equal(np.count_nonzero(x['b']), 4) - assert_equal(np.nonzero(x['a']), ([0,2,3],)) - assert_equal(np.nonzero(x['b']), ([0,2,3,4],)) + assert_equal(np.nonzero(x['a']), ([0, 2, 3],)) + assert_equal(np.nonzero(x['b']), ([0, 2, 3, 4],)) def test_nonzero_twodim(self): - x = array([[0,1,0],[2,0,3]]) + x = array([[0, 1, 0], [2, 0, 3]]) assert_equal(np.count_nonzero(x), 3) - assert_equal(np.nonzero(x), ([0,1,1],[1,0,2])) + assert_equal(np.nonzero(x), ([0, 1, 1], [1, 0, 2])) x = np.eye(3) assert_equal(np.count_nonzero(x), 3) - assert_equal(np.nonzero(x), ([0,1,2],[0,1,2])) + assert_equal(np.nonzero(x), ([0, 1, 2], [0, 1, 2])) - x = array([[(0,1),(0,0),(1,11)], - [(1,1),(1,0),(0,0)], - [(0,0),(1,5),(0,1)]], dtype=[('a','f4'),('b','u1')]) + x = array([[(0, 1), (0, 0), (1, 11)], + [(1, 1), (1, 0), (0, 0)], + [(0, 0), (1, 5), (0, 1)]], dtype=[('a', 'f4'), ('b', 'u1')]) assert_equal(np.count_nonzero(x['a']), 4) assert_equal(np.count_nonzero(x['b']), 5) - assert_equal(np.nonzero(x['a']), ([0,1,1,2],[2,0,1,1])) - assert_equal(np.nonzero(x['b']), ([0,0,1,2,2],[0,2,0,1,2])) + assert_equal(np.nonzero(x['a']), ([0, 1, 1, 2], [2, 0, 1, 1])) + assert_equal(np.nonzero(x['b']), ([0, 0, 1, 2, 2], [0, 2, 0, 1, 2])) assert_equal(np.count_nonzero(x['a'].T), 4) assert_equal(np.count_nonzero(x['b'].T), 5) - assert_equal(np.nonzero(x['a'].T), ([0,1,1,2],[1,1,2,0])) - assert_equal(np.nonzero(x['b'].T), ([0,0,1,2,2],[0,1,2,0,2])) + assert_equal(np.nonzero(x['a'].T), ([0, 1, 1, 2], [1, 1, 2, 0])) + assert_equal(np.nonzero(x['b'].T), ([0, 0, 1, 2, 2], [0, 1, 2, 0, 2])) class TestIndex(TestCase): def test_boolean(self): - a = rand(3,5,8) - V = rand(5,8) - g1 = randint(0,5,size=15) - g2 = randint(0,8,size=15) - V[g1,g2] = -V[g1,g2] - assert_((array([a[0][V>0],a[1][V>0],a[2][V>0]]) == a[:,V>0]).all()) + a = rand(3, 5, 8) + V = rand(5, 8) + g1 = randint(0, 5, size=15) + g2 = randint(0, 8, size=15) + V[g1, g2] = -V[g1, g2] + assert_((array([a[0][V>0], a[1][V>0], a[2][V>0]]) == a[:, V>0]).all()) def test_boolean_edgecase(self): a = np.array([], dtype='int32') @@ -784,10 +784,10 @@ class TestIndex(TestCase): class TestBinaryRepr(TestCase): def test_zero(self): - assert_equal(binary_repr(0),'0') + assert_equal(binary_repr(0), '0') def test_large(self): - assert_equal(binary_repr(10736848),'101000111101010011010000') + assert_equal(binary_repr(10736848), '101000111101010011010000') def test_negative(self): assert_equal(binary_repr(-1), '-1') @@ -810,52 +810,52 @@ class TestBaseRepr(TestCase): class TestArrayComparisons(TestCase): def test_array_equal(self): - res = array_equal(array([1,2]), array([1,2])) + res = array_equal(array([1, 2]), array([1, 2])) assert_(res) assert_(type(res) is bool) - res = array_equal(array([1,2]), array([1,2,3])) + res = array_equal(array([1, 2]), array([1, 2, 3])) assert_(not res) assert_(type(res) is bool) - res = array_equal(array([1,2]), array([3,4])) + res = array_equal(array([1, 2]), array([3, 4])) assert_(not res) assert_(type(res) is bool) - res = array_equal(array([1,2]), array([1,3])) + res = array_equal(array([1, 2]), array([1, 3])) assert_(not res) assert_(type(res) is bool) res = array_equal(array(['a'], dtype='S1'), array(['a'], dtype='S1')) assert_(res) assert_(type(res) is bool) - res = array_equal(array([('a',1)], dtype='S1,u4'), array([('a',1)], dtype='S1,u4')) + res = array_equal(array([('a', 1)], dtype='S1,u4'), array([('a', 1)], dtype='S1,u4')) assert_(res) assert_(type(res) is bool) def test_array_equiv(self): - res = array_equiv(array([1,2]), array([1,2])) + res = array_equiv(array([1, 2]), array([1, 2])) assert_(res) assert_(type(res) is bool) - res = array_equiv(array([1,2]), array([1,2,3])) + res = array_equiv(array([1, 2]), array([1, 2, 3])) assert_(not res) assert_(type(res) is bool) - res = array_equiv(array([1,2]), array([3,4])) + res = array_equiv(array([1, 2]), array([3, 4])) assert_(not res) assert_(type(res) is bool) - res = array_equiv(array([1,2]), array([1,3])) + res = array_equiv(array([1, 2]), array([1, 3])) assert_(not res) assert_(type(res) is bool) - res = array_equiv(array([1,1]), array([1])) + res = array_equiv(array([1, 1]), array([1])) assert_(res) assert_(type(res) is bool) - res = array_equiv(array([1,1]), array([[1],[1]])) + res = array_equiv(array([1, 1]), array([[1], [1]])) assert_(res) assert_(type(res) is bool) - res = array_equiv(array([1,2]), array([2])) + res = array_equiv(array([1, 2]), array([2])) assert_(not res) assert_(type(res) is bool) - res = array_equiv(array([1,2]), array([[1],[2]])) + res = array_equiv(array([1, 2]), array([[1], [2]])) assert_(not res) assert_(type(res) is bool) - res = array_equiv(array([1,2]), array([[1,2,3],[4,5,6],[7,8,9]])) + res = array_equiv(array([1, 2]), array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) assert_(not res) assert_(type(res) is bool) @@ -875,9 +875,9 @@ class TestClip(TestCase): def fastclip(self, a, m, M, out=None): if out is None: - return a.clip(m,M) + return a.clip(m, M) else: - return a.clip(m,M,out) + return a.clip(m, M, out) def clip(self, a, m, M, out=None): # use slow-clip @@ -1111,8 +1111,8 @@ class TestClip(TestCase): a = self._generate_int32_data(self.nr, self.nc) m = float32(-2) M = float32(4) - act = self.fastclip(a,m,M) - ac = self.clip(a,m,M) + act = self.fastclip(a, m, M) + ac = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_type_cast_05(self): @@ -1152,7 +1152,7 @@ class TestClip(TestCase): M = 1. a_s = self._neg_byteorder(a) assert_(not a_s.dtype.isnative) - ac = self.fastclip(a_s, m , M) + ac = self.fastclip(a_s, m, M) act = a_s.clip(m, M) assert_array_strict_equal(ac, act) @@ -1163,7 +1163,7 @@ class TestClip(TestCase): M = 1. m_s = self._neg_byteorder(m) assert_(not m_s.dtype.isnative) - ac = self.fastclip(a, m_s , M) + ac = self.fastclip(a, m_s, M) act = self.clip(a, m_s, M) assert_array_strict_equal(ac, act) @@ -1174,7 +1174,7 @@ class TestClip(TestCase): m = float32(-0.5) M = float32(1) act = self.clip(a, m, M, out = b) - ac = self.fastclip(a, m , M, out = b) + ac = self.fastclip(a, m, M, out = b) assert_array_strict_equal(ac, act) def test_type_cast_11(self): @@ -1185,7 +1185,7 @@ class TestClip(TestCase): bt = b.copy() m = -0.5 M = 1. - self.fastclip(a, m , M, out = b) + self.fastclip(a, m, M, out = b) self.clip(a, m, M, out = bt) assert_array_strict_equal(b, bt) @@ -1196,7 +1196,7 @@ class TestClip(TestCase): m = int32(0) M = int32(1) act = self.clip(a, m, M, out = b) - ac = self.fastclip(a, m , M, out = b) + ac = self.fastclip(a, m, M, out = b) assert_array_strict_equal(ac, act) def test_clip_with_out_simple(self): @@ -1296,21 +1296,21 @@ class TestAllclose(object): def tearDown(self): np.seterr(**self.olderr) - def tst_allclose(self,x,y): - assert_(allclose(x,y), "%s and %s not close" % (x,y)) + def tst_allclose(self, x, y): + assert_(allclose(x, y), "%s and %s not close" % (x, y)) - def tst_not_allclose(self,x,y): - assert_(not allclose(x,y), "%s and %s shouldn't be close" % (x,y)) + def tst_not_allclose(self, x, y): + assert_(not allclose(x, y), "%s and %s shouldn't be close" % (x, y)) def test_ip_allclose(self): #Parametric test factory. - arr = array([100,1000]) - aran = arange(125).reshape((5,5,5)) + arr = array([100, 1000]) + aran = arange(125).reshape((5, 5, 5)) atol = self.atol rtol = self.rtol - data = [([1,0], [1,0]), + data = [([1, 0], [1, 0]), ([atol], [0]), ([1], [1+rtol+atol]), (arr, arr + arr*rtol), @@ -1319,36 +1319,36 @@ class TestAllclose(object): (inf, inf), (inf, [inf])] - for (x,y) in data: - yield (self.tst_allclose,x,y) + for (x, y) in data: + yield (self.tst_allclose, x, y) def test_ip_not_allclose(self): #Parametric test factory. - aran = arange(125).reshape((5,5,5)) + aran = arange(125).reshape((5, 5, 5)) atol = self.atol rtol = self.rtol - data = [([inf,0], [1,inf]), - ([inf,0], [1,0]), - ([inf,inf], [1,inf]), - ([inf,inf], [1,0]), + data = [([inf, 0], [1, inf]), + ([inf, 0], [1, 0]), + ([inf, inf], [1, inf]), + ([inf, inf], [1, 0]), ([-inf, 0], [inf, 0]), - ([nan,0], [nan,0]), + ([nan, 0], [nan, 0]), ([atol*2], [0]), ([1], [1+rtol+atol*2]), (aran, aran + aran*atol + atol*2), - (array([inf,1]), array([0,inf]))] + (array([inf, 1]), array([0, inf]))] - for (x,y) in data: - yield (self.tst_not_allclose,x,y) + for (x, y) in data: + yield (self.tst_not_allclose, x, y) def test_no_parameter_modification(self): - x = array([inf,1]) - y = array([0,inf]) - allclose(x,y) - assert_array_equal(x,array([inf,1])) - assert_array_equal(y,array([0,inf])) + x = array([inf, 1]) + y = array([0, inf]) + allclose(x, y) + assert_array_equal(x, array([inf, 1])) + assert_array_equal(y, array([0, inf])) class TestIsclose(object): @@ -1358,8 +1358,8 @@ class TestIsclose(object): def setup(self): atol = self.atol rtol = self.rtol - arr = array([100,1000]) - aran = arange(125).reshape((5,5,5)) + arr = array([100, 1000]) + aran = arange(125).reshape((5, 5, 5)) self.all_close_tests = [ ([1, 0], [1, 0]), @@ -1420,12 +1420,12 @@ class TestIsclose(object): def test_ip_all_isclose(self): self.setup() - for (x,y) in self.all_close_tests: + for (x, y) in self.all_close_tests: yield (self.tst_all_isclose, x, y) def test_ip_none_isclose(self): self.setup() - for (x,y) in self.none_close_tests: + for (x, y) in self.none_close_tests: yield (self.tst_none_isclose, x, y) def test_ip_isclose_allclose(self): @@ -1465,31 +1465,31 @@ class TestIsclose(object): class TestStdVar(TestCase): def setUp(self): - self.A = array([1,-1,1,-1]) + self.A = array([1, -1, 1, -1]) self.real_var = 1 def test_basic(self): - assert_almost_equal(var(self.A),self.real_var) - assert_almost_equal(std(self.A)**2,self.real_var) + assert_almost_equal(var(self.A), self.real_var) + assert_almost_equal(std(self.A)**2, self.real_var) def test_ddof1(self): - assert_almost_equal(var(self.A,ddof=1), + assert_almost_equal(var(self.A, ddof=1), self.real_var*len(self.A)/float(len(self.A)-1)) - assert_almost_equal(std(self.A,ddof=1)**2, + assert_almost_equal(std(self.A, ddof=1)**2, self.real_var*len(self.A)/float(len(self.A)-1)) def test_ddof2(self): - assert_almost_equal(var(self.A,ddof=2), + assert_almost_equal(var(self.A, ddof=2), self.real_var*len(self.A)/float(len(self.A)-2)) - assert_almost_equal(std(self.A,ddof=2)**2, + assert_almost_equal(std(self.A, ddof=2)**2, self.real_var*len(self.A)/float(len(self.A)-2)) class TestStdVarComplex(TestCase): def test_basic(self): - A = array([1,1.j,-1,-1.j]) + A = array([1, 1.j, -1, -1.j]) real_var = 1 - assert_almost_equal(var(A),real_var) - assert_almost_equal(std(A)**2,real_var) + assert_almost_equal(var(A), real_var) + assert_almost_equal(std(A)**2, real_var) class TestCreationFuncs(TestCase): @@ -1573,20 +1573,20 @@ class TestLikeFuncs(TestCase): (arange(6, dtype='f4'), None), (arange(6), 'c16'), # 2D C-layout arrays - (arange(6).reshape(2,3), None), - (arange(6).reshape(3,2), 'i1'), + (arange(6).reshape(2, 3), None), + (arange(6).reshape(3, 2), 'i1'), # 2D F-layout arrays - (arange(6).reshape((2,3), order='F'), None), - (arange(6).reshape((3,2), order='F'), 'i1'), + (arange(6).reshape((2, 3), order='F'), None), + (arange(6).reshape((3, 2), order='F'), 'i1'), # 3D C-layout arrays - (arange(24).reshape(2,3,4), None), - (arange(24).reshape(4,3,2), 'f4'), + (arange(24).reshape(2, 3, 4), None), + (arange(24).reshape(4, 3, 2), 'f4'), # 3D F-layout arrays - (arange(24).reshape((2,3,4), order='F'), None), - (arange(24).reshape((4,3,2), order='F'), 'f4'), + (arange(24).reshape((2, 3, 4), order='F'), None), + (arange(24).reshape((4, 3, 2), order='F'), 'f4'), # 3D non-C/F-layout arrays - (arange(24).reshape(2,3,4).swapaxes(0,1), None), - (arange(24).reshape(4,3,2).swapaxes(0,1), '?'), + (arange(24).reshape(2, 3, 4).swapaxes(0, 1), None), + (arange(24).reshape(4, 3, 2).swapaxes(0, 1), '?'), ] def compare_array_value(self, dz, value, fill_value): @@ -1654,7 +1654,7 @@ class TestLikeFuncs(TestCase): self.compare_array_value(dz, value, fill_value) # Test the 'subok' parameter - a = np.matrix([[1,2],[3,4]]) + a = np.matrix([[1, 2], [3, 4]]) b = like_function(a, **fill_kwarg) assert_(type(b) is np.matrix) @@ -1769,7 +1769,7 @@ class TestRoll(TestCase): assert_equal(xr, np.array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])) def test_roll2d(self): - x2 = np.reshape(np.arange(10), (2,5)) + x2 = np.reshape(np.arange(10), (2, 5)) x2r = np.roll(x2, 1) assert_equal(x2r, np.array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]])) diff --git a/numpy/core/tests/test_numerictypes.py b/numpy/core/tests/test_numerictypes.py index 173ebbf9c..3cafcf65e 100644 --- a/numpy/core/tests/test_numerictypes.py +++ b/numpy/core/tests/test_numerictypes.py @@ -20,8 +20,8 @@ Pdescr = [ # A plain list of tuples with values for testing: PbufferT = [ # x y z - ([3,2], [[6.,4.],[6.,4.]], 8), - ([4,3], [[7.,5.],[7.,5.]], 9), + ([3, 2], [[6., 4.], [6., 4.]], 8), + ([4, 3], [[7., 5.], [7., 5.]], 9), ] @@ -60,8 +60,8 @@ NbufferT = [ # x Info color info y z # value y2 Info2 name z2 Name Value # name value y3 z3 - ([3,2], (6j, 6., (asbytes('nn'), [6j,4j], [6.,4.], [1,2]), asbytes('NN'), True), asbytes('cc'), (asunicode('NN'), 6j), [[6.,4.],[6.,4.]], 8), - ([4,3], (7j, 7., (asbytes('oo'), [7j,5j], [7.,5.], [2,1]), asbytes('OO'), False), asbytes('dd'), (asunicode('OO'), 7j), [[7.,5.],[7.,5.]], 9), + ([3, 2], (6j, 6., (asbytes('nn'), [6j, 4j], [6., 4.], [1, 2]), asbytes('NN'), True), asbytes('cc'), (asunicode('NN'), 6j), [[6., 4.], [6., 4.]], 8), + ([4, 3], (7j, 7., (asbytes('oo'), [7j, 5j], [7., 5.], [2, 1]), asbytes('OO'), False), asbytes('dd'), (asunicode('OO'), 7j), [[7., 5.], [7., 5.]], 9), ] @@ -74,7 +74,7 @@ def normalize_descr(descr): for item in descr: dtype = item[1] if isinstance(dtype, str): - if dtype[0] not in ['|','<','>']: + if dtype[0] not in ['|', '<', '>']: onebyte = dtype[1:] == "1" if onebyte or dtype[0] in ['S', 'V', 'b']: dtype = "|" + dtype @@ -125,13 +125,13 @@ class create_zeros(object): def test_zerosMD(self): """Check creation of multi-dimensional objects""" - h = np.zeros((2,3), dtype=self._descr) + h = np.zeros((2, 3), dtype=self._descr) self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) self.assertTrue(h.dtype['z'].name == 'uint8') self.assertTrue(h.dtype['z'].char == 'B') self.assertTrue(h.dtype['z'].type == np.uint8) # A small check that data is ok - assert_equal(h['z'], np.zeros((2,3), dtype='u1')) + assert_equal(h['z'], np.zeros((2, 3), dtype='u1')) class test_create_zeros_plain(create_zeros, TestCase): @@ -160,7 +160,7 @@ class create_values(object): h = np.array([self._buffer], dtype=self._descr) self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) if self.multiple_rows: - self.assertTrue(h.shape == (1,2)) + self.assertTrue(h.shape == (1, 2)) else: self.assertTrue(h.shape == (1,)) @@ -169,9 +169,9 @@ class create_values(object): h = np.array([[self._buffer]], dtype=self._descr) self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) if self.multiple_rows: - self.assertTrue(h.shape == (1,1,2)) + self.assertTrue(h.shape == (1, 1, 2)) else: - self.assertTrue(h.shape == (1,1)) + self.assertTrue(h.shape == (1, 1)) class test_create_values_plain_single(create_values, TestCase): @@ -338,37 +338,37 @@ class test_read_values_nested_multiple(read_values_nested, TestCase): class TestEmptyField(TestCase): def test_assign(self): a = np.arange(10, dtype=np.float32) - a.dtype = [("int", "<0i4"),("float", "<2f4")] - assert_(a['int'].shape == (5,0)) - assert_(a['float'].shape == (5,2)) + a.dtype = [("int", "<0i4"), ("float", "<2f4")] + assert_(a['int'].shape == (5, 0)) + assert_(a['float'].shape == (5, 2)) class TestCommonType(TestCase): def test_scalar_loses1(self): - res = np.find_common_type(['f4','f4','i2'],['f8']) + res = np.find_common_type(['f4', 'f4', 'i2'], ['f8']) assert_(res == 'f4') def test_scalar_loses2(self): - res = np.find_common_type(['f4','f4'],['i8']) + res = np.find_common_type(['f4', 'f4'], ['i8']) assert_(res == 'f4') def test_scalar_wins(self): - res = np.find_common_type(['f4','f4','i2'],['c8']) + res = np.find_common_type(['f4', 'f4', 'i2'], ['c8']) assert_(res == 'c8') def test_scalar_wins2(self): - res = np.find_common_type(['u4','i4','i4'],['f4']) + res = np.find_common_type(['u4', 'i4', 'i4'], ['f4']) assert_(res == 'f8') def test_scalar_wins3(self): # doesn't go up to 'f16' on purpose - res = np.find_common_type(['u8','i8','i8'],['f8']) + res = np.find_common_type(['u8', 'i8', 'i8'], ['f8']) assert_(res == 'f8') class TestMultipleFields(TestCase): def setUp(self): - self.ary = np.array([(1,2,3,4),(5,6,7,8)], dtype='i4,f4,i2,c8') + self.ary = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype='i4,f4,i2,c8') def _bad_call(self): - return self.ary['f0','f1'] + return self.ary['f0', 'f1'] def test_no_tuple(self): self.assertRaises(ValueError, self._bad_call) def test_return(self): - res = self.ary[['f0','f2']].tolist() - assert_(res == [(1,3), (5,7)]) + res = self.ary[['f0', 'f2']].tolist() + assert_(res == [(1, 3), (5, 7)]) if __name__ == "__main__": run_module_suite() diff --git a/numpy/core/tests/test_print.py b/numpy/core/tests/test_print.py index 342ca27c6..487b5de7d 100644 --- a/numpy/core/tests/test_print.py +++ b/numpy/core/tests/test_print.py @@ -16,7 +16,7 @@ _REF = {np.inf: 'inf', -np.inf: '-inf', np.nan: 'nan'} def check_float_type(tp): - for x in [0, 1,-1, 1e20] : + for x in [0, 1, -1, 1e20] : assert_equal(str(tp(x)), str(float(x)), err_msg='Failed str formatting for type %s' % tp) @@ -56,7 +56,7 @@ def test_nan_inf_float(): yield check_nan_inf_float, t def check_complex_type(tp): - for x in [0, 1,-1, 1e20] : + for x in [0, 1, -1, 1e20] : assert_equal(str(tp(x)), str(complex(x)), err_msg='Failed str formatting for type %s' % tp) assert_equal(str(tp(x*1j)), str(complex(x*1j)), @@ -130,7 +130,7 @@ def _test_redirected_print(x, tp, ref=None): err_msg='print failed for type%s' % tp) def check_float_type_print(tp): - for x in [0, 1,-1, 1e20]: + for x in [0, 1, -1, 1e20]: _test_redirected_print(float(x), tp) for x in [np.inf, -np.inf, np.nan]: diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py index 86b0e48a2..7118af8c3 100644 --- a/numpy/core/tests/test_regression.py +++ b/numpy/core/tests/test_regression.py @@ -25,34 +25,34 @@ class TestRegression(TestCase): def test_invalid_round(self,level=rlevel): """Ticket #3""" v = 4.7599999999999998 - assert_array_equal(np.array([v]),np.array(v)) + assert_array_equal(np.array([v]), np.array(v)) def test_mem_empty(self,level=rlevel): """Ticket #7""" - np.empty((1,),dtype=[('x',np.int64)]) + np.empty((1,), dtype=[('x', np.int64)]) def test_pickle_transposed(self,level=rlevel): """Ticket #16""" - a = np.transpose(np.array([[2,9],[7,0],[3,8]])) + a = np.transpose(np.array([[2, 9], [7, 0], [3, 8]])) f = BytesIO() - pickle.dump(a,f) + pickle.dump(a, f) f.seek(0) b = pickle.load(f) f.close() - assert_array_equal(a,b) + assert_array_equal(a, b) def test_typeNA(self,level=rlevel): """Ticket #31""" - assert_equal(np.typeNA[np.int64],'Int64') - assert_equal(np.typeNA[np.uint64],'UInt64') + assert_equal(np.typeNA[np.int64], 'Int64') + assert_equal(np.typeNA[np.uint64], 'UInt64') def test_dtype_names(self,level=rlevel): """Ticket #35""" - dt = np.dtype([(('name','label'),np.int32,3)]) + dt = np.dtype([(('name', 'label'), np.int32, 3)]) def test_reduce(self,level=rlevel): """Ticket #40""" - assert_almost_equal(np.add.reduce([1.,.5],dtype=None), 1.5) + assert_almost_equal(np.add.reduce([1., .5], dtype=None), 1.5) def test_zeros_order(self,level=rlevel): """Ticket #43""" @@ -79,7 +79,7 @@ class TestRegression(TestCase): def test_negative_nd_indexing(self,level=rlevel): """Ticket #49""" - c = np.arange(125).reshape((5,5,5)) + c = np.arange(125).reshape((5, 5, 5)) origidx = np.array([-1, 0, 1]) idx = np.array(origidx) c[idx] @@ -88,7 +88,7 @@ class TestRegression(TestCase): def test_char_dump(self,level=rlevel): """Ticket #50""" f = BytesIO() - ca = np.char.array(np.arange(1000,1010),itemsize=4) + ca = np.char.array(np.arange(1000, 1010), itemsize=4) ca.dump(f) f.seek(0) ca = np.load(f) @@ -96,11 +96,11 @@ class TestRegression(TestCase): def test_noncontiguous_fill(self,level=rlevel): """Ticket #58.""" - a = np.zeros((5,3)) - b = a[:,:2,] + a = np.zeros((5, 3)) + b = a[:, :2,] def rs(): b.shape = (10,) - self.assertRaises(AttributeError,rs) + self.assertRaises(AttributeError, rs) def test_bool(self,level=rlevel): """Ticket #60""" @@ -109,14 +109,14 @@ class TestRegression(TestCase): def test_indexing1(self,level=rlevel): """Ticket #64""" descr = [('x', [('y', [('z', 'c16', (2,)),]),]),] - buffer = ((([6j,4j],),),) + buffer = ((([6j, 4j],),),) h = np.array(buffer, dtype=descr) h['x']['y']['z'] def test_indexing2(self,level=rlevel): """Ticket #65""" descr = [('x', 'i4', (2,))] - buffer = ([3,2],) + buffer = ([3, 2],) h = np.array(buffer, dtype=descr) h['x'] @@ -128,7 +128,7 @@ class TestRegression(TestCase): def test_scalar_compare(self,level=rlevel): """Ticket #72""" a = np.array(['test', 'auto']) - assert_array_equal(a == 'auto', np.array([False,True])) + assert_array_equal(a == 'auto', np.array([False, True])) self.assertTrue(a[1] == 'auto') self.assertTrue(a[0] != 'auto') b = np.linspace(0, 10, 11) @@ -149,8 +149,8 @@ class TestRegression(TestCase): def test_mem_dtype_align(self,level=rlevel): """Ticket #93""" - self.assertRaises(TypeError,np.dtype, - {'names':['a'],'formats':['foo']},align=1) + self.assertRaises(TypeError, np.dtype, + {'names':['a'],'formats':['foo']}, align=1) @dec.knownfailureif((sys.version_info[0] >= 3) or (sys.platform == "win32" and platform.architecture()[0] == "64bit"), @@ -159,22 +159,22 @@ class TestRegression(TestCase): def test_intp(self,level=rlevel): """Ticket #99""" i_width = np.int_(0).nbytes*2 - 1 - np.intp('0x' + 'f'*i_width,16) - self.assertRaises(OverflowError,np.intp,'0x' + 'f'*(i_width+1),16) - self.assertRaises(ValueError,np.intp,'0x1',32) - assert_equal(255,np.intp('0xFF',16)) - assert_equal(1024,np.intp(1024)) + np.intp('0x' + 'f'*i_width, 16) + self.assertRaises(OverflowError, np.intp, '0x' + 'f'*(i_width+1), 16) + self.assertRaises(ValueError, np.intp, '0x1', 32) + assert_equal(255, np.intp('0xFF', 16)) + assert_equal(1024, np.intp(1024)) def test_endian_bool_indexing(self,level=rlevel): """Ticket #105""" - a = np.arange(10.,dtype='>f8') - b = np.arange(10.,dtype='<f8') + a = np.arange(10., dtype='>f8') + b = np.arange(10., dtype='<f8') xa = np.where((a>2) & (a<6)) xb = np.where((b>2) & (b<6)) ya = ((a>2) & (a<6)) yb = ((b>2) & (b<6)) - assert_array_almost_equal(xa,ya.nonzero()) - assert_array_almost_equal(xb,yb.nonzero()) + assert_array_almost_equal(xa, ya.nonzero()) + assert_array_almost_equal(xb, yb.nonzero()) assert_(np.all(a[ya] > 0.5)) assert_(np.all(b[yb] > 0.5)) @@ -196,7 +196,7 @@ class TestRegression(TestCase): ]) buf = np.recarray(1, dtype=dt) buf[0]['head'] = 1 - buf[0]['data'][:] = [1,1] + buf[0]['data'][:] = [1, 1] h = buf[0]['head'] d = buf[0]['data'][0] @@ -206,8 +206,8 @@ class TestRegression(TestCase): def test_mem_dot(self,level=rlevel): """Ticket #106""" - x = np.random.randn(0,1) - y = np.random.randn(10,1) + x = np.random.randn(0, 1) + y = np.random.randn(10, 1) # Dummy array to detect bad memory access: _z = np.ones(10) _dummy = np.empty((0, 10)) @@ -221,10 +221,10 @@ class TestRegression(TestCase): def test_arange_endian(self,level=rlevel): """Ticket #111""" ref = np.arange(10) - x = np.arange(10,dtype='<f8') - assert_array_equal(ref,x) - x = np.arange(10,dtype='>f8') - assert_array_equal(ref,x) + x = np.arange(10, dtype='<f8') + assert_array_equal(ref, x) + x = np.arange(10, dtype='>f8') + assert_array_equal(ref, x) # Longfloat support is not consistent enough across # platforms for this test to be meaningful. @@ -236,21 +236,21 @@ class TestRegression(TestCase): def test_argmax(self,level=rlevel): """Ticket #119""" - a = np.random.normal(0,1,(4,5,6,7,8)) + a = np.random.normal(0, 1, (4, 5, 6, 7, 8)) for i in range(a.ndim): aargmax = a.argmax(i) def test_mem_divmod(self,level=rlevel): """Ticket #126""" for i in range(10): - divmod(np.array([i])[0],10) + divmod(np.array([i])[0], 10) def test_hstack_invalid_dims(self,level=rlevel): """Ticket #128""" - x = np.arange(9).reshape((3,3)) - y = np.array([0,0,0]) - self.assertRaises(ValueError,np.hstack,(x,y)) + x = np.arange(9).reshape((3, 3)) + y = np.array([0, 0, 0]) + self.assertRaises(ValueError, np.hstack, (x, y)) def test_squeeze_type(self,level=rlevel): """Ticket #133""" @@ -261,7 +261,7 @@ class TestRegression(TestCase): def test_add_identity(self,level=rlevel): """Ticket #143""" - assert_equal(0,np.add.identity) + assert_equal(0, np.add.identity) def test_numpy_float_python_long_addition(self): # Check that numpy float and python longs can be added correctly. @@ -270,41 +270,41 @@ class TestRegression(TestCase): def test_binary_repr_0(self,level=rlevel): """Ticket #151""" - assert_equal('0',np.binary_repr(0)) + assert_equal('0', np.binary_repr(0)) def test_rec_iterate(self,level=rlevel): """Ticket #160""" - descr = np.dtype([('i',int),('f',float),('s','|S3')]) - x = np.rec.array([(1,1.1,'1.0'), - (2,2.2,'2.0')],dtype=descr) + descr = np.dtype([('i', int), ('f', float), ('s', '|S3')]) + x = np.rec.array([(1, 1.1, '1.0'), + (2, 2.2, '2.0')], dtype=descr) x[0].tolist() [i for i in x[0]] def test_unicode_string_comparison(self,level=rlevel): """Ticket #190""" - a = np.array('hello',np.unicode_) + a = np.array('hello', np.unicode_) b = np.array('world') a == b def test_tostring_FORTRANORDER_discontiguous(self,level=rlevel): """Fix in r2836""" # Create discontiguous Fortran-ordered array - x = np.array(np.random.rand(3,3),order='F')[:,:2] - assert_array_almost_equal(x.ravel(),np.fromstring(x.tostring())) + x = np.array(np.random.rand(3, 3), order='F')[:, :2] + assert_array_almost_equal(x.ravel(), np.fromstring(x.tostring())) def test_flat_assignment(self,level=rlevel): """Correct behaviour of ticket #194""" - x = np.empty((3,1)) + x = np.empty((3, 1)) x.flat = np.arange(3) - assert_array_almost_equal(x,[[0],[1],[2]]) - x.flat = np.arange(3,dtype=float) - assert_array_almost_equal(x,[[0],[1],[2]]) + assert_array_almost_equal(x, [[0], [1], [2]]) + x.flat = np.arange(3, dtype=float) + assert_array_almost_equal(x, [[0], [1], [2]]) def test_broadcast_flat_assignment(self,level=rlevel): """Ticket #194""" - x = np.empty((3,1)) + x = np.empty((3, 1)) def bfa(): x[:] = np.arange(3) - def bfb(): x[:] = np.arange(3,dtype=float) + def bfb(): x[:] = np.arange(3, dtype=float) self.assertRaises(ValueError, bfa) self.assertRaises(ValueError, bfb) @@ -323,29 +323,29 @@ class TestRegression(TestCase): def test_unpickle_dtype_with_object(self,level=rlevel): """Implemented in r2840""" - dt = np.dtype([('x',int),('y',np.object_),('z','O')]) + dt = np.dtype([('x', int), ('y', np.object_), ('z', 'O')]) f = BytesIO() - pickle.dump(dt,f) + pickle.dump(dt, f) f.seek(0) dt_ = pickle.load(f) f.close() - assert_equal(dt,dt_) + assert_equal(dt, dt_) def test_mem_array_creation_invalid_specification(self,level=rlevel): """Ticket #196""" - dt = np.dtype([('x',int),('y',np.object_)]) + dt = np.dtype([('x', int), ('y', np.object_)]) # Wrong way - self.assertRaises(ValueError, np.array, [1,'object'], dt) + self.assertRaises(ValueError, np.array, [1, 'object'], dt) # Correct way - np.array([(1,'object')],dt) + np.array([(1, 'object')], dt) def test_recarray_single_element(self,level=rlevel): """Ticket #202""" - a = np.array([1,2,3],dtype=np.int32) + a = np.array([1, 2, 3], dtype=np.int32) b = a.copy() - r = np.rec.array(a,shape=1,formats=['3i4'],names=['d']) - assert_array_equal(a,b) - assert_equal(a,r[0][0]) + r = np.rec.array(a, shape=1, formats=['3i4'], names=['d']) + assert_array_equal(a, b) + assert_equal(a, r[0][0]) def test_zero_sized_array_indexing(self,level=rlevel): """Ticket #205""" @@ -355,36 +355,36 @@ class TestRegression(TestCase): def test_chararray_rstrip(self,level=rlevel): """Ticket #222""" - x = np.chararray((1,),5) + x = np.chararray((1,), 5) x[0] = asbytes('a ') x = x.rstrip() assert_equal(x[0], asbytes('a')) def test_object_array_shape(self,level=rlevel): """Ticket #239""" - assert_equal(np.array([[1,2],3,4],dtype=object).shape, (3,)) - assert_equal(np.array([[1,2],[3,4]],dtype=object).shape, (2,2)) - assert_equal(np.array([(1,2),(3,4)],dtype=object).shape, (2,2)) - assert_equal(np.array([],dtype=object).shape, (0,)) - assert_equal(np.array([[],[],[]],dtype=object).shape, (3,0)) - assert_equal(np.array([[3,4],[5,6],None],dtype=object).shape, (3,)) + assert_equal(np.array([[1, 2], 3, 4], dtype=object).shape, (3,)) + assert_equal(np.array([[1, 2], [3, 4]], dtype=object).shape, (2, 2)) + assert_equal(np.array([(1, 2), (3, 4)], dtype=object).shape, (2, 2)) + assert_equal(np.array([], dtype=object).shape, (0,)) + assert_equal(np.array([[], [], []], dtype=object).shape, (3, 0)) + assert_equal(np.array([[3, 4], [5, 6], None], dtype=object).shape, (3,)) def test_mem_around(self,level=rlevel): """Ticket #243""" x = np.zeros((1,)) y = [0] decimal = 6 - np.around(abs(x-y),decimal) <= 10.0**(-decimal) + np.around(abs(x-y), decimal) <= 10.0**(-decimal) def test_character_array_strip(self,level=rlevel): """Ticket #246""" - x = np.char.array(("x","x ","x ")) - for c in x: assert_equal(c,"x") + x = np.char.array(("x", "x ", "x ")) + for c in x: assert_equal(c, "x") def test_lexsort(self,level=rlevel): """Lexsort memory error""" - v = np.array([1,2,3,4,5,6,7,8,9,10]) - assert_equal(np.lexsort(v),0) + v = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + assert_equal(np.lexsort(v), 0) def test_pickle_dtype(self,level=rlevel): """Ticket #251""" @@ -392,26 +392,26 @@ class TestRegression(TestCase): def test_swap_real(self, level=rlevel): """Ticket #265""" - assert_equal(np.arange(4,dtype='>c8').imag.max(),0.0) - assert_equal(np.arange(4,dtype='<c8').imag.max(),0.0) - assert_equal(np.arange(4,dtype='>c8').real.max(),3.0) - assert_equal(np.arange(4,dtype='<c8').real.max(),3.0) + assert_equal(np.arange(4, dtype='>c8').imag.max(), 0.0) + assert_equal(np.arange(4, dtype='<c8').imag.max(), 0.0) + assert_equal(np.arange(4, dtype='>c8').real.max(), 3.0) + assert_equal(np.arange(4, dtype='<c8').real.max(), 3.0) def test_object_array_from_list(self, level=rlevel): """Ticket #270""" - a = np.array([1,'A',None]) + a = np.array([1, 'A', None]) def test_multiple_assign(self, level=rlevel): """Ticket #273""" - a = np.zeros((3,1),int) - a[[1,2]] = 1 + a = np.zeros((3, 1), int) + a[[1, 2]] = 1 def test_empty_array_type(self, level=rlevel): assert_equal(np.array([]).dtype, np.zeros(0).dtype) def test_void_copyswap(self, level=rlevel): - dt = np.dtype([('one', '<i4'),('two', '<i4')]) - x = np.array((1,2), dtype=dt) + dt = np.dtype([('one', '<i4'), ('two', '<i4')]) + x = np.array((1, 2), dtype=dt) x = x.byteswap() assert_(x['one'] > 1 and x['two'] > 2) @@ -426,7 +426,7 @@ class TestRegression(TestCase): funcs2 = ['compress', 'take', 'repeat'] for func in funcs1: - arr = np.random.rand(8,7) + arr = np.random.rand(8, 7) arr2 = arr.copy() if isinstance(func, tuple): func_meth = func[1] @@ -441,8 +441,8 @@ class TestRegression(TestCase): assert_(abs(res1-res2).max() < 1e-8, func) for func in funcs2: - arr1 = np.random.rand(8,7) - arr2 = np.random.rand(8,7) + arr1 = np.random.rand(8, 7) + arr2 = np.random.rand(8, 7) res1 = None if func == 'compress': arr1 = arr1.ravel() @@ -456,51 +456,51 @@ class TestRegression(TestCase): def test_mem_lexsort_strings(self, level=rlevel): """Ticket #298""" - lst = ['abc','cde','fgh'] + lst = ['abc', 'cde', 'fgh'] np.lexsort((lst,)) def test_fancy_index(self, level=rlevel): """Ticket #302""" - x = np.array([1,2])[np.array([0])] - assert_equal(x.shape,(1,)) + x = np.array([1, 2])[np.array([0])] + assert_equal(x.shape, (1,)) def test_recarray_copy(self, level=rlevel): """Ticket #312""" - dt = [('x',np.int16),('y',np.float64)] - ra = np.array([(1,2.3)], dtype=dt) + dt = [('x', np.int16), ('y', np.float64)] + ra = np.array([(1, 2.3)], dtype=dt) rb = np.rec.array(ra, dtype=dt) rb['x'] = 2. assert_(ra['x'] != rb['x']) def test_rec_fromarray(self, level=rlevel): """Ticket #322""" - x1 = np.array([[1,2],[3,4],[5,6]]) - x2 = np.array(['a','dd','xyz']) - x3 = np.array([1.1,2,3]) - np.rec.fromarrays([x1,x2,x3], formats="(2,)i4,a3,f8") + x1 = np.array([[1, 2], [3, 4], [5, 6]]) + x2 = np.array(['a', 'dd', 'xyz']) + x3 = np.array([1.1, 2, 3]) + np.rec.fromarrays([x1, x2, x3], formats="(2,)i4,a3,f8") def test_object_array_assign(self, level=rlevel): - x = np.empty((2,2),object) - x.flat[2] = (1,2,3) - assert_equal(x.flat[2],(1,2,3)) + x = np.empty((2, 2), object) + x.flat[2] = (1, 2, 3) + assert_equal(x.flat[2], (1, 2, 3)) def test_ndmin_float64(self, level=rlevel): """Ticket #324""" - x = np.array([1,2,3],dtype=np.float64) - assert_equal(np.array(x,dtype=np.float32,ndmin=2).ndim,2) - assert_equal(np.array(x,dtype=np.float64,ndmin=2).ndim,2) + x = np.array([1, 2, 3], dtype=np.float64) + assert_equal(np.array(x, dtype=np.float32, ndmin=2).ndim, 2) + assert_equal(np.array(x, dtype=np.float64, ndmin=2).ndim, 2) def test_ndmin_order(self, level=rlevel): """Issue #465 and related checks""" - assert_(np.array([1,2], order='C', ndmin=3).flags.c_contiguous) - assert_(np.array([1,2], order='F', ndmin=3).flags.f_contiguous) - assert_(np.array(np.ones((2,2), order='F'), ndmin=3).flags.f_contiguous) - assert_(np.array(np.ones((2,2), order='C'), ndmin=3).flags.c_contiguous) + assert_(np.array([1, 2], order='C', ndmin=3).flags.c_contiguous) + assert_(np.array([1, 2], order='F', ndmin=3).flags.f_contiguous) + assert_(np.array(np.ones((2, 2), order='F'), ndmin=3).flags.f_contiguous) + assert_(np.array(np.ones((2, 2), order='C'), ndmin=3).flags.c_contiguous) def test_mem_axis_minimization(self, level=rlevel): """Ticket #327""" data = np.arange(5) - data = np.add.outer(data,data) + data = np.add.outer(data, data) def test_mem_float_imag(self, level=rlevel): """Ticket #330""" @@ -508,7 +508,7 @@ class TestRegression(TestCase): def test_dtype_tuple(self, level=rlevel): """Ticket #334""" - assert_(np.dtype('i4') == np.dtype(('i4',()))) + assert_(np.dtype('i4') == np.dtype(('i4', ()))) def test_dtype_posttuple(self, level=rlevel): """Ticket #335""" @@ -521,7 +521,7 @@ class TestRegression(TestCase): def test_string_array_size(self, level=rlevel): """Ticket #342""" self.assertRaises(ValueError, - np.array,[['X'],['X','X','X']],'|S1') + np.array, [['X'], ['X', 'X', 'X']], '|S1') def test_dtype_repr(self, level=rlevel): """Ticket #344""" @@ -531,22 +531,22 @@ class TestRegression(TestCase): def test_reshape_order(self, level=rlevel): """Make sure reshape order works.""" - a = np.arange(6).reshape(2,3,order='F') - assert_equal(a,[[0,2,4],[1,3,5]]) - a = np.array([[1,2],[3,4],[5,6],[7,8]]) - b = a[:,1] - assert_equal(b.reshape(2,2,order='F'), [[2,6],[4,8]]) + a = np.arange(6).reshape(2, 3, order='F') + assert_equal(a, [[0, 2, 4], [1, 3, 5]]) + a = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) + b = a[:, 1] + assert_equal(b.reshape(2, 2, order='F'), [[2, 6], [4, 8]]) def test_reshape_zero_strides(self, level=rlevel): """Issue #380, test reshaping of zero strided arrays""" a = np.ones(1) a = np.lib.stride_tricks.as_strided(a, shape=(5,), strides=(0,)) - assert_(a.reshape(5,1).strides[0] == 0) + assert_(a.reshape(5, 1).strides[0] == 0) def test_reshape_zero_size(self, level=rlevel): """Github Issue #2700, setting shape failed for 0-sized arrays""" - a = np.ones((0,2)) - a.shape = (-1,2) + a = np.ones((0, 2)) + a.shape = (-1, 2) # Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides. # With NPY_RELAXED_STRIDES_CHECKING the test becomes superfluous. @@ -558,48 +558,48 @@ class TestRegression(TestCase): strides_f = (8, 24, 48, 48) assert_equal(a.reshape(3, 2, 1, 1).strides, strides_c) assert_equal(a.reshape(3, 2, 1, 1, order='F').strides, strides_f) - assert_equal(np.array(0, dtype=np.int32).reshape(1,1).strides, (4,4)) + assert_equal(np.array(0, dtype=np.int32).reshape(1, 1).strides, (4, 4)) def test_repeat_discont(self, level=rlevel): """Ticket #352""" - a = np.arange(12).reshape(4,3)[:,2] - assert_equal(a.repeat(3), [2,2,2,5,5,5,8,8,8,11,11,11]) + a = np.arange(12).reshape(4, 3)[:, 2] + assert_equal(a.repeat(3), [2, 2, 2, 5, 5, 5, 8, 8, 8, 11, 11, 11]) def test_array_index(self, level=rlevel): """Make sure optimization is not called in this case.""" - a = np.array([1,2,3]) - a2 = np.array([[1,2,3]]) + a = np.array([1, 2, 3]) + a2 = np.array([[1, 2, 3]]) assert_equal(a[np.where(a==3)], a2[np.where(a2==3)]) def test_object_argmax(self, level=rlevel): - a = np.array([1,2,3],dtype=object) + a = np.array([1, 2, 3], dtype=object) assert_(a.argmax() == 2) def test_recarray_fields(self, level=rlevel): """Ticket #372""" - dt0 = np.dtype([('f0','i4'),('f1','i4')]) - dt1 = np.dtype([('f0','i8'),('f1','i8')]) - for a in [np.array([(1,2),(3,4)],"i4,i4"), - np.rec.array([(1,2),(3,4)],"i4,i4"), - np.rec.array([(1,2),(3,4)]), - np.rec.fromarrays([(1,2),(3,4)],"i4,i4"), - np.rec.fromarrays([(1,2),(3,4)])]: - assert_(a.dtype in [dt0,dt1]) + dt0 = np.dtype([('f0', 'i4'), ('f1', 'i4')]) + dt1 = np.dtype([('f0', 'i8'), ('f1', 'i8')]) + for a in [np.array([(1, 2), (3, 4)], "i4,i4"), + np.rec.array([(1, 2), (3, 4)], "i4,i4"), + np.rec.array([(1, 2), (3, 4)]), + np.rec.fromarrays([(1, 2), (3, 4)], "i4,i4"), + np.rec.fromarrays([(1, 2), (3, 4)])]: + assert_(a.dtype in [dt0, dt1]) def test_random_shuffle(self, level=rlevel): """Ticket #374""" - a = np.arange(5).reshape((5,1)) + a = np.arange(5).reshape((5, 1)) b = a.copy() np.random.shuffle(b) - assert_equal(np.sort(b, axis=0),a) + assert_equal(np.sort(b, axis=0), a) def test_refcount_vdot(self, level=rlevel): """Changeset #3443""" _assert_valid_refcount(np.vdot) def test_startswith(self, level=rlevel): - ca = np.char.array(['Hi','There']) - assert_equal(ca.startswith('H'),[True,False]) + ca = np.char.array(['Hi', 'There']) + assert_equal(ca.startswith('H'), [True, False]) def test_noncommutative_reduce_accumulate(self, level=rlevel): """Ticket #413""" @@ -614,14 +614,14 @@ class TestRegression(TestCase): def test_convolve_empty(self, level=rlevel): """Convolve should raise an error for empty input array.""" - self.assertRaises(ValueError,np.convolve,[],[1]) - self.assertRaises(ValueError,np.convolve,[1],[]) + self.assertRaises(ValueError, np.convolve, [], [1]) + self.assertRaises(ValueError, np.convolve, [1], []) def test_multidim_byteswap(self, level=rlevel): """Ticket #449""" - r=np.array([(1,(0,1,2))], dtype="i2,3i2") + r=np.array([(1, (0, 1, 2))], dtype="i2,3i2") assert_array_equal(r.byteswap(), - np.array([(256,(0,256,512))],r.dtype)) + np.array([(256, (0, 256, 512))], r.dtype)) def test_string_NULL(self, level=rlevel): """Changeset 3557""" @@ -635,11 +635,11 @@ class TestRegression(TestCase): def test_take_output(self, level=rlevel): """Ensure that 'take' honours output parameter.""" - x = np.arange(12).reshape((3,4)) - a = np.take(x,[0,2],axis=1) + x = np.arange(12).reshape((3, 4)) + a = np.take(x, [0, 2], axis=1) b = np.zeros_like(a) - np.take(x,[0,2],axis=1,out=b) - assert_array_equal(a,b) + np.take(x, [0, 2], axis=1, out=b) + assert_array_equal(a, b) def test_take_object_fail(self): # Issue gh-3001 @@ -654,7 +654,7 @@ class TestRegression(TestCase): def test_array_str_64bit(self, level=rlevel): """Ticket #501""" - s = np.array([1, np.nan],dtype=np.float64) + s = np.array([1, np.nan], dtype=np.float64) with np.errstate(all='raise'): sstr = np.array_str(s) @@ -695,31 +695,31 @@ class TestRegression(TestCase): def test_mem_deallocation_leak(self, level=rlevel): """Ticket #562""" - a = np.zeros(5,dtype=float) - b = np.array(a,dtype=float) + a = np.zeros(5, dtype=float) + b = np.array(a, dtype=float) del a, b def test_mem_on_invalid_dtype(self): "Ticket #583" - self.assertRaises(ValueError, np.fromiter, [['12',''],['13','']], str) + self.assertRaises(ValueError, np.fromiter, [['12', ''], ['13', '']], str) def test_dot_negative_stride(self, level=rlevel): """Ticket #588""" - x = np.array([[1,5,25,125.,625]]) - y = np.array([[20.],[160.],[640.],[1280.],[1024.]]) + x = np.array([[1, 5, 25, 125., 625]]) + y = np.array([[20.], [160.], [640.], [1280.], [1024.]]) z = y[::-1].copy() y2 = y[::-1] - assert_equal(np.dot(x,z),np.dot(x,y2)) + assert_equal(np.dot(x, z), np.dot(x, y2)) def test_object_casting(self, level=rlevel): # This used to trigger the object-type version of # the bitwise_or operation, because float64 -> object # casting succeeds def rs(): - x = np.ones([484,286]) - y = np.zeros([484,286]) + x = np.ones([484, 286]) + y = np.zeros([484, 286]) x |= y - self.assertRaises(TypeError,rs) + self.assertRaises(TypeError, rs) def test_unicode_scalar(self, level=rlevel): """Ticket #600""" @@ -730,42 +730,42 @@ class TestRegression(TestCase): def test_arange_non_native_dtype(self, level=rlevel): """Ticket #616""" - for T in ('>f4','<f4'): + for T in ('>f4', '<f4'): dt = np.dtype(T) - assert_equal(np.arange(0,dtype=dt).dtype,dt) - assert_equal(np.arange(0.5,dtype=dt).dtype,dt) - assert_equal(np.arange(5,dtype=dt).dtype,dt) + assert_equal(np.arange(0, dtype=dt).dtype, dt) + assert_equal(np.arange(0.5, dtype=dt).dtype, dt) + assert_equal(np.arange(5, dtype=dt).dtype, dt) def test_bool_indexing_invalid_nr_elements(self, level=rlevel): - s = np.ones(10,dtype=float) - x = np.array((15,),dtype=float) - def ia(x,s,v): x[(s>0)]=v - self.assertRaises(ValueError,ia,x,s,np.zeros(9,dtype=float)) - self.assertRaises(ValueError,ia,x,s,np.zeros(11,dtype=float)) + s = np.ones(10, dtype=float) + x = np.array((15,), dtype=float) + def ia(x, s, v): x[(s>0)]=v + self.assertRaises(ValueError, ia, x, s, np.zeros(9, dtype=float)) + self.assertRaises(ValueError, ia, x, s, np.zeros(11, dtype=float)) def test_mem_scalar_indexing(self, level=rlevel): """Ticket #603""" - x = np.array([0],dtype=float) - index = np.array(0,dtype=np.int32) + x = np.array([0], dtype=float) + index = np.array(0, dtype=np.int32) x[index] def test_binary_repr_0_width(self, level=rlevel): - assert_equal(np.binary_repr(0,width=3),'000') + assert_equal(np.binary_repr(0, width=3), '000') def test_fromstring(self, level=rlevel): assert_equal(np.fromstring("12:09:09", dtype=int, sep=":"), - [12,9,9]) + [12, 9, 9]) def test_searchsorted_variable_length(self, level=rlevel): - x = np.array(['a','aa','b']) - y = np.array(['d','e']) - assert_equal(x.searchsorted(y), [3,3]) + x = np.array(['a', 'aa', 'b']) + y = np.array(['d', 'e']) + assert_equal(x.searchsorted(y), [3, 3]) def test_string_argsort_with_zeros(self, level=rlevel): """Check argsort for strings containing zeros.""" x = np.fromstring("\x00\x02\x00\x01", dtype="|S2") - assert_array_equal(x.argsort(kind='m'), np.array([1,0])) - assert_array_equal(x.argsort(kind='q'), np.array([1,0])) + assert_array_equal(x.argsort(kind='m'), np.array([1, 0])) + assert_array_equal(x.argsort(kind='q'), np.array([1, 0])) def test_string_sort_with_zeros(self, level=rlevel): """Check sort for strings containing zeros.""" @@ -775,29 +775,29 @@ class TestRegression(TestCase): def test_copy_detection_zero_dim(self, level=rlevel): """Ticket #658""" - np.indices((0,3,4)).T.reshape(-1,3) + np.indices((0, 3, 4)).T.reshape(-1, 3) def test_flat_byteorder(self, level=rlevel): """Ticket #657""" x = np.arange(10) - assert_array_equal(x.astype('>i4'),x.astype('<i4').flat[:]) - assert_array_equal(x.astype('>i4').flat[:],x.astype('<i4')) + assert_array_equal(x.astype('>i4'), x.astype('<i4').flat[:]) + assert_array_equal(x.astype('>i4').flat[:], x.astype('<i4')) def test_uint64_from_negative(self, level=rlevel) : assert_equal(np.uint64(-2), np.uint64(18446744073709551614)) def test_sign_bit(self, level=rlevel): - x = np.array([0,-0.0,0]) - assert_equal(str(np.abs(x)),'[ 0. 0. 0.]') + x = np.array([0, -0.0, 0]) + assert_equal(str(np.abs(x)), '[ 0. 0. 0.]') def test_flat_index_byteswap(self, level=rlevel): - for dt in (np.dtype('<i4'),np.dtype('>i4')): - x = np.array([-1,0,1],dtype=dt) + for dt in (np.dtype('<i4'), np.dtype('>i4')): + x = np.array([-1, 0, 1], dtype=dt) assert_equal(x.flat[0].dtype, x[0].dtype) def test_copy_detection_corner_case(self, level=rlevel): """Ticket #658""" - np.indices((0,3,4)).T.reshape(-1,3) + np.indices((0, 3, 4)).T.reshape(-1, 3) # Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides. # With NPY_RELAXED_STRIDES_CHECKING the test becomes superfluous, @@ -806,7 +806,7 @@ class TestRegression(TestCase): def test_copy_detection_corner_case2(self, level=rlevel): """Ticket #771: strides are not set correctly when reshaping 0-sized arrays""" - b = np.indices((0,3,4)).T.reshape(-1,3) + b = np.indices((0, 3, 4)).T.reshape(-1, 3) assert_equal(b.strides, (3 * b.itemsize, b.itemsize)) def test_object_array_refcounting(self, level=rlevel): @@ -857,7 +857,7 @@ class TestRegression(TestCase): assert_(cnt(a) == cnt0_a + 6) assert_(cnt(b) == cnt0_b + 6) - arr[:,0] = None + arr[:, 0] = None assert_(cnt(a) == cnt0_a + 1) del arr, arr0 @@ -866,8 +866,8 @@ class TestRegression(TestCase): arr = np.zeros((5, 2), dtype=np.object_) - arr[:,0] = a - arr[:,1] = b + arr[:, 0] = a + arr[:, 1] = b assert_(cnt(a) == cnt0_a + 5) assert_(cnt(b) == cnt0_b + 5) @@ -875,7 +875,7 @@ class TestRegression(TestCase): assert_(cnt(a) == cnt0_a + 10) assert_(cnt(b) == cnt0_b + 10) - arr2 = arr[:,0].copy() + arr2 = arr[:, 0].copy() assert_(cnt(a) == cnt0_a + 10) assert_(cnt(b) == cnt0_b + 5) @@ -902,10 +902,10 @@ class TestRegression(TestCase): arr3 = arr1.repeat(3, axis=0) assert_(cnt(a) == cnt0_a + 5 + 3*5) - arr3 = arr1.take([1,2,3], axis=0) + arr3 = arr1.take([1, 2, 3], axis=0) assert_(cnt(a) == cnt0_a + 5 + 3) - x = np.array([[0],[1],[0],[1],[1]], int) + x = np.array([[0], [1], [0], [1], [1]], int) arr3 = x.choose(arr1, arr2) assert_(cnt(a) == cnt0_a + 5 + 2) assert_(cnt(b) == cnt0_b + 5 + 3) @@ -935,7 +935,7 @@ class TestRegression(TestCase): assert_(not arr[0].deleted) def test_mem_fromiter_invalid_dtype_string(self, level=rlevel): - x = [1,2,3] + x = [1, 2, 3] self.assertRaises(ValueError, np.fromiter, [xi for xi in x], dtype='S') @@ -973,7 +973,7 @@ class TestRegression(TestCase): def test_dot_alignment_sse2(self, level=rlevel): """Test for ticket #551, changeset r5140""" - x = np.zeros((30,40)) + x = np.zeros((30, 40)) y = pickle.loads(pickle.dumps(x)) # y is now typically not aligned on a 8-byte boundary z = np.ones((1, y.shape[0])) @@ -1024,17 +1024,17 @@ class TestRegression(TestCase): return result def __array_finalize__(self, obj): self.info = getattr(obj, 'info', '') - dat = TestArray([[1,2,3,4],[5,6,7,8]],'jubba') + dat = TestArray([[1, 2, 3, 4], [5, 6, 7, 8]], 'jubba') assert_(dat.info == 'jubba') - dat.resize((4,2)) + dat.resize((4, 2)) assert_(dat.info == 'jubba') dat.sort() assert_(dat.info == 'jubba') dat.fill(2) assert_(dat.info == 'jubba') - dat.put([2,3,4],[6,3,4]) + dat.put([2, 3, 4], [6, 3, 4]) assert_(dat.info == 'jubba') - dat.setfield(4, np.int32,0) + dat.setfield(4, np.int32, 0) assert_(dat.info == 'jubba') dat.setflags() assert_(dat.info == 'jubba') @@ -1045,12 +1045,12 @@ class TestRegression(TestCase): assert_(dat.argsort(1).info == 'jubba') assert_(dat.astype(TestArray).info == 'jubba') assert_(dat.byteswap().info == 'jubba') - assert_(dat.clip(2,7).info == 'jubba') - assert_(dat.compress([0,1,1]).info == 'jubba') + assert_(dat.clip(2, 7).info == 'jubba') + assert_(dat.compress([0, 1, 1]).info == 'jubba') assert_(dat.conj().info == 'jubba') assert_(dat.conjugate().info == 'jubba') assert_(dat.copy().info == 'jubba') - dat2 = TestArray([2, 3, 1, 0],'jubba') + dat2 = TestArray([2, 3, 1, 0], 'jubba') choices = [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]] assert_(dat2.choose(choices).info == 'jubba') @@ -1058,7 +1058,7 @@ class TestRegression(TestCase): assert_(dat.cumsum(1).info == 'jubba') assert_(dat.diagonal().info == 'jubba') assert_(dat.flatten().info == 'jubba') - assert_(dat.getfield(np.int32,0).info == 'jubba') + assert_(dat.getfield(np.int32, 0).info == 'jubba') assert_(dat.imag.info == 'jubba') assert_(dat.max(1).info == 'jubba') assert_(dat.mean(1).info == 'jubba') @@ -1071,13 +1071,13 @@ class TestRegression(TestCase): assert_(dat.ravel().info == 'jubba') assert_(dat.real.info == 'jubba') assert_(dat.repeat(2).info == 'jubba') - assert_(dat.reshape((2,4)).info == 'jubba') + assert_(dat.reshape((2, 4)).info == 'jubba') assert_(dat.round().info == 'jubba') assert_(dat.squeeze().info == 'jubba') assert_(dat.std(1).info == 'jubba') assert_(dat.sum(1).info == 'jubba') - assert_(dat.swapaxes(0,1).info == 'jubba') - assert_(dat.take([2,3,5]).info == 'jubba') + assert_(dat.swapaxes(0, 1).info == 'jubba') + assert_(dat.take([2, 3, 5]).info == 'jubba') assert_(dat.transpose().info == 'jubba') assert_(dat.T.info == 'jubba') assert_(dat.var(1).info == 'jubba') @@ -1101,15 +1101,15 @@ class TestRegression(TestCase): def test_char_array_creation(self, level=rlevel): a = np.array('123', dtype='c') - b = np.array(asbytes_nested(['1','2','3'])) - assert_equal(a,b) + b = np.array(asbytes_nested(['1', '2', '3'])) + assert_equal(a, b) def test_unaligned_unicode_access(self, level=rlevel) : """Ticket #825""" - for i in range(1,9) : + for i in range(1, 9) : msg = 'unicode offset: %d chars'%i - t = np.dtype([('a','S%d'%i),('b','U2')]) - x = np.array([(asbytes('a'),sixu('b'))], dtype=t) + t = np.dtype([('a', 'S%d'%i), ('b', 'U2')]) + x = np.array([(asbytes('a'), sixu('b'))], dtype=t) if sys.version_info[0] >= 3: assert_equal(str(x), "[(b'a', 'b')]", err_msg=msg) else: @@ -1138,7 +1138,7 @@ class TestRegression(TestCase): a = np.object_() b = np.object_(3) b2 = np.object_(3.0) - c = np.object_([4,5]) + c = np.object_([4, 5]) d = np.object_([None, {}, []]) assert_(a is None) assert_(type(b) is int) @@ -1149,8 +1149,8 @@ class TestRegression(TestCase): def test_array_resize_method_system_error(self): """Ticket #840 - order should be an invalid keyword.""" - x = np.array([[0,1],[2,3]]) - self.assertRaises(TypeError, x.resize, (2,2), order='C') + x = np.array([[0, 1], [2, 3]]) + self.assertRaises(TypeError, x.resize, (2, 2), order='C') def test_for_zero_length_in_choose(self, level=rlevel): "Ticket #882" @@ -1189,7 +1189,7 @@ class TestRegression(TestCase): #that void scalar contains original data. test_string = np.array("test") test_string_void_scalar = np.core.multiarray.scalar( - np.dtype(("V",test_string.dtype.itemsize)), test_string.tostring()) + np.dtype(("V", test_string.dtype.itemsize)), test_string.tostring()) assert_(test_string_void_scalar.view(test_string.dtype) == test_string) @@ -1252,8 +1252,8 @@ class TestRegression(TestCase): """Ticket #1058""" a = np.fromiter(list(range(10)), dtype='b') b = np.fromiter(list(range(10)), dtype='B') - assert_(np.alltrue(a == np.array([0,1,2,3,4,5,6,7,8,9]))) - assert_(np.alltrue(b == np.array([0,1,2,3,4,5,6,7,8,9]))) + assert_(np.alltrue(a == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))) + assert_(np.alltrue(b == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))) def test_array_from_sequence_scalar_array(self): """Ticket #1078: segfaults when creating an array with a sequence of 0d @@ -1379,9 +1379,9 @@ class TestRegression(TestCase): """Ticket #1299""" stra = 'aaaa' strb = 'bbbb' - x = np.array([[(0,stra),(1,strb)]], 'i8,O') + x = np.array([[(0, stra), (1, strb)]], 'i8,O') x[x.nonzero()] = x.ravel()[:1] - assert_(x[0,1] == x[0,0]) + assert_(x[0, 1] == x[0, 0]) def test_structured_arrays_with_objects2(self): """Ticket #1299 second test""" @@ -1389,7 +1389,7 @@ class TestRegression(TestCase): strb = 'bbbb' numb = sys.getrefcount(strb) numa = sys.getrefcount(stra) - x = np.array([[(0,stra),(1,strb)]], 'i8,O') + x = np.array([[(0, stra), (1, strb)]], 'i8,O') x[x.nonzero()] = x.ravel()[:1] assert_(sys.getrefcount(strb) == numb) assert_(sys.getrefcount(stra) == numa + 2) @@ -1416,7 +1416,7 @@ class TestRegression(TestCase): except ImportError: from md5 import new as md5 - x = np.array([1,2,3], dtype=np.dtype('<i4')) + x = np.array([1, 2, 3], dtype=np.dtype('<i4')) assert_equal(md5(x).hexdigest(), '2a1dd1e1e59d0a384c26951e316cd7e6') def test_numeric_handleError(self): @@ -1436,8 +1436,8 @@ class TestRegression(TestCase): def test_fromiter_comparison(self, level=rlevel): a = np.fromiter(list(range(10)), dtype='b') b = np.fromiter(list(range(10)), dtype='B') - assert_(np.alltrue(a == np.array([0,1,2,3,4,5,6,7,8,9]))) - assert_(np.alltrue(b == np.array([0,1,2,3,4,5,6,7,8,9]))) + assert_(np.alltrue(a == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))) + assert_(np.alltrue(b == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))) def test_fromstring_crash(self): # Ticket #1345: the following should not cause a crash @@ -1471,7 +1471,7 @@ class TestRegression(TestCase): def test_ticket_1434(self): # Check that the out= argument in var and std has an effect - data = np.array(((1,2,3),(4,5,6),(7,8,9))) + data = np.array(((1, 2, 3), (4, 5, 6), (7, 8, 9))) out = np.zeros((3,)) ret = data.var(axis=1, out=out) @@ -1489,7 +1489,7 @@ class TestRegression(TestCase): def test_subclass_int_tuple_assignment(self): # ticket #1563 class Subclass(np.ndarray): - def __new__(cls,i): + def __new__(cls, i): return np.ones((i,)).view(cls) x = Subclass(5) x[(0,)] = 2 # shouldn't raise an exception @@ -1499,14 +1499,14 @@ class TestRegression(TestCase): # ticket #1548 class Subclass(np.ndarray): pass - x = np.array([1,2,3]).view(Subclass) + x = np.array([1, 2, 3]).view(Subclass) y = np.add(x, x, x) assert_equal(id(x), id(y)) def test_take_refcount(self): # ticket #939 a = np.arange(16, dtype=np.float) - a.shape = (4,4) + a.shape = (4, 4) lut = np.ones((5 + 3, 4), np.float) rgba = np.empty(shape=a.shape + (4,), dtype=lut.dtype) c1 = sys.getrefcount(rgba) @@ -1591,7 +1591,7 @@ class TestRegression(TestCase): def test_find_common_type_boolean(self): # Ticket #1695 - assert_(np.find_common_type([],['?','?']) == '?') + assert_(np.find_common_type([], ['?', '?']) == '?') def test_empty_mul(self): a = np.array([1.]) @@ -1636,16 +1636,16 @@ class TestRegression(TestCase): def test_squeeze_contiguous(self): """Similar to GitHub issue #387""" - a = np.zeros((1,2)).squeeze() - b = np.zeros((2,2,2), order='F')[:,:,::2].squeeze() + a = np.zeros((1, 2)).squeeze() + b = np.zeros((2, 2, 2), order='F')[:,:, ::2].squeeze() assert_(a.flags.c_contiguous) assert_(a.flags.f_contiguous) assert_(b.flags.f_contiguous) def test_reduce_contiguous(self): """GitHub issue #387""" - a = np.add.reduce(np.zeros((2,1,2)), (0,1)) - b = np.add.reduce(np.zeros((2,1,2)), 1) + a = np.add.reduce(np.zeros((2, 1, 2)), (0, 1)) + b = np.add.reduce(np.zeros((2, 1, 2)), 1) assert_(a.flags.c_contiguous) assert_(a.flags.f_contiguous) assert_(b.flags.c_contiguous) @@ -1668,12 +1668,12 @@ class TestRegression(TestCase): def test_zerosize_accumulate(self): "Ticket #1733" x = np.array([[42, 0]], dtype=np.uint32) - assert_equal(np.add.accumulate(x[:-1,0]), []) + assert_equal(np.add.accumulate(x[:-1, 0]), []) def test_objectarray_setfield(self): # Setfield directly manipulates the raw array data, # so is invalid for object arrays. - x = np.array([1,2,3], dtype=object) + x = np.array([1, 2, 3], dtype=object) assert_raises(RuntimeError, x.setfield, 4, np.int32, 0) def test_setting_rank0_string(self): @@ -1697,7 +1697,7 @@ class TestRegression(TestCase): s1 = asbytes('black') s2 = asbytes('white') s3 = asbytes('other') - a = np.array([[s1],[s2],[s3]]) + a = np.array([[s1], [s2], [s3]]) assert_equal(a.dtype, np.dtype('S5')) b = a.astype(np.dtype('S0')) assert_equal(b.dtype, np.dtype('S5')) @@ -1706,7 +1706,7 @@ class TestRegression(TestCase): """Ticket #1756 """ s = asbytes('0123456789abcdef') a = np.array([s]*5) - for i in range(1,17): + for i in range(1, 17): a1 = np.array(a, "|S%d"%i) a2 = np.array([s[:i]]*5) assert_equal(a1, a2) @@ -1740,9 +1740,9 @@ class TestRegression(TestCase): def test_ticket_1608(self): "x.flat shouldn't modify data" - x = np.array([[1,2],[3,4]]).T + x = np.array([[1, 2], [3, 4]]).T y = np.array(x.flat) - assert_equal(x, [[1,3],[2,4]]) + assert_equal(x, [[1, 3], [2, 4]]) def test_pickle_string_overwrite(self): import re @@ -1767,10 +1767,10 @@ class TestRegression(TestCase): assert_equal(bytestring[0:1], '\x01'.encode('ascii')) def test_structured_type_to_object(self): - a_rec = np.array([(0,1), (3,2)], dtype='i4,i8') + a_rec = np.array([(0, 1), (3, 2)], dtype='i4,i8') a_obj = np.empty((2,), dtype=object) - a_obj[0] = (0,1) - a_obj[1] = (3,2) + a_obj[0] = (0, 1) + a_obj[1] = (3, 2) # astype records -> object assert_equal(a_rec.astype(object), a_obj) # '=' records -> object @@ -1794,9 +1794,9 @@ class TestRegression(TestCase): b[...] = [[1], [2], [3], [4]] assert_equal(a, b) # The first dimension should get broadcast - a = np.zeros((2,2), dtype=object) - a[...] = [[1,2]] - assert_equal(a, [[1,2], [1,2]]) + a = np.zeros((2, 2), dtype=object) + a[...] = [[1, 2]] + assert_equal(a, [[1, 2], [1, 2]]) def test_memoryleak(self): # Ticket #1917 - ensure that array data doesn't leak diff --git a/numpy/core/tests/test_scalarmath.py b/numpy/core/tests/test_scalarmath.py index 3e1aaef3b..ed038e82d 100644 --- a/numpy/core/tests/test_scalarmath.py +++ b/numpy/core/tests/test_scalarmath.py @@ -16,16 +16,16 @@ class TestTypes(TestCase): def test_types(self, level=1): for atype in types: a = atype(1) - assert_(a == 1, "error with %r: got %r" % (atype,a)) + assert_(a == 1, "error with %r: got %r" % (atype, a)) def test_type_add(self, level=1): # list of types for k, atype in enumerate(types): a_scalar = atype(3) - a_array = np.array([3],dtype=atype) + a_array = np.array([3], dtype=atype) for l, btype in enumerate(types): b_scalar = btype(1) - b_array = np.array([1],dtype=btype) + b_array = np.array([1], dtype=btype) c_scalar = a_scalar + b_scalar c_array = a_array + b_array # It was comparing the type numbers, but the new ufunc @@ -36,13 +36,13 @@ class TestTypes(TestCase): # does not produce properly symmetric results... assert_equal(c_scalar.dtype, c_array.dtype, "error with types (%d/'%c' + %d/'%c')" % - (k,np.dtype(atype).char,l,np.dtype(btype).char)) + (k, np.dtype(atype).char, l, np.dtype(btype).char)) def test_type_create(self, level=1): for k, atype in enumerate(types): - a = np.array([1,2,3],atype) - b = atype([1,2,3]) - assert_equal(a,b) + a = np.array([1, 2, 3], atype) + b = atype([1, 2, 3]) + assert_equal(a, b) class TestBaseMath(TestCase): @@ -81,21 +81,21 @@ class TestPower(TestCase): for t in [np.int8, np.int16, np.float16]: a = t(3) b = a ** 4 - assert_(b == 81, "error with %r: got %r" % (t,b)) + assert_(b == 81, "error with %r: got %r" % (t, b)) def test_large_types(self): for t in [np.int32, np.int64, np.float32, np.float64, np.longdouble]: a = t(51) b = a ** 4 - msg = "error with %r: got %r" % (t,b) + msg = "error with %r: got %r" % (t, b) if np.issubdtype(t, np.integer): assert_(b == 6765201, msg) else: assert_almost_equal(b, 6765201, err_msg=msg) def test_mixed_types(self): - typelist = [np.int8,np.int16,np.float16, - np.float32,np.float64,np.int8, - np.int16,np.int32,np.int64] + typelist = [np.int8, np.int16, np.float16, + np.float32, np.float64, np.int8, + np.int16, np.int32, np.int64] for t1 in typelist: for t2 in typelist: a = t1(3) @@ -132,7 +132,7 @@ class TestConversion(TestCase): l = [1e6, 1e12, 1e18, -1e6, -1e12, -1e18] li = [10**6, 10**12, 10**18, -10**6, -10**12, -10**18] for T in [None, np.float64, np.int64]: - a = np.array(l,dtype=T) + a = np.array(l, dtype=T) assert_equal([int(_m) for _m in a], li) a = np.array(l[:3], dtype=np.uint64) @@ -155,9 +155,9 @@ class TestRepr(object): last_exponent_bit_idx = finfo.nexp storage_bytes = np.dtype(t).itemsize*8 # could add some more types to the list below - for which in ['small denorm','small norm']: + for which in ['small denorm', 'small norm']: # Values from http://en.wikipedia.org/wiki/IEEE_754 - constr = np.array([0x00]*storage_bytes,dtype=np.uint8) + constr = np.array([0x00]*storage_bytes, dtype=np.uint8) if which == 'small denorm': byte = last_fraction_bit_idx // 8 bytebit = 7-(last_fraction_bit_idx % 8) diff --git a/numpy/core/tests/test_shape_base.py b/numpy/core/tests/test_shape_base.py index 921cfaf1c..09bb2f308 100644 --- a/numpy/core/tests/test_shape_base.py +++ b/numpy/core/tests/test_shape_base.py @@ -13,14 +13,14 @@ class TestAtleast1d(TestCase): a = array(1) b = array(2) res = [atleast_1d(a), atleast_1d(b)] - desired = [array([1]),array([2])] + desired = [array([1]), array([2])] assert_array_equal(res, desired) def test_1D_array(self): a = array([1, 2]) b = array([2, 3]) res = [atleast_1d(a), atleast_1d(b)] - desired = [array([1, 2]),array([2, 3])] + desired = [array([1, 2]), array([2, 3])] assert_array_equal(res, desired) def test_2D_array(self): @@ -46,7 +46,7 @@ class TestAtleast1d(TestCase): assert_(atleast_1d(3j).shape == (1,)) assert_(atleast_1d(long(3)).shape == (1,)) assert_(atleast_1d(3.0).shape == (1,)) - assert_(atleast_1d([[2,3],[4,5]]).shape == (2,2)) + assert_(atleast_1d([[2, 3], [4, 5]]).shape == (2, 2)) class TestAtleast2d(TestCase): @@ -83,9 +83,9 @@ class TestAtleast2d(TestCase): def test_r2array(self): """ Test to make sure equivalent Travis O's r2array function """ - assert_(atleast_2d(3).shape == (1,1)) - assert_(atleast_2d([3j,1]).shape == (1,2)) - assert_(atleast_2d([[[3,1],[4,5]],[[3,5],[1,2]]]).shape == (2,2,2)) + assert_(atleast_2d(3).shape == (1, 1)) + assert_(atleast_2d([3j, 1]).shape == (1, 2)) + assert_(atleast_2d([[[3, 1], [4, 5]], [[3, 5], [1, 2]]]).shape == (2, 2, 2)) class TestAtleast3d(TestCase): @@ -107,7 +107,7 @@ class TestAtleast3d(TestCase): a = array([[1, 2], [1, 2]]) b = array([[2, 3], [2, 3]]) res = [atleast_3d(a), atleast_3d(b)] - desired = [a[:,:,newaxis], b[:,:,newaxis]] + desired = [a[:,:, newaxis], b[:,:, newaxis]] assert_array_equal(res, desired) def test_3D_array(self): @@ -124,56 +124,56 @@ class TestHstack(TestCase): def test_0D_array(self): a = array(1) b = array(2) - res=hstack([a,b]) - desired = array([1,2]) - assert_array_equal(res,desired) + res=hstack([a, b]) + desired = array([1, 2]) + assert_array_equal(res, desired) def test_1D_array(self): a = array([1]) b = array([2]) - res=hstack([a,b]) - desired = array([1,2]) - assert_array_equal(res,desired) + res=hstack([a, b]) + desired = array([1, 2]) + assert_array_equal(res, desired) def test_2D_array(self): - a = array([[1],[2]]) - b = array([[1],[2]]) - res=hstack([a,b]) - desired = array([[1,1],[2,2]]) - assert_array_equal(res,desired) + a = array([[1], [2]]) + b = array([[1], [2]]) + res=hstack([a, b]) + desired = array([[1, 1], [2, 2]]) + assert_array_equal(res, desired) class TestVstack(TestCase): def test_0D_array(self): a = array(1) b = array(2) - res=vstack([a,b]) - desired = array([[1],[2]]) - assert_array_equal(res,desired) + res=vstack([a, b]) + desired = array([[1], [2]]) + assert_array_equal(res, desired) def test_1D_array(self): a = array([1]) b = array([2]) - res=vstack([a,b]) - desired = array([[1],[2]]) - assert_array_equal(res,desired) + res=vstack([a, b]) + desired = array([[1], [2]]) + assert_array_equal(res, desired) def test_2D_array(self): - a = array([[1],[2]]) - b = array([[1],[2]]) - res=vstack([a,b]) - desired = array([[1],[2],[1],[2]]) - assert_array_equal(res,desired) + a = array([[1], [2]]) + b = array([[1], [2]]) + res=vstack([a, b]) + desired = array([[1], [2], [1], [2]]) + assert_array_equal(res, desired) def test_2D_array2(self): - a = array([1,2]) - b = array([1,2]) - res=vstack([a,b]) - desired = array([[1,2],[1,2]]) - assert_array_equal(res,desired) + a = array([1, 2]) + b = array([1, 2]) + res=vstack([a, b]) + desired = array([[1, 2], [1, 2]]) + assert_array_equal(res, desired) def test_concatenate_axis_None(): - a = np.arange(4, dtype=np.float64).reshape((2,2)) + a = np.arange(4, dtype=np.float64).reshape((2, 2)) b = list(range(3)) c = ['x'] r = np.concatenate((a, a), axis=None) @@ -185,7 +185,7 @@ def test_concatenate_axis_None(): r = np.concatenate((a, b, c), axis=None) d = array(['0', '1', '2', '3', '0', '1', '2', 'x']) - assert_array_equal(r,d) + assert_array_equal(r, d) def test_concatenate(): diff --git a/numpy/core/tests/test_ufunc.py b/numpy/core/tests/test_ufunc.py index 42a8e1609..7074a60a5 100644 --- a/numpy/core/tests/test_ufunc.py +++ b/numpy/core/tests/test_ufunc.py @@ -24,7 +24,7 @@ class TestUfunc(TestCase): L = 6 x = np.arange(L) idx = np.array(list(zip(np.arange(L - 2), np.arange(L - 2) + 2))).ravel() - assert_array_equal(np.add.reduceat(x,idx)[::2], [1,3,5,7]) + assert_array_equal(np.add.reduceat(x, idx)[::2], [1, 3, 5, 7]) def test_generic_loops(self) : """Test generic loops. @@ -80,7 +80,7 @@ class TestUfunc(TestCase): """ fone = np.exp - ftwo = lambda x,y : x**y + ftwo = lambda x, y : x**y fone_val = 1 ftwo_val = 1 # check unary PyUFunc_f_f. @@ -111,27 +111,27 @@ class TestUfunc(TestCase): # check binary PyUFunc_ff_f. msg = "PyUFunc_ff_f" x = np.ones(10, dtype=np.single)[0::2] - assert_almost_equal(ftwo(x,x), ftwo_val, err_msg=msg) + assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) # check binary PyUFunc_dd_d. msg = "PyUFunc_dd_d" x = np.ones(10, dtype=np.double)[0::2] - assert_almost_equal(ftwo(x,x), ftwo_val, err_msg=msg) + assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) # check binary PyUFunc_gg_g. msg = "PyUFunc_gg_g" x = np.ones(10, dtype=np.longdouble)[0::2] - assert_almost_equal(ftwo(x,x), ftwo_val, err_msg=msg) + assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) # check binary PyUFunc_FF_F. msg = "PyUFunc_FF_F" x = np.ones(10, dtype=np.csingle)[0::2] - assert_almost_equal(ftwo(x,x), ftwo_val, err_msg=msg) + assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) # check binary PyUFunc_DD_D. msg = "PyUFunc_DD_D" x = np.ones(10, dtype=np.cdouble)[0::2] - assert_almost_equal(ftwo(x,x), ftwo_val, err_msg=msg) + assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) # check binary PyUFunc_GG_G. msg = "PyUFunc_GG_G" x = np.ones(10, dtype=np.clongdouble)[0::2] - assert_almost_equal(ftwo(x,x), ftwo_val, err_msg=msg) + assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) # class to use in testing object method loops class foo(object): @@ -154,13 +154,13 @@ class TestUfunc(TestCase): # check binary PyUFunc_OO_O msg = "PyUFunc_OO_O" x = np.ones(10, dtype=np.object)[0::2] - assert_(np.all(np.add(x,x) == 2), msg) + assert_(np.all(np.add(x, x) == 2), msg) # check binary PyUFunc_OO_O_method msg = "PyUFunc_OO_O_method" x = np.zeros(10, dtype=np.object)[0::2] for i in range(len(x)) : x[i] = foo() - assert_(np.all(np.logical_xor(x,x)), msg) + assert_(np.all(np.logical_xor(x, x)), msg) # check PyUFunc_On_Om # fixme -- I don't know how to do this yet @@ -252,117 +252,117 @@ class TestUfunc(TestCase): def test_signature(self): # the arguments to test_signature are: nin, nout, core_signature # pass - assert_equal(umt.test_signature(2,1,"(i),(i)->()"), 1) + assert_equal(umt.test_signature(2, 1, "(i),(i)->()"), 1) # pass. empty core signature; treat as plain ufunc (with trivial core) - assert_equal(umt.test_signature(2,1,"(),()->()"), 0) + assert_equal(umt.test_signature(2, 1, "(),()->()"), 0) # in the following calls, a ValueError should be raised because # of error in core signature # error: extra parenthesis msg = "core_sig: extra parenthesis" try: - ret = umt.test_signature(2,1,"((i)),(i)->()") + ret = umt.test_signature(2, 1, "((i)),(i)->()") assert_equal(ret, None, err_msg=msg) except ValueError: None # error: parenthesis matching msg = "core_sig: parenthesis matching" try: - ret = umt.test_signature(2,1,"(i),)i(->()") + ret = umt.test_signature(2, 1, "(i),)i(->()") assert_equal(ret, None, err_msg=msg) except ValueError: None # error: incomplete signature. letters outside of parenthesis are ignored msg = "core_sig: incomplete signature" try: - ret = umt.test_signature(2,1,"(i),->()") + ret = umt.test_signature(2, 1, "(i),->()") assert_equal(ret, None, err_msg=msg) except ValueError: None # error: incomplete signature. 2 output arguments are specified msg = "core_sig: incomplete signature" try: - ret = umt.test_signature(2,2,"(i),(i)->()") + ret = umt.test_signature(2, 2, "(i),(i)->()") assert_equal(ret, None, err_msg=msg) except ValueError: None # more complicated names for variables - assert_equal(umt.test_signature(2,1,"(i1,i2),(J_1)->(_kAB)"),1) + assert_equal(umt.test_signature(2, 1, "(i1,i2),(J_1)->(_kAB)"), 1) def test_get_signature(self): assert_equal(umt.inner1d.signature, "(i),(i)->()") def test_forced_sig(self): - a = 0.5*np.arange(3,dtype='f8') - assert_equal(np.add(a,0.5), [0.5, 1, 1.5]) - assert_equal(np.add(a,0.5,sig='i',casting='unsafe'), [0, 0, 1]) - assert_equal(np.add(a,0.5,sig='ii->i',casting='unsafe'), [0, 0, 1]) - assert_equal(np.add(a,0.5,sig=('i4',),casting='unsafe'), [0, 0, 1]) - assert_equal(np.add(a,0.5,sig=('i4','i4','i4'), + a = 0.5*np.arange(3, dtype='f8') + assert_equal(np.add(a, 0.5), [0.5, 1, 1.5]) + assert_equal(np.add(a, 0.5, sig='i', casting='unsafe'), [0, 0, 1]) + assert_equal(np.add(a, 0.5, sig='ii->i', casting='unsafe'), [0, 0, 1]) + assert_equal(np.add(a, 0.5, sig=('i4',), casting='unsafe'), [0, 0, 1]) + assert_equal(np.add(a, 0.5, sig=('i4', 'i4', 'i4'), casting='unsafe'), [0, 0, 1]) - b = np.zeros((3,),dtype='f8') - np.add(a,0.5,out=b) + b = np.zeros((3,), dtype='f8') + np.add(a, 0.5, out=b) assert_equal(b, [0.5, 1, 1.5]) b[:] = 0 - np.add(a,0.5,sig='i',out=b, casting='unsafe') + np.add(a, 0.5, sig='i', out=b, casting='unsafe') assert_equal(b, [0, 0, 1]) b[:] = 0 - np.add(a,0.5,sig='ii->i',out=b, casting='unsafe') + np.add(a, 0.5, sig='ii->i', out=b, casting='unsafe') assert_equal(b, [0, 0, 1]) b[:] = 0 - np.add(a,0.5,sig=('i4',),out=b, casting='unsafe') + np.add(a, 0.5, sig=('i4',), out=b, casting='unsafe') assert_equal(b, [0, 0, 1]) b[:] = 0 - np.add(a,0.5,sig=('i4','i4','i4'),out=b, casting='unsafe') + np.add(a, 0.5, sig=('i4', 'i4', 'i4'), out=b, casting='unsafe') assert_equal(b, [0, 0, 1]) def test_inner1d(self): - a = np.arange(6).reshape((2,3)) - assert_array_equal(umt.inner1d(a,a), np.sum(a*a,axis=-1)) + a = np.arange(6).reshape((2, 3)) + assert_array_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1)) a = np.arange(6) - assert_array_equal(umt.inner1d(a,a), np.sum(a*a)) + assert_array_equal(umt.inner1d(a, a), np.sum(a*a)) def test_broadcast(self): msg = "broadcast" - a = np.arange(4).reshape((2,1,2)) - b = np.arange(4).reshape((1,2,2)) - assert_array_equal(umt.inner1d(a,b), np.sum(a*b,axis=-1), err_msg=msg) + a = np.arange(4).reshape((2, 1, 2)) + b = np.arange(4).reshape((1, 2, 2)) + assert_array_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1), err_msg=msg) msg = "extend & broadcast loop dimensions" - b = np.arange(4).reshape((2,2)) - assert_array_equal(umt.inner1d(a,b), np.sum(a*b,axis=-1), err_msg=msg) + b = np.arange(4).reshape((2, 2)) + assert_array_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1), err_msg=msg) msg = "broadcast in core dimensions" - a = np.arange(8).reshape((4,2)) - b = np.arange(4).reshape((4,1)) - assert_array_equal(umt.inner1d(a,b), np.sum(a*b,axis=-1), err_msg=msg) + a = np.arange(8).reshape((4, 2)) + b = np.arange(4).reshape((4, 1)) + assert_array_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1), err_msg=msg) msg = "extend & broadcast core and loop dimensions" - a = np.arange(8).reshape((4,2)) + a = np.arange(8).reshape((4, 2)) b = np.array(7) - assert_array_equal(umt.inner1d(a,b), np.sum(a*b,axis=-1), err_msg=msg) + assert_array_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1), err_msg=msg) msg = "broadcast should fail" - a = np.arange(2).reshape((2,1,1)) - b = np.arange(3).reshape((3,1,1)) + a = np.arange(2).reshape((2, 1, 1)) + b = np.arange(3).reshape((3, 1, 1)) try: - ret = umt.inner1d(a,b) + ret = umt.inner1d(a, b) assert_equal(ret, None, err_msg=msg) except ValueError: None def test_type_cast(self): msg = "type cast" - a = np.arange(6, dtype='short').reshape((2,3)) - assert_array_equal(umt.inner1d(a,a), np.sum(a*a,axis=-1), err_msg=msg) + a = np.arange(6, dtype='short').reshape((2, 3)) + assert_array_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1), err_msg=msg) msg = "type cast on one argument" - a = np.arange(6).reshape((2,3)) + a = np.arange(6).reshape((2, 3)) b = a+0.1 - assert_array_almost_equal(umt.inner1d(a,a), np.sum(a*a,axis=-1), + assert_array_almost_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1), err_msg=msg) def test_endian(self): msg = "big endian" - a = np.arange(6, dtype='>i4').reshape((2,3)) - assert_array_equal(umt.inner1d(a,a), np.sum(a*a,axis=-1), err_msg=msg) + a = np.arange(6, dtype='>i4').reshape((2, 3)) + assert_array_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1), err_msg=msg) msg = "little endian" - a = np.arange(6, dtype='<i4').reshape((2,3)) - assert_array_equal(umt.inner1d(a,a), np.sum(a*a,axis=-1), err_msg=msg) + a = np.arange(6, dtype='<i4').reshape((2, 3)) + assert_array_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1), err_msg=msg) # Output should always be native-endian Ba = np.arange(1, dtype='>f8') @@ -379,71 +379,71 @@ class TestUfunc(TestCase): def test_incontiguous_array(self): msg = "incontiguous memory layout of array" - x = np.arange(64).reshape((2,2,2,2,2,2)) - a = x[:,0,:,0,:,0] - b = x[:,1,:,1,:,1] - a[0,0,0] = -1 + x = np.arange(64).reshape((2, 2, 2, 2, 2, 2)) + a = x[:, 0,:, 0,:, 0] + b = x[:, 1,:, 1,:, 1] + a[0, 0, 0] = -1 msg2 = "make sure it references to the original array" - assert_equal(x[0,0,0,0,0,0], -1, err_msg=msg2) - assert_array_equal(umt.inner1d(a,b), np.sum(a*b,axis=-1), err_msg=msg) - x = np.arange(24).reshape(2,3,4) + assert_equal(x[0, 0, 0, 0, 0, 0], -1, err_msg=msg2) + assert_array_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1), err_msg=msg) + x = np.arange(24).reshape(2, 3, 4) a = x.T b = x.T - a[0,0,0] = -1 - assert_equal(x[0,0,0], -1, err_msg=msg2) - assert_array_equal(umt.inner1d(a,b), np.sum(a*b,axis=-1), err_msg=msg) + a[0, 0, 0] = -1 + assert_equal(x[0, 0, 0], -1, err_msg=msg2) + assert_array_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1), err_msg=msg) def test_output_argument(self): msg = "output argument" - a = np.arange(12).reshape((2,3,2)) - b = np.arange(4).reshape((2,1,2)) + 1 - c = np.zeros((2,3),dtype='int') - umt.inner1d(a,b,c) - assert_array_equal(c, np.sum(a*b,axis=-1), err_msg=msg) + a = np.arange(12).reshape((2, 3, 2)) + b = np.arange(4).reshape((2, 1, 2)) + 1 + c = np.zeros((2, 3), dtype='int') + umt.inner1d(a, b, c) + assert_array_equal(c, np.sum(a*b, axis=-1), err_msg=msg) c[:] = -1 - umt.inner1d(a,b,out=c) - assert_array_equal(c, np.sum(a*b,axis=-1), err_msg=msg) + umt.inner1d(a, b, out=c) + assert_array_equal(c, np.sum(a*b, axis=-1), err_msg=msg) msg = "output argument with type cast" - c = np.zeros((2,3),dtype='int16') - umt.inner1d(a,b,c) - assert_array_equal(c, np.sum(a*b,axis=-1), err_msg=msg) + c = np.zeros((2, 3), dtype='int16') + umt.inner1d(a, b, c) + assert_array_equal(c, np.sum(a*b, axis=-1), err_msg=msg) c[:] = -1 - umt.inner1d(a,b,out=c) - assert_array_equal(c, np.sum(a*b,axis=-1), err_msg=msg) + umt.inner1d(a, b, out=c) + assert_array_equal(c, np.sum(a*b, axis=-1), err_msg=msg) msg = "output argument with incontiguous layout" - c = np.zeros((2,3,4),dtype='int16') - umt.inner1d(a,b,c[...,0]) - assert_array_equal(c[...,0], np.sum(a*b,axis=-1), err_msg=msg) + c = np.zeros((2, 3, 4), dtype='int16') + umt.inner1d(a, b, c[..., 0]) + assert_array_equal(c[..., 0], np.sum(a*b, axis=-1), err_msg=msg) c[:] = -1 - umt.inner1d(a,b,out=c[...,0]) - assert_array_equal(c[...,0], np.sum(a*b,axis=-1), err_msg=msg) + umt.inner1d(a, b, out=c[..., 0]) + assert_array_equal(c[..., 0], np.sum(a*b, axis=-1), err_msg=msg) def test_innerwt(self): - a = np.arange(6).reshape((2,3)) - b = np.arange(10,16).reshape((2,3)) - w = np.arange(20,26).reshape((2,3)) - assert_array_equal(umt.innerwt(a,b,w), np.sum(a*b*w,axis=-1)) - a = np.arange(100,124).reshape((2,3,4)) - b = np.arange(200,224).reshape((2,3,4)) - w = np.arange(300,324).reshape((2,3,4)) - assert_array_equal(umt.innerwt(a,b,w), np.sum(a*b*w,axis=-1)) + a = np.arange(6).reshape((2, 3)) + b = np.arange(10, 16).reshape((2, 3)) + w = np.arange(20, 26).reshape((2, 3)) + assert_array_equal(umt.innerwt(a, b, w), np.sum(a*b*w, axis=-1)) + a = np.arange(100, 124).reshape((2, 3, 4)) + b = np.arange(200, 224).reshape((2, 3, 4)) + w = np.arange(300, 324).reshape((2, 3, 4)) + assert_array_equal(umt.innerwt(a, b, w), np.sum(a*b*w, axis=-1)) def test_innerwt_empty(self): """Test generalized ufunc with zero-sized operands""" a = np.array([], dtype='f8') b = np.array([], dtype='f8') w = np.array([], dtype='f8') - assert_array_equal(umt.innerwt(a,b,w), np.sum(a*b*w,axis=-1)) + assert_array_equal(umt.innerwt(a, b, w), np.sum(a*b*w, axis=-1)) def test_matrix_multiply(self): self.compare_matrix_multiply_results(np.long) self.compare_matrix_multiply_results(np.double) def compare_matrix_multiply_results(self, tp): - d1 = np.array(rand(2,3,4), dtype=tp) - d2 = np.array(rand(2,3,4), dtype=tp) + d1 = np.array(rand(2, 3, 4), dtype=tp) + d2 = np.array(rand(2, 3, 4), dtype=tp) msg = "matrix multiply on type %s" % d1.dtype.name def permute_n(n): @@ -466,14 +466,14 @@ class TestUfunc(TestCase): base = slice_n(n-1) for sl in base: ret += (sl+(slice(None),),) - ret += (sl+(slice(0,1),),) + ret += (sl+(slice(0, 1),),) return ret - def broadcastable(s1,s2): + def broadcastable(s1, s2): return s1 == s2 or s1 == 1 or s2 == 1 permute_3 = permute_n(3) - slice_3 = slice_n(3) + ((slice(None,None,-1),)*3,) + slice_3 = slice_n(3) + ((slice(None, None, -1),)*3,) ref = True for p1 in permute_3: @@ -487,9 +487,9 @@ class TestUfunc(TestCase): if broadcastable(a1.shape[-1], a2.shape[-2]) and \ broadcastable(a1.shape[0], a2.shape[0]): assert_array_almost_equal( - umt.matrix_multiply(a1,a2), - np.sum(a2[...,np.newaxis].swapaxes(-3,-1) * - a1[...,np.newaxis,:], axis=-1), + umt.matrix_multiply(a1, a2), + np.sum(a2[..., np.newaxis].swapaxes(-3, -1) * + a1[..., np.newaxis,:], axis=-1), err_msg = msg+' %s %s' % (str(a1.shape), str(a2.shape))) @@ -587,9 +587,9 @@ class TestUfunc(TestCase): def test_casting_out_param(self): # Test that it's possible to do casts on output - a = np.ones((200,100), np.int64) - b = np.ones((200,100), np.int64) - c = np.ones((200,100), np.float64) + a = np.ones((200, 100), np.int64) + b = np.ones((200, 100), np.int64) + c = np.ones((200, 100), np.float64) np.add(a, b, out=c) assert_equal(c, 2) @@ -604,13 +604,13 @@ class TestUfunc(TestCase): b = np.ones(7) c = np.zeros(7) np.add(a, b, out=c, where=(a % 2 == 1)) - assert_equal(c, [0,2,0,4,0,6,0]) + assert_equal(c, [0, 2, 0, 4, 0, 6, 0]) - a = np.arange(4).reshape(2,2) + 2 - np.power(a, [2,3], out=a, where=[[0,1],[1,0]]) + a = np.arange(4).reshape(2, 2) + 2 + np.power(a, [2, 3], out=a, where=[[0, 1], [1, 0]]) assert_equal(a, [[2, 27], [16, 5]]) # Broadcasting the where= parameter - np.subtract(a, 2, out=a, where=[True,False]) + np.subtract(a, 2, out=a, where=[True, False]) assert_equal(a, [[0, 27], [14, 5]]) def test_where_param_buffer_output(self): @@ -621,76 +621,76 @@ class TestUfunc(TestCase): a = np.ones(10, np.int64) b = np.ones(10, np.int64) c = 1.5 * np.ones(10, np.float64) - np.add(a, b, out=c, where=[1,0,0,1,0,0,1,1,1,0]) - assert_equal(c, [2,1.5,1.5,2,1.5,1.5,2,2,2,1.5]) + np.add(a, b, out=c, where=[1, 0, 0, 1, 0, 0, 1, 1, 1, 0]) + assert_equal(c, [2, 1.5, 1.5, 2, 1.5, 1.5, 2, 2, 2, 1.5]) def check_identityless_reduction(self, a): # np.minimum.reduce is a identityless reduction # Verify that it sees the zero at various positions a[...] = 1 - a[1,0,0] = 0 + a[1, 0, 0] = 0 assert_equal(np.minimum.reduce(a, axis=None), 0) - assert_equal(np.minimum.reduce(a, axis=(0,1)), [0,1,1,1]) - assert_equal(np.minimum.reduce(a, axis=(0,2)), [0,1,1]) - assert_equal(np.minimum.reduce(a, axis=(1,2)), [1,0]) + assert_equal(np.minimum.reduce(a, axis=(0, 1)), [0, 1, 1, 1]) + assert_equal(np.minimum.reduce(a, axis=(0, 2)), [0, 1, 1]) + assert_equal(np.minimum.reduce(a, axis=(1, 2)), [1, 0]) assert_equal(np.minimum.reduce(a, axis=0), - [[0,1,1,1], [1,1,1,1], [1,1,1,1]]) + [[0, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]) assert_equal(np.minimum.reduce(a, axis=1), - [[1,1,1,1], [0,1,1,1]]) + [[1, 1, 1, 1], [0, 1, 1, 1]]) assert_equal(np.minimum.reduce(a, axis=2), - [[1,1,1], [0,1,1]]) + [[1, 1, 1], [0, 1, 1]]) assert_equal(np.minimum.reduce(a, axis=()), a) a[...] = 1 - a[0,1,0] = 0 + a[0, 1, 0] = 0 assert_equal(np.minimum.reduce(a, axis=None), 0) - assert_equal(np.minimum.reduce(a, axis=(0,1)), [0,1,1,1]) - assert_equal(np.minimum.reduce(a, axis=(0,2)), [1,0,1]) - assert_equal(np.minimum.reduce(a, axis=(1,2)), [0,1]) + assert_equal(np.minimum.reduce(a, axis=(0, 1)), [0, 1, 1, 1]) + assert_equal(np.minimum.reduce(a, axis=(0, 2)), [1, 0, 1]) + assert_equal(np.minimum.reduce(a, axis=(1, 2)), [0, 1]) assert_equal(np.minimum.reduce(a, axis=0), - [[1,1,1,1], [0,1,1,1], [1,1,1,1]]) + [[1, 1, 1, 1], [0, 1, 1, 1], [1, 1, 1, 1]]) assert_equal(np.minimum.reduce(a, axis=1), - [[0,1,1,1], [1,1,1,1]]) + [[0, 1, 1, 1], [1, 1, 1, 1]]) assert_equal(np.minimum.reduce(a, axis=2), - [[1,0,1], [1,1,1]]) + [[1, 0, 1], [1, 1, 1]]) assert_equal(np.minimum.reduce(a, axis=()), a) a[...] = 1 - a[0,0,1] = 0 + a[0, 0, 1] = 0 assert_equal(np.minimum.reduce(a, axis=None), 0) - assert_equal(np.minimum.reduce(a, axis=(0,1)), [1,0,1,1]) - assert_equal(np.minimum.reduce(a, axis=(0,2)), [0,1,1]) - assert_equal(np.minimum.reduce(a, axis=(1,2)), [0,1]) + assert_equal(np.minimum.reduce(a, axis=(0, 1)), [1, 0, 1, 1]) + assert_equal(np.minimum.reduce(a, axis=(0, 2)), [0, 1, 1]) + assert_equal(np.minimum.reduce(a, axis=(1, 2)), [0, 1]) assert_equal(np.minimum.reduce(a, axis=0), - [[1,0,1,1], [1,1,1,1], [1,1,1,1]]) + [[1, 0, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]) assert_equal(np.minimum.reduce(a, axis=1), - [[1,0,1,1], [1,1,1,1]]) + [[1, 0, 1, 1], [1, 1, 1, 1]]) assert_equal(np.minimum.reduce(a, axis=2), - [[0,1,1], [1,1,1]]) + [[0, 1, 1], [1, 1, 1]]) assert_equal(np.minimum.reduce(a, axis=()), a) def test_identityless_reduction_corder(self): - a = np.empty((2,3,4), order='C') + a = np.empty((2, 3, 4), order='C') self.check_identityless_reduction(a) def test_identityless_reduction_forder(self): - a = np.empty((2,3,4), order='F') + a = np.empty((2, 3, 4), order='F') self.check_identityless_reduction(a) def test_identityless_reduction_otherorder(self): - a = np.empty((2,4,3), order='C').swapaxes(1,2) + a = np.empty((2, 4, 3), order='C').swapaxes(1, 2) self.check_identityless_reduction(a) def test_identityless_reduction_noncontig(self): - a = np.empty((3,5,4), order='C').swapaxes(1,2) + a = np.empty((3, 5, 4), order='C').swapaxes(1, 2) a = a[1:, 1:, 1:] self.check_identityless_reduction(a) def test_identityless_reduction_noncontig_unaligned(self): a = np.empty((3*4*5*8 + 1,), dtype='i1') a = a[1:].view(dtype='f8') - a.shape = (3,4,5) + a.shape = (3, 4, 5) a = a[1:, 1:, 1:] self.check_identityless_reduction(a) @@ -706,7 +706,7 @@ class TestUfunc(TestCase): res = np.divide.reduce(a, axis=()) assert_equal(res, a) - assert_raises(ValueError, np.divide.reduce, a, axis=(0,1)) + assert_raises(ValueError, np.divide.reduce, a, axis=(0, 1)) def test_reduce_zero_axis(self): # If we have a n x m array and do a reduction with axis=1, then we are @@ -803,11 +803,11 @@ class TestUfunc(TestCase): assert_raises(TypeError, test_add, a, b) def test_operand_flags(self): - a = np.arange(16, dtype='l').reshape(4,4) - b = np.arange(9, dtype='l').reshape(3,3) - opflag_tests.inplace_add(a[:-1,:-1], b) - assert_equal(a, np.array([[0,2,4,3],[7,9,11,7], - [14,16,18,11],[12,13,14,15]], dtype='l')) + a = np.arange(16, dtype='l').reshape(4, 4) + b = np.arange(9, dtype='l').reshape(3, 3) + opflag_tests.inplace_add(a[:-1, :-1], b) + assert_equal(a, np.array([[0, 2, 4, 3], [7, 9, 11, 7], + [14, 16, 18, 11], [12, 13, 14, 15]], dtype='l')) a = np.array(0) opflag_tests.inplace_add(a, 3) @@ -818,20 +818,20 @@ class TestUfunc(TestCase): def test_struct_ufunc(self): import numpy.core.struct_ufunc_test as struct_ufunc - a = np.array([(1,2,3)], dtype='u8,u8,u8') - b = np.array([(1,2,3)], dtype='u8,u8,u8') + a = np.array([(1, 2, 3)], dtype='u8,u8,u8') + b = np.array([(1, 2, 3)], dtype='u8,u8,u8') result = struct_ufunc.add_triplet(a, b) assert_equal(result, np.array([(2, 4, 6)], dtype='u8,u8,u8')) def test_custom_ufunc(self): - a = np.array([rational(1,2), rational(1,3), rational(1,4)], + a = np.array([rational(1, 2), rational(1, 3), rational(1, 4)], dtype=rational); - b = np.array([rational(1,2), rational(1,3), rational(1,4)], + b = np.array([rational(1, 2), rational(1, 3), rational(1, 4)], dtype=rational); result = test_add_rationals(a, b) - expected = np.array([rational(1), rational(2,3), rational(1,2)], + expected = np.array([rational(1), rational(2, 3), rational(1, 2)], dtype=rational); assert_equal(result, expected); @@ -868,95 +868,95 @@ class TestUfunc(TestCase): def test_inplace_fancy_indexing(self): a = np.arange(10) - np.add.at(a, [2,5,2], 1) + np.add.at(a, [2, 5, 2], 1) assert_equal(a, [0, 1, 4, 3, 4, 6, 6, 7, 8, 9]) a = np.arange(10) - b = np.array([100,100,100]) - np.add.at(a, [2,5,2], b) + b = np.array([100, 100, 100]) + np.add.at(a, [2, 5, 2], b) assert_equal(a, [0, 1, 202, 3, 4, 105, 6, 7, 8, 9]) - a = np.arange(9).reshape(3,3) - b = np.array([[100,100,100],[200,200,200],[300,300,300]]) - np.add.at(a, (slice(None), [1,2,1]), b) - assert_equal(a, [[0,201,102], [3,404,205], [6,607,308]]) + a = np.arange(9).reshape(3, 3) + b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]]) + np.add.at(a, (slice(None), [1, 2, 1]), b) + assert_equal(a, [[0, 201, 102], [3, 404, 205], [6, 607, 308]]) - a = np.arange(27).reshape(3,3,3) - b = np.array([100,200,300]) - np.add.at(a, (slice(None), slice(None), [1,2,1]), b) + a = np.arange(27).reshape(3, 3, 3) + b = np.array([100, 200, 300]) + np.add.at(a, (slice(None), slice(None), [1, 2, 1]), b) assert_equal(a, - [[[0,401,202], - [3,404,205], - [6,407,208]], - - [[9, 410,211], - [12,413,214], - [15,416,217]], - - [[18,419,220], - [21,422,223], - [24,425,226]]]) - - a = np.arange(9).reshape(3,3) - b = np.array([[100,100,100],[200,200,200],[300,300,300]]) - np.add.at(a, ([1,2,1], slice(None)), b) - assert_equal(a, [[0,1,2], [403,404,405], [206,207,208]]) - - a = np.arange(27).reshape(3,3,3) - b = np.array([100,200,300]) - np.add.at(a, (slice(None), [1,2,1], slice(None)), b) + [[[0, 401, 202], + [3, 404, 205], + [6, 407, 208]], + + [[9, 410, 211], + [12, 413, 214], + [15, 416, 217]], + + [[18, 419, 220], + [21, 422, 223], + [24, 425, 226]]]) + + a = np.arange(9).reshape(3, 3) + b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]]) + np.add.at(a, ([1, 2, 1], slice(None)), b) + assert_equal(a, [[0, 1, 2], [403, 404, 405], [206, 207, 208]]) + + a = np.arange(27).reshape(3, 3, 3) + b = np.array([100, 200, 300]) + np.add.at(a, (slice(None), [1, 2, 1], slice(None)), b) assert_equal(a, [[[0, 1, 2 ], - [203,404,605], - [106,207,308]], + [203, 404, 605], + [106, 207, 308]], [[9, 10, 11 ], - [212,413,614], - [115,216,317]], + [212, 413, 614], + [115, 216, 317]], [[18, 19, 20 ], - [221,422,623], - [124,225,326]]]) + [221, 422, 623], + [124, 225, 326]]]) - a = np.arange(9).reshape(3,3) - b = np.array([100,200,300]) - np.add.at(a, (0, [1,2,1]), b) - assert_equal(a, [[0,401,202], [3,4,5], [6,7,8]]) + a = np.arange(9).reshape(3, 3) + b = np.array([100, 200, 300]) + np.add.at(a, (0, [1, 2, 1]), b) + assert_equal(a, [[0, 401, 202], [3, 4, 5], [6, 7, 8]]) - a = np.arange(27).reshape(3,3,3) - b = np.array([100,200,300]) - np.add.at(a, ([1,2,1], 0, slice(None)), b) + a = np.arange(27).reshape(3, 3, 3) + b = np.array([100, 200, 300]) + np.add.at(a, ([1, 2, 1], 0, slice(None)), b) assert_equal(a, [[[0, 1, 2], [3, 4, 5], [6, 7, 8]], - [[209,410,611], + [[209, 410, 611], [12, 13, 14], [15, 16, 17]], - [[118,219,320], + [[118, 219, 320], [21, 22, 23], [24, 25, 26]]]) - a = np.arange(27).reshape(3,3,3) - b = np.array([100,200,300]) + a = np.arange(27).reshape(3, 3, 3) + b = np.array([100, 200, 300]) np.add.at(a, (slice(None), slice(None), slice(None)), b) assert_equal(a, - [[[100,201,302], - [103,204,305], - [106,207,308]], + [[[100, 201, 302], + [103, 204, 305], + [106, 207, 308]], - [[109,210,311], - [112,213,314], - [115,216,317]], + [[109, 210, 311], + [112, 213, 314], + [115, 216, 317]], - [[118,219,320], - [121,222,323], - [124,225,326]]]) + [[118, 219, 320], + [121, 222, 323], + [124, 225, 326]]]) a = np.arange(10) - np.negative.at(a, [2,5,2]) + np.negative.at(a, [2, 5, 2]) assert_equal(a, [0, 1, 2, 3, 4, -5, 6, 7, 8, 9]) # Test 0-dim array @@ -969,7 +969,7 @@ class TestUfunc(TestCase): # Test mixed dtypes a = np.arange(10) - np.power.at(a, [1,2,3,2], 3.5) + np.power.at(a, [1, 2, 3, 2], 3.5) assert_equal(a, np.array([0, 1, 4414, 46, 4, 5, 6, 7, 8, 9])) # Test boolean indexing and boolean ufuncs @@ -985,19 +985,19 @@ class TestUfunc(TestCase): # Test empty subspace orig = np.arange(4) - a = orig[:,None][:,0:0] - np.add.at(a, [0,1], 3) + a = orig[:, None][:, 0:0] + np.add.at(a, [0, 1], 3) assert_array_equal(orig, np.arange(4)) # Test with swapped byte order - index = np.array([1,2,1], np.dtype('i').newbyteorder()) - values = np.array([1,2,3,4], np.dtype('f').newbyteorder()) + index = np.array([1, 2, 1], np.dtype('i').newbyteorder()) + values = np.array([1, 2, 3, 4], np.dtype('f').newbyteorder()) np.add.at(values, index, 3) - assert_array_equal(values, [1,8,6,4]) + assert_array_equal(values, [1, 8, 6, 4]) # Test exception thrown values = np.array(['a', 1], dtype=np.object) - self.assertRaises(TypeError, np.add.at, values, [0,1], 1) + self.assertRaises(TypeError, np.add.at, values, [0, 1], 1) assert_array_equal(values, np.array(['a', 1], dtype=np.object)) if __name__ == "__main__": diff --git a/numpy/core/tests/test_umath.py b/numpy/core/tests/test_umath.py index b2d47d052..eb18304ea 100644 --- a/numpy/core/tests/test_umath.py +++ b/numpy/core/tests/test_umath.py @@ -78,7 +78,7 @@ class TestDivision(TestCase): 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) + 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) @@ -169,14 +169,14 @@ class TestPower(TestCase): assert_complex_equal(np.power(zero, -1+0.2j), cnan) def test_fast_power(self): - x = np.array([1,2,3], np.int16) + x = np.array([1, 2, 3], np.int16) assert_((x**2.00001).dtype is (x**2.0).dtype) class TestLog2(TestCase): 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'] : + 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) @@ -186,7 +186,7 @@ class TestExp2(TestCase): 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'] : + 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) @@ -198,7 +198,7 @@ class TestLogAddExp2(_FilterInvalids): 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]) : + 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)) @@ -208,7 +208,7 @@ class TestLogAddExp2(_FilterInvalids): x = [1000000, -1000000, 1000200, -1000200] y = [1000200, -1000200, 1000000, -1000000] z = [1000200, -1000000, 1000200, -1000000] - for dt in ['f','d','g'] : + for dt in ['f', 'd', 'g'] : logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) @@ -220,7 +220,7 @@ class TestLogAddExp2(_FilterInvalids): y = [inf, inf, -inf, -inf, 1, inf, 1, -inf] z = [inf, inf, inf, -inf, inf, inf, 1, 1] with np.errstate(invalid='ignore'): - for dt in ['f','d','g'] : + for dt in ['f', 'd', 'g'] : logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) @@ -238,7 +238,7 @@ class TestLog(TestCase): 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'] : + for dt in ['f', 'd', 'g'] : log2_ = 0.69314718055994530943 xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt)*log2_ @@ -249,7 +249,7 @@ class TestExp(TestCase): 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'] : + for dt in ['f', 'd', 'g'] : log2_ = 0.69314718055994530943 xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt)*log2_ @@ -261,7 +261,7 @@ class TestLogAddExp(_FilterInvalids): 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]) : + 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)) @@ -271,7 +271,7 @@ class TestLogAddExp(_FilterInvalids): x = [1000000, -1000000, 1000200, -1000200] y = [1000200, -1000200, 1000000, -1000000] z = [1000200, -1000000, 1000200, -1000000] - for dt in ['f','d','g'] : + for dt in ['f', 'd', 'g'] : logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) @@ -283,7 +283,7 @@ class TestLogAddExp(_FilterInvalids): y = [inf, inf, -inf, -inf, 1, inf, 1, -inf] z = [inf, inf, inf, -inf, inf, inf, 1, 1] with np.errstate(invalid='ignore'): - for dt in ['f','d','g'] : + for dt in ['f', 'd', 'g'] : logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) @@ -479,8 +479,8 @@ class TestMaximum(_FilterInvalids): 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) + 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 @@ -526,8 +526,8 @@ class TestMinimum(_FilterInvalids): 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) + 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 @@ -573,8 +573,8 @@ class TestFmax(_FilterInvalids): 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) + 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 @@ -615,8 +615,8 @@ class TestFmin(_FilterInvalids): 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) + 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 @@ -784,21 +784,21 @@ class TestSpecialMethods(TestCase): b = B() c = C() f = ncu.minimum - self.assertTrue(type(f(x,x)) is np.ndarray) - self.assertTrue(type(f(x,a)) is A) - self.assertTrue(type(f(x,b)) is B) - self.assertTrue(type(f(x,c)) is C) - self.assertTrue(type(f(a,x)) is A) - self.assertTrue(type(f(b,x)) is B) - self.assertTrue(type(f(c,x)) is C) - - self.assertTrue(type(f(a,a)) is A) - self.assertTrue(type(f(a,b)) is B) - self.assertTrue(type(f(b,a)) is B) - self.assertTrue(type(f(b,b)) is B) - self.assertTrue(type(f(b,c)) is C) - self.assertTrue(type(f(c,b)) is C) - self.assertTrue(type(f(c,c)) is C) + self.assertTrue(type(f(x, x)) is np.ndarray) + self.assertTrue(type(f(x, a)) is A) + self.assertTrue(type(f(x, b)) is B) + self.assertTrue(type(f(x, c)) is C) + self.assertTrue(type(f(a, x)) is A) + self.assertTrue(type(f(b, x)) is B) + self.assertTrue(type(f(c, x)) is C) + + self.assertTrue(type(f(a, a)) is A) + self.assertTrue(type(f(a, b)) is B) + self.assertTrue(type(f(b, a)) is B) + self.assertTrue(type(f(b, b)) is B) + self.assertTrue(type(f(b, c)) is C) + self.assertTrue(type(f(c, b)) is C) + self.assertTrue(type(f(c, c)) is C) self.assertTrue(type(ncu.exp(a) is A)) self.assertTrue(type(ncu.exp(b) is B)) @@ -871,9 +871,9 @@ class TestSpecialMethods(TestCase): class TestChoose(TestCase): 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])) + 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(): @@ -966,7 +966,7 @@ class TestComplexFunctions(object): 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)) + 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""" @@ -1046,8 +1046,8 @@ class TestComplexFunctions(object): 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) + 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) @@ -1081,7 +1081,7 @@ class TestSubclass(TestCase): self = np.ndarray.__new__(subtype, shape, dtype=object) self.fill(0) return self - a = simple((3,4)) + 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, @@ -1237,12 +1237,12 @@ def test_pos_nan(): def test_reduceat(): """Test bug in reduceat when structured arrays are not copied.""" - db = np.dtype([('name', 'S11'),('time', np.int64), ('value', np.float32)]) + 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] + indx = [0, 7, 15, 25] h2 = [] val1 = indx[0] @@ -1271,7 +1271,7 @@ def test_reduceat_empty(): 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)) + x = np.ones((5, 2)) result = np.add.reduceat(x, [], axis=0) assert_equal(result.dtype, x.dtype) assert_equal(result.shape, (0, 2)) diff --git a/numpy/core/tests/test_umath_complex.py b/numpy/core/tests/test_umath_complex.py index ebf805c6d..4f3da4397 100644 --- a/numpy/core/tests/test_umath_complex.py +++ b/numpy/core/tests/test_umath_complex.py @@ -484,7 +484,7 @@ class TestCarg(object): # carg(+- 0 + yi) returns -pi/2 for y < 0 yield check_real_value, ncu._arg, np.PZERO, -1, 0.5 * np.pi, False - yield check_real_value, ncu._arg, np.NZERO, -1,-0.5 * np.pi, False + yield check_real_value, ncu._arg, np.NZERO, -1, -0.5 * np.pi, False #def test_branch_cuts(self): # _check_branch_cut(ncu._arg, -1, 1j, -1, 1) diff --git a/numpy/core/tests/test_unicode.py b/numpy/core/tests/test_unicode.py index b29fe2010..d184b3a9f 100644 --- a/numpy/core/tests/test_unicode.py +++ b/numpy/core/tests/test_unicode.py @@ -84,9 +84,9 @@ class create_zeros(object): def test_zerosMD(self): """Check creation of multi-dimensional objects""" - ua = zeros((2,3,4), dtype='U%s' % self.ulen) - self.content_check(ua, ua[0,0,0], 4*self.ulen*2*3*4) - self.content_check(ua, ua[-1,-1,-1], 4*self.ulen*2*3*4) + ua = zeros((2, 3, 4), dtype='U%s' % self.ulen) + self.content_check(ua, ua[0, 0, 0], 4*self.ulen*2*3*4) + self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4) class test_create_zeros_1(create_zeros, TestCase): @@ -145,8 +145,8 @@ class create_values(object): def test_valuesMD(self): """Check creation of multi-dimensional objects with values""" ua = array([[[self.ucs_value*self.ulen]*2]*3]*4, dtype='U%s' % self.ulen) - self.content_check(ua, ua[0,0,0], 4*self.ulen*2*3*4) - self.content_check(ua, ua[-1,-1,-1], 4*self.ulen*2*3*4) + self.content_check(ua, ua[0, 0, 0], 4*self.ulen*2*3*4) + self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4) class test_create_values_1_ucs2(create_values, TestCase): @@ -232,11 +232,11 @@ class assign_values(object): def test_valuesMD(self): """Check assignment of multi-dimensional objects with values""" - ua = zeros((2,3,4), dtype='U%s' % self.ulen) - ua[0,0,0] = self.ucs_value*self.ulen - self.content_check(ua, ua[0,0,0], 4*self.ulen*2*3*4) - ua[-1,-1,-1] = self.ucs_value*self.ulen - self.content_check(ua, ua[-1,-1,-1], 4*self.ulen*2*3*4) + ua = zeros((2, 3, 4), dtype='U%s' % self.ulen) + ua[0, 0, 0] = self.ucs_value*self.ulen + self.content_check(ua, ua[0, 0, 0], 4*self.ulen*2*3*4) + ua[-1, -1, -1] = self.ucs_value*self.ulen + self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4) class test_assign_values_1_ucs2(assign_values, TestCase): @@ -310,8 +310,8 @@ class byteorder_values: ua = array([[[self.ucs_value*self.ulen]*2]*3]*4, dtype='U%s' % self.ulen) ua2 = ua.newbyteorder() - self.assertTrue(ua[0,0,0] != ua2[0,0,0]) - self.assertTrue(ua[-1,-1,-1] != ua2[-1,-1,-1]) + self.assertTrue(ua[0, 0, 0] != ua2[0, 0, 0]) + self.assertTrue(ua[-1, -1, -1] != ua2[-1, -1, -1]) ua3 = ua2.newbyteorder() # Arrays must be equal after the round-trip assert_equal(ua, ua3) |