diff options
Diffstat (limited to 'numpy')
196 files changed, 14449 insertions, 34836 deletions
diff --git a/numpy/__init__.py b/numpy/__init__.py index 1029652c8..772c75b63 100644 --- a/numpy/__init__.py +++ b/numpy/__init__.py @@ -121,6 +121,17 @@ class ModuleDeprecationWarning(DeprecationWarning): pass +class VisibleDeprecationWarning(UserWarning): + """Visible deprecation warning. + + By default, python will not show deprecation warnings, so this class + can be used when a very visible warning is helpful, for example because + the usage is most likely a user bug. + + """ + pass + + # oldnumeric and numarray were removed in 1.9. In case some packages import # but do not use them, we define them here for backward compatibility. oldnumeric = 'removed' @@ -145,7 +156,7 @@ else: except ImportError: msg = """Error importing numpy: you should not try to import numpy from its source directory; please exit the numpy source tree, and relaunch - your python intepreter from there.""" + your python interpreter from there.""" raise ImportError(msg) from .version import git_revision as __git_revision__ from .version import version as __version__ @@ -157,7 +168,9 @@ else: return loader(*packages, **options) from . import add_newdocs - __all__ = ['add_newdocs', 'ModuleDeprecationWarning'] + __all__ = ['add_newdocs', + 'ModuleDeprecationWarning', + 'VisibleDeprecationWarning'] pkgload.__doc__ = PackageLoader.__call__.__doc__ diff --git a/numpy/_import_tools.py b/numpy/_import_tools.py index 3343f6c05..526217359 100644 --- a/numpy/_import_tools.py +++ b/numpy/_import_tools.py @@ -111,13 +111,13 @@ class PackageLoader(object): depend_dict[name] = getattr(info_module, 'depends', []) package_names = [] - for name in depend_dict.keys(): + for name in list(depend_dict.keys()): if not depend_dict[name]: package_names.append(name) del depend_dict[name] while depend_dict: - for name, lst in depend_dict.items(): + for name, lst in list(depend_dict.items()): new_lst = [n for n in lst if n in depend_dict] if not new_lst: package_names.append(name) diff --git a/numpy/add_newdocs.py b/numpy/add_newdocs.py index 62ca6dca3..86ea4b8b6 100644 --- a/numpy/add_newdocs.py +++ b/numpy/add_newdocs.py @@ -1598,6 +1598,14 @@ add_newdoc('numpy.core.multiarray', 'can_cast', out : bool True if cast can occur according to the casting rule. + Notes + ----- + Starting in NumPy 1.9, can_cast function now returns False in 'safe' + casting mode for integer/float dtype and string dtype if the string dtype + length is not long enough to store the max integer/float value converted + to a string. Previously can_cast in 'safe' mode returned True for + integer/float dtype and a string dtype of any length. + See also -------- dtype, result_type @@ -1618,7 +1626,7 @@ add_newdoc('numpy.core.multiarray', 'can_cast', >>> np.can_cast('i8', 'f4') False >>> np.can_cast('i4', 'S4') - True + False Casting scalars @@ -1693,6 +1701,11 @@ add_newdoc('numpy.core.multiarray', 'promote_types', Notes ----- .. versionadded:: 1.6.0 + Starting in NumPy 1.9, promote_types function now returns a valid string + length when given an integer or float dtype as one argument and a string + dtype as another argument. Previously it always returned the input string + dtype, even if it wasn't long enough to store the max integer/float value + converted to a string. See Also -------- @@ -1709,10 +1722,8 @@ add_newdoc('numpy.core.multiarray', 'promote_types', >>> np.promote_types('>i8', '<c8') dtype('complex128') - >>> np.promote_types('i1', 'S8') - Traceback (most recent call last): - File "<stdin>", line 1, in <module> - TypeError: invalid type promotion + >>> np.promote_types('i4', 'S8') + dtype('S11') """) @@ -2078,6 +2089,8 @@ add_newdoc('numpy.core', 'einsum', array([ 30, 80, 130, 180, 230]) >>> np.dot(a, b) array([ 30, 80, 130, 180, 230]) + >>> np.einsum('...j,j', a, b) + array([ 30, 80, 130, 180, 230]) >>> np.einsum('ji', c) array([[0, 3], @@ -2147,6 +2160,18 @@ add_newdoc('numpy.core', 'einsum', [ 4796., 5162.], [ 4928., 5306.]]) + >>> a = np.arange(6).reshape((3,2)) + >>> b = np.arange(12).reshape((4,3)) + >>> np.einsum('ki,jk->ij', a, b) + array([[10, 28, 46, 64], + [13, 40, 67, 94]]) + >>> np.einsum('ki,...k->i...', a, b) + array([[10, 28, 46, 64], + [13, 40, 67, 94]]) + >>> np.einsum('k...,jk', a, b) + array([[10, 28, 46, 64], + [13, 40, 67, 94]]) + """) add_newdoc('numpy.core', 'alterdot', @@ -3053,7 +3078,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('argsort', add_newdoc('numpy.core.multiarray', 'ndarray', ('argpartition', """ - a.argpartition(kth, axis=-1, kind='quickselect', order=None) + a.argpartition(kth, axis=-1, kind='introselect', order=None) Returns the indices that would partition this array. @@ -3112,6 +3137,13 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('astype', is a new array of the same shape as the input array, with dtype, order given by `dtype`, `order`. + Notes + ----- + Starting in NumPy 1.9, astype method now returns an error if the string + dtype to cast to is not long enough in 'safe' casting mode to hold the max + value of integer/float array that is being casted. Previously the casting + was allowed even if the result was truncated. + Raises ------ ComplexWarning @@ -4372,7 +4404,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('tofile', sep : str Separator between array items for text output. If "" (empty), a binary file is written, equivalent to - ``file.write(a.tostring())``. + ``file.write(a.tobytes())``. format : str Format string for text file output. Each entry in the array is formatted to text by first converting @@ -4426,8 +4458,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('tolist', """)) -add_newdoc('numpy.core.multiarray', 'ndarray', ('tostring', - """ +tobytesdoc = """ a.tostring(order='C') Construct a Python string containing the raw data bytes in the array. @@ -4438,9 +4469,11 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('tostring', unless the F_CONTIGUOUS flag in the array is set, in which case it means 'Fortran' order. + {deprecated} + Parameters ---------- - order : {'C', 'F', None}, optional + order : {{'C', 'F', None}}, optional Order of the data for multidimensional arrays: C, Fortran, or the same as for the original array. @@ -4452,15 +4485,23 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('tostring', Examples -------- >>> x = np.array([[0, 1], [2, 3]]) - >>> x.tostring() + >>> x.tobytes() '\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x03\\x00\\x00\\x00' - >>> x.tostring('C') == x.tostring() + >>> x.tobytes('C') == x.tobytes() True - >>> x.tostring('F') + >>> x.tobytes('F') '\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x03\\x00\\x00\\x00' - """)) + """ +add_newdoc('numpy.core.multiarray', 'ndarray', + ('tostring', tobytesdoc.format(deprecated= + 'This function is a compatibility ' + 'alias for tobytes. Despite its ' + 'name it returns bytes not ' + 'strings.'))) +add_newdoc('numpy.core.multiarray', 'ndarray', + ('tobytes', tobytesdoc.format(deprecated='.. versionadded:: 1.9.0'))) add_newdoc('numpy.core.multiarray', 'ndarray', ('trace', """ @@ -4652,45 +4693,6 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('view', # ############################################################################## -add_newdoc('numpy.core.umath', 'frexp', - """ - Return normalized fraction and exponent of 2 of input array, element-wise. - - Returns (`out1`, `out2`) from equation ``x` = out1 * 2**out2``. - - Parameters - ---------- - x : array_like - Input array. - - Returns - ------- - (out1, out2) : tuple of ndarrays, (float, int) - `out1` is a float array with values between -1 and 1. - `out2` is an int array which represent the exponent of 2. - - See Also - -------- - ldexp : Compute ``y = x1 * 2**x2``, the inverse of `frexp`. - - Notes - ----- - Complex dtypes are not supported, they will raise a TypeError. - - Examples - -------- - >>> x = np.arange(9) - >>> y1, y2 = np.frexp(x) - >>> y1 - array([ 0. , 0.5 , 0.5 , 0.75 , 0.5 , 0.625, 0.75 , 0.875, - 0.5 ]) - >>> y2 - array([0, 1, 2, 2, 3, 3, 3, 3, 4]) - >>> y1 * 2**y2 - array([ 0., 1., 2., 3., 4., 5., 6., 7., 8.]) - - """) - add_newdoc('numpy.core.umath', 'frompyfunc', """ frompyfunc(func, nin, nout) @@ -4731,44 +4733,6 @@ add_newdoc('numpy.core.umath', 'frompyfunc', """) -add_newdoc('numpy.core.umath', 'ldexp', - """ - Compute y = x1 * 2**x2. - - Parameters - ---------- - x1 : array_like - The array of multipliers. - x2 : array_like - The array of exponents. - - Returns - ------- - y : array_like - The output array, the result of ``x1 * 2**x2``. - - See Also - -------- - frexp : Return (y1, y2) from ``x = y1 * 2**y2``, the inverse of `ldexp`. - - Notes - ----- - Complex dtypes are not supported, they will raise a TypeError. - - `ldexp` is useful as the inverse of `frexp`, if used by itself it is - more clear to simply use the expression ``x1 * 2**x2``. - - Examples - -------- - >>> np.ldexp(5, np.arange(4)) - array([ 5., 10., 20., 40.], dtype=float32) - - >>> x = np.arange(6) - >>> np.ldexp(*np.frexp(x)) - array([ 0., 1., 2., 3., 4., 5.]) - - """) - add_newdoc('numpy.core.umath', 'geterrobj', """ geterrobj() @@ -5672,12 +5636,13 @@ add_newdoc('numpy.core', 'ufunc', ('reduceat', ``ufunc.reduce(a[indices[i]:indices[i+1]])``, which becomes the i-th generalized "row" parallel to `axis` in the final result (i.e., in a 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if - `axis = 1`, it becomes the i-th column). There are two exceptions to this: + `axis = 1`, it becomes the i-th column). There are three exceptions to this: - * when ``i = len(indices) - 1`` (so for the last index), - ``indices[i+1] = a.shape[axis]``. - * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is - simply ``a[indices[i]]``. + * when ``i = len(indices) - 1`` (so for the last index), + ``indices[i+1] = a.shape[axis]``. + * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is + simply ``a[indices[i]]``. + * if ``indices[i] >= len(a)`` or ``indices[i] < 0``, an error is raised. The shape of the output depends on the size of `indices`, and may be larger than `a` (this happens if ``len(indices) > a.shape[axis]``). @@ -5836,6 +5801,8 @@ add_newdoc('numpy.core', 'ufunc', ('at', increment the first element once because of buffering, whereas `add.at(a, [0,0], 1)` will increment the first element twice. + .. versionadded:: 1.8.0 + Parameters ---------- a : array_like @@ -6151,7 +6118,19 @@ add_newdoc('numpy.core.multiarray', 'dtype', ('itemsize', add_newdoc('numpy.core.multiarray', 'dtype', ('kind', """ - A character code (one of 'biufcSUV') identifying the general kind of data. + A character code (one of 'biufcOSUV') identifying the general kind of data. + + = ====================== + b boolean + i signed integer + u unsigned integer + f floating-point + c complex floating-point + O object + S (byte-)string + U Unicode + V void + = ====================== """)) diff --git a/numpy/compat/py3k.py b/numpy/compat/py3k.py index f5ac3f9f8..4607d9502 100644 --- a/numpy/compat/py3k.py +++ b/numpy/compat/py3k.py @@ -36,7 +36,7 @@ if sys.version_info[0] >= 3: return str(s) def isfileobj(f): - return isinstance(f, (io.FileIO, io.BufferedReader)) + return isinstance(f, (io.FileIO, io.BufferedReader, io.BufferedWriter)) def open_latin1(filename, mode='r'): return open(filename, mode=mode, encoding='iso-8859-1') diff --git a/numpy/compat/tests/test_compat.py b/numpy/compat/tests/test_compat.py new file mode 100644 index 000000000..3df142e04 --- /dev/null +++ b/numpy/compat/tests/test_compat.py @@ -0,0 +1,19 @@ +from os.path import join + +from numpy.compat import isfileobj +from numpy.testing import TestCase, assert_ +from numpy.testing.utils import tempdir + + +def test_isfileobj(): + with tempdir(prefix="numpy_test_compat_") as folder: + filename = join(folder, 'a.bin') + + with open(filename, 'wb') as f: + assert_(isfileobj(f)) + + with open(filename, 'ab') as f: + assert_(isfileobj(f)) + + with open(filename, 'rb') as f: + assert_(isfileobj(f)) diff --git a/numpy/core/__init__.py b/numpy/core/__init__.py index 79bc72a8c..0b8d5bb17 100644 --- a/numpy/core/__init__.py +++ b/numpy/core/__init__.py @@ -52,7 +52,11 @@ bench = Tester().bench # The name numpy.core._ufunc_reconstruct must be # available for unpickling to work. def _ufunc_reconstruct(module, name): - mod = __import__(module) + # The `fromlist` kwarg is required to ensure that `mod` points to the + # inner-most module rather than the parent package when module name is + # nested. This makes it possible to pickle non-toplevel ufuncs such as + # scipy.special.expit for instance. + mod = __import__(module, fromlist=[name]) return getattr(mod, name) def _ufunc_reduce(func): diff --git a/numpy/core/_methods.py b/numpy/core/_methods.py index a064f70c7..00716e1b4 100644 --- a/numpy/core/_methods.py +++ b/numpy/core/_methods.py @@ -12,29 +12,33 @@ from numpy.core import umath as um from numpy.core.numeric import asanyarray from numpy.core import numerictypes as nt +# save those O(100) nanoseconds! +umr_maximum = um.maximum.reduce +umr_minimum = um.minimum.reduce +umr_sum = um.add.reduce +umr_prod = um.multiply.reduce +umr_any = um.logical_or.reduce +umr_all = um.logical_and.reduce + +# avoid keyword arguments to speed up parsing, saves about 15%-20% for very +# small reductions def _amax(a, axis=None, out=None, keepdims=False): - return um.maximum.reduce(a, axis=axis, - out=out, keepdims=keepdims) + return umr_maximum(a, axis, None, out, keepdims) def _amin(a, axis=None, out=None, keepdims=False): - return um.minimum.reduce(a, axis=axis, - out=out, keepdims=keepdims) + return umr_minimum(a, axis, None, out, keepdims) def _sum(a, axis=None, dtype=None, out=None, keepdims=False): - return um.add.reduce(a, axis=axis, dtype=dtype, - out=out, keepdims=keepdims) + return umr_sum(a, axis, dtype, out, keepdims) def _prod(a, axis=None, dtype=None, out=None, keepdims=False): - return um.multiply.reduce(a, axis=axis, dtype=dtype, - out=out, keepdims=keepdims) + return umr_prod(a, axis, dtype, out, keepdims) def _any(a, axis=None, dtype=None, out=None, keepdims=False): - return um.logical_or.reduce(a, axis=axis, dtype=dtype, out=out, - keepdims=keepdims) + return umr_any(a, axis, dtype, out, keepdims) def _all(a, axis=None, dtype=None, out=None, keepdims=False): - return um.logical_and.reduce(a, axis=axis, dtype=dtype, out=out, - keepdims=keepdims) + return umr_all(a, axis, dtype, out, keepdims) def _count_reduce_items(arr, axis): if axis is None: @@ -59,12 +63,14 @@ def _mean(a, axis=None, dtype=None, out=None, keepdims=False): if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)): dtype = mu.dtype('f8') - ret = um.add.reduce(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims) + ret = umr_sum(arr, axis, dtype, out, keepdims) if isinstance(ret, mu.ndarray): ret = um.true_divide( ret, rcount, out=ret, casting='unsafe', subok=False) - else: + elif hasattr(ret, 'dtype'): ret = ret.dtype.type(ret / rcount) + else: + ret = ret / rcount return ret @@ -83,7 +89,7 @@ def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): # Compute the mean. # Note that if dtype is not of inexact type then arraymean will # not be either. - arrmean = um.add.reduce(arr, axis=axis, dtype=dtype, keepdims=True) + arrmean = umr_sum(arr, axis, dtype, keepdims=True) if isinstance(arrmean, mu.ndarray): arrmean = um.true_divide( arrmean, rcount, out=arrmean, casting='unsafe', subok=False) @@ -98,7 +104,7 @@ def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): x = um.multiply(x, um.conjugate(x), out=x).real else: x = um.multiply(x, x, out=x) - ret = um.add.reduce(x, axis=axis, dtype=dtype, out=out, keepdims=keepdims) + ret = umr_sum(x, axis, dtype, out, keepdims) # Compute degrees of freedom and make sure it is not negative. rcount = max([rcount - ddof, 0]) @@ -107,8 +113,10 @@ def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): if isinstance(ret, mu.ndarray): ret = um.true_divide( ret, rcount, out=ret, casting='unsafe', subok=False) - else: + elif hasattr(ret, 'dtype'): ret = ret.dtype.type(ret / rcount) + else: + ret = ret / rcount return ret @@ -118,7 +126,9 @@ def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): if isinstance(ret, mu.ndarray): ret = um.sqrt(ret, out=ret) - else: + elif hasattr(ret, 'dtype'): ret = ret.dtype.type(um.sqrt(ret)) + else: + ret = um.sqrt(ret) return ret diff --git a/numpy/core/bento.info b/numpy/core/bento.info index 6089b5d7b..299bd8ca5 100644 --- a/numpy/core/bento.info +++ b/numpy/core/bento.info @@ -11,10 +11,12 @@ Library: CompiledLibrary: npysort Sources: src/private/npy_partition.h.src, + src/private/npy_binsearch.h.src, src/npysort/quicksort.c.src, src/npysort/mergesort.c.src, src/npysort/heapsort.c.src, - src/npysort/selection.c.src + src/npysort/selection.c.src, + src/npysort/binsearch.c.src Extension: multiarray Sources: src/multiarray/multiarraymodule_onefile.c diff --git a/numpy/core/bscript b/numpy/core/bscript index a2222eb66..5230aa428 100644 --- a/numpy/core/bscript +++ b/numpy/core/bscript @@ -416,7 +416,7 @@ def pre_build(context): "lib", "npy-pkg-config", "mlib.ini")) inifile_npymath = context.local_node.declare(os.path.join( "lib", "npy-pkg-config", "npymath.ini")) - context.register_outputs("numpy_gen_inifiles", "numpyconfig", + context.register_outputs("numpy_gen_inifiles", "numpyconfig", [inifile_mlib, inifile_npymath]) context.register_category("numpy_gen_headers") @@ -444,6 +444,7 @@ def pre_build(context): bld(target="multiarray_templates", source=multiarray_templates) if ENABLE_SEPARATE_COMPILATION: sources = [pjoin('src', 'multiarray', 'arrayobject.c'), + pjoin('src', 'multiarray', 'alloc.c'), pjoin('src', 'multiarray', 'arraytypes.c.src'), pjoin('src', 'multiarray', 'array_assign.c'), pjoin('src', 'multiarray', 'array_assign_array.c'), @@ -491,7 +492,11 @@ def pre_build(context): return context.default_builder(extension, includes=includes, source=sources, - use="npysort npymath") + use="npysort npymath", + defines=['_FILE_OFFSET_BITS=64', + '_LARGEFILE_SOURCE=1', + '_LARGEFILE64_SOURCE=1'] + ) context.register_builder("multiarray", builder_multiarray) def build_ufunc(extension): @@ -501,6 +506,7 @@ def pre_build(context): name="ufunc_api") ufunc_templates = [ + "src/umath/loops.h.src", "src/umath/loops.c.src", "src/umath/funcs.inc.src", "src/umath/simd.inc.src"] @@ -513,6 +519,7 @@ def pre_build(context): includes = ["src/umath", "src/multiarray", "src/private"] if ENABLE_SEPARATE_COMPILATION: sources = [ + pjoin("src", "umath", "loops.h.src"), pjoin("src", "umath", "loops.c.src"), pjoin('src', 'umath', 'reduction.c'), pjoin('src', 'umath', 'ufunc_object.c'), diff --git a/numpy/core/code_generators/cversions.txt b/numpy/core/code_generators/cversions.txt index 6ab422055..acfced812 100644 --- a/numpy/core/code_generators/cversions.txt +++ b/numpy/core/code_generators/cversions.txt @@ -4,16 +4,28 @@ 0x00000001 = 603580d224763e58c5e7147f804dc0f5 0x00000002 = 8ecb29306758515ae69749c803a75da1 0x00000003 = bf22c0d05b31625d2a7015988d61ce5a + # Starting from here, the hash is defined from numpy_api.full_api dict # version 4 added neighborhood iterators and PyArray_Correlate2 0x00000004 = 3d8940bf7b0d2a4e25be4338c14c3c85 0x00000005 = 77e2e846db87f25d7cf99f9d812076f0 + # Version 6 (NumPy 1.6) added new iterator, half float and casting functions, # PyArray_CountNonzero, PyArray_NewLikeArray and PyArray_MatrixProduct2. 0x00000006 = e61d5dc51fa1c6459328266e215d6987 + # Version 7 (NumPy 1.7) improved datetime64, misc utilities. 0x00000007 = e396ba3912dcf052eaee1b0b203a7724 + # Version 8 Added interface to MapIterObject 0x00000008 = 17321775fc884de0b1eda478cd61c74b -# Version 9 Added interface for partition functions, PyArray_NEW_ZEROED -0x00000009 = 327bd114df09c2eb7a0bcc6901e2a3ed + +# Version 9 (NumPy 1.8) Added interface for partition functions, +# PyArray_NEW_ZEROED, commented out as the hash changed in +# Numpy 1.9 due to annotation. +#0x00000009 = 327bd114df09c2eb7a0bcc6901e2a3ed + +# Version 9 (NumPy 1.9) Added function annotations. +# The interface has not changed, but the hash is different due to +# the annotations, so keep the previous version number. +0x00000009 = 982c4ebb6e7e4c194bf46b1535b4ef1b diff --git a/numpy/core/code_generators/genapi.py b/numpy/core/code_generators/genapi.py index ad054920a..84bd042f5 100644 --- a/numpy/core/code_generators/genapi.py +++ b/numpy/core/code_generators/genapi.py @@ -23,7 +23,8 @@ from os.path import join __docformat__ = 'restructuredtext' # The files under src/ that are scanned for API functions -API_FILES = [join('multiarray', 'array_assign_array.c'), +API_FILES = [join('multiarray', 'alloc.c'), + join('multiarray', 'array_assign_array.c'), join('multiarray', 'array_assign_scalar.c'), join('multiarray', 'arrayobject.c'), join('multiarray', 'arraytypes.c.src'), @@ -74,6 +75,29 @@ def remove_whitespace(s): def _repl(str): return str.replace('Bool', 'npy_bool') + +class StealRef: + def __init__(self, arg): + self.arg = arg # counting from 1 + + def __str__(self): + try: + return ' '.join('NPY_STEALS_REF_TO_ARG(%d)' % x for x in self.arg) + except TypeError: + return 'NPY_STEALS_REF_TO_ARG(%d)' % self.arg + + +class NonNull: + def __init__(self, arg): + self.arg = arg # counting from 1 + + def __str__(self): + try: + return ' '.join('NPY_GCC_NONNULL(%d)' % x for x in self.arg) + except TypeError: + return 'NPY_GCC_NONNULL(%d)' % self.arg + + class Function(object): def __init__(self, name, return_type, args, doc=''): self.name = name @@ -350,9 +374,10 @@ NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[2]; return astr class FunctionApi(object): - def __init__(self, name, index, return_type, args, api_name): + def __init__(self, name, index, annotations, return_type, args, api_name): self.name = name self.index = index + self.annotations = annotations self.return_type = return_type self.args = args self.api_name = api_name @@ -377,17 +402,21 @@ class FunctionApi(object): return " (void *) %s" % self.name def internal_define(self): + annstr = [] + for a in self.annotations: + annstr.append(str(a)) + annstr = ' '.join(annstr) astr = """\ -NPY_NO_EXPORT %s %s \\\n (%s);""" % (self.return_type, - self.name, - self._argtypes_string()) +NPY_NO_EXPORT %s %s %s \\\n (%s);""" % (annstr, self.return_type, + self.name, + self._argtypes_string()) return astr def order_dict(d): """Order dict by its values.""" o = list(d.items()) def _key(x): - return (x[1], x[0]) + return x[1] + (x[0],) return sorted(o, key=_key) def merge_api_dicts(dicts): @@ -419,7 +448,7 @@ Same index has been used twice in api definition: %s raise ValueError(msg) # No 'hole' in the indexes may be allowed, and it must starts at 0 - indexes = set(d.values()) + indexes = set(v[0] for v in d.values()) expected = set(range(len(indexes))) if not indexes == expected: diff = expected.symmetric_difference(indexes) @@ -434,7 +463,7 @@ def get_api_functions(tagname, api_dict): functions.extend(find_functions(f, tagname)) dfunctions = [] for func in functions: - o = api_dict[func.name] + o = api_dict[func.name][0] dfunctions.append( (o, func) ) dfunctions.sort() return [a[1] for a in dfunctions] @@ -444,13 +473,9 @@ def fullapi_hash(api_dicts): of the list of items in the API (as a string).""" a = [] for d in api_dicts: - def sorted_by_values(d): - """Sort a dictionary by its values. Assume the dictionary items is of - the form func_name -> order""" - return sorted(d.items(), key=lambda x_y: (x_y[1], x_y[0])) - for name, index in sorted_by_values(d): + for name, data in order_dict(d): a.extend(name) - a.extend(str(index)) + a.extend(','.join(map(str, data))) return md5new(''.join(a).encode('ascii')).hexdigest() diff --git a/numpy/core/code_generators/generate_numpy_api.py b/numpy/core/code_generators/generate_numpy_api.py index ce270a6a0..415cbf7fc 100644 --- a/numpy/core/code_generators/generate_numpy_api.py +++ b/numpy/core/code_generators/generate_numpy_api.py @@ -8,8 +8,9 @@ from genapi import \ import numpy_api +# use annotated api when running under cpychecker h_template = r""" -#ifdef _MULTIARRAYMODULE +#if defined(_MULTIARRAYMODULE) || defined(WITH_CPYCHECKER_STEALS_REFERENCE_TO_ARG_ATTRIBUTE) typedef struct { PyObject_HEAD @@ -183,13 +184,11 @@ def do_generate_api(targets, sources): doc_file = targets[2] global_vars = sources[0] - global_vars_types = sources[1] - scalar_bool_values = sources[2] - types_api = sources[3] - multiarray_funcs = sources[4] + scalar_bool_values = sources[1] + types_api = sources[2] + multiarray_funcs = sources[3] - # Remove global_vars_type: not a api dict - multiarray_api = sources[:1] + sources[2:] + multiarray_api = sources[:] module_list = [] extension_list = [] @@ -208,18 +207,22 @@ def do_generate_api(targets, sources): multiarray_api_dict = {} for f in numpyapi_list: name = f.name - index = multiarray_funcs[name] - multiarray_api_dict[f.name] = FunctionApi(f.name, index, f.return_type, + index = multiarray_funcs[name][0] + annotations = multiarray_funcs[name][1:] + multiarray_api_dict[f.name] = FunctionApi(f.name, index, annotations, + f.return_type, f.args, api_name) - for name, index in global_vars.items(): - type = global_vars_types[name] + for name, val in global_vars.items(): + index, type = val multiarray_api_dict[name] = GlobalVarApi(name, index, type, api_name) - for name, index in scalar_bool_values.items(): + for name, val in scalar_bool_values.items(): + index = val[0] multiarray_api_dict[name] = BoolValuesApi(name, index, api_name) - for name, index in types_api.items(): + for name, val in types_api.items(): + index = val[0] multiarray_api_dict[name] = TypeApi(name, index, 'PyTypeObject', api_name) if len(multiarray_api_dict) != len(multiarray_api_index): diff --git a/numpy/core/code_generators/generate_ufunc_api.py b/numpy/core/code_generators/generate_ufunc_api.py index 6305385af..b594fccf7 100644 --- a/numpy/core/code_generators/generate_ufunc_api.py +++ b/numpy/core/code_generators/generate_ufunc_api.py @@ -172,11 +172,13 @@ def do_generate_api(targets, sources): api_name = 'PyUFunc_API' for f in ufunc_api_list: name = f.name - index = ufunc_api_index[name] - ufunc_api_dict[name] = FunctionApi(f.name, index, f.return_type, - f.args, api_name) + index = ufunc_api_index[name][0] + annotations = ufunc_api_index[name][1:] + ufunc_api_dict[name] = FunctionApi(f.name, index, annotations, + f.return_type, f.args, api_name) - for name, index in numpy_api.ufunc_types_api.items(): + for name, val in numpy_api.ufunc_types_api.items(): + index = val[0] ufunc_api_dict[name] = TypeApi(name, index, 'PyTypeObject', api_name) # set up object API diff --git a/numpy/core/code_generators/generate_umath.py b/numpy/core/code_generators/generate_umath.py index e02cb8709..e3c9cf28b 100644 --- a/numpy/core/code_generators/generate_umath.py +++ b/numpy/core/code_generators/generate_umath.py @@ -369,7 +369,7 @@ defdict = { 'negative': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.negative'), - 'PyUFunc_SimpleUnaryOperationTypeResolver', + 'PyUFunc_NegativeTypeResolver', TD(bints+flts+timedeltaonly), TD(cmplx, f='neg'), TD(O, f='PyNumber_Negative'), diff --git a/numpy/core/code_generators/numpy_api.py b/numpy/core/code_generators/numpy_api.py index 791bc6ffc..cd6d2f176 100644 --- a/numpy/core/code_generators/numpy_api.py +++ b/numpy/core/code_generators/numpy_api.py @@ -14,64 +14,64 @@ exception, so it should hopefully not get unnoticed). """ from __future__ import division, absolute_import, print_function -multiarray_global_vars = { - 'NPY_NUMUSERTYPES': 7, - 'NPY_DEFAULT_ASSIGN_CASTING': 292, -} +from code_generators.genapi import StealRef, NonNull -multiarray_global_vars_types = { - 'NPY_NUMUSERTYPES': 'int', - 'NPY_DEFAULT_ASSIGN_CASTING': 'NPY_CASTING', +# index, type +multiarray_global_vars = { + 'NPY_NUMUSERTYPES': (7, 'int'), + 'NPY_DEFAULT_ASSIGN_CASTING': (292, 'NPY_CASTING'), } multiarray_scalar_bool_values = { - '_PyArrayScalar_BoolValues': 9 + '_PyArrayScalar_BoolValues': (9,) } +# index, annotations +# please mark functions that have been checked to not need any annotations multiarray_types_api = { - 'PyBigArray_Type': 1, - 'PyArray_Type': 2, - 'PyArrayDescr_Type': 3, - 'PyArrayFlags_Type': 4, - 'PyArrayIter_Type': 5, - 'PyArrayMultiIter_Type': 6, - 'PyBoolArrType_Type': 8, - 'PyGenericArrType_Type': 10, - 'PyNumberArrType_Type': 11, - 'PyIntegerArrType_Type': 12, - 'PySignedIntegerArrType_Type': 13, - 'PyUnsignedIntegerArrType_Type': 14, - 'PyInexactArrType_Type': 15, - 'PyFloatingArrType_Type': 16, - 'PyComplexFloatingArrType_Type': 17, - 'PyFlexibleArrType_Type': 18, - 'PyCharacterArrType_Type': 19, - 'PyByteArrType_Type': 20, - 'PyShortArrType_Type': 21, - 'PyIntArrType_Type': 22, - 'PyLongArrType_Type': 23, - 'PyLongLongArrType_Type': 24, - 'PyUByteArrType_Type': 25, - 'PyUShortArrType_Type': 26, - 'PyUIntArrType_Type': 27, - 'PyULongArrType_Type': 28, - 'PyULongLongArrType_Type': 29, - 'PyFloatArrType_Type': 30, - 'PyDoubleArrType_Type': 31, - 'PyLongDoubleArrType_Type': 32, - 'PyCFloatArrType_Type': 33, - 'PyCDoubleArrType_Type': 34, - 'PyCLongDoubleArrType_Type': 35, - 'PyObjectArrType_Type': 36, - 'PyStringArrType_Type': 37, - 'PyUnicodeArrType_Type': 38, - 'PyVoidArrType_Type': 39, + 'PyBigArray_Type': (1,), + 'PyArray_Type': (2,), + 'PyArrayDescr_Type': (3,), + 'PyArrayFlags_Type': (4,), + 'PyArrayIter_Type': (5,), + 'PyArrayMultiIter_Type': (6,), + 'PyBoolArrType_Type': (8,), + 'PyGenericArrType_Type': (10,), + 'PyNumberArrType_Type': (11,), + 'PyIntegerArrType_Type': (12,), + 'PySignedIntegerArrType_Type': (13,), + 'PyUnsignedIntegerArrType_Type': (14,), + 'PyInexactArrType_Type': (15,), + 'PyFloatingArrType_Type': (16,), + 'PyComplexFloatingArrType_Type': (17,), + 'PyFlexibleArrType_Type': (18,), + 'PyCharacterArrType_Type': (19,), + 'PyByteArrType_Type': (20,), + 'PyShortArrType_Type': (21,), + 'PyIntArrType_Type': (22,), + 'PyLongArrType_Type': (23,), + 'PyLongLongArrType_Type': (24,), + 'PyUByteArrType_Type': (25,), + 'PyUShortArrType_Type': (26,), + 'PyUIntArrType_Type': (27,), + 'PyULongArrType_Type': (28,), + 'PyULongLongArrType_Type': (29,), + 'PyFloatArrType_Type': (30,), + 'PyDoubleArrType_Type': (31,), + 'PyLongDoubleArrType_Type': (32,), + 'PyCFloatArrType_Type': (33,), + 'PyCDoubleArrType_Type': (34,), + 'PyCLongDoubleArrType_Type': (35,), + 'PyObjectArrType_Type': (36,), + 'PyStringArrType_Type': (37,), + 'PyUnicodeArrType_Type': (38,), + 'PyVoidArrType_Type': (39,), # End 1.5 API - 'PyTimeIntegerArrType_Type': 214, - 'PyDatetimeArrType_Type': 215, - 'PyTimedeltaArrType_Type': 216, - 'PyHalfArrType_Type': 217, - 'NpyIter_Type': 218, + 'PyTimeIntegerArrType_Type': (214,), + 'PyDatetimeArrType_Type': (215,), + 'PyTimedeltaArrType_Type': (216,), + 'PyHalfArrType_Type': (217,), + 'NpyIter_Type': (218,), # End 1.6 API } @@ -80,318 +80,318 @@ multiarray_types_api = { #define _PyArrayScalar_BoolValues ((PyBoolScalarObject *)PyArray_API[8]) multiarray_funcs_api = { - 'PyArray_GetNDArrayCVersion': 0, - 'PyArray_SetNumericOps': 40, - 'PyArray_GetNumericOps': 41, - 'PyArray_INCREF': 42, - 'PyArray_XDECREF': 43, - 'PyArray_SetStringFunction': 44, - 'PyArray_DescrFromType': 45, - 'PyArray_TypeObjectFromType': 46, - 'PyArray_Zero': 47, - 'PyArray_One': 48, - 'PyArray_CastToType': 49, - 'PyArray_CastTo': 50, - 'PyArray_CastAnyTo': 51, - 'PyArray_CanCastSafely': 52, - 'PyArray_CanCastTo': 53, - 'PyArray_ObjectType': 54, - 'PyArray_DescrFromObject': 55, - 'PyArray_ConvertToCommonType': 56, - 'PyArray_DescrFromScalar': 57, - 'PyArray_DescrFromTypeObject': 58, - 'PyArray_Size': 59, - 'PyArray_Scalar': 60, - 'PyArray_FromScalar': 61, - 'PyArray_ScalarAsCtype': 62, - 'PyArray_CastScalarToCtype': 63, - 'PyArray_CastScalarDirect': 64, - 'PyArray_ScalarFromObject': 65, - 'PyArray_GetCastFunc': 66, - 'PyArray_FromDims': 67, - 'PyArray_FromDimsAndDataAndDescr': 68, - 'PyArray_FromAny': 69, - 'PyArray_EnsureArray': 70, - 'PyArray_EnsureAnyArray': 71, - 'PyArray_FromFile': 72, - 'PyArray_FromString': 73, - 'PyArray_FromBuffer': 74, - 'PyArray_FromIter': 75, - 'PyArray_Return': 76, - 'PyArray_GetField': 77, - 'PyArray_SetField': 78, - 'PyArray_Byteswap': 79, - 'PyArray_Resize': 80, - 'PyArray_MoveInto': 81, - 'PyArray_CopyInto': 82, - 'PyArray_CopyAnyInto': 83, - 'PyArray_CopyObject': 84, - 'PyArray_NewCopy': 85, - 'PyArray_ToList': 86, - 'PyArray_ToString': 87, - 'PyArray_ToFile': 88, - 'PyArray_Dump': 89, - 'PyArray_Dumps': 90, - 'PyArray_ValidType': 91, - 'PyArray_UpdateFlags': 92, - 'PyArray_New': 93, - 'PyArray_NewFromDescr': 94, - 'PyArray_DescrNew': 95, - 'PyArray_DescrNewFromType': 96, - 'PyArray_GetPriority': 97, - 'PyArray_IterNew': 98, - 'PyArray_MultiIterNew': 99, - 'PyArray_PyIntAsInt': 100, - 'PyArray_PyIntAsIntp': 101, - 'PyArray_Broadcast': 102, - 'PyArray_FillObjectArray': 103, - 'PyArray_FillWithScalar': 104, - 'PyArray_CheckStrides': 105, - 'PyArray_DescrNewByteorder': 106, - 'PyArray_IterAllButAxis': 107, - 'PyArray_CheckFromAny': 108, - 'PyArray_FromArray': 109, - 'PyArray_FromInterface': 110, - 'PyArray_FromStructInterface': 111, - 'PyArray_FromArrayAttr': 112, - 'PyArray_ScalarKind': 113, - 'PyArray_CanCoerceScalar': 114, - 'PyArray_NewFlagsObject': 115, - 'PyArray_CanCastScalar': 116, - 'PyArray_CompareUCS4': 117, - 'PyArray_RemoveSmallest': 118, - 'PyArray_ElementStrides': 119, - 'PyArray_Item_INCREF': 120, - 'PyArray_Item_XDECREF': 121, - 'PyArray_FieldNames': 122, - 'PyArray_Transpose': 123, - 'PyArray_TakeFrom': 124, - 'PyArray_PutTo': 125, - 'PyArray_PutMask': 126, - 'PyArray_Repeat': 127, - 'PyArray_Choose': 128, - 'PyArray_Sort': 129, - 'PyArray_ArgSort': 130, - 'PyArray_SearchSorted': 131, - 'PyArray_ArgMax': 132, - 'PyArray_ArgMin': 133, - 'PyArray_Reshape': 134, - 'PyArray_Newshape': 135, - 'PyArray_Squeeze': 136, - 'PyArray_View': 137, - 'PyArray_SwapAxes': 138, - 'PyArray_Max': 139, - 'PyArray_Min': 140, - 'PyArray_Ptp': 141, - 'PyArray_Mean': 142, - 'PyArray_Trace': 143, - 'PyArray_Diagonal': 144, - 'PyArray_Clip': 145, - 'PyArray_Conjugate': 146, - 'PyArray_Nonzero': 147, - 'PyArray_Std': 148, - 'PyArray_Sum': 149, - 'PyArray_CumSum': 150, - 'PyArray_Prod': 151, - 'PyArray_CumProd': 152, - 'PyArray_All': 153, - 'PyArray_Any': 154, - 'PyArray_Compress': 155, - 'PyArray_Flatten': 156, - 'PyArray_Ravel': 157, - 'PyArray_MultiplyList': 158, - 'PyArray_MultiplyIntList': 159, - 'PyArray_GetPtr': 160, - 'PyArray_CompareLists': 161, - 'PyArray_AsCArray': 162, - 'PyArray_As1D': 163, - 'PyArray_As2D': 164, - 'PyArray_Free': 165, - 'PyArray_Converter': 166, - 'PyArray_IntpFromSequence': 167, - 'PyArray_Concatenate': 168, - 'PyArray_InnerProduct': 169, - 'PyArray_MatrixProduct': 170, - 'PyArray_CopyAndTranspose': 171, - 'PyArray_Correlate': 172, - 'PyArray_TypestrConvert': 173, - 'PyArray_DescrConverter': 174, - 'PyArray_DescrConverter2': 175, - 'PyArray_IntpConverter': 176, - 'PyArray_BufferConverter': 177, - 'PyArray_AxisConverter': 178, - 'PyArray_BoolConverter': 179, - 'PyArray_ByteorderConverter': 180, - 'PyArray_OrderConverter': 181, - 'PyArray_EquivTypes': 182, - 'PyArray_Zeros': 183, - 'PyArray_Empty': 184, - 'PyArray_Where': 185, - 'PyArray_Arange': 186, - 'PyArray_ArangeObj': 187, - 'PyArray_SortkindConverter': 188, - 'PyArray_LexSort': 189, - 'PyArray_Round': 190, - 'PyArray_EquivTypenums': 191, - 'PyArray_RegisterDataType': 192, - 'PyArray_RegisterCastFunc': 193, - 'PyArray_RegisterCanCast': 194, - 'PyArray_InitArrFuncs': 195, - 'PyArray_IntTupleFromIntp': 196, - 'PyArray_TypeNumFromName': 197, - 'PyArray_ClipmodeConverter': 198, - 'PyArray_OutputConverter': 199, - 'PyArray_BroadcastToShape': 200, - '_PyArray_SigintHandler': 201, - '_PyArray_GetSigintBuf': 202, - 'PyArray_DescrAlignConverter': 203, - 'PyArray_DescrAlignConverter2': 204, - 'PyArray_SearchsideConverter': 205, - 'PyArray_CheckAxis': 206, - 'PyArray_OverflowMultiplyList': 207, - 'PyArray_CompareString': 208, - 'PyArray_MultiIterFromObjects': 209, - 'PyArray_GetEndianness': 210, - 'PyArray_GetNDArrayCFeatureVersion': 211, - 'PyArray_Correlate2': 212, - 'PyArray_NeighborhoodIterNew': 213, + 'PyArray_GetNDArrayCVersion': (0,), + 'PyArray_SetNumericOps': (40,), + 'PyArray_GetNumericOps': (41,), + 'PyArray_INCREF': (42,), + 'PyArray_XDECREF': (43,), + 'PyArray_SetStringFunction': (44,), + 'PyArray_DescrFromType': (45,), + 'PyArray_TypeObjectFromType': (46,), + 'PyArray_Zero': (47,), + 'PyArray_One': (48,), + 'PyArray_CastToType': (49, StealRef(2), NonNull(2)), + 'PyArray_CastTo': (50,), + 'PyArray_CastAnyTo': (51,), + 'PyArray_CanCastSafely': (52,), + 'PyArray_CanCastTo': (53,), + 'PyArray_ObjectType': (54,), + 'PyArray_DescrFromObject': (55,), + 'PyArray_ConvertToCommonType': (56,), + 'PyArray_DescrFromScalar': (57,), + 'PyArray_DescrFromTypeObject': (58,), + 'PyArray_Size': (59,), + 'PyArray_Scalar': (60,), + 'PyArray_FromScalar': (61, StealRef(2)), + 'PyArray_ScalarAsCtype': (62,), + 'PyArray_CastScalarToCtype': (63,), + 'PyArray_CastScalarDirect': (64,), + 'PyArray_ScalarFromObject': (65,), + 'PyArray_GetCastFunc': (66,), + 'PyArray_FromDims': (67,), + 'PyArray_FromDimsAndDataAndDescr': (68, StealRef(3)), + 'PyArray_FromAny': (69, StealRef(2)), + 'PyArray_EnsureArray': (70, StealRef(1)), + 'PyArray_EnsureAnyArray': (71, StealRef(1)), + 'PyArray_FromFile': (72,), + 'PyArray_FromString': (73,), + 'PyArray_FromBuffer': (74,), + 'PyArray_FromIter': (75, StealRef(2)), + 'PyArray_Return': (76, StealRef(1)), + 'PyArray_GetField': (77, StealRef(2), NonNull(2)), + 'PyArray_SetField': (78, StealRef(2), NonNull(2)), + 'PyArray_Byteswap': (79,), + 'PyArray_Resize': (80,), + 'PyArray_MoveInto': (81,), + 'PyArray_CopyInto': (82,), + 'PyArray_CopyAnyInto': (83,), + 'PyArray_CopyObject': (84,), + 'PyArray_NewCopy': (85, NonNull(1)), + 'PyArray_ToList': (86,), + 'PyArray_ToString': (87,), + 'PyArray_ToFile': (88,), + 'PyArray_Dump': (89,), + 'PyArray_Dumps': (90,), + 'PyArray_ValidType': (91,), + 'PyArray_UpdateFlags': (92,), + 'PyArray_New': (93, NonNull(1)), + 'PyArray_NewFromDescr': (94, StealRef(2), NonNull([1, 2])), + 'PyArray_DescrNew': (95,), + 'PyArray_DescrNewFromType': (96,), + 'PyArray_GetPriority': (97,), + 'PyArray_IterNew': (98,), + 'PyArray_MultiIterNew': (99,), + 'PyArray_PyIntAsInt': (100,), + 'PyArray_PyIntAsIntp': (101,), + 'PyArray_Broadcast': (102,), + 'PyArray_FillObjectArray': (103,), + 'PyArray_FillWithScalar': (104,), + 'PyArray_CheckStrides': (105,), + 'PyArray_DescrNewByteorder': (106,), + 'PyArray_IterAllButAxis': (107,), + 'PyArray_CheckFromAny': (108, StealRef(2)), + 'PyArray_FromArray': (109, StealRef(2)), + 'PyArray_FromInterface': (110,), + 'PyArray_FromStructInterface': (111,), + 'PyArray_FromArrayAttr': (112,), + 'PyArray_ScalarKind': (113,), + 'PyArray_CanCoerceScalar': (114,), + 'PyArray_NewFlagsObject': (115,), + 'PyArray_CanCastScalar': (116,), + 'PyArray_CompareUCS4': (117,), + 'PyArray_RemoveSmallest': (118,), + 'PyArray_ElementStrides': (119,), + 'PyArray_Item_INCREF': (120,), + 'PyArray_Item_XDECREF': (121,), + 'PyArray_FieldNames': (122,), + 'PyArray_Transpose': (123,), + 'PyArray_TakeFrom': (124,), + 'PyArray_PutTo': (125,), + 'PyArray_PutMask': (126,), + 'PyArray_Repeat': (127,), + 'PyArray_Choose': (128,), + 'PyArray_Sort': (129,), + 'PyArray_ArgSort': (130,), + 'PyArray_SearchSorted': (131,), + 'PyArray_ArgMax': (132,), + 'PyArray_ArgMin': (133,), + 'PyArray_Reshape': (134,), + 'PyArray_Newshape': (135,), + 'PyArray_Squeeze': (136,), + 'PyArray_View': (137, StealRef(2)), + 'PyArray_SwapAxes': (138,), + 'PyArray_Max': (139,), + 'PyArray_Min': (140,), + 'PyArray_Ptp': (141,), + 'PyArray_Mean': (142,), + 'PyArray_Trace': (143,), + 'PyArray_Diagonal': (144,), + 'PyArray_Clip': (145,), + 'PyArray_Conjugate': (146,), + 'PyArray_Nonzero': (147,), + 'PyArray_Std': (148,), + 'PyArray_Sum': (149,), + 'PyArray_CumSum': (150,), + 'PyArray_Prod': (151,), + 'PyArray_CumProd': (152,), + 'PyArray_All': (153,), + 'PyArray_Any': (154,), + 'PyArray_Compress': (155,), + 'PyArray_Flatten': (156,), + 'PyArray_Ravel': (157,), + 'PyArray_MultiplyList': (158,), + 'PyArray_MultiplyIntList': (159,), + 'PyArray_GetPtr': (160,), + 'PyArray_CompareLists': (161,), + 'PyArray_AsCArray': (162, StealRef(5)), + 'PyArray_As1D': (163,), + 'PyArray_As2D': (164,), + 'PyArray_Free': (165,), + 'PyArray_Converter': (166,), + 'PyArray_IntpFromSequence': (167,), + 'PyArray_Concatenate': (168,), + 'PyArray_InnerProduct': (169,), + 'PyArray_MatrixProduct': (170,), + 'PyArray_CopyAndTranspose': (171,), + 'PyArray_Correlate': (172,), + 'PyArray_TypestrConvert': (173,), + 'PyArray_DescrConverter': (174,), + 'PyArray_DescrConverter2': (175,), + 'PyArray_IntpConverter': (176,), + 'PyArray_BufferConverter': (177,), + 'PyArray_AxisConverter': (178,), + 'PyArray_BoolConverter': (179,), + 'PyArray_ByteorderConverter': (180,), + 'PyArray_OrderConverter': (181,), + 'PyArray_EquivTypes': (182,), + 'PyArray_Zeros': (183, StealRef(3)), + 'PyArray_Empty': (184, StealRef(3)), + 'PyArray_Where': (185,), + 'PyArray_Arange': (186,), + 'PyArray_ArangeObj': (187,), + 'PyArray_SortkindConverter': (188,), + 'PyArray_LexSort': (189,), + 'PyArray_Round': (190,), + 'PyArray_EquivTypenums': (191,), + 'PyArray_RegisterDataType': (192,), + 'PyArray_RegisterCastFunc': (193,), + 'PyArray_RegisterCanCast': (194,), + 'PyArray_InitArrFuncs': (195,), + 'PyArray_IntTupleFromIntp': (196,), + 'PyArray_TypeNumFromName': (197,), + 'PyArray_ClipmodeConverter': (198,), + 'PyArray_OutputConverter': (199,), + 'PyArray_BroadcastToShape': (200,), + '_PyArray_SigintHandler': (201,), + '_PyArray_GetSigintBuf': (202,), + 'PyArray_DescrAlignConverter': (203,), + 'PyArray_DescrAlignConverter2': (204,), + 'PyArray_SearchsideConverter': (205,), + 'PyArray_CheckAxis': (206,), + 'PyArray_OverflowMultiplyList': (207,), + 'PyArray_CompareString': (208,), + 'PyArray_MultiIterFromObjects': (209,), + 'PyArray_GetEndianness': (210,), + 'PyArray_GetNDArrayCFeatureVersion': (211,), + 'PyArray_Correlate2': (212,), + 'PyArray_NeighborhoodIterNew': (213,), # End 1.5 API - 'PyArray_SetDatetimeParseFunction': 219, - 'PyArray_DatetimeToDatetimeStruct': 220, - 'PyArray_TimedeltaToTimedeltaStruct': 221, - 'PyArray_DatetimeStructToDatetime': 222, - 'PyArray_TimedeltaStructToTimedelta': 223, + 'PyArray_SetDatetimeParseFunction': (219,), + 'PyArray_DatetimeToDatetimeStruct': (220,), + 'PyArray_TimedeltaToTimedeltaStruct': (221,), + 'PyArray_DatetimeStructToDatetime': (222,), + 'PyArray_TimedeltaStructToTimedelta': (223,), # NDIter API - 'NpyIter_New': 224, - 'NpyIter_MultiNew': 225, - 'NpyIter_AdvancedNew': 226, - 'NpyIter_Copy': 227, - 'NpyIter_Deallocate': 228, - 'NpyIter_HasDelayedBufAlloc': 229, - 'NpyIter_HasExternalLoop': 230, - 'NpyIter_EnableExternalLoop': 231, - 'NpyIter_GetInnerStrideArray': 232, - 'NpyIter_GetInnerLoopSizePtr': 233, - 'NpyIter_Reset': 234, - 'NpyIter_ResetBasePointers': 235, - 'NpyIter_ResetToIterIndexRange': 236, - 'NpyIter_GetNDim': 237, - 'NpyIter_GetNOp': 238, - 'NpyIter_GetIterNext': 239, - 'NpyIter_GetIterSize': 240, - 'NpyIter_GetIterIndexRange': 241, - 'NpyIter_GetIterIndex': 242, - 'NpyIter_GotoIterIndex': 243, - 'NpyIter_HasMultiIndex': 244, - 'NpyIter_GetShape': 245, - 'NpyIter_GetGetMultiIndex': 246, - 'NpyIter_GotoMultiIndex': 247, - 'NpyIter_RemoveMultiIndex': 248, - 'NpyIter_HasIndex': 249, - 'NpyIter_IsBuffered': 250, - 'NpyIter_IsGrowInner': 251, - 'NpyIter_GetBufferSize': 252, - 'NpyIter_GetIndexPtr': 253, - 'NpyIter_GotoIndex': 254, - 'NpyIter_GetDataPtrArray': 255, - 'NpyIter_GetDescrArray': 256, - 'NpyIter_GetOperandArray': 257, - 'NpyIter_GetIterView': 258, - 'NpyIter_GetReadFlags': 259, - 'NpyIter_GetWriteFlags': 260, - 'NpyIter_DebugPrint': 261, - 'NpyIter_IterationNeedsAPI': 262, - 'NpyIter_GetInnerFixedStrideArray': 263, - 'NpyIter_RemoveAxis': 264, - 'NpyIter_GetAxisStrideArray': 265, - 'NpyIter_RequiresBuffering': 266, - 'NpyIter_GetInitialDataPtrArray': 267, - 'NpyIter_CreateCompatibleStrides': 268, + 'NpyIter_New': (224,), + 'NpyIter_MultiNew': (225,), + 'NpyIter_AdvancedNew': (226,), + 'NpyIter_Copy': (227,), + 'NpyIter_Deallocate': (228,), + 'NpyIter_HasDelayedBufAlloc': (229,), + 'NpyIter_HasExternalLoop': (230,), + 'NpyIter_EnableExternalLoop': (231,), + 'NpyIter_GetInnerStrideArray': (232,), + 'NpyIter_GetInnerLoopSizePtr': (233,), + 'NpyIter_Reset': (234,), + 'NpyIter_ResetBasePointers': (235,), + 'NpyIter_ResetToIterIndexRange': (236,), + 'NpyIter_GetNDim': (237,), + 'NpyIter_GetNOp': (238,), + 'NpyIter_GetIterNext': (239,), + 'NpyIter_GetIterSize': (240,), + 'NpyIter_GetIterIndexRange': (241,), + 'NpyIter_GetIterIndex': (242,), + 'NpyIter_GotoIterIndex': (243,), + 'NpyIter_HasMultiIndex': (244,), + 'NpyIter_GetShape': (245,), + 'NpyIter_GetGetMultiIndex': (246,), + 'NpyIter_GotoMultiIndex': (247,), + 'NpyIter_RemoveMultiIndex': (248,), + 'NpyIter_HasIndex': (249,), + 'NpyIter_IsBuffered': (250,), + 'NpyIter_IsGrowInner': (251,), + 'NpyIter_GetBufferSize': (252,), + 'NpyIter_GetIndexPtr': (253,), + 'NpyIter_GotoIndex': (254,), + 'NpyIter_GetDataPtrArray': (255,), + 'NpyIter_GetDescrArray': (256,), + 'NpyIter_GetOperandArray': (257,), + 'NpyIter_GetIterView': (258,), + 'NpyIter_GetReadFlags': (259,), + 'NpyIter_GetWriteFlags': (260,), + 'NpyIter_DebugPrint': (261,), + 'NpyIter_IterationNeedsAPI': (262,), + 'NpyIter_GetInnerFixedStrideArray': (263,), + 'NpyIter_RemoveAxis': (264,), + 'NpyIter_GetAxisStrideArray': (265,), + 'NpyIter_RequiresBuffering': (266,), + 'NpyIter_GetInitialDataPtrArray': (267,), + 'NpyIter_CreateCompatibleStrides': (268,), # - 'PyArray_CastingConverter': 269, - 'PyArray_CountNonzero': 270, - 'PyArray_PromoteTypes': 271, - 'PyArray_MinScalarType': 272, - 'PyArray_ResultType': 273, - 'PyArray_CanCastArrayTo': 274, - 'PyArray_CanCastTypeTo': 275, - 'PyArray_EinsteinSum': 276, - 'PyArray_NewLikeArray': 277, - 'PyArray_GetArrayParamsFromObject': 278, - 'PyArray_ConvertClipmodeSequence': 279, - 'PyArray_MatrixProduct2': 280, + 'PyArray_CastingConverter': (269,), + 'PyArray_CountNonzero': (270,), + 'PyArray_PromoteTypes': (271,), + 'PyArray_MinScalarType': (272,), + 'PyArray_ResultType': (273,), + 'PyArray_CanCastArrayTo': (274,), + 'PyArray_CanCastTypeTo': (275,), + 'PyArray_EinsteinSum': (276,), + 'PyArray_NewLikeArray': (277, StealRef(3), NonNull(1)), + 'PyArray_GetArrayParamsFromObject': (278,), + 'PyArray_ConvertClipmodeSequence': (279,), + 'PyArray_MatrixProduct2': (280,), # End 1.6 API - 'NpyIter_IsFirstVisit': 281, - 'PyArray_SetBaseObject': 282, - 'PyArray_CreateSortedStridePerm': 283, - 'PyArray_RemoveAxesInPlace': 284, - 'PyArray_DebugPrint': 285, - 'PyArray_FailUnlessWriteable': 286, - 'PyArray_SetUpdateIfCopyBase': 287, - 'PyDataMem_NEW': 288, - 'PyDataMem_FREE': 289, - 'PyDataMem_RENEW': 290, - 'PyDataMem_SetEventHook': 291, - 'PyArray_MapIterSwapAxes': 293, - 'PyArray_MapIterArray': 294, - 'PyArray_MapIterNext': 295, + 'NpyIter_IsFirstVisit': (281,), + 'PyArray_SetBaseObject': (282, StealRef(2)), + 'PyArray_CreateSortedStridePerm': (283,), + 'PyArray_RemoveAxesInPlace': (284,), + 'PyArray_DebugPrint': (285,), + 'PyArray_FailUnlessWriteable': (286,), + 'PyArray_SetUpdateIfCopyBase': (287, StealRef(2)), + 'PyDataMem_NEW': (288,), + 'PyDataMem_FREE': (289,), + 'PyDataMem_RENEW': (290,), + 'PyDataMem_SetEventHook': (291,), + 'PyArray_MapIterSwapAxes': (293,), + 'PyArray_MapIterArray': (294,), + 'PyArray_MapIterNext': (295,), # End 1.7 API - 'PyArray_Partition': 296, - 'PyArray_ArgPartition': 297, - 'PyArray_SelectkindConverter': 298, - 'PyDataMem_NEW_ZEROED': 299, + 'PyArray_Partition': (296,), + 'PyArray_ArgPartition': (297,), + 'PyArray_SelectkindConverter': (298,), + 'PyDataMem_NEW_ZEROED': (299,), # End 1.8 API } ufunc_types_api = { - 'PyUFunc_Type': 0 + 'PyUFunc_Type': (0,) } ufunc_funcs_api = { - 'PyUFunc_FromFuncAndData': 1, - 'PyUFunc_RegisterLoopForType': 2, - 'PyUFunc_GenericFunction': 3, - 'PyUFunc_f_f_As_d_d': 4, - 'PyUFunc_d_d': 5, - 'PyUFunc_f_f': 6, - 'PyUFunc_g_g': 7, - 'PyUFunc_F_F_As_D_D': 8, - 'PyUFunc_F_F': 9, - 'PyUFunc_D_D': 10, - 'PyUFunc_G_G': 11, - 'PyUFunc_O_O': 12, - 'PyUFunc_ff_f_As_dd_d': 13, - 'PyUFunc_ff_f': 14, - 'PyUFunc_dd_d': 15, - 'PyUFunc_gg_g': 16, - 'PyUFunc_FF_F_As_DD_D': 17, - 'PyUFunc_DD_D': 18, - 'PyUFunc_FF_F': 19, - 'PyUFunc_GG_G': 20, - 'PyUFunc_OO_O': 21, - 'PyUFunc_O_O_method': 22, - 'PyUFunc_OO_O_method': 23, - 'PyUFunc_On_Om': 24, - 'PyUFunc_GetPyValues': 25, - 'PyUFunc_checkfperr': 26, - 'PyUFunc_clearfperr': 27, - 'PyUFunc_getfperr': 28, - 'PyUFunc_handlefperr': 29, - 'PyUFunc_ReplaceLoopBySignature': 30, - 'PyUFunc_FromFuncAndDataAndSignature': 31, - 'PyUFunc_SetUsesArraysAsData': 32, + 'PyUFunc_FromFuncAndData': (1,), + 'PyUFunc_RegisterLoopForType': (2,), + 'PyUFunc_GenericFunction': (3,), + 'PyUFunc_f_f_As_d_d': (4,), + 'PyUFunc_d_d': (5,), + 'PyUFunc_f_f': (6,), + 'PyUFunc_g_g': (7,), + 'PyUFunc_F_F_As_D_D': (8,), + 'PyUFunc_F_F': (9,), + 'PyUFunc_D_D': (10,), + 'PyUFunc_G_G': (11,), + 'PyUFunc_O_O': (12,), + 'PyUFunc_ff_f_As_dd_d': (13,), + 'PyUFunc_ff_f': (14,), + 'PyUFunc_dd_d': (15,), + 'PyUFunc_gg_g': (16,), + 'PyUFunc_FF_F_As_DD_D': (17,), + 'PyUFunc_DD_D': (18,), + 'PyUFunc_FF_F': (19,), + 'PyUFunc_GG_G': (20,), + 'PyUFunc_OO_O': (21,), + 'PyUFunc_O_O_method': (22,), + 'PyUFunc_OO_O_method': (23,), + 'PyUFunc_On_Om': (24,), + 'PyUFunc_GetPyValues': (25,), + 'PyUFunc_checkfperr': (26,), + 'PyUFunc_clearfperr': (27,), + 'PyUFunc_getfperr': (28,), + 'PyUFunc_handlefperr': (29,), + 'PyUFunc_ReplaceLoopBySignature': (30,), + 'PyUFunc_FromFuncAndDataAndSignature': (31,), + 'PyUFunc_SetUsesArraysAsData': (32,), # End 1.5 API - 'PyUFunc_e_e': 33, - 'PyUFunc_e_e_As_f_f': 34, - 'PyUFunc_e_e_As_d_d': 35, - 'PyUFunc_ee_e': 36, - 'PyUFunc_ee_e_As_ff_f': 37, - 'PyUFunc_ee_e_As_dd_d': 38, + 'PyUFunc_e_e': (33,), + 'PyUFunc_e_e_As_f_f': (34,), + 'PyUFunc_e_e_As_d_d': (35,), + 'PyUFunc_ee_e': (36,), + 'PyUFunc_ee_e_As_ff_f': (37,), + 'PyUFunc_ee_e_As_dd_d': (38,), # End 1.6 API - 'PyUFunc_DefaultTypeResolver': 39, - 'PyUFunc_ValidateCasting': 40, + 'PyUFunc_DefaultTypeResolver': (39,), + 'PyUFunc_ValidateCasting': (40,), # End 1.7 API - 'PyUFunc_RegisterLoopForDescr': 41, + 'PyUFunc_RegisterLoopForDescr': (41,), # End 1.8 API } @@ -399,7 +399,6 @@ ufunc_funcs_api = { # XXX: DO NOT CHANGE THE ORDER OF TUPLES BELOW ! multiarray_api = ( multiarray_global_vars, - multiarray_global_vars_types, multiarray_scalar_bool_values, multiarray_types_api, multiarray_funcs_api, diff --git a/numpy/core/code_generators/ufunc_docstrings.py b/numpy/core/code_generators/ufunc_docstrings.py index 59e877750..4d302969e 100644 --- a/numpy/core/code_generators/ufunc_docstrings.py +++ b/numpy/core/code_generators/ufunc_docstrings.py @@ -162,7 +162,7 @@ add_newdoc('numpy.core.umath', 'arccos', add_newdoc('numpy.core.umath', 'arccosh', """ - Inverse hyperbolic cosine, elementwise. + Inverse hyperbolic cosine, element-wise. Parameters ---------- @@ -272,7 +272,7 @@ add_newdoc('numpy.core.umath', 'arcsin', add_newdoc('numpy.core.umath', 'arcsinh', """ - Inverse hyperbolic sine elementwise. + Inverse hyperbolic sine element-wise. Parameters ---------- @@ -467,7 +467,7 @@ add_newdoc('numpy.core.umath', '_arg', add_newdoc('numpy.core.umath', 'arctanh', """ - Inverse hyperbolic tangent elementwise. + Inverse hyperbolic tangent element-wise. Parameters ---------- @@ -486,15 +486,15 @@ add_newdoc('numpy.core.umath', 'arctanh', Notes ----- `arctanh` is a multivalued function: for each `x` there are infinitely - many numbers `z` such that `tanh(z) = x`. The convention is to return the - `z` whose imaginary part lies in `[-pi/2, pi/2]`. + many numbers `z` such that `tanh(z) = x`. The convention is to return + the `z` whose imaginary part lies in `[-pi/2, pi/2]`. For real-valued input data types, `arctanh` always returns real output. - For each value that cannot be expressed as a real number or infinity, it - yields ``nan`` and sets the `invalid` floating point error flag. + For each value that cannot be expressed as a real number or infinity, + it yields ``nan`` and sets the `invalid` floating point error flag. - For complex-valued input, `arctanh` is a complex analytical function that - has branch cuts `[-1, -inf]` and `[1, inf]` and is continuous from + For complex-valued input, `arctanh` is a complex analytical function + that has branch cuts `[-1, -inf]` and `[1, inf]` and is continuous from above on the former and from below on the latter. The inverse hyperbolic tangent is also known as `atanh` or ``tanh^-1``. @@ -524,7 +524,7 @@ add_newdoc('numpy.core.umath', 'bitwise_and', Parameters ---------- x1, x2 : array_like - Only integer types are handled (including booleans). + Only integer and boolean types are handled. Returns ------- @@ -575,7 +575,7 @@ add_newdoc('numpy.core.umath', 'bitwise_or', Parameters ---------- x1, x2 : array_like - Only integer types are handled (including booleans). + Only integer and boolean types are handled. out : ndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See doc.ufuncs. @@ -634,7 +634,7 @@ add_newdoc('numpy.core.umath', 'bitwise_xor', Parameters ---------- x1, x2 : array_like - Only integer types are handled (including booleans). + Only integer and boolean types are handled. Returns ------- @@ -766,7 +766,7 @@ add_newdoc('numpy.core.umath', 'conjugate', add_newdoc('numpy.core.umath', 'cos', """ - Cosine elementwise. + Cosine element-wise. Parameters ---------- @@ -937,8 +937,8 @@ add_newdoc('numpy.core.umath', 'divide', See Also -------- - seterr : Set whether to raise or warn on overflow, underflow and division - by zero. + seterr : Set whether to raise or warn on overflow, underflow and + division by zero. Notes ----- @@ -1048,8 +1048,8 @@ add_newdoc('numpy.core.umath', 'exp', For complex arguments, ``x = a + ib``, we can write :math:`e^x = e^a e^{ib}`. The first term, :math:`e^a`, is already known (it is the real argument, described above). The second term, - :math:`e^{ib}`, is :math:`\\cos b + i \\sin b`, a function with magnitude - 1 and a periodic phase. + :math:`e^{ib}`, is :math:`\\cos b + i \\sin b`, a function with + magnitude 1 and a periodic phase. References ---------- @@ -1137,7 +1137,7 @@ add_newdoc('numpy.core.umath', 'expm1', Notes ----- - This function provides greater precision than the formula ``exp(x) - 1`` + This function provides greater precision than ``exp(x) - 1`` for small values of ``x``. Examples @@ -1155,10 +1155,10 @@ add_newdoc('numpy.core.umath', 'expm1', add_newdoc('numpy.core.umath', 'fabs', """ - Compute the absolute values elementwise. + Compute the absolute values element-wise. - This function returns the absolute values (positive magnitude) of the data - in `x`. Complex values are not handled, use `absolute` to find the + This function returns the absolute values (positive magnitude) of the + data in `x`. Complex values are not handled, use `absolute` to find the absolute values of complex data. Parameters @@ -1212,8 +1212,8 @@ add_newdoc('numpy.core.umath', 'floor', Notes ----- Some spreadsheet programs calculate the "floor-towards-zero", in other - words ``floor(-2.5) == -2``. NumPy, however, uses the a definition of - `floor` such that `floor(-2.5) == -3`. + words ``floor(-2.5) == -2``. NumPy instead uses the definition of + `floor` where `floor(-2.5) == -3`. Examples -------- @@ -1225,7 +1225,8 @@ add_newdoc('numpy.core.umath', 'floor', add_newdoc('numpy.core.umath', 'floor_divide', """ - Return the largest integer smaller or equal to the division of the inputs. + Return the largest integer smaller or equal to the division of the + inputs. Parameters ---------- @@ -1259,7 +1260,10 @@ add_newdoc('numpy.core.umath', 'fmod', """ Return the element-wise remainder of division. - This is the NumPy implementation of the Python modulo operator `%`. + This is the NumPy implementation of the C library function fmod, the + remainder has the same sign as the dividend `x1`. It is equivalent to + the Matlab(TM) ``rem`` function and should not be confused with the + Python modulus operator ``x1 % x2``. Parameters ---------- @@ -1275,15 +1279,16 @@ add_newdoc('numpy.core.umath', 'fmod', See Also -------- - remainder : Modulo operation where the quotient is `floor(x1/x2)`. + remainder : Equivalent to the Python ``%`` operator. divide Notes ----- - The result of the modulo operation for negative dividend and divisors is - bound by conventions. In `fmod`, the sign of the remainder is the sign of - the dividend. In `remainder`, the sign of the divisor does not affect the - sign of the result. + The result of the modulo operation for negative dividend and divisors + is bound by conventions. For `fmod`, the sign of result is the sign of + the dividend, while for `remainder` the sign of the result is the sign + of the divisor. The `fmod` function is equivalent to the Matlab(TM) + ``rem`` function. Examples -------- @@ -1414,17 +1419,17 @@ add_newdoc('numpy.core.umath', 'invert', the integers in the input arrays. This ufunc implements the C/Python operator ``~``. - For signed integer inputs, the two's complement is returned. - In a two's-complement system negative numbers are represented by the two's + For signed integer inputs, the two's complement is returned. In a + two's-complement system negative numbers are represented by the two's complement of the absolute value. This is the most common method of - representing signed integers on computers [1]_. A N-bit two's-complement - system can represent every integer in the range + representing signed integers on computers [1]_. A N-bit + two's-complement system can represent every integer in the range :math:`-2^{N-1}` to :math:`+2^{N-1}-1`. Parameters ---------- x1 : array_like - Only integer types are handled (including booleans). + Only integer and boolean types are handled. Returns ------- @@ -1488,7 +1493,7 @@ add_newdoc('numpy.core.umath', 'invert', add_newdoc('numpy.core.umath', 'isfinite', """ - Test element-wise for finite-ness (not infinity or not Not a Number). + Test element-wise for finiteness (not infinity or not Not a Number). The result is returned as a boolean array. @@ -1508,9 +1513,10 @@ add_newdoc('numpy.core.umath', 'isfinite', either positive infinity, negative infinity or Not a Number). For array input, the result is a boolean array with the same - dimensions as the input and the values are True if the corresponding - element of the input is finite; otherwise the values are False (element - is either positive infinity, negative infinity or Not a Number). + dimensions as the input and the values are True if the + corresponding element of the input is finite; otherwise the values + are False (element is either positive infinity, negative infinity + or Not a Number). See Also -------- @@ -1524,9 +1530,9 @@ add_newdoc('numpy.core.umath', 'isfinite', Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Also that positive infinity is not equivalent to negative infinity. But - infinity is equivalent to positive infinity. - Errors result if the second argument is also supplied when `x` is a scalar - input, or if first and second arguments have different shapes. + infinity is equivalent to positive infinity. Errors result if the + second argument is also supplied when `x` is a scalar input, or if + first and second arguments have different shapes. Examples -------- @@ -1556,8 +1562,8 @@ add_newdoc('numpy.core.umath', 'isinf', """ Test element-wise for positive or negative infinity. - Return a bool-type array, the same shape as `x`, True where ``x == - +/-inf``, False everywhere else. + Returns a boolean array of the same shape as `x`, True where ``x == + +/-inf``, otherwise False. Parameters ---------- @@ -1568,19 +1574,19 @@ add_newdoc('numpy.core.umath', 'isinf', Returns ------- - y : bool (scalar) or bool-type ndarray - For scalar input, the result is a new boolean with value True - if the input is positive or negative infinity; otherwise the value - is False. + y : bool (scalar) or boolean ndarray + For scalar input, the result is a new boolean with value True if + the input is positive or negative infinity; otherwise the value is + False. - For array input, the result is a boolean array with the same - shape as the input and the values are True where the - corresponding element of the input is positive or negative - infinity; elsewhere the values are False. If a second argument - was supplied the result is stored there. If the type of that array - is a numeric type the result is represented as zeros and ones, if - the type is boolean then as False and True, respectively. - The return value `y` is then a reference to that array. + For array input, the result is a boolean array with the same shape + as the input and the values are True where the corresponding + element of the input is positive or negative infinity; elsewhere + the values are False. If a second argument was supplied the result + is stored there. If the type of that array is a numeric type the + result is represented as zeros and ones, if the type is boolean + then as False and True, respectively. The return value `y` is then + a reference to that array. See Also -------- @@ -1617,7 +1623,7 @@ add_newdoc('numpy.core.umath', 'isinf', add_newdoc('numpy.core.umath', 'isnan', """ - Test element-wise for Not a Number (NaN), return result as a bool array. + Test element-wise for NaN and return result as a boolean array. Parameters ---------- @@ -1627,12 +1633,13 @@ add_newdoc('numpy.core.umath', 'isnan', Returns ------- y : {ndarray, bool} - For scalar input, the result is a new boolean with value True - if the input is NaN; otherwise the value is False. + For scalar input, the result is a new boolean with value True if + the input is NaN; otherwise the value is False. - For array input, the result is a boolean array with the same - dimensions as the input and the values are True if the corresponding - element of the input is NaN; otherwise the values are False. + For array input, the result is a boolean array of the same + dimensions as the input and the values are True if the + corresponding element of the input is NaN; otherwise the values are + False. See Also -------- @@ -1753,7 +1760,8 @@ add_newdoc('numpy.core.umath', 'log', Natural logarithm, element-wise. The natural logarithm `log` is the inverse of the exponential function, - so that `log(exp(x)) = x`. The natural logarithm is logarithm in base `e`. + so that `log(exp(x)) = x`. The natural logarithm is logarithm in base + `e`. Parameters ---------- @@ -1772,8 +1780,8 @@ add_newdoc('numpy.core.umath', 'log', Notes ----- Logarithm is a multivalued function: for each `x` there is an infinite - number of `z` such that `exp(z) = x`. The convention is to return the `z` - whose imaginary part lies in `[-pi, pi]`. + number of `z` such that `exp(z) = x`. The convention is to return the + `z` whose imaginary part lies in `[-pi, pi]`. For real-valued input data types, `log` always returns real output. For each value that cannot be expressed as a real number or infinity, it @@ -1819,17 +1827,17 @@ add_newdoc('numpy.core.umath', 'log10', Notes ----- Logarithm is a multivalued function: for each `x` there is an infinite - number of `z` such that `10**z = x`. The convention is to return the `z` - whose imaginary part lies in `[-pi, pi]`. + number of `z` such that `10**z = x`. The convention is to return the + `z` whose imaginary part lies in `[-pi, pi]`. - For real-valued input data types, `log10` always returns real output. For - each value that cannot be expressed as a real number or infinity, it - yields ``nan`` and sets the `invalid` floating point error flag. + For real-valued input data types, `log10` always returns real output. + For each value that cannot be expressed as a real number or infinity, + it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `log10` is a complex analytical function that - has a branch cut `[-inf, 0]` and is continuous from above on it. `log10` - handles the floating-point negative zero as an infinitesimal negative - number, conforming to the C99 standard. + has a branch cut `[-inf, 0]` and is continuous from above on it. + `log10` handles the floating-point negative zero as an infinitesimal + negative number, conforming to the C99 standard. References ---------- @@ -1870,9 +1878,9 @@ add_newdoc('numpy.core.umath', 'log2', number of `z` such that `2**z = x`. The convention is to return the `z` whose imaginary part lies in `[-pi, pi]`. - For real-valued input data types, `log2` always returns real output. For - each value that cannot be expressed as a real number or infinity, it - yields ``nan`` and sets the `invalid` floating point error flag. + For real-valued input data types, `log2` always returns real output. + For each value that cannot be expressed as a real number or infinity, + it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `log2` is a complex analytical function that has a branch cut `[-inf, 0]` and is continuous from above on it. `log2` @@ -1913,7 +1921,7 @@ add_newdoc('numpy.core.umath', 'logaddexp', See Also -------- - logaddexp2: Logarithm of the sum of exponentiations of inputs in base-2. + logaddexp2: Logarithm of the sum of exponentiations of inputs in base 2. Notes ----- @@ -1936,8 +1944,8 @@ add_newdoc('numpy.core.umath', 'logaddexp2', Logarithm of the sum of exponentiations of the inputs in base-2. Calculates ``log2(2**x1 + 2**x2)``. This function is useful in machine - learning when the calculated probabilities of events may be so small - as to exceed the range of normal floating point numbers. In such cases + learning when the calculated probabilities of events may be so small as + to exceed the range of normal floating point numbers. In such cases the base-2 logarithm of the calculated probability can be used instead. This function allows adding probabilities stored in such a fashion. @@ -2002,14 +2010,14 @@ add_newdoc('numpy.core.umath', 'log1p', number of `z` such that `exp(z) = 1 + x`. The convention is to return the `z` whose imaginary part lies in `[-pi, pi]`. - For real-valued input data types, `log1p` always returns real output. For - each value that cannot be expressed as a real number or infinity, it - yields ``nan`` and sets the `invalid` floating point error flag. + For real-valued input data types, `log1p` always returns real output. + For each value that cannot be expressed as a real number or infinity, + it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `log1p` is a complex analytical function that - has a branch cut `[-inf, -1]` and is continuous from above on it. `log1p` - handles the floating-point negative zero as an infinitesimal negative - number, conforming to the C99 standard. + has a branch cut `[-inf, -1]` and is continuous from above on it. + `log1p` handles the floating-point negative zero as an infinitesimal + negative number, conforming to the C99 standard. References ---------- @@ -2028,7 +2036,7 @@ add_newdoc('numpy.core.umath', 'log1p', add_newdoc('numpy.core.umath', 'logical_and', """ - Compute the truth value of x1 AND x2 elementwise. + Compute the truth value of x1 AND x2 element-wise. Parameters ---------- @@ -2062,7 +2070,7 @@ add_newdoc('numpy.core.umath', 'logical_and', add_newdoc('numpy.core.umath', 'logical_not', """ - Compute the truth value of NOT x elementwise. + Compute the truth value of NOT x element-wise. Parameters ---------- @@ -2094,7 +2102,7 @@ add_newdoc('numpy.core.umath', 'logical_not', add_newdoc('numpy.core.umath', 'logical_or', """ - Compute the truth value of x1 OR x2 elementwise. + Compute the truth value of x1 OR x2 element-wise. Parameters ---------- @@ -2171,11 +2179,11 @@ add_newdoc('numpy.core.umath', 'maximum', Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise - maxima. If one of the elements being compared is a nan, then that element - is returned. If both elements are nans then the first is returned. The - latter distinction is important for complex nans, which are defined as at - least one of the real or imaginary parts being a nan. The net effect is - that nans are propagated. + maxima. If one of the elements being compared is a NaN, then that + element is returned. If both elements are NaNs then the first is + returned. The latter distinction is important for complex NaNs, which + are defined as at least one of the real or imaginary parts being a NaN. + The net effect is that NaNs are propagated. Parameters ---------- @@ -2192,20 +2200,21 @@ add_newdoc('numpy.core.umath', 'maximum', See Also -------- minimum : - Element-wise minimum of two arrays, propagating any NaNs. + Element-wise minimum of two arrays, propagates NaNs. fmax : - Element-wise maximum of two arrays, ignoring any NaNs. + Element-wise maximum of two arrays, ignores NaNs. amax : - The maximum value of an array along a given axis, propagating any NaNs. + The maximum value of an array along a given axis, propagates NaNs. nanmax : - The maximum value of an array along a given axis, ignoring any NaNs. + The maximum value of an array along a given axis, ignores NaNs. fmin, amin, nanmin Notes ----- - The maximum is equivalent to ``np.where(x1 >= x2, x1, x2)`` when neither - x1 nor x2 are nans, but it is faster and does proper broadcasting. + The maximum is equivalent to ``np.where(x1 >= x2, x1, x2)`` when + neither x1 nor x2 are nans, but it is faster and does proper + broadcasting. Examples -------- @@ -2228,11 +2237,11 @@ add_newdoc('numpy.core.umath', 'minimum', Element-wise minimum of array elements. Compare two arrays and returns a new array containing the element-wise - minima. If one of the elements being compared is a nan, then that element - is returned. If both elements are nans then the first is returned. The - latter distinction is important for complex nans, which are defined as at - least one of the real or imaginary parts being a nan. The net effect is - that nans are propagated. + minima. If one of the elements being compared is a NaN, then that + element is returned. If both elements are NaNs then the first is + returned. The latter distinction is important for complex NaNs, which + are defined as at least one of the real or imaginary parts being a NaN. + The net effect is that NaNs are propagated. Parameters ---------- @@ -2249,20 +2258,21 @@ add_newdoc('numpy.core.umath', 'minimum', See Also -------- maximum : - Element-wise maximum of two arrays, propagating any NaNs. + Element-wise maximum of two arrays, propagates NaNs. fmin : - Element-wise minimum of two arrays, ignoring any NaNs. + Element-wise minimum of two arrays, ignores NaNs. amin : - The minimum value of an array along a given axis, propagating any NaNs. + The minimum value of an array along a given axis, propagates NaNs. nanmin : - The minimum value of an array along a given axis, ignoring any NaNs. + The minimum value of an array along a given axis, ignores NaNs. fmax, amax, nanmax Notes ----- - The minimum is equivalent to ``np.where(x1 <= x2, x1, x2)`` when neither - x1 nor x2 are nans, but it is faster and does proper broadcasting. + The minimum is equivalent to ``np.where(x1 <= x2, x1, x2)`` when + neither x1 nor x2 are NaNs, but it is faster and does proper + broadcasting. Examples -------- @@ -2285,11 +2295,11 @@ add_newdoc('numpy.core.umath', 'fmax', Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise - maxima. If one of the elements being compared is a nan, then the non-nan - element is returned. If both elements are nans then the first is returned. - The latter distinction is important for complex nans, which are defined as - at least one of the real or imaginary parts being a nan. The net effect is - that nans are ignored when possible. + maxima. If one of the elements being compared is a NaN, then the + non-nan element is returned. If both elements are NaNs then the first + is returned. The latter distinction is important for complex NaNs, + which are defined as at least one of the real or imaginary parts being + a NaN. The net effect is that NaNs are ignored when possible. Parameters ---------- @@ -2306,13 +2316,13 @@ add_newdoc('numpy.core.umath', 'fmax', See Also -------- fmin : - Element-wise minimum of two arrays, ignoring any NaNs. + Element-wise minimum of two arrays, ignores NaNs. maximum : - Element-wise maximum of two arrays, propagating any NaNs. + Element-wise maximum of two arrays, propagates NaNs. amax : - The maximum value of an array along a given axis, propagating any NaNs. + The maximum value of an array along a given axis, propagates NaNs. nanmax : - The maximum value of an array along a given axis, ignoring any NaNs. + The maximum value of an array along a given axis, ignores NaNs. minimum, amin, nanmin @@ -2321,7 +2331,7 @@ add_newdoc('numpy.core.umath', 'fmax', .. versionadded:: 1.3.0 The fmax is equivalent to ``np.where(x1 >= x2, x1, x2)`` when neither - x1 nor x2 are nans, but it is faster and does proper broadcasting. + x1 nor x2 are NaNs, but it is faster and does proper broadcasting. Examples -------- @@ -2342,11 +2352,11 @@ add_newdoc('numpy.core.umath', 'fmin', Element-wise minimum of array elements. Compare two arrays and returns a new array containing the element-wise - minima. If one of the elements being compared is a nan, then the non-nan - element is returned. If both elements are nans then the first is returned. - The latter distinction is important for complex nans, which are defined as - at least one of the real or imaginary parts being a nan. The net effect is - that nans are ignored when possible. + minima. If one of the elements being compared is a NaN, then the + non-nan element is returned. If both elements are NaNs then the first + is returned. The latter distinction is important for complex NaNs, + which are defined as at least one of the real or imaginary parts being + a NaN. The net effect is that NaNs are ignored when possible. Parameters ---------- @@ -2363,13 +2373,13 @@ add_newdoc('numpy.core.umath', 'fmin', See Also -------- fmax : - Element-wise maximum of two arrays, ignoring any NaNs. + Element-wise maximum of two arrays, ignores NaNs. minimum : - Element-wise minimum of two arrays, propagating any NaNs. + Element-wise minimum of two arrays, propagates NaNs. amin : - The minimum value of an array along a given axis, propagating any NaNs. + The minimum value of an array along a given axis, propagates NaNs. nanmin : - The minimum value of an array along a given axis, ignoring any NaNs. + The minimum value of an array along a given axis, ignores NaNs. maximum, amax, nanmax @@ -2378,7 +2388,7 @@ add_newdoc('numpy.core.umath', 'fmin', .. versionadded:: 1.3.0 The fmin is equivalent to ``np.where(x1 <= x2, x1, x2)`` when neither - x1 nor x2 are nans, but it is faster and does proper broadcasting. + x1 nor x2 are NaNs, but it is faster and does proper broadcasting. Examples -------- @@ -2461,7 +2471,7 @@ add_newdoc('numpy.core.umath', 'multiply', add_newdoc('numpy.core.umath', 'negative', """ - Returns an array with the negative of each element of the original array. + Numerical negative, element-wise. Parameters ---------- @@ -2515,10 +2525,9 @@ add_newdoc('numpy.core.umath', 'not_equal', add_newdoc('numpy.core.umath', '_ones_like', """ - This function used to be the numpy.ones_like, but now a - specific function for that has been written for consistency with - the other *_like functions. It is only used internally in a limited - fashion now. + This function used to be the numpy.ones_like, but now a specific + function for that has been written for consistency with the other + *_like functions. It is only used internally in a limited fashion now. See Also -------- @@ -2664,8 +2673,8 @@ add_newdoc('numpy.core.umath', 'reciprocal', This function is not designed to work with integers. For integer arguments with absolute value larger than 1 the result is - always zero because of the way Python handles integer division. - For integer zero the result is an overflow. + always zero because of the way Python handles integer division. For + integer zero the result is an overflow. Examples -------- @@ -2680,7 +2689,10 @@ add_newdoc('numpy.core.umath', 'remainder', """ Return element-wise remainder of division. - Computes ``x1 - floor(x1 / x2) * x2``. + Computes ``x1 - floor(x1 / x2) * x2``, the result has the same sign as + the divisor `x2`. It is equivalent to the Python modulus operator + ``x1 % x2`` and should not be confused with the Matlab(TM) ``rem`` + function. Parameters ---------- @@ -2695,16 +2707,18 @@ add_newdoc('numpy.core.umath', 'remainder', Returns ------- y : ndarray - The remainder of the quotient ``x1/x2``, element-wise. Returns a scalar - if both `x1` and `x2` are scalars. + The remainder of the quotient ``x1/x2``, element-wise. Returns a + scalar if both `x1` and `x2` are scalars. See Also -------- + fmod : Equivalent of the Matlab(TM) ``rem`` function. divide, floor Notes ----- - Returns 0 when `x2` is 0 and both `x1` and `x2` are (arrays of) integers. + Returns 0 when `x2` is 0 and both `x1` and `x2` are (arrays of) + integers. Examples -------- @@ -2719,9 +2733,9 @@ add_newdoc('numpy.core.umath', 'right_shift', """ Shift the bits of an integer to the right. - Bits are shifted to the right by removing `x2` bits at the right of `x1`. - Since the internal representation of numbers is in binary format, this - operation is equivalent to dividing `x1` by ``2**x2``. + Bits are shifted to the right `x2`. Because the internal + representation of numbers is in binary format, this operation is + equivalent to dividing `x1` by ``2**x2``. Parameters ---------- @@ -2815,9 +2829,8 @@ add_newdoc('numpy.core.umath', 'signbit', x : array_like The input value(s). out : ndarray, optional - Array into which the output is placed. Its type is preserved - and it must be of the right shape to hold the output. - See `doc.ufuncs`. + Array into which the output is placed. Its type is preserved and it + must be of the right shape to hold the output. See `doc.ufuncs`. Returns ------- @@ -2874,8 +2887,7 @@ add_newdoc('numpy.core.umath', 'copysign', add_newdoc('numpy.core.umath', 'nextafter', """ - Return the next representable floating-point value after x1 in the direction - of x2 element-wise. + Return the next floating-point value after x1 towards x2, element-wise. Parameters ---------- @@ -2923,7 +2935,7 @@ add_newdoc('numpy.core.umath', 'spacing', should not be any representable number between ``x + spacing(x)`` and x for any finite x. - Spacing of +- inf and nan is nan. + Spacing of +- inf and NaN is NaN. Examples -------- @@ -2952,17 +2964,17 @@ add_newdoc('numpy.core.umath', 'sin', Notes ----- - The sine is one of the fundamental functions of trigonometry - (the mathematical study of triangles). Consider a circle of radius - 1 centered on the origin. A ray comes in from the :math:`+x` axis, - makes an angle at the origin (measured counter-clockwise from that - axis), and departs from the origin. The :math:`y` coordinate of - the outgoing ray's intersection with the unit circle is the sine - of that angle. It ranges from -1 for :math:`x=3\\pi / 2` to - +1 for :math:`\\pi / 2.` The function has zeroes where the angle is - a multiple of :math:`\\pi`. Sines of angles between :math:`\\pi` and - :math:`2\\pi` are negative. The numerous properties of the sine and - related functions are included in any standard trigonometry text. + The sine is one of the fundamental functions of trigonometry (the + mathematical study of triangles). Consider a circle of radius 1 + centered on the origin. A ray comes in from the :math:`+x` axis, makes + an angle at the origin (measured counter-clockwise from that axis), and + departs from the origin. The :math:`y` coordinate of the outgoing + ray's intersection with the unit circle is the sine of that angle. It + ranges from -1 for :math:`x=3\\pi / 2` to +1 for :math:`\\pi / 2.` The + function has zeroes where the angle is a multiple of :math:`\\pi`. + Sines of angles between :math:`\\pi` and :math:`2\\pi` are negative. + The numerous properties of the sine and related functions are included + in any standard trigonometry text. Examples -------- @@ -3076,8 +3088,8 @@ add_newdoc('numpy.core.umath', 'sqrt', ----- *sqrt* has--consistent with common convention--as its branch cut the real "interval" [`-inf`, 0), and is continuous from above on it. - (A branch cut is a curve in the complex plane across which a given - complex function fails to be continuous.) + A branch cut is a curve in the complex plane across which a given + complex function fails to be continuous. Examples -------- @@ -3210,8 +3222,7 @@ add_newdoc('numpy.core.umath', 'tanh', """ Compute hyperbolic tangent element-wise. - Equivalent to ``np.sinh(x)/np.cosh(x)`` or - ``-1j * np.tan(1j*x)``. + Equivalent to ``np.sinh(x)/np.cosh(x)`` or ``-1j * np.tan(1j*x)``. Parameters ---------- @@ -3285,10 +3296,10 @@ add_newdoc('numpy.core.umath', 'true_divide', Notes ----- - The floor division operator ``//`` was added in Python 2.2 making ``//`` - and ``/`` equivalent operators. The default floor division operation of - ``/`` can be replaced by true division with - ``from __future__ import division``. + The floor division operator ``//`` was added in Python 2.2 making + ``//`` and ``/`` equivalent operators. The default floor division + operation of ``/`` can be replaced by true division with ``from + __future__ import division``. In Python 3.0, ``//`` is the floor division operator and ``/`` the true division operator. The ``true_divide(x1, x2)`` function is @@ -3312,3 +3323,97 @@ add_newdoc('numpy.core.umath', 'true_divide', array([0, 0, 0, 0, 1]) """) + +# This doc is not currently used, but has been converted to a C string +# that can be found in numpy/core/src/umath/umathmodule.c where the +# frexp ufunc is constructed. +add_newdoc('numpy.core.umath', 'frexp', + """ + Decompose the elements of x into mantissa and twos exponent. + + Returns (`mantissa`, `exponent`), where `x = mantissa * 2**exponent``. + The mantissa is lies in the open interval(-1, 1), while the twos + exponent is a signed integer. + + Parameters + ---------- + x : array_like + Array of numbers to be decomposed. + out1: ndarray, optional + Output array for the mantissa. Must have the same shape as `x`. + out2: ndarray, optional + Output array for the exponent. Must have the same shape as `x`. + + Returns + ------- + (mantissa, exponent) : tuple of ndarrays, (float, int) + `mantissa` is a float array with values between -1 and 1. + `exponent` is an int array which represents the exponent of 2. + + See Also + -------- + ldexp : Compute ``y = x1 * 2**x2``, the inverse of `frexp`. + + Notes + ----- + Complex dtypes are not supported, they will raise a TypeError. + + Examples + -------- + >>> x = np.arange(9) + >>> y1, y2 = np.frexp(x) + >>> y1 + array([ 0. , 0.5 , 0.5 , 0.75 , 0.5 , 0.625, 0.75 , 0.875, + 0.5 ]) + >>> y2 + array([0, 1, 2, 2, 3, 3, 3, 3, 4]) + >>> y1 * 2**y2 + array([ 0., 1., 2., 3., 4., 5., 6., 7., 8.]) + + """) + +# This doc is not currently used, but has been converted to a C string +# that can be found in numpy/core/src/umath/umathmodule.c where the +# ldexp ufunc is constructed. +add_newdoc('numpy.core.umath', 'ldexp', + """ + Returns x1 * 2**x2, element-wise. + + The mantissas `x1` and twos exponents `x2` are used to construct + floating point numbers ``x1 * 2**x2``. + + Parameters + ---------- + x1 : array_like + Array of multipliers. + x2 : array_like, int + Array of twos exponents. + out : ndarray, optional + Output array for the result. + + Returns + ------- + y : ndarray or scalar + The result of ``x1 * 2**x2``. + + See Also + -------- + frexp : Return (y1, y2) from ``x = y1 * 2**y2``, inverse to `ldexp`. + + Notes + ----- + Complex dtypes are not supported, they will raise a TypeError. + + `ldexp` is useful as the inverse of `frexp`, if used by itself it is + more clear to simply use the expression ``x1 * 2**x2``. + + Examples + -------- + >>> np.ldexp(5, np.arange(4)) + array([ 5., 10., 20., 40.], dtype=float32) + + >>> x = np.arange(6) + >>> np.ldexp(*np.frexp(x)) + array([ 0., 1., 2., 3., 4., 5.]) + + """) diff --git a/numpy/core/code_generators/cversions.py b/numpy/core/cversions.py index 840251aa8..7995dd993 100644 --- a/numpy/core/code_generators/cversions.py +++ b/numpy/core/cversions.py @@ -7,10 +7,9 @@ from __future__ import division, absolute_import, print_function from os.path import dirname -from genapi import fullapi_hash -import numpy_api - +from code_generators.genapi import fullapi_hash +from code_generators.numpy_api import full_api if __name__ == '__main__': curdir = dirname(__file__) - print(fullapi_hash(numpy_api.full_api)) + print(fullapi_hash(full_api)) diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index 152cceb1b..49fd57e29 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -4,7 +4,9 @@ from __future__ import division, absolute_import, print_function import types +import warnings +from .. import VisibleDeprecationWarning from . import multiarray as mu from . import umath as um from . import numerictypes as nt @@ -90,6 +92,7 @@ def take(a, indices, axis=None, out=None, mode='raise'): See Also -------- + compress : Take elements using a boolean mask ndarray.take : equivalent method Examples @@ -583,7 +586,7 @@ def partition(a, kth, axis=-1, kind='introselect', order=None): The various selection algorithms are characterized by their average speed, worst case performance, work space size, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The - three available algorithms have the following properties: + available algorithms have the following properties: ================= ======= ============= ============ ======= kind speed worst case work space stable @@ -1087,7 +1090,7 @@ def squeeze(a, axis=None): Returns ------- squeezed : ndarray - The input array, but with with all or a subset of the + The input array, but with all or a subset of the dimensions of length 1 removed. This is always `a` itself or a view into `a`. @@ -1770,7 +1773,7 @@ def any(a, axis=None, out=None, keepdims=False): Input array or object that can be converted to an array. axis : None or int or tuple of ints, optional Axis or axes along which a logical OR reduction is performed. - The default (`axis` = `None`) is perform a logical OR over all + The default (`axis` = `None`) is to perform a logical OR over all the dimensions of the input array. `axis` may be negative, in which case it counts from the last to the first axis. @@ -1848,7 +1851,7 @@ def all(a, axis=None, out=None, keepdims=False): Input array or object that can be converted to an array. axis : None or int or tuple of ints, optional Axis or axes along which a logical AND reduction is performed. - The default (`axis` = `None`) is perform a logical OR over all + The default (`axis` = `None`) is to perform a logical AND over all the dimensions of the input array. `axis` may be negative, in which case it counts from the last to the first axis. @@ -2452,6 +2455,11 @@ def rank(a): If `a` is not already an array, a conversion is attempted. Scalars are zero dimensional. + .. note:: + This function is deprecated in NumPy 1.9 to avoid confusion with + `numpy.linalg.matrix_rank`. The ``ndim`` attribute or function + should be used instead. + Parameters ---------- a : array_like @@ -2485,6 +2493,10 @@ def rank(a): 0 """ + warnings.warn( + "`rank` is deprecated; use the `ndim` attribute or function instead. " + "To find the rank of a matrix see `numpy.linalg.matrix_rank`.", + VisibleDeprecationWarning) try: return a.ndim except AttributeError: diff --git a/numpy/core/function_base.py b/numpy/core/function_base.py index 3396adf3d..400e75eb5 100644 --- a/numpy/core/function_base.py +++ b/numpy/core/function_base.py @@ -79,6 +79,10 @@ def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None): """ num = int(num) + # Convert float/complex array scalars to float, gh-3504 + start = start * 1. + stop = stop * 1. + if dtype is None: dtype = result_type(start, stop, float(num)) diff --git a/numpy/core/include/numpy/_numpyconfig.h.in b/numpy/core/include/numpy/_numpyconfig.h.in index 2a159f56d..20f21c1a7 100644 --- a/numpy/core/include/numpy/_numpyconfig.h.in +++ b/numpy/core/include/numpy/_numpyconfig.h.in @@ -30,6 +30,8 @@ @DEFINE_NPY_SIZEOF_PY_LONG_LONG@ @DEFINE_NPY_ENABLE_SEPARATE_COMPILATION@ +@DEFINE_NPY_RELAXED_STRIDES_CHECKING@ + #define NPY_VISIBILITY_HIDDEN @VISIBILITY_HIDDEN@ @DEFINE_NPY_USE_C99_FORMATS@ diff --git a/numpy/core/include/numpy/ndarraytypes.h b/numpy/core/include/numpy/ndarraytypes.h index fd64cd75f..21ff8cd1a 100644 --- a/numpy/core/include/numpy/ndarraytypes.h +++ b/numpy/core/include/numpy/ndarraytypes.h @@ -928,12 +928,14 @@ typedef int (PyArray_FinalizeFunc)(PyArrayObject *, PyObject *); #define PyArray_IS_C_CONTIGUOUS(m) PyArray_CHKFLAGS(m, NPY_ARRAY_C_CONTIGUOUS) #define PyArray_IS_F_CONTIGUOUS(m) PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS) +/* the variable is used in some places, so always define it */ +#define NPY_BEGIN_THREADS_DEF PyThreadState *_save=NULL; #if NPY_ALLOW_THREADS #define NPY_BEGIN_ALLOW_THREADS Py_BEGIN_ALLOW_THREADS #define NPY_END_ALLOW_THREADS Py_END_ALLOW_THREADS -#define NPY_BEGIN_THREADS_DEF PyThreadState *_save=NULL; #define NPY_BEGIN_THREADS do {_save = PyEval_SaveThread();} while (0); -#define NPY_END_THREADS do {if (_save) PyEval_RestoreThread(_save);} while (0); +#define NPY_END_THREADS do { if (_save) \ + { PyEval_RestoreThread(_save); _save = NULL;} } while (0); #define NPY_BEGIN_THREADS_THRESHOLDED(loop_size) do { if (loop_size > 500) \ { _save = PyEval_SaveThread();} } while (0); @@ -951,9 +953,9 @@ typedef int (PyArray_FinalizeFunc)(PyArrayObject *, PyObject *); #else #define NPY_BEGIN_ALLOW_THREADS #define NPY_END_ALLOW_THREADS -#define NPY_BEGIN_THREADS_DEF #define NPY_BEGIN_THREADS #define NPY_END_THREADS +#define NPY_BEGIN_THREADS_THRESHOLDED(loop_size) #define NPY_BEGIN_THREADS_DESCR(dtype) #define NPY_END_THREADS_DESCR(dtype) #define NPY_ALLOW_C_API_DEF @@ -1254,8 +1256,12 @@ typedef struct { #define PyArray_MultiIter_NOTDONE(multi) \ (_PyMIT(multi)->index < _PyMIT(multi)->size) -/* Store the information needed for fancy-indexing over an array */ +/* + * Store the information needed for fancy-indexing over an array. The + * fields are slightly unordered to keep consec, dataptr and subspace + * where they were originally. + */ typedef struct { PyObject_HEAD /* @@ -1270,33 +1276,71 @@ typedef struct { npy_intp index; /* current index */ int nd; /* number of dims */ npy_intp dimensions[NPY_MAXDIMS]; /* dimensions */ - PyArrayIterObject *iters[NPY_MAXDIMS]; /* index object - iterators */ - PyArrayIterObject *ait; /* flat Iterator for - underlying array */ + NpyIter *outer; /* index objects + iterator */ + void *unused[NPY_MAXDIMS - 2]; + PyArrayObject *array; + /* Flat iterator for the indexed array. For compatibility solely. */ + PyArrayIterObject *ait; - /* flat iterator for subspace (when numiter < nd) */ - PyArrayIterObject *subspace; + /* + * Subspace array. For binary compatibility (was an iterator, + * but only the check for NULL should be used). + */ + PyArrayObject *subspace; /* * if subspace iteration, then this is the array of axes in * the underlying array represented by the index objects */ int iteraxes[NPY_MAXDIMS]; - /* - * if subspace iteration, the these are the coordinates to the - * start of the subspace. - */ - npy_intp bscoord[NPY_MAXDIMS]; + npy_intp fancy_strides[NPY_MAXDIMS]; + + /* pointer when all fancy indices are 0 */ + char *baseoffset; - PyObject *indexobj; /* creating obj */ /* - * consec is first used to indicate wether fancy indices are - * consecutive and then denotes at which axis they are inserted + * after binding consec denotes at which axis the fancy axes + * are inserted. */ int consec; char *dataptr; + int nd_fancy; + npy_intp fancy_dims[NPY_MAXDIMS]; + + /* Whether the iterator (any of the iterators) requires API */ + int needs_api; + + /* + * Extra op information. + */ + PyArrayObject *extra_op; + PyArray_Descr *extra_op_dtype; /* desired dtype */ + npy_uint32 *extra_op_flags; /* Iterator flags */ + + NpyIter *extra_op_iter; + NpyIter_IterNextFunc *extra_op_next; + char **extra_op_ptrs; + + /* + * Information about the iteration state. + */ + NpyIter_IterNextFunc *outer_next; + char **outer_ptrs; + npy_intp *outer_strides; + + /* + * Information about the subspace iterator. + */ + NpyIter *subspace_iter; + NpyIter_IterNextFunc *subspace_next; + char **subspace_ptrs; + npy_intp *subspace_strides; + + /* Count for the external loop (which ever it is) for API iteration */ + npy_intp iter_count; + } PyArrayMapIterObject; enum { @@ -1448,13 +1492,13 @@ PyArray_STRIDE(const PyArrayObject *arr, int istride) return ((PyArrayObject_fields *)arr)->strides[istride]; } -static NPY_INLINE PyObject * +static NPY_INLINE NPY_RETURNS_BORROWED_REF PyObject * PyArray_BASE(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->base; } -static NPY_INLINE PyArray_Descr * +static NPY_INLINE NPY_RETURNS_BORROWED_REF PyArray_Descr * PyArray_DESCR(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->descr; diff --git a/numpy/core/include/numpy/npy_3kcompat.h b/numpy/core/include/numpy/npy_3kcompat.h index f4078dad2..fec95779a 100644 --- a/numpy/core/include/numpy/npy_3kcompat.h +++ b/numpy/core/include/numpy/npy_3kcompat.h @@ -141,12 +141,11 @@ PyUnicode_Concat2(PyObject **left, PyObject *right) * PyFile_* compatibility */ #if defined(NPY_PY3K) - /* * Get a FILE* handle to the file represented by the Python object */ static NPY_INLINE FILE* -npy_PyFile_Dup(PyObject *file, char *mode, npy_off_t *orig_pos) +npy_PyFile_Dup2(PyObject *file, char *mode, npy_off_t *orig_pos) { int fd, fd2; PyObject *ret, *os; @@ -164,8 +163,10 @@ npy_PyFile_Dup(PyObject *file, char *mode, npy_off_t *orig_pos) return NULL; } - /* The handle needs to be dup'd because we have to call fclose - at the end */ + /* + * The handle needs to be dup'd because we have to call fclose + * at the end + */ os = PyImport_ImportModule("os"); if (os == NULL) { return NULL; @@ -193,7 +194,8 @@ npy_PyFile_Dup(PyObject *file, char *mode, npy_off_t *orig_pos) *orig_pos = npy_ftell(handle); if (*orig_pos == -1) { PyErr_SetString(PyExc_IOError, "obtaining file position failed"); - return -1; + fclose(handle); + return NULL; } /* Seek raw handle to the Python-side position */ @@ -202,7 +204,7 @@ npy_PyFile_Dup(PyObject *file, char *mode, npy_off_t *orig_pos) fclose(handle); return NULL; } - pos = PyNumber_AsSsize_t(ret, PyExc_OverflowError); + pos = PyLong_AsLongLong(ret); Py_DECREF(ret); if (PyErr_Occurred()) { fclose(handle); @@ -210,7 +212,8 @@ npy_PyFile_Dup(PyObject *file, char *mode, npy_off_t *orig_pos) } if (npy_fseek(handle, pos, SEEK_SET) == -1) { PyErr_SetString(PyExc_IOError, "seeking file failed"); - return -1; + fclose(handle); + return NULL; } return handle; } @@ -219,7 +222,7 @@ npy_PyFile_Dup(PyObject *file, char *mode, npy_off_t *orig_pos) * Close the dup-ed file handle, and seek the Python one to the current position */ static NPY_INLINE int -npy_PyFile_DupClose(PyObject *file, FILE* handle, npy_off_t orig_pos) +npy_PyFile_DupClose2(PyObject *file, FILE* handle, npy_off_t orig_pos) { int fd; PyObject *ret; @@ -230,8 +233,10 @@ npy_PyFile_DupClose(PyObject *file, FILE* handle, npy_off_t orig_pos) /* Close the FILE* handle */ fclose(handle); - /* Restore original file handle position, in order to not confuse - Python-side data structures */ + /* + * Restore original file handle position, in order to not confuse + * Python-side data structures + */ fd = PyObject_AsFileDescriptor(file); if (fd == -1) { return -1; @@ -267,14 +272,71 @@ npy_PyFile_Check(PyObject *file) return 1; } +/* + * DEPRECATED DO NOT USE + * use npy_PyFile_DupClose2 instead + * this function will mess ups python3 internal file object buffering + * Close the dup-ed file handle, and seek the Python one to the current position + */ +static NPY_INLINE int +npy_PyFile_DupClose(PyObject *file, FILE* handle) +{ + PyObject *ret; + Py_ssize_t position; + position = npy_ftell(handle); + fclose(handle); + + ret = PyObject_CallMethod(file, "seek", NPY_SSIZE_T_PYFMT "i", position, 0); + if (ret == NULL) { + return -1; + } + Py_DECREF(ret); + return 0; +} + + #else -#define npy_PyFile_Dup(file, mode, orig_pos_p) PyFile_AsFile(file) -#define npy_PyFile_DupClose(file, handle, orig_pos) (0) +/* DEPRECATED, DO NOT USE */ +#define npy_PyFile_DupClose(f, h, p) npy_PyFile_DupClose2((f), (h), (p)) + +/* use these */ +static NPY_INLINE FILE * +npy_PyFile_Dup2(PyObject *file, + const char *NPY_UNUSED(mode), npy_off_t *NPY_UNUSED(orig_pos)) +{ + return PyFile_AsFile(file); +} + +static NPY_INLINE int +npy_PyFile_DupClose2(PyObject *NPY_UNUSED(file), FILE* NPY_UNUSED(handle), + npy_off_t NPY_UNUSED(orig_pos)) +{ + return 0; +} + #define npy_PyFile_Check PyFile_Check #endif +/* + * DEPRECATED, DO NOT USE + * Use npy_PyFile_Dup2 instead. + * This function will mess up python3 internal file object buffering. + * Get a FILE* handle to the file represented by the Python object. + */ +static NPY_INLINE FILE* +npy_PyFile_Dup(PyObject *file, char *mode) +{ + npy_off_t orig; + if (DEPRECATE("npy_PyFile_Dup is deprecated, use " + "npy_PyFile_Dup2") < 0) { + return NULL; + } + + return npy_PyFile_Dup2(file, mode, &orig); +} + static NPY_INLINE PyObject* npy_PyFile_OpenFile(PyObject *filename, const char *mode) { @@ -389,12 +451,6 @@ NpyCapsule_Check(PyObject *ptr) return PyCapsule_CheckExact(ptr); } -static NPY_INLINE void -simple_capsule_dtor(PyObject *cap) -{ - PyArray_free(PyCapsule_GetPointer(cap, NULL)); -} - #else static NPY_INLINE PyObject * @@ -428,12 +484,6 @@ NpyCapsule_Check(PyObject *ptr) return PyCObject_Check(ptr); } -static NPY_INLINE void -simple_capsule_dtor(void *ptr) -{ - PyArray_free(ptr); -} - #endif /* diff --git a/numpy/core/include/numpy/npy_common.h b/numpy/core/include/numpy/npy_common.h index 15961e853..5cba8c9d2 100644 --- a/numpy/core/include/numpy/npy_common.h +++ b/numpy/core/include/numpy/npy_common.h @@ -18,6 +18,23 @@ #define NPY_GCC_UNROLL_LOOPS #endif +/* highest gcc optimization level, enabled autovectorizer */ +#ifdef HAVE_ATTRIBUTE_OPTIMIZE_OPT_3 +#define NPY_GCC_OPT_3 __attribute__((optimize("O3"))) +#else +#define NPY_GCC_OPT_3 +#endif + +/* + * mark an argument (starting from 1) that must not be NULL and is not checked + * DO NOT USE IF FUNCTION CHECKS FOR NULL!! the compiler will remove the check + */ +#ifdef HAVE_ATTRIBUTE_NONNULL +#define NPY_GCC_NONNULL(n) __attribute__((nonnull(n))) +#else +#define NPY_GCC_NONNULL(n) +#endif + #if defined HAVE_XMMINTRIN_H && defined HAVE__MM_LOAD_PS #define NPY_HAVE_SSE_INTRINSICS #endif @@ -56,9 +73,41 @@ #define NPY_INLINE #endif +#ifdef HAVE___THREAD + #define NPY_TLS __thread +#else + #ifdef HAVE___DECLSPEC_THREAD_ + #define NPY_TLS __declspec(thread) + #else + #define NPY_TLS + #endif +#endif + +#ifdef WITH_CPYCHECKER_RETURNS_BORROWED_REF_ATTRIBUTE + #define NPY_RETURNS_BORROWED_REF \ + __attribute__((cpychecker_returns_borrowed_ref)) +#else + #define NPY_RETURNS_BORROWED_REF +#endif + +#ifdef WITH_CPYCHECKER_STEALS_REFERENCE_TO_ARG_ATTRIBUTE + #define NPY_STEALS_REF_TO_ARG(n) \ + __attribute__((cpychecker_steals_reference_to_arg(n))) +#else + #define NPY_STEALS_REF_TO_ARG(n) +#endif + /* 64 bit file position support, also on win-amd64. Ticket #1660 */ -#if defined(_MSC_VER) && defined(_WIN64) && (_MSC_VER > 1400) +#if defined(_MSC_VER) && defined(_WIN64) && (_MSC_VER > 1400) || \ + defined(__MINGW32__) || defined(__MINGW64__) #include <io.h> + +/* mingw based on 3.4.5 has lseek but not ftell/fseek */ +#if defined(__MINGW32__) || defined(__MINGW64__) +extern int __cdecl _fseeki64(FILE *, long long, int); +extern long long __cdecl _ftelli64(FILE *); +#endif + #define npy_fseek _fseeki64 #define npy_ftell _ftelli64 #define npy_lseek _lseeki64 @@ -74,8 +123,16 @@ #error Unsupported size for type off_t #endif #else +#ifdef HAVE_FSEEKO + #define npy_fseek fseeko +#else #define npy_fseek fseek +#endif +#ifdef HAVE_FTELLO + #define npy_ftell ftello +#else #define npy_ftell ftell +#endif #define npy_lseek lseek #define npy_off_t off_t diff --git a/numpy/core/include/numpy/npy_cpu.h b/numpy/core/include/numpy/npy_cpu.h index 80bd5fc56..24d4ce1fc 100644 --- a/numpy/core/include/numpy/npy_cpu.h +++ b/numpy/core/include/numpy/npy_cpu.h @@ -5,6 +5,7 @@ * NPY_CPU_AMD64 * NPY_CPU_PPC * NPY_CPU_PPC64 + * NPY_CPU_PPC64LE * NPY_CPU_SPARC * NPY_CPU_S390 * NPY_CPU_IA64 @@ -41,6 +42,8 @@ * _ARCH_PPC is used by at least gcc on AIX */ #define NPY_CPU_PPC +#elif defined(__ppc64le__) + #define NPY_CPU_PPC64LE #elif defined(__ppc64__) #define NPY_CPU_PPC64 #elif defined(__sparc__) || defined(__sparc) @@ -66,6 +69,8 @@ #define NPY_CPU_MIPSEL #elif defined(__MIPSEB__) #define NPY_CPU_MIPSEB +#elif defined(__or1k__) + #define NPY_CPU_OR1K #elif defined(__aarch64__) #define NPY_CPU_AARCH64 #elif defined(__mc68000__) diff --git a/numpy/core/include/numpy/npy_endian.h b/numpy/core/include/numpy/npy_endian.h index 36d09232f..3ba03d0e3 100644 --- a/numpy/core/include/numpy/npy_endian.h +++ b/numpy/core/include/numpy/npy_endian.h @@ -27,7 +27,8 @@ || defined(NPY_CPU_ARMEL) \ || defined(NPY_CPU_AARCH64) \ || defined(NPY_CPU_SH_LE) \ - || defined(NPY_CPU_MIPSEL) + || defined(NPY_CPU_MIPSEL) \ + || defined(NPY_CPU_PPC64LE) #define NPY_BYTE_ORDER NPY_LITTLE_ENDIAN #elif defined(NPY_CPU_PPC) \ || defined(NPY_CPU_SPARC) \ @@ -37,6 +38,7 @@ || defined(NPY_CPU_ARMEB) \ || defined(NPY_CPU_SH_BE) \ || defined(NPY_CPU_MIPSEB) \ + || defined(NPY_CPU_OR1K) \ || defined(NPY_CPU_M68K) #define NPY_BYTE_ORDER NPY_BIG_ENDIAN #else diff --git a/numpy/core/include/numpy/numpyconfig.h b/numpy/core/include/numpy/numpyconfig.h index 5ca171f21..9d6dce004 100644 --- a/numpy/core/include/numpy/numpyconfig.h +++ b/numpy/core/include/numpy/numpyconfig.h @@ -30,5 +30,6 @@ */ #define NPY_1_7_API_VERSION 0x00000007 #define NPY_1_8_API_VERSION 0x00000008 +#define NPY_1_9_API_VERSION 0x00000008 #endif diff --git a/numpy/core/include/numpy/ufuncobject.h b/numpy/core/include/numpy/ufuncobject.h index 38e3dcf0f..a24a0d837 100644 --- a/numpy/core/include/numpy/ufuncobject.h +++ b/numpy/core/include/numpy/ufuncobject.h @@ -152,13 +152,13 @@ typedef struct _tagPyUFuncObject { int check_return; /* The name of the ufunc */ - char *name; + const char *name; /* Array of type numbers, of size ('nargs' * 'ntypes') */ char *types; /* Documentation string */ - char *doc; + const char *doc; void *ptr; PyObject *obj; diff --git a/numpy/core/memmap.py b/numpy/core/memmap.py index 4e0c194f3..b1c96ee29 100644 --- a/numpy/core/memmap.py +++ b/numpy/core/memmap.py @@ -38,6 +38,9 @@ class memmap(ndarray): This class may at some point be turned into a factory function which returns a view into an mmap buffer. + Delete the memmap instance to close. + + Parameters ---------- filename : str or file-like object @@ -91,8 +94,6 @@ class memmap(ndarray): Methods ------- - close - Close the memmap file. flush Flush any changes in memory to file on disk. When you delete a memmap object, flush is called first to write diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 39e5a4cd5..12e690f1e 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1,13 +1,16 @@ from __future__ import division, absolute_import, print_function +import os import sys import warnings import collections from . import multiarray from . import umath -from .umath import * +from .umath import (invert, sin, UFUNC_BUFSIZE_DEFAULT, ERR_IGNORE, + ERR_WARN, ERR_RAISE, ERR_CALL, ERR_PRINT, ERR_LOG, + ERR_DEFAULT, PINF, NAN) from . import numerictypes -from .numerictypes import * +from .numerictypes import longlong, intc, int_, float_, complex_, bool_ if sys.version_info[0] >= 3: import pickle @@ -355,9 +358,6 @@ def extend_all(module): if a not in adict: __all__.append(a) -extend_all(umath) -extend_all(numerictypes) - newaxis = None @@ -766,7 +766,7 @@ def argwhere(a): [1, 2]]) """ - return transpose(asanyarray(a).nonzero()) + return transpose(nonzero(a)) def flatnonzero(a): """ @@ -941,6 +941,8 @@ def convolve(a,v,mode='full'): scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier Transform. scipy.linalg.toeplitz : Used to construct the convolution operator. + polymul : Polynomial multiplication. Same output as convolve, but also + accepts poly1d objects as input. Notes ----- @@ -991,7 +993,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, out=None): """ Compute the outer product of two vectors. @@ -1012,6 +1014,10 @@ def outer(a, b): b : (N,) array_like Second input vector. Input is flattened if not already 1-dimensional. + out : (M, N) ndarray, optional + A location where the result is stored + + .. versionadded:: 1.9.0 Returns ------- @@ -1065,12 +1071,20 @@ def outer(a, b): """ a = asarray(a) b = asarray(b) - return a.ravel()[:, newaxis]*b.ravel()[newaxis,:] + return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis,:], out) # try to import blas optimized dot if available +envbak = os.environ.copy() try: # importing this changes the dot function for basic 4 types # to blas-optimized versions. + + # disables openblas affinity setting of the main thread that limits + # python threads or processes to one core + if 'OPENBLAS_MAIN_FREE' not in os.environ: + os.environ['OPENBLAS_MAIN_FREE'] = '1' + if 'GOTOBLAS_MAIN_FREE' not in os.environ: + os.environ['GOTOBLAS_MAIN_FREE'] = '1' from ._dotblas import dot, vdot, inner, alterdot, restoredot except ImportError: # docstrings are in add_newdocs.py @@ -1082,6 +1096,10 @@ except ImportError: pass def restoredot(): pass +finally: + os.environ.clear() + os.environ.update(envbak) + del envbak def tensordot(a, b, axes=2): """ @@ -1429,6 +1447,11 @@ def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): outer : Outer product. ix_ : Construct index arrays. + Notes + ----- + .. versionadded:: 1.9.0 + Supports full broadcasting of the inputs. + Examples -------- Vector cross-product. @@ -1490,39 +1513,86 @@ def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): """ if axis is not None: - 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]): + axisa, axisb, axisc = (axis,) * 3 + a = asarray(a) + b = asarray(b) + # Move working axis to the end of the shape + a = rollaxis(a, axisa, a.ndim) + b = rollaxis(b, axisb, b.ndim) + msg = ("incompatible dimensions for cross product\n" + "(dimension must be 2 or 3)") + if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3): raise ValueError(msg) - if a.shape[0] == 2: - if (b.shape[0] == 2): - cp = a[0]*b[1] - a[1]*b[0] + + # Create the output array + shape = broadcast(a[..., 0], b[..., 0]).shape + if a.shape[-1] == 3 or b.shape[-1] == 3: + shape += (3,) + dtype = promote_types(a.dtype, b.dtype) + cp = empty(shape, dtype) + + # create local aliases for readability + a0 = a[..., 0] + a1 = a[..., 1] + if a.shape[-1] == 3: + a2 = a[..., 2] + b0 = b[..., 0] + b1 = b[..., 1] + if b.shape[-1] == 3: + b2 = b[..., 2] + if cp.ndim != 0 and cp.shape[-1] == 3: + cp0 = cp[..., 0] + cp1 = cp[..., 1] + cp2 = cp[..., 2] + + if a.shape[-1] == 2: + if b.shape[-1] == 2: + # a0 * b1 - a1 * b0 + multiply(a0, b1, out=cp) + cp -= a1 * b0 if cp.ndim == 0: return cp else: - return cp.swapaxes(0, axisc) + # This works because we are moving the last axis + return rollaxis(cp, -1, axisc) else: - x = a[1]*b[2] - y = -a[0]*b[2] - z = a[0]*b[1] - a[1]*b[0] - elif a.shape[0] == 3: - if (b.shape[0] == 3): - x = a[1]*b[2] - a[2]*b[1] - y = a[2]*b[0] - a[0]*b[2] - z = a[0]*b[1] - a[1]*b[0] + # cp0 = a1 * b2 - 0 (a2 = 0) + # cp1 = 0 - a0 * b2 (a2 = 0) + # cp2 = a0 * b1 - a1 * b0 + multiply(a1, b2, out=cp0) + multiply(a0, b2, out=cp1) + negative(cp1, out=cp1) + multiply(a0, b1, out=cp2) + cp2 -= a1 * b0 + elif a.shape[-1] == 3: + if b.shape[-1] == 3: + # cp0 = a1 * b2 - a2 * b1 + # cp1 = a2 * b0 - a0 * b2 + # cp2 = a0 * b1 - a1 * b0 + multiply(a1, b2, out=cp0) + tmp = array(a2 * b1) + cp0 -= tmp + multiply(a2, b0, out=cp1) + multiply(a0, b2, out=tmp) + cp1 -= tmp + multiply(a0, b1, out=cp2) + multiply(a1, b0, out=tmp) + cp2 -= tmp else: - x = -a[2]*b[1] - y = a[2]*b[0] - z = a[0]*b[1] - a[1]*b[0] - cp = array([x, y, z]) + # cp0 = 0 - a2 * b1 (b2 = 0) + # cp1 = a2 * b0 - 0 (b2 = 0) + # cp2 = a0 * b1 - a1 * b0 + multiply(a2, b1, out=cp0) + negative(cp0, out=cp0) + multiply(a2, b0, out=cp1) + multiply(a0, b1, out=cp2) + cp2 -= a1 * b0 + if cp.ndim == 1: return cp else: - return cp.swapaxes(0, axisc) - + # This works because we are moving the last axis + return rollaxis(cp, -1, axisc) #Use numarray's printing function from .arrayprint import array2string, get_printoptions, set_printoptions @@ -2139,6 +2209,11 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8): x = array(a, copy=False, ndmin=1) y = array(b, copy=False, ndmin=1) + # make sure y is an inexact type to avoid abs(MIN_INT); will cause + # casting of x later. + dtype = multiarray.result_type(y, 1.) + y = array(y, dtype=dtype, copy=False) + xinf = isinf(x) yinf = isinf(y) if any(xinf) or any(yinf): @@ -2154,7 +2229,7 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8): # ignore invalid fpe's with errstate(invalid='ignore'): - r = all(less_equal(abs(x-y), atol + rtol * abs(y))) + r = all(less_equal(abs(x - y), atol + rtol * abs(y))) return r @@ -2329,10 +2404,12 @@ def array_equiv(a1, a2): except: return False try: - return bool(asarray(a1 == a2).all()) - except ValueError: + multiarray.broadcast(a1, a2) + except: return False + return bool(asarray(a1 == a2).all()) + _errdict = {"ignore":ERR_IGNORE, "warn":ERR_WARN, @@ -2404,7 +2481,7 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): >>> np.seterr(over='raise') {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} - >>> np.seterr(all='ignore') # reset to default + >>> np.seterr(**old_settings) # reset to default {'over': 'raise', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} >>> np.int16(32000) * np.int16(3) @@ -2754,6 +2831,10 @@ nan = NaN = NAN False_ = bool_(False) True_ = bool_(True) +from .umath import * +from .numerictypes import * from . import fromnumeric from .fromnumeric import * extend_all(fromnumeric) +extend_all(umath) +extend_all(numerictypes) diff --git a/numpy/core/numerictypes.py b/numpy/core/numerictypes.py index 8dc4ca75e..1545bc734 100644 --- a/numpy/core/numerictypes.py +++ b/numpy/core/numerictypes.py @@ -98,6 +98,7 @@ from numpy.core.multiarray import ( import types as _types import sys from numpy.compat import bytes, long +import numbers # we don't export these for import *, but we do want them accessible # as numerictypes.bool, etc. @@ -960,6 +961,12 @@ def _can_coerce_all(dtypelist, start=0): thisind += 1 return None +def _register_types(): + numbers.Integral.register(integer) + numbers.Complex.register(inexact) + numbers.Real.register(floating) +_register_types() + def find_common_type(array_types, scalar_types): """ Determine common type following standard coercion rules. diff --git a/numpy/core/setup.py b/numpy/core/setup.py index 2cb2f3a8b..5da042413 100644 --- a/numpy/core/setup.py +++ b/numpy/core/setup.py @@ -175,12 +175,16 @@ def check_math_capabilities(config, moredefs, mathlibs): headers=headers): moredefs.append((fname2def(f), 1)) - for dec, fn in OPTIONAL_GCC_ATTRIBUTES: - if config.check_funcs_once([fn], - decl=dict((('%s %s' % (dec, fn), True),)), - call=False): + for dec, fn in OPTIONAL_FUNCTION_ATTRIBUTES: + if config.check_func(fn, decl='int %s %s(void *);' % (dec, fn), + call=False): moredefs.append((fname2def(fn), 1)) + for fn in OPTIONAL_VARIABLE_ATTRIBUTES: + if config.check_func(fn, decl='int %s a;' % (fn), call=False): + m = fn.replace("(", "_").replace(")", "_") + moredefs.append((fname2def(m), 1)) + # C99 functions: float and long double versions check_funcs(C99_FUNCS_SINGLE) check_funcs(C99_FUNCS_EXTENDED) @@ -466,7 +470,7 @@ def configuration(parent_package='',top_path=None): 'MOTOROLA_EXTENDED_12_BYTES_BE', 'IEEE_QUAD_LE', 'IEEE_QUAD_BE', 'IEEE_DOUBLE_LE', 'IEEE_DOUBLE_BE', - 'DOUBLE_DOUBLE_BE']: + 'DOUBLE_DOUBLE_BE', 'DOUBLE_DOUBLE_LE']: moredefs.append(('HAVE_LDOUBLE_%s' % rep, 1)) else: raise ValueError("Unrecognized long double format: %s" % rep) @@ -629,6 +633,9 @@ def configuration(parent_package='',top_path=None): config.add_include_dirs(join('src', 'npysort')) config.add_define_macros([("HAVE_NPY_CONFIG_H", "1")]) + config.add_define_macros([("_FILE_OFFSET_BITS", "64")]) + config.add_define_macros([('_LARGEFILE_SOURCE', '1')]) + config.add_define_macros([('_LARGEFILE64_SOURCE', '1')]) config.numpy_include_dirs.extend(config.paths('include')) @@ -704,8 +711,11 @@ def configuration(parent_package='',top_path=None): npysort_sources=[join('src', 'npysort', 'quicksort.c.src'), join('src', 'npysort', 'mergesort.c.src'), join('src', 'npysort', 'heapsort.c.src'), - join('src','private', 'npy_partition.h.src'), - join('src', 'npysort', 'selection.c.src')] + join('src', 'private', 'npy_partition.h.src'), + join('src', 'npysort', 'selection.c.src'), + join('src', 'private', 'npy_binsearch.h.src'), + join('src', 'npysort', 'binsearch.c.src'), + ] config.add_library('npysort', sources=npysort_sources, include_dirs=[]) @@ -787,6 +797,7 @@ def configuration(parent_package='',top_path=None): ] + npysort_sources + npymath_sources multiarray_src = [ + join('src', 'multiarray', 'alloc.c'), join('src', 'multiarray', 'arrayobject.c'), join('src', 'multiarray', 'arraytypes.c.src'), join('src', 'multiarray', 'array_assign.c'), @@ -857,9 +868,8 @@ def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import get_cmd subpath = join('src', 'umath') - # NOTE: For manual template conversion of loops.h.src, read the note - # in that file. sources = [ + join(local_dir, subpath, 'loops.h.src'), join(local_dir, subpath, 'loops.c.src'), join(local_dir, subpath, 'simd.inc.src')] @@ -889,6 +899,7 @@ def configuration(parent_package='',top_path=None): join('src', 'umath', 'reduction.c'), join('src', 'umath', 'funcs.inc.src'), join('src', 'umath', 'simd.inc.src'), + join('src', 'umath', 'loops.h.src'), join('src', 'umath', 'loops.c.src'), join('src', 'umath', 'ufunc_object.c'), join('src', 'umath', 'ufunc_type_resolution.c')] diff --git a/numpy/core/setup_common.py b/numpy/core/setup_common.py index bad3607fa..be5673a47 100644 --- a/numpy/core/setup_common.py +++ b/numpy/core/setup_common.py @@ -34,6 +34,7 @@ C_ABI_VERSION = 0x01000009 # # 0x00000008 - 1.7.x # 0x00000009 - 1.8.x +# 0x00000009 - 1.9.x C_API_VERSION = 0x00000009 class MismatchCAPIWarning(Warning): @@ -98,7 +99,8 @@ MANDATORY_FUNCS = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", # replacement implementation. Note that some of these are C99 functions. OPTIONAL_STDFUNCS = ["expm1", "log1p", "acosh", "asinh", "atanh", "rint", "trunc", "exp2", "log2", "hypot", "atan2", "pow", - "copysign", "nextafter"] + "copysign", "nextafter", "ftello", "fseeko", + "strtoll", "strtoull"] OPTIONAL_HEADERS = [ @@ -120,16 +122,23 @@ OPTIONAL_INTRINSICS = [("__builtin_isnan", '5.'), ("_mm_load_pd", '(double*)0', "emmintrin.h"), # SSE2 ] -# gcc function attributes -# (attribute as understood by gcc, function name), +# function attributes +# tested via "int %s %s(void *);" % (attribute, name) # function name will be converted to HAVE_<upper-case-name> preprocessor macro -OPTIONAL_GCC_ATTRIBUTES = [('__attribute__((optimize("unroll-loops")))', - 'attribute_optimize_unroll_loops'), - ] +OPTIONAL_FUNCTION_ATTRIBUTES = [('__attribute__((optimize("unroll-loops")))', + 'attribute_optimize_unroll_loops'), + ('__attribute__((optimize("O3")))', + 'attribute_optimize_opt_3'), + ('__attribute__((nonnull (1)))', + 'attribute_nonnull'), + ] + +# variable attributes tested via "int %s a" % attribute +OPTIONAL_VARIABLE_ATTRIBUTES = ["__thread", "__declspec(thread)"] # Subset of OPTIONAL_STDFUNCS which may alreay have HAVE_* defined by Python.h OPTIONAL_STDFUNCS_MAYBE = ["expm1", "log1p", "acosh", "atanh", "asinh", "hypot", - "copysign"] + "copysign", "ftello", "fseeko"] # C99 functions: float and long double versions C99_FUNCS = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", "floor", @@ -256,6 +265,8 @@ _IEEE_QUAD_PREC_BE = ['300', '031', '326', '363', '105', '100', '000', '000', _IEEE_QUAD_PREC_LE = _IEEE_QUAD_PREC_BE[::-1] _DOUBLE_DOUBLE_BE = ['301', '235', '157', '064', '124', '000', '000', '000'] + \ ['000'] * 8 +_DOUBLE_DOUBLE_LE = ['000', '000', '000', '124', '064', '157', '235', '301'] + \ + ['000'] * 8 def long_double_representation(lines): """Given a binary dump as given by GNU od -b, look for long double @@ -295,6 +306,8 @@ def long_double_representation(lines): return 'IEEE_QUAD_LE' elif read[8:-8] == _DOUBLE_DOUBLE_BE: return 'DOUBLE_DOUBLE_BE' + elif read[8:-8] == _DOUBLE_DOUBLE_LE: + return 'DOUBLE_DOUBLE_LE' elif read[:16] == _BEFORE_SEQ: if read[16:-8] == _IEEE_DOUBLE_LE: return 'IEEE_DOUBLE_LE' diff --git a/numpy/core/src/dummymodule.c b/numpy/core/src/dummymodule.c index e051cc6ff..718199f70 100644 --- a/numpy/core/src/dummymodule.c +++ b/numpy/core/src/dummymodule.c @@ -6,6 +6,7 @@ */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION +#define NO_IMPORT_ARRAY #include <Python.h> #include <npy_pycompat.h> diff --git a/numpy/core/src/multiarray/alloc.c b/numpy/core/src/multiarray/alloc.c new file mode 100644 index 000000000..06c9ff296 --- /dev/null +++ b/numpy/core/src/multiarray/alloc.c @@ -0,0 +1,241 @@ +#define PY_SSIZE_T_CLEAN +#include <Python.h> +#include "structmember.h" + +#define NPY_NO_DEPRECATED_API NPY_API_VERSION +#define _MULTIARRAYMODULE +#include <numpy/ndarraytypes.h> +#include "numpy/arrayobject.h" +#include <numpy/npy_common.h> +#include "npy_config.h" + +#include <assert.h> + +#define NBUCKETS 1024 /* number of buckets for data*/ +#define NBUCKETS_DIM 16 /* number of buckets for dimensions/strides */ +#define NCACHE 8 /* 1 + number of cache entries per bucket */ +static void * datacache[NBUCKETS][NCACHE]; +static void * dimcache[NBUCKETS_DIM][NCACHE]; + +/* + * very simplistic small memory block cache to avoid more expensive libc + * allocations + * base function for data cache with 1 byte buckets and dimension cache with + * sizeof(npy_intp) byte buckets + */ +static NPY_INLINE void * +_npy_alloc_cache(npy_uintp nelem, npy_uintp esz, npy_uint msz, + void * (*cache)[NCACHE], void * (*alloc)(size_t)) +{ + assert((esz == 1 && cache == datacache) || + (esz == sizeof(npy_intp) && cache == dimcache)); + if (nelem < msz) { + /* first entry is used as fill counter */ + npy_uintp * idx = (npy_uintp *)&(cache[nelem][0]); + if (*idx > 0) { + return cache[nelem][(*idx)--]; + } + } + return alloc(nelem * esz); +} + +/* + * return pointer p to cache, nelem is number of elements of the cache bucket + * size (1 or sizeof(npy_intp)) of the block pointed too + */ +static NPY_INLINE void +_npy_free_cache(void * p, npy_uintp nelem, npy_uint msz, + void * (*cache)[NCACHE], void (*dealloc)(void *)) +{ + if (p != NULL && nelem < msz) { + /* first entry is used as fill counter */ + npy_uintp * idx = (npy_uintp *)&(cache[nelem][0]); + if (*idx < NCACHE - 1) { + cache[nelem][++(*idx)] = p; + return; + } + } + dealloc(p); +} + + +/* + * array data cache, sz is number of bytes to allocate + */ +NPY_NO_EXPORT void * +npy_alloc_cache(npy_uintp sz) +{ + return _npy_alloc_cache(sz, 1, NBUCKETS, datacache, &PyDataMem_NEW); +} + +/* zero initialized data, sz is number of bytes to allocate */ +NPY_NO_EXPORT void * +npy_alloc_cache_zero(npy_uintp sz) +{ + void * p; + NPY_BEGIN_THREADS_DEF; + if (sz < NBUCKETS) { + p = _npy_alloc_cache(sz, 1, NBUCKETS, datacache, &PyDataMem_NEW); + memset(p, 0, sz); + return p; + } + NPY_BEGIN_THREADS; + p = PyDataMem_NEW_ZEROED(sz, 1); + NPY_END_THREADS; + return p; +} + +NPY_NO_EXPORT void +npy_free_cache(void * p, npy_uintp sz) +{ + _npy_free_cache(p, sz, NBUCKETS, datacache, &PyDataMem_FREE); +} + +/* + * dimension/stride cache, uses a different allocator and is always a multiple + * of npy_intp + */ +NPY_NO_EXPORT void * +npy_alloc_cache_dim(npy_uintp sz) +{ + /* dims + strides */ + if (NPY_UNLIKELY(sz < 2)) { + sz = 2; + } + return _npy_alloc_cache(sz, sizeof(npy_intp), NBUCKETS_DIM, dimcache, + &PyArray_malloc); +} + +NPY_NO_EXPORT void +npy_free_cache_dim(void * p, npy_uintp sz) +{ + /* dims + strides */ + if (NPY_UNLIKELY(sz < 2)) { + sz = 2; + } + _npy_free_cache(p, sz, NBUCKETS_DIM, dimcache, + &PyArray_free); +} + + +/* malloc/free/realloc hook */ +NPY_NO_EXPORT PyDataMem_EventHookFunc *_PyDataMem_eventhook; +NPY_NO_EXPORT void *_PyDataMem_eventhook_user_data; + +/*NUMPY_API + * Sets the allocation event hook for numpy array data. + * Takes a PyDataMem_EventHookFunc *, which has the signature: + * void hook(void *old, void *new, size_t size, void *user_data). + * Also takes a void *user_data, and void **old_data. + * + * Returns a pointer to the previous hook or NULL. If old_data is + * non-NULL, the previous user_data pointer will be copied to it. + * + * If not NULL, hook will be called at the end of each PyDataMem_NEW/FREE/RENEW: + * result = PyDataMem_NEW(size) -> (*hook)(NULL, result, size, user_data) + * PyDataMem_FREE(ptr) -> (*hook)(ptr, NULL, 0, user_data) + * result = PyDataMem_RENEW(ptr, size) -> (*hook)(ptr, result, size, user_data) + * + * When the hook is called, the GIL will be held by the calling + * thread. The hook should be written to be reentrant, if it performs + * operations that might cause new allocation events (such as the + * creation/descruction numpy objects, or creating/destroying Python + * objects which might cause a gc) + */ +NPY_NO_EXPORT PyDataMem_EventHookFunc * +PyDataMem_SetEventHook(PyDataMem_EventHookFunc *newhook, + void *user_data, void **old_data) +{ + PyDataMem_EventHookFunc *temp; + NPY_ALLOW_C_API_DEF + NPY_ALLOW_C_API + temp = _PyDataMem_eventhook; + _PyDataMem_eventhook = newhook; + if (old_data != NULL) { + *old_data = _PyDataMem_eventhook_user_data; + } + _PyDataMem_eventhook_user_data = user_data; + NPY_DISABLE_C_API + return temp; +} + +/*NUMPY_API + * Allocates memory for array data. + */ +NPY_NO_EXPORT void * +PyDataMem_NEW(size_t size) +{ + void *result; + + result = malloc(size); + if (_PyDataMem_eventhook != NULL) { + NPY_ALLOW_C_API_DEF + NPY_ALLOW_C_API + if (_PyDataMem_eventhook != NULL) { + (*_PyDataMem_eventhook)(NULL, result, size, + _PyDataMem_eventhook_user_data); + } + NPY_DISABLE_C_API + } + return result; +} + +/*NUMPY_API + * Allocates zeroed memory for array data. + */ +NPY_NO_EXPORT void * +PyDataMem_NEW_ZEROED(size_t size, size_t elsize) +{ + void *result; + + result = calloc(size, elsize); + if (_PyDataMem_eventhook != NULL) { + NPY_ALLOW_C_API_DEF + NPY_ALLOW_C_API + if (_PyDataMem_eventhook != NULL) { + (*_PyDataMem_eventhook)(NULL, result, size * elsize, + _PyDataMem_eventhook_user_data); + } + NPY_DISABLE_C_API + } + return result; +} + +/*NUMPY_API + * Free memory for array data. + */ +NPY_NO_EXPORT void +PyDataMem_FREE(void *ptr) +{ + free(ptr); + if (_PyDataMem_eventhook != NULL) { + NPY_ALLOW_C_API_DEF + NPY_ALLOW_C_API + if (_PyDataMem_eventhook != NULL) { + (*_PyDataMem_eventhook)(ptr, NULL, 0, + _PyDataMem_eventhook_user_data); + } + NPY_DISABLE_C_API + } +} + +/*NUMPY_API + * Reallocate/resize memory for array data. + */ +NPY_NO_EXPORT void * +PyDataMem_RENEW(void *ptr, size_t size) +{ + void *result; + + result = realloc(ptr, size); + if (_PyDataMem_eventhook != NULL) { + NPY_ALLOW_C_API_DEF + NPY_ALLOW_C_API + if (_PyDataMem_eventhook != NULL) { + (*_PyDataMem_eventhook)(ptr, result, size, + _PyDataMem_eventhook_user_data); + } + NPY_DISABLE_C_API + } + return result; +} diff --git a/numpy/core/src/multiarray/alloc.h b/numpy/core/src/multiarray/alloc.h new file mode 100644 index 000000000..8f6b167d0 --- /dev/null +++ b/numpy/core/src/multiarray/alloc.h @@ -0,0 +1,22 @@ +#ifndef _NPY_ARRAY_ALLOC_H_ +#define _NPY_ARRAY_ALLOC_H_ +#define NPY_NO_DEPRECATED_API NPY_API_VERSION +#define _MULTIARRAYMODULE +#include <numpy/ndarraytypes.h> + +NPY_NO_EXPORT void * +npy_alloc_cache(npy_uintp sz); + +NPY_NO_EXPORT void * +npy_alloc_cache_zero(npy_uintp sz); + +NPY_NO_EXPORT void +npy_free_cache(void * p, npy_uintp sd); + +NPY_NO_EXPORT void * +npy_alloc_cache_dim(npy_uintp sz); + +NPY_NO_EXPORT void +npy_free_cache_dim(void * p, npy_uintp sd); + +#endif diff --git a/numpy/core/src/multiarray/array_assign_array.c b/numpy/core/src/multiarray/array_assign_array.c index 1cf4b3a3b..67c98d8b5 100644 --- a/numpy/core/src/multiarray/array_assign_array.c +++ b/numpy/core/src/multiarray/array_assign_array.c @@ -99,9 +99,7 @@ raw_array_assign_array(int ndim, npy_intp *shape, dst_data, dst_strides_it, src_data, src_strides_it); - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; NPY_AUXDATA_FREE(transferdata); @@ -194,9 +192,7 @@ raw_array_wheremasked_assign_array(int ndim, npy_intp *shape, src_data, src_strides_it, wheremask_data, wheremask_strides_it); - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; NPY_AUXDATA_FREE(transferdata); @@ -238,9 +234,9 @@ PyArray_AssignArray(PyArrayObject *dst, PyArrayObject *src, * case, first an in-place add is done, followed by an assignment, * equivalently expressed like this: * - * tmp = a[1000:6000] # Calls array_subscript_nice in mapping.c + * tmp = a[1000:6000] # Calls array_subscript in mapping.c * np.add(tmp, x, tmp) - * a[1000:6000] = tmp # Calls array_ass_sub in mapping.c + * a[1000:6000] = tmp # Calls array_assign_subscript in mapping.c * * In the assignment the underlying data type, shape, strides, and * data pointers are identical, but src != dst because they are separately diff --git a/numpy/core/src/multiarray/array_assign_scalar.c b/numpy/core/src/multiarray/array_assign_scalar.c index df7facad6..7c1b1f16a 100644 --- a/numpy/core/src/multiarray/array_assign_scalar.c +++ b/numpy/core/src/multiarray/array_assign_scalar.c @@ -72,7 +72,11 @@ raw_array_assign_scalar(int ndim, npy_intp *shape, } if (!needs_api) { - NPY_BEGIN_THREADS; + npy_intp nitems = 1, i; + for (i = 0; i < ndim; i++) { + nitems *= shape_it[i]; + } + NPY_BEGIN_THREADS_THRESHOLDED(nitems); } NPY_RAW_ITER_START(idim, ndim, coord, shape_it) { @@ -82,9 +86,7 @@ raw_array_assign_scalar(int ndim, npy_intp *shape, } NPY_RAW_ITER_ONE_NEXT(idim, ndim, coord, shape_it, dst_data, dst_strides_it); - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; NPY_AUXDATA_FREE(transferdata); @@ -145,7 +147,11 @@ raw_array_wheremasked_assign_scalar(int ndim, npy_intp *shape, } if (!needs_api) { - NPY_BEGIN_THREADS; + npy_intp nitems = 1, i; + for (i = 0; i < ndim; i++) { + nitems *= shape_it[i]; + } + NPY_BEGIN_THREADS_THRESHOLDED(nitems); } NPY_RAW_ITER_START(idim, ndim, coord, shape_it) { @@ -157,9 +163,7 @@ raw_array_wheremasked_assign_scalar(int ndim, npy_intp *shape, dst_data, dst_strides_it, wheremask_data, wheremask_strides_it); - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; NPY_AUXDATA_FREE(transferdata); @@ -234,10 +238,16 @@ PyArray_AssignRawScalar(PyArrayObject *dst, } else { tmp_src_data = PyArray_malloc(PyArray_DESCR(dst)->elsize); + if (tmp_src_data == NULL) { + PyErr_NoMemory(); + goto fail; + } allocated_src_data = 1; } + if (PyArray_CastRawArrays(1, src_data, tmp_src_data, 0, 0, src_dtype, PyArray_DESCR(dst), 0) != NPY_SUCCEED) { + src_data = tmp_src_data; goto fail; } diff --git a/numpy/core/src/multiarray/arrayobject.c b/numpy/core/src/multiarray/arrayobject.c index e3ac1e0d0..d92522a9f 100644 --- a/numpy/core/src/multiarray/arrayobject.c +++ b/numpy/core/src/multiarray/arrayobject.c @@ -50,6 +50,7 @@ maintainer email: oliphant.travis@ieee.org #include "sequence.h" #include "buffer.h" #include "array_assign.h" +#include "alloc.h" /*NUMPY_API Compute the size of an array (in number of items) @@ -419,10 +420,11 @@ array_dealloc(PyArrayObject *self) * self already... */ } - PyDataMem_FREE(fa->data); + npy_free_cache(fa->data, PyArray_NBYTES(self)); } - PyDimMem_FREE(fa->dimensions); + /* must match allocation in PyArray_NewFromDescr */ + npy_free_cache_dim(fa->dimensions, 2 * fa->nd); Py_DECREF(fa->descr); Py_TYPE(self)->tp_free((PyObject *)self); } @@ -1269,11 +1271,12 @@ NPY_NO_EXPORT PyObject * array_richcompare(PyArrayObject *self, PyObject *other, int cmp_op) { PyArrayObject *array_other; + PyObject *obj_self = (PyObject *)self; PyObject *result = NULL; switch (cmp_op) { case Py_LT: - if (needs_right_binop_forward(self, other, "__gt__", 0)) { + if (needs_right_binop_forward(obj_self, other, "__gt__", 0)) { /* See discussion in number.c */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; @@ -1282,7 +1285,7 @@ array_richcompare(PyArrayObject *self, PyObject *other, int cmp_op) n_ops.less); break; case Py_LE: - if (needs_right_binop_forward(self, other, "__ge__", 0)) { + if (needs_right_binop_forward(obj_self, other, "__ge__", 0)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } @@ -1291,10 +1294,14 @@ array_richcompare(PyArrayObject *self, PyObject *other, int cmp_op) break; case Py_EQ: if (other == Py_None) { + if (DEPRECATE_FUTUREWARNING("comparison to `None` will result in " + "an elementwise object comparison in the future.") < 0) { + return NULL; + } Py_INCREF(Py_False); return Py_False; } - if (needs_right_binop_forward(self, other, "__eq__", 0)) { + if (needs_right_binop_forward(obj_self, other, "__eq__", 0)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } @@ -1324,16 +1331,16 @@ array_richcompare(PyArrayObject *self, PyObject *other, int cmp_op) return Py_NotImplemented; } - _res = PyObject_RichCompareBool - ((PyObject *)PyArray_DESCR(self), - (PyObject *)PyArray_DESCR(array_other), - Py_EQ); - if (_res < 0) { + _res = PyArray_CanCastTypeTo(PyArray_DESCR(self), + PyArray_DESCR(array_other), + NPY_EQUIV_CASTING); + if (_res == 0) { Py_DECREF(result); Py_DECREF(array_other); - return NULL; + Py_INCREF(Py_False); + return Py_False; } - if (_res) { + else { Py_DECREF(result); result = _void_compare(self, array_other, cmp_op); } @@ -1346,17 +1353,30 @@ array_richcompare(PyArrayObject *self, PyObject *other, int cmp_op) * indicate that */ if (result == NULL) { + /* + * Comparisons should raise errors when element-wise comparison + * is not possible. + */ PyErr_Clear(); + if (DEPRECATE("elementwise comparison failed; " + "this will raise the error in the future.") < 0) { + return NULL; + } + Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } break; case Py_NE: if (other == Py_None) { + if (DEPRECATE_FUTUREWARNING("comparison to `None` will result in " + "an elementwise object comparison in the future.") < 0) { + return NULL; + } Py_INCREF(Py_True); return Py_True; } - if (needs_right_binop_forward(self, other, "__ne__", 0)) { + if (needs_right_binop_forward(obj_self, other, "__ne__", 0)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } @@ -1385,16 +1405,16 @@ array_richcompare(PyArrayObject *self, PyObject *other, int cmp_op) return Py_NotImplemented; } - _res = PyObject_RichCompareBool( - (PyObject *)PyArray_DESCR(self), - (PyObject *)PyArray_DESCR(array_other), - Py_EQ); - if (_res < 0) { + _res = PyArray_CanCastTypeTo(PyArray_DESCR(self), + PyArray_DESCR(array_other), + NPY_EQUIV_CASTING); + if (_res == 0) { Py_DECREF(result); Py_DECREF(array_other); - return NULL; + Py_INCREF(Py_True); + return Py_True; } - if (_res) { + else { Py_DECREF(result); result = _void_compare(self, array_other, cmp_op); Py_DECREF(array_other); @@ -1403,13 +1423,22 @@ array_richcompare(PyArrayObject *self, PyObject *other, int cmp_op) } if (result == NULL) { + /* + * Comparisons should raise errors when element-wise comparison + * is not possible. + */ PyErr_Clear(); + if (DEPRECATE("elementwise comparison failed; " + "this will raise the error in the future.") < 0) { + return NULL; + } + Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } break; case Py_GT: - if (needs_right_binop_forward(self, other, "__lt__", 0)) { + if (needs_right_binop_forward(obj_self, other, "__lt__", 0)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } @@ -1417,7 +1446,7 @@ array_richcompare(PyArrayObject *self, PyObject *other, int cmp_op) n_ops.greater); break; case Py_GE: - if (needs_right_binop_forward(self, other, "__le__", 0)) { + if (needs_right_binop_forward(obj_self, other, "__le__", 0)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } @@ -1434,7 +1463,11 @@ array_richcompare(PyArrayObject *self, PyObject *other, int cmp_op) return result; } array_other = (PyArrayObject *)PyArray_FromObject(other, - NPY_NOTYPE, 0, 0); + NPY_NOTYPE, 0, 0); + if (array_other == NULL) { + PyErr_Clear(); + return result; + } if (PyArray_ISSTRING(self) && PyArray_ISSTRING(array_other)) { Py_DECREF(result); result = _strings_richcompare(self, (PyArrayObject *) @@ -1683,6 +1716,13 @@ array_alloc(PyTypeObject *type, Py_ssize_t NPY_UNUSED(nitems)) return obj; } +static void +array_free(PyObject * v) +{ + /* avoid same deallocator as PyBaseObject, see gentype_free */ + PyObject_Free(v); +} + NPY_NO_EXPORT PyTypeObject PyArray_Type = { #if defined(NPY_PY3K) @@ -1737,9 +1777,9 @@ NPY_NO_EXPORT PyTypeObject PyArray_Type = { 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)0, /* tp_init */ - array_alloc, /* tp_alloc */ + (allocfunc)array_alloc, /* tp_alloc */ (newfunc)array_new, /* tp_new */ - 0, /* tp_free */ + (freefunc)array_free, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ diff --git a/numpy/core/src/multiarray/arraytypes.c.src b/numpy/core/src/multiarray/arraytypes.c.src index 1bfbf160d..8a0b1826b 100644 --- a/numpy/core/src/multiarray/arraytypes.c.src +++ b/numpy/core/src/multiarray/arraytypes.c.src @@ -18,6 +18,7 @@ #include "usertypes.h" #include "_datetime.h" #include "arrayobject.h" +#include "alloc.h" #include "numpyos.h" @@ -105,6 +106,31 @@ MyPyLong_AsUnsigned@Type@ (PyObject *obj) /**end repeat**/ +static npy_longlong +npy_strtoll(const char *str, char **endptr, int base) +{ +#if defined HAVE_STRTOLL + return strtoll(str, endptr, base); +#elif defined _MSC_VER + return _strtoi64(str, endptr, base); +#else + /* ok on 64 bit posix */ + return PyOS_strtol(str, endptr, base); +#endif +} + +static npy_ulonglong +npy_strtoull(const char *str, char **endptr, int base) +{ +#if defined HAVE_STRTOULL + return strtoull(str, endptr, base); +#elif defined _MSC_VER + return _strtoui64(str, endptr, base); +#else + /* ok on 64 bit posix */ + return PyOS_strtoul(str, endptr, base); +#endif +} /* ***************************************************************************** @@ -401,7 +427,7 @@ STRING_getitem(char *ip, PyArrayObject *ap) int size = PyArray_DESCR(ap)->elsize; ptr = ip + size - 1; - while (*ptr-- == '\0' && size > 0) { + while (size > 0 && *ptr-- == '\0') { size--; } return PyBytes_FromStringAndSize(ip,size); @@ -519,6 +545,31 @@ OBJECT_setitem(PyObject *op, char *ov, PyArrayObject *ap) /* VOID */ +/* unpack tuple of dtype->fields (descr, offset, title[not-needed]) */ +static int +unpack_field(PyObject * value, PyArray_Descr ** descr, npy_intp * offset) +{ + PyObject * off; + if (PyTuple_GET_SIZE(value) < 2) { + return -1; + } + *descr = (PyArray_Descr *)PyTuple_GET_ITEM(value, 0); + off = PyTuple_GET_ITEM(value, 1); + + if (PyInt_Check(off)) { + *offset = PyInt_AsSsize_t(off); + } + else if (PyLong_Check(off)) { + *offset = PyLong_AsSsize_t(off); + } + else { + return -1; + } + + return 0; +} + + static PyObject * VOID_getitem(char *ip, PyArrayObject *ap) { @@ -532,9 +583,7 @@ VOID_getitem(char *ip, PyArrayObject *ap) PyObject *names; int i, n; PyObject *ret; - PyObject *tup, *title; - PyArray_Descr *new; - int offset; + PyObject *tup; int savedflags; /* get the names from the fields dictionary*/ @@ -543,9 +592,11 @@ VOID_getitem(char *ip, PyArrayObject *ap) ret = PyTuple_New(n); savedflags = PyArray_FLAGS(ap); for (i = 0; i < n; i++) { + npy_intp offset; + PyArray_Descr *new; key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(descr->fields, key); - if (!PyArg_ParseTuple(tup, "Oi|O", &new, &offset, &title)) { + if (unpack_field(tup, &new, &offset) < 0) { Py_DECREF(ret); ((PyArrayObject_fields *)ap)->descr = descr; return NULL; @@ -662,9 +713,7 @@ VOID_setitem(PyObject *op, char *ip, PyArrayObject *ap) PyObject *key; PyObject *names; int i, n; - PyObject *tup, *title; - PyArray_Descr *new; - int offset; + PyObject *tup; int savedflags; res = -1; @@ -678,9 +727,11 @@ VOID_setitem(PyObject *op, char *ip, PyArrayObject *ap) } savedflags = PyArray_FLAGS(ap); for (i = 0; i < n; i++) { + PyArray_Descr *new; + npy_intp offset; key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(descr->fields, key); - if (!PyArg_ParseTuple(tup, "Oi|O", &new, &offset, &title)) { + if (unpack_field(tup, &new, &offset) < 0) { ((PyArrayObject_fields *)ap)->descr = descr; return -1; } @@ -1506,8 +1557,10 @@ BOOL_scan(FILE *fp, npy_bool *ip, void *NPY_UNUSED(ignore), * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_datetime, npy_timedelta# - * #func = (l, ul)*5, l, l# - * #btype = (npy_long, npy_ulong)*5, npy_long, npy_long# + * #func = (PyOS_strtol, PyOS_strtoul)*4, npy_strtoll, npy_strtoull, + * npy_strtoll*2# + * #btype = (npy_long, npy_ulong)*4, npy_longlong, npy_ulonglong, + * npy_longlong*2# */ static int @fname@_fromstr(char *str, @type@ *ip, char **endptr, @@ -1515,7 +1568,7 @@ static int { @btype@ result; - result = PyOS_strto@func@(str, endptr, 10); + result = @func@(str, endptr, 10); *ip = (@type@) result; return 0; } @@ -1941,17 +1994,18 @@ VOID_copyswapn (char *dst, npy_intp dstride, char *src, npy_intp sstride, return; } if (PyArray_HASFIELDS(arr)) { - PyObject *key, *value, *title = NULL; - PyArray_Descr *new, *descr; - int offset; + PyObject *key, *value; + PyArray_Descr *descr; Py_ssize_t pos = 0; descr = PyArray_DESCR(arr); while (PyDict_Next(descr->fields, &pos, &key, &value)) { - if NPY_TITLE_KEY(key, value) { + npy_intp offset; + PyArray_Descr * new; + if (NPY_TITLE_KEY(key, value)) { continue; } - if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) { + if (unpack_field(value, &new, &offset) < 0) { ((PyArrayObject_fields *)arr)->descr = descr; return; } @@ -2009,17 +2063,18 @@ VOID_copyswap (char *dst, char *src, int swap, PyArrayObject *arr) return; } if (PyArray_HASFIELDS(arr)) { - PyObject *key, *value, *title = NULL; - PyArray_Descr *new, *descr; - int offset; + PyObject *key, *value; + PyArray_Descr *descr; Py_ssize_t pos = 0; descr = PyArray_DESCR(arr); while (PyDict_Next(descr->fields, &pos, &key, &value)) { - if NPY_TITLE_KEY(key, value) { + npy_intp offset; + PyArray_Descr * new; + if (NPY_TITLE_KEY(key, value)) { continue; } - if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) { + if (unpack_field(value, &new, &offset) < 0) { ((PyArrayObject_fields *)arr)->descr = descr; return; } @@ -2311,19 +2366,20 @@ VOID_nonzero (char *ip, PyArrayObject *ap) npy_bool nonz = NPY_FALSE; if (PyArray_HASFIELDS(ap)) { - PyArray_Descr *descr, *new; - PyObject *key, *value, *title; - int savedflags, offset; + PyArray_Descr *descr; + PyObject *key, *value; + int savedflags; Py_ssize_t pos = 0; descr = PyArray_DESCR(ap); savedflags = PyArray_FLAGS(ap); while (PyDict_Next(descr->fields, &pos, &key, &value)) { - if NPY_TITLE_KEY(key, value) { + PyArray_Descr * new; + npy_intp offset; + if (NPY_TITLE_KEY(key, value)) { continue; } - if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, - &title)) { + if (unpack_field(value, &new, &offset) < 0) { PyErr_Clear(); continue; } @@ -2618,11 +2674,11 @@ UNICODE_compare(npy_ucs4 *ip1, npy_ucs4 *ip2, static int VOID_compare(char *ip1, char *ip2, PyArrayObject *ap) { - PyArray_Descr *descr, *new; + PyArray_Descr *descr; PyObject *names, *key; - PyObject *tup, *title; + PyObject *tup; char *nip1, *nip2; - int i, offset, res = 0, swap=0; + int i, res = 0, swap=0; if (!PyArray_HASFIELDS(ap)) { return STRING_compare(ip1, ip2, ap); @@ -2634,9 +2690,11 @@ VOID_compare(char *ip1, char *ip2, PyArrayObject *ap) */ names = descr->names; for (i = 0; i < PyTuple_GET_SIZE(names); i++) { + PyArray_Descr * new; + npy_intp offset; key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(descr->fields, key); - if (!PyArg_ParseTuple(tup, "Oi|O", &new, &offset, &title)) { + if (unpack_field(tup, &new, &offset) < 0) { goto finish; } /* @@ -2648,9 +2706,9 @@ VOID_compare(char *ip1, char *ip2, PyArrayObject *ap) nip1 = ip1 + offset; nip2 = ip2 + offset; if ((swap) || (new->alignment > 1)) { - if ((swap) || (((npy_intp)(nip1) % new->alignment) != 0)) { + if ((swap) || (!npy_is_aligned(nip1, new->alignment))) { /* create buffer and copy */ - nip1 = PyArray_malloc(new->elsize); + nip1 = npy_alloc_cache(new->elsize); if (nip1 == NULL) { goto finish; } @@ -2658,12 +2716,12 @@ VOID_compare(char *ip1, char *ip2, PyArrayObject *ap) if (swap) new->f->copyswap(nip1, NULL, swap, ap); } - if ((swap) || (((npy_intp)(nip2) % new->alignment) != 0)) { + if ((swap) || (!npy_is_aligned(nip2, new->alignment))) { /* copy data to a buffer */ - nip2 = PyArray_malloc(new->elsize); + nip2 = npy_alloc_cache(new->elsize); if (nip2 == NULL) { if (nip1 != ip1 + offset) { - PyArray_free(nip1); + npy_free_cache(nip1, new->elsize); } goto finish; } @@ -2675,10 +2733,10 @@ VOID_compare(char *ip1, char *ip2, PyArrayObject *ap) res = new->f->compare(nip1, nip2, ap); if ((swap) || (new->alignment > 1)) { if (nip1 != ip1 + offset) { - PyArray_free(nip1); + npy_free_cache(nip1, new->elsize); } if (nip2 != ip2 + offset) { - PyArray_free(nip2); + npy_free_cache(nip2, new->elsize); } } if (res != 0) { @@ -2714,6 +2772,7 @@ finish: * npy_half, npy_float, npy_double, npy_longdouble, * npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# + * #isbool = 1, 0*19# * #isfloat = 0*11, 1*7, 0*2# * #isnan = nop*11, npy_half_isnan, npy_isnan*6, nop*2# * #le = _LESS_THAN_OR_EQUAL*11, npy_half_le, _LESS_THAN_OR_EQUAL*8# @@ -2744,6 +2803,12 @@ static int return 0; } #endif +#if @isbool@ + if (mp) { + /* True encountered; it's maximal */ + return 0; + } +#endif for (i = 1; i < n; i++) { @incr@; @@ -2772,6 +2837,12 @@ static int break; } #endif +#if @isbool@ + if (mp) { + /* True encountered; it's maximal */ + break; + } +#endif } #endif } @@ -2794,6 +2865,7 @@ static int * npy_half, npy_float, npy_double, npy_longdouble, * npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# + * #isbool = 1, 0*19# * #isfloat = 0*11, 1*7, 0*2# * #isnan = nop*11, npy_half_isnan, npy_isnan*6, nop*2# * #le = _LESS_THAN_OR_EQUAL*11, npy_half_le, _LESS_THAN_OR_EQUAL*8# @@ -2824,6 +2896,12 @@ static int return 0; } #endif +#if @isbool@ + if (!mp) { + /* False encountered; it's minimal */ + return 0; + } +#endif for (i = 1; i < n; i++) { @incr@; @@ -2852,6 +2930,12 @@ static int break; } #endif +#if @isbool@ + if (!mp) { + /* False encountered; it's minimal */ + break; + } +#endif } #endif } @@ -3501,16 +3585,23 @@ static int NPY_CLIPMODE clipmode) { npy_intp i, j, k, tmp; + NPY_BEGIN_THREADS_DEF; + + NPY_BEGIN_THREADS; switch(clipmode) { case NPY_RAISE: for (i = 0; i < n_outer; i++) { for (j = 0; j < m_middle; j++) { tmp = indarray[j]; - /* We don't know what axis we're operating on, so don't report it in case of an error. */ - if (check_and_adjust_index(&tmp, nindarray, -1) < 0) + /* + * We don't know what axis we're operating on, + * so don't report it in case of an error. + */ + if (check_and_adjust_index(&tmp, nindarray, -1, _save) < 0) { return 1; - if (nelem == 1) { + } + if (NPY_LIKELY(nelem == 1)) { *dest++ = *(src + tmp); } else { @@ -3536,7 +3627,7 @@ static int tmp -= nindarray; } } - if (nelem == 1) { + if (NPY_LIKELY(nelem == 1)) { *dest++ = *(src+tmp); } else { @@ -3558,7 +3649,7 @@ static int else if (tmp >= nindarray) { tmp = nindarray - 1; } - if (nelem == 1) { + if (NPY_LIKELY(nelem == 1)) { *dest++ = *(src + tmp); } else { @@ -3571,6 +3662,8 @@ static int } break; } + + NPY_END_THREADS; return 0; } /**end repeat**/ @@ -3829,7 +3922,8 @@ NPY_NO_EXPORT PyArray_Descr @from@_Descr = { /* elsize */ @num@ * sizeof(@fromtype@), /* alignment */ - @num@ * _ALIGN(@fromtype@), + @num@ * _ALIGN(@fromtype@) > NPY_MAX_COPY_ALIGNMENT ? + NPY_MAX_COPY_ALIGNMENT : @num@ * _ALIGN(@fromtype@), /* subarray */ NULL, /* fields */ @@ -3950,7 +4044,7 @@ datetime_dtype_metadata_clone(NpyAuxData *data) * Initializes the c_metadata field for the _builtin_descrs DATETIME * and TIMEDELTA. */ -int +static int initialize_builtin_datetime_metadata(void) { PyArray_DatetimeDTypeMetaData *data1, *data2; @@ -4171,7 +4265,8 @@ set_typeinfo(PyObject *dict) #endif NPY_@name@, NPY_BITSOF_@name@, - @num@ * _ALIGN(@type@), + @num@ * _ALIGN(@type@) > NPY_MAX_COPY_ALIGNMENT ? + NPY_MAX_COPY_ALIGNMENT : @num@ * _ALIGN(@type@), (PyObject *) &Py@Name@ArrType_Type)); Py_DECREF(s); diff --git a/numpy/core/src/multiarray/buffer.c b/numpy/core/src/multiarray/buffer.c index e32bc76eb..ea1a885ed 100644 --- a/numpy/core/src/multiarray/buffer.c +++ b/numpy/core/src/multiarray/buffer.c @@ -444,7 +444,7 @@ static _buffer_info_t* _buffer_info_new(PyArrayObject *arr) { _buffer_info_t *info; - _tmp_string_t fmt = {0,0,0}; + _tmp_string_t fmt = {NULL, 0, 0}; int k; info = malloc(sizeof(_buffer_info_t)); @@ -454,6 +454,7 @@ _buffer_info_new(PyArrayObject *arr) /* Fill in format */ if (_buffer_format_string(PyArray_DESCR(arr), &fmt, arr, NULL, NULL) != 0) { + free(fmt.s); goto fail; } _append_char(&fmt, '\0'); @@ -804,18 +805,19 @@ _descriptor_from_pep3118_format(char *s) if (*s == ':') { in_name = !in_name; *p = *s; + p++; } else if (in_name || !NumPyOS_ascii_isspace(*s)) { *p = *s; + p++; } - ++p; - ++s; + s++; } *p = '\0'; str = PyUString_FromStringAndSize(buf, strlen(buf)); - free(buf); if (str == NULL) { + free(buf); return NULL; } @@ -823,6 +825,7 @@ _descriptor_from_pep3118_format(char *s) _numpy_internal = PyImport_ImportModule("numpy.core._internal"); if (_numpy_internal == NULL) { Py_DECREF(str); + free(buf); return NULL; } descr = PyObject_CallMethod( @@ -832,14 +835,18 @@ _descriptor_from_pep3118_format(char *s) if (descr == NULL) { PyErr_Format(PyExc_ValueError, "'%s' is not a valid PEP 3118 buffer format string", buf); + free(buf); return NULL; } if (!PyArray_DescrCheck(descr)) { PyErr_Format(PyExc_RuntimeError, "internal error: numpy.core._internal._dtype_from_pep3118 " "did not return a valid dtype, got %s", buf); + Py_DECREF(descr); + free(buf); return NULL; } + free(buf); return (PyArray_Descr*)descr; } diff --git a/numpy/core/src/multiarray/common.c b/numpy/core/src/multiarray/common.c index 87aecf41c..54b9e3c1a 100644 --- a/numpy/core/src/multiarray/common.c +++ b/numpy/core/src/multiarray/common.c @@ -205,6 +205,10 @@ PyArray_DTypeFromObjectHelper(PyObject *obj, int maxdims, PyArray_Descr *dtype = NULL; PyObject *ip; Py_buffer buffer_view; + /* types for sequence handling */ + PyObject ** objects; + PyObject * seq; + PyTypeObject * common_type; /* Check if it's an ndarray */ if (PyArray_Check(obj)) { @@ -514,31 +518,49 @@ PyArray_DTypeFromObjectHelper(PyObject *obj, int maxdims, return 0; } - /* Recursive case */ - size = PySequence_Size(obj); - if (size < 0) { + /* Recursive case, first check the sequence contains only one type */ + seq = PySequence_Fast(obj, "Could not convert object to sequence"); + if (seq == NULL) { goto fail; } + size = PySequence_Fast_GET_SIZE(seq); + objects = PySequence_Fast_ITEMS(seq); + common_type = size > 0 ? Py_TYPE(objects[0]) : NULL; + for (i = 1; i < size; ++i) { + if (Py_TYPE(objects[i]) != common_type) { + common_type = NULL; + break; + } + } + + /* all types are the same and scalar, one recursive call is enough */ + if (common_type != NULL && !string_type && + (common_type == &PyFloat_Type || +/* TODO: we could add longs if we add a range check */ +#if !defined(NPY_PY3K) + common_type == &PyInt_Type || +#endif + common_type == &PyBool_Type || + common_type == &PyComplex_Type)) { + size = 1; + } + /* Recursive call for each sequence item */ for (i = 0; i < size; ++i) { - int res; - ip = PySequence_GetItem(obj, i); - if (ip == NULL) { - goto fail; - } - res = PyArray_DTypeFromObjectHelper(ip, maxdims - 1, - out_dtype, string_type); + int res = PyArray_DTypeFromObjectHelper(objects[i], maxdims - 1, + out_dtype, string_type); if (res < 0) { - Py_DECREF(ip); + Py_DECREF(seq); goto fail; } else if (res > 0) { - Py_DECREF(ip); + Py_DECREF(seq); return res; } - Py_DECREF(ip); } + Py_DECREF(seq); + return 0; @@ -618,7 +640,7 @@ index2ptr(PyArrayObject *mp, npy_intp i) return NULL; } dim0 = PyArray_DIMS(mp)[0]; - if (check_and_adjust_index(&i, dim0, 0) < 0) + if (check_and_adjust_index(&i, dim0, 0, NULL) < 0) return NULL; if (i == 0) { return PyArray_DATA(mp); @@ -650,14 +672,12 @@ _IsAligned(PyArrayObject *ap) { unsigned int i; npy_uintp aligned; - const unsigned int alignment = PyArray_DESCR(ap)->alignment; + npy_uintp alignment = PyArray_DESCR(ap)->alignment; - /* The special casing for STRING and VOID types was removed - * in accordance with http://projects.scipy.org/numpy/ticket/1227 - * It used to be that IsAligned always returned True for these - * types, which is indeed the case when they are created using - * PyArray_DescrConverter(), but not necessarily when using - * PyArray_DescrAlignConverter(). */ + /* alignment 1 types should have a efficient alignment for copy loops */ + if (PyArray_ISFLEXIBLE(ap) || PyArray_ISSTRING(ap)) { + alignment = NPY_MAX_COPY_ALIGNMENT; + } if (alignment == 1) { return 1; @@ -761,24 +781,62 @@ offset_bounds_from_strides(const int itemsize, const int nd, } -NPY_NO_EXPORT int -_is_basic_python_type(PyObject * obj) +/** + * Convert an array shape to a string such as "(1, 2)". + * + * @param Dimensionality of the shape + * @param npy_intp pointer to shape array + * @param String to append after the shape `(1, 2)%s`. + * + * @return Python unicode string + */ +NPY_NO_EXPORT PyObject * +convert_shape_to_string(npy_intp n, npy_intp *vals, char *ending) { - if (obj == Py_None || - /* Basic number types */ -#if !defined(NPY_PY3K) - PyInt_CheckExact(obj) || -#endif - PyLong_CheckExact(obj) || - PyFloat_CheckExact(obj) || - PyComplex_CheckExact(obj) || - /* Basic sequence types */ - PyList_CheckExact(obj) || - PyTuple_CheckExact(obj) || - PyDict_CheckExact(obj) || - PyAnySet_CheckExact(obj)) { - return 1; + npy_intp i; + PyObject *ret, *tmp; + + /* + * Negative dimension indicates "newaxis", which can + * be discarded for printing if it's a leading dimension. + * Find the first non-"newaxis" dimension. + */ + for (i = 0; i < n && vals[i] < 0; i++); + + if (i == n) { + return PyUString_FromFormat("()%s", ending); + } + else { + ret = PyUString_FromFormat("(%" NPY_INTP_FMT, vals[i++]); + if (ret == NULL) { + return NULL; + } } - return 0; + for (; i < n; ++i) { + if (vals[i] < 0) { + tmp = PyUString_FromString(",newaxis"); + } + else { + tmp = PyUString_FromFormat(",%" NPY_INTP_FMT, vals[i]); + } + if (tmp == NULL) { + Py_DECREF(ret); + return NULL; + } + + PyUString_ConcatAndDel(&ret, tmp); + if (ret == NULL) { + return NULL; + } + } + + if (i == 1) { + tmp = PyUString_FromFormat(",)%s", ending); + } + else { + tmp = PyUString_FromFormat(")%s", ending); + } + PyUString_ConcatAndDel(&ret, tmp); + return ret; } diff --git a/numpy/core/src/multiarray/common.h b/numpy/core/src/multiarray/common.h index e2a3b006d..6b49d6b4c 100644 --- a/numpy/core/src/multiarray/common.h +++ b/numpy/core/src/multiarray/common.h @@ -2,9 +2,21 @@ #define _NPY_PRIVATE_COMMON_H_ #include <numpy/npy_common.h> #include <numpy/npy_cpu.h> +#include <numpy/ndarraytypes.h> #define error_converting(x) (((x) == -1) && PyErr_Occurred()) +#ifdef NPY_ALLOW_THREADS +#define NPY_BEGIN_THREADS_NDITER(iter) \ + do { \ + if (!NpyIter_IterationNeedsAPI(iter)) { \ + NPY_BEGIN_THREADS_THRESHOLDED(NpyIter_GetIterSize(iter)); \ + } \ + } while(0) +#else +#define NPY_BEGIN_THREADS_NDITER(iter) +#endif + /* * Recursively examines the object to determine an appropriate dtype * to use for converting to an ndarray. @@ -52,14 +64,14 @@ _IsAligned(PyArrayObject *ap); NPY_NO_EXPORT npy_bool _IsWriteable(PyArrayObject *ap); -NPY_NO_EXPORT int -_is_basic_python_type(PyObject * obj); - NPY_NO_EXPORT void offset_bounds_from_strides(const int itemsize, const int nd, const npy_intp *dims, const npy_intp *strides, npy_intp *lower_offset, npy_intp *upper_offset); +NPY_NO_EXPORT PyObject * +convert_shape_to_string(npy_intp n, npy_intp *vals, char *ending); + /* * Returns -1 and sets an exception if *index is an invalid index for @@ -67,12 +79,17 @@ offset_bounds_from_strides(const int itemsize, const int nd, * 0 <= *index < max_item, and returns 0. * 'axis' should be the array axis that is being indexed over, if known. If * unknown, use -1. + * If _save is NULL it is assumed the GIL is taken + * If _save is not NULL it is assumed the GIL is not taken and it + * is acquired in the case of an error */ static NPY_INLINE int -check_and_adjust_index(npy_intp *index, npy_intp max_item, int axis) +check_and_adjust_index(npy_intp *index, npy_intp max_item, int axis, + PyThreadState * _save) { /* Check that index is valid, taking into account negative indices */ - if ((*index < -max_item) || (*index >= max_item)) { + if (NPY_UNLIKELY((*index < -max_item) || (*index >= max_item))) { + NPY_END_THREADS; /* Try to be as clear as possible about what went wrong. */ if (axis >= 0) { PyErr_Format(PyExc_IndexError, @@ -82,8 +99,7 @@ check_and_adjust_index(npy_intp *index, npy_intp max_item, int axis) } else { PyErr_Format(PyExc_IndexError, "index %"NPY_INTP_FMT" is out of bounds " - "for size %"NPY_INTP_FMT, - *index, max_item); + "for size %"NPY_INTP_FMT, *index, max_item); } return -1; } @@ -164,6 +180,34 @@ npy_memchr(char * haystack, char needle, return p; } +static NPY_INLINE int +_is_basic_python_type(PyObject * obj) +{ + if (obj == Py_None || + PyBool_Check(obj) || + /* Basic number types */ +#if !defined(NPY_PY3K) + PyInt_CheckExact(obj) || + PyString_CheckExact(obj) || +#endif + PyLong_CheckExact(obj) || + PyFloat_CheckExact(obj) || + PyComplex_CheckExact(obj) || + /* Basic sequence types */ + PyList_CheckExact(obj) || + PyTuple_CheckExact(obj) || + PyDict_CheckExact(obj) || + PyAnySet_CheckExact(obj) || + PyUnicode_CheckExact(obj) || + PyBytes_CheckExact(obj) || + PySlice_Check(obj)) { + + return 1; + } + + return 0; +} + #include "ucsnarrow.h" #endif diff --git a/numpy/core/src/multiarray/conversion_utils.c b/numpy/core/src/multiarray/conversion_utils.c index 1f56f942c..b84dff864 100644 --- a/numpy/core/src/multiarray/conversion_utils.c +++ b/numpy/core/src/multiarray/conversion_utils.c @@ -395,6 +395,9 @@ PyArray_SortkindConverter(PyObject *obj, NPY_SORTKIND *sortkind) if (PyUnicode_Check(obj)) { obj = tmp = PyUnicode_AsASCIIString(obj); + if (obj == NULL) { + return NPY_FAIL; + } } *sortkind = NPY_QUICKSORT; @@ -440,6 +443,9 @@ PyArray_SelectkindConverter(PyObject *obj, NPY_SELECTKIND *selectkind) if (PyUnicode_Check(obj)) { obj = tmp = PyUnicode_AsASCIIString(obj); + if (obj == NULL) { + return NPY_FAIL; + } } *selectkind = NPY_INTROSELECT; @@ -591,6 +597,9 @@ PyArray_ClipmodeConverter(PyObject *object, NPY_CLIPMODE *val) PyObject *tmp; int ret; tmp = PyUnicode_AsASCIIString(object); + if (tmp == NULL) { + return NPY_FAIL; + } ret = PyArray_ClipmodeConverter(tmp, val); Py_DECREF(tmp); return ret; @@ -774,7 +783,7 @@ PyArray_PyIntAsIntp(PyObject *o) * an exact check, since otherwise __index__ is used. */ #if !defined(NPY_PY3K) - if PyInt_CheckExact(o) { + if (PyInt_CheckExact(o)) { #if (NPY_SIZEOF_LONG <= NPY_SIZEOF_INTP) /* No overflow is possible, so we can just return */ return PyInt_AS_LONG(o); @@ -785,7 +794,7 @@ PyArray_PyIntAsIntp(PyObject *o) } else #endif - if PyLong_CheckExact(o) { + if (PyLong_CheckExact(o)) { #if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP) long_value = PyLong_AsLongLong(o); #else diff --git a/numpy/core/src/multiarray/convert.c b/numpy/core/src/multiarray/convert.c index 62b9034c2..b610343cc 100644 --- a/numpy/core/src/multiarray/convert.c +++ b/numpy/core/src/multiarray/convert.c @@ -88,9 +88,8 @@ PyArray_ToFile(PyArrayObject *self, FILE *fp, char *sep, char *format) if (n3 == 0) { /* binary data */ if (PyDataType_FLAGCHK(PyArray_DESCR(self), NPY_LIST_PICKLE)) { - PyErr_SetString(PyExc_ValueError, "cannot write " \ - "object arrays to a file in " \ - "binary mode"); + PyErr_SetString(PyExc_IOError, + "cannot write object arrays to a file in binary mode"); return -1; } @@ -126,7 +125,7 @@ PyArray_ToFile(PyArrayObject *self, FILE *fp, char *sep, char *format) #endif NPY_END_ALLOW_THREADS; if (n < size) { - PyErr_Format(PyExc_ValueError, + PyErr_Format(PyExc_IOError, "%ld requested and %ld written", (long) size, (long) n); return -1; @@ -143,9 +142,8 @@ PyArray_ToFile(PyArrayObject *self, FILE *fp, char *sep, char *format) 1, fp) < 1) { NPY_END_THREADS; PyErr_Format(PyExc_IOError, - "problem writing element"\ - " %"NPY_INTP_FMT" to file", - it->index); + "problem writing element %" NPY_INTP_FMT + " to file", it->index); Py_DECREF(it); return -1; } @@ -218,7 +216,7 @@ PyArray_ToFile(PyArrayObject *self, FILE *fp, char *sep, char *format) #endif if (n < n2) { PyErr_Format(PyExc_IOError, - "problem writing element %"NPY_INTP_FMT\ + "problem writing element %" NPY_INTP_FMT " to file", it->index); Py_DECREF(strobj); Py_DECREF(it); @@ -228,8 +226,7 @@ PyArray_ToFile(PyArrayObject *self, FILE *fp, char *sep, char *format) if (it->index != it->size-1) { if (fwrite(sep, 1, n3, fp) < n3) { PyErr_Format(PyExc_IOError, - "problem writing "\ - "separator to file"); + "problem writing separator to file"); Py_DECREF(strobj); Py_DECREF(it); return -1; diff --git a/numpy/core/src/multiarray/convert_datatype.c b/numpy/core/src/multiarray/convert_datatype.c index 4f0202ffb..1db3bfe85 100644 --- a/numpy/core/src/multiarray/convert_datatype.c +++ b/numpy/core/src/multiarray/convert_datatype.c @@ -10,6 +10,7 @@ #include "npy_config.h" #include "npy_pycompat.h" +#include "numpy/npy_math.h" #include "common.h" #include "scalartypes.h" @@ -19,11 +20,23 @@ #include "_datetime.h" #include "datetime_strings.h" + +/* + * Required length of string when converting from unsigned integer type. + * Array index is integer size in bytes. + * - 3 chars needed for cast to max value of 255 or 127 + * - 5 chars needed for cast to max value of 65535 or 32767 + * - 10 chars needed for cast to max value of 4294967295 or 2147483647 + * - 20 chars needed for cast to max value of 18446744073709551615 + * or 9223372036854775807 + */ +NPY_NO_EXPORT npy_intp REQUIRED_STR_LEN[] = {0, 3, 5, 10, 10, 20, 20, 20, 20}; + /*NUMPY_API * For backward compatibility * * Cast an array using typecode structure. - * steals reference to at --- cannot be NULL + * steals reference to dtype --- cannot be NULL * * This function always makes a copy of arr, even if the dtype * doesn't change. @@ -140,7 +153,6 @@ PyArray_AdaptFlexibleDType(PyObject *data_obj, PyArray_Descr *data_dtype, PyArray_Descr *dtype = NULL; int ndim = 0; npy_intp dims[NPY_MAXDIMS]; - PyObject *list = NULL; int result; if (*flex_dtype == NULL) { @@ -166,7 +178,7 @@ PyArray_AdaptFlexibleDType(PyObject *data_obj, PyArray_Descr *data_dtype, flex_type_num == NPY_VOID) { (*flex_dtype)->elsize = data_dtype->elsize; } - else { + else if (flex_type_num == NPY_STRING || flex_type_num == NPY_UNICODE) { npy_intp size = 8; /* @@ -176,37 +188,35 @@ PyArray_AdaptFlexibleDType(PyObject *data_obj, PyArray_Descr *data_dtype, */ switch (data_dtype->type_num) { case NPY_BOOL: - size = 8; - break; case NPY_UBYTE: - size = 8; - break; case NPY_BYTE: - size = 8; - break; case NPY_USHORT: - size = 8; - break; case NPY_SHORT: - size = 8; - break; case NPY_UINT: - size = 16; - break; case NPY_INT: - size = 16; - break; case NPY_ULONG: - size = 24; - break; case NPY_LONG: - size = 24; - break; case NPY_ULONGLONG: - size = 24; - break; case NPY_LONGLONG: - size = 24; + if (data_dtype->kind == 'b') { + /* 5 chars needed for cast to 'True' or 'False' */ + size = 5; + } + else if (data_dtype->elsize > 8 || + data_dtype->elsize < 0) { + /* + * Element size should never be greater than 8 or + * less than 0 for integer type, but just in case... + */ + break; + } + else if (data_dtype->kind == 'u') { + size = REQUIRED_STR_LEN[data_dtype->elsize]; + } + else if (data_dtype->kind == 'i') { + /* Add character for sign symbol */ + size = REQUIRED_STR_LEN[data_dtype->elsize] + 1; + } break; case NPY_HALF: case NPY_FLOAT: @@ -224,12 +234,14 @@ PyArray_AdaptFlexibleDType(PyObject *data_obj, PyArray_Descr *data_dtype, if ((flex_type_num == NPY_STRING || flex_type_num == NPY_UNICODE) && data_obj != NULL) { + PyObject *list; + if (PyArray_CheckScalar(data_obj)) { - PyObject *scalar = PyArray_ToList(data_obj); - if (scalar != NULL) { - PyObject *s = PyObject_Str(scalar); + list = PyArray_ToList((PyArrayObject *)data_obj); + if (list != NULL) { + PyObject *s = PyObject_Str(list); if (s == NULL) { - Py_DECREF(scalar); + Py_DECREF(list); Py_DECREF(*flex_dtype); *flex_dtype = NULL; return; @@ -238,7 +250,7 @@ PyArray_AdaptFlexibleDType(PyObject *data_obj, PyArray_Descr *data_dtype, size = PyObject_Length(s); Py_DECREF(s); } - Py_DECREF(scalar); + Py_DECREF(list); } } else if (PyArray_Check(data_obj)) { @@ -247,7 +259,7 @@ PyArray_AdaptFlexibleDType(PyObject *data_obj, PyArray_Descr *data_dtype, * GetArrayParamsFromObject won't iterate over * array. */ - list = PyArray_ToList(data_obj); + list = PyArray_ToList((PyArrayObject *)data_obj); result = PyArray_GetArrayParamsFromObject( list, *flex_dtype, @@ -305,6 +317,16 @@ PyArray_AdaptFlexibleDType(PyObject *data_obj, PyArray_Descr *data_dtype, (*flex_dtype)->elsize = size * 4; } } + else { + /* + * We should never get here, but just in case someone adds + * a new flex dtype... + */ + PyErr_SetString(PyExc_TypeError, + "don't know how to adapt flex dtype"); + *flex_dtype = NULL; + return; + } } /* Flexible type with generic time unit that adapts */ else if (flex_type_num == NPY_DATETIME || @@ -489,10 +511,53 @@ PyArray_CanCastTo(PyArray_Descr *from, PyArray_Descr *to) NPY_SAFE_CASTING); } /* - * TODO: If to_type_num is STRING or unicode + * If to_type_num is STRING or unicode * see if the length is long enough to hold the * stringified value of the object. */ + else if (to_type_num == NPY_STRING || to_type_num == NPY_UNICODE) { + /* + * Boolean value cast to string type is 5 characters max + * for string 'False'. + */ + int char_size = 1; + if (to_type_num == NPY_UNICODE) { + char_size = 4; + } + + ret = 0; + if (to->elsize == 0) { + ret = 1; + } + /* + * Need at least 5 characters to convert from boolean + * to 'True' or 'False'. + */ + else if (from->kind == 'b' && to->elsize >= 5 * char_size) { + ret = 1; + } + else if (from->kind == 'u') { + /* Guard against unexpected integer size */ + if (from->elsize > 8 || from->elsize < 0) { + ret = 0; + } + else if (to->elsize >= + REQUIRED_STR_LEN[from->elsize] * char_size) { + ret = 1; + } + } + else if (from->kind == 'i') { + /* Guard against unexpected integer size */ + if (from->elsize > 8 || from->elsize < 0) { + ret = 0; + } + /* Extra character needed for sign */ + else if (to->elsize >= + (REQUIRED_STR_LEN[from->elsize] + 1) * char_size) { + ret = 1; + } + } + } } return ret; } @@ -577,7 +642,13 @@ NPY_NO_EXPORT npy_bool PyArray_CanCastTypeTo(PyArray_Descr *from, PyArray_Descr *to, NPY_CASTING casting) { - if (casting == NPY_INTERNAL_UNSAFE_CASTING_BUT_WARN_UNLESS_SAME_KIND) { + /* fast path for basic types */ + if (NPY_LIKELY(from->type_num < NPY_OBJECT) && + NPY_LIKELY(from->type_num == to->type_num) && + NPY_LIKELY(from->byteorder == to->byteorder)) { + return 1; + } + else if (casting == NPY_INTERNAL_UNSAFE_CASTING_BUT_WARN_UNLESS_SAME_KIND) { npy_bool unsafe_ok, same_kind_ok; unsafe_ok = PyArray_CanCastTypeTo_impl(from, to, NPY_UNSAFE_CASTING); same_kind_ok = PyArray_CanCastTypeTo_impl(from, to, @@ -1017,12 +1088,25 @@ PyArray_PromoteTypes(PyArray_Descr *type1, PyArray_Descr *type2) switch (type_num1) { /* BOOL can convert to anything except datetime/void */ case NPY_BOOL: - if (type_num2 != NPY_DATETIME && type_num2 != NPY_VOID) { + if (type_num2 == NPY_STRING || type_num2 == NPY_UNICODE) { + int char_size = 1; + if (type_num2 == NPY_UNICODE) { + char_size = 4; + } + if (type2->elsize < 5 * char_size) { + PyArray_Descr *ret = NULL; + PyArray_Descr *temp = PyArray_DescrNew(type2); + ret = ensure_dtype_nbo(temp); + ret->elsize = 5 * char_size; + Py_DECREF(temp); + return ret; + } return ensure_dtype_nbo(type2); } - else { - break; + else if (type_num2 != NPY_DATETIME && type_num2 != NPY_VOID) { + return ensure_dtype_nbo(type2); } + break; /* For strings and unicodes, take the larger size */ case NPY_STRING: if (type_num2 == NPY_STRING) { @@ -1048,8 +1132,20 @@ PyArray_PromoteTypes(PyArray_Descr *type1, PyArray_Descr *type2) } /* Allow NUMBER -> STRING */ else if (PyTypeNum_ISNUMBER(type_num2)) { - return ensure_dtype_nbo(type1); + PyArray_Descr *ret = NULL; + PyArray_Descr *temp = PyArray_DescrNew(type1); + temp->elsize = 0; + PyArray_AdaptFlexibleDType(NULL, type2, &temp); + if (temp->elsize > type1->elsize) { + ret = ensure_dtype_nbo(temp); + } + else { + ret = ensure_dtype_nbo(type1); + } + Py_DECREF(temp); + return ret; } + break; case NPY_UNICODE: if (type_num2 == NPY_UNICODE) { if (type1->elsize > type2->elsize) { @@ -1074,7 +1170,18 @@ PyArray_PromoteTypes(PyArray_Descr *type1, PyArray_Descr *type2) } /* Allow NUMBER -> UNICODE */ else if (PyTypeNum_ISNUMBER(type_num2)) { - return ensure_dtype_nbo(type1); + PyArray_Descr *ret = NULL; + PyArray_Descr *temp = PyArray_DescrNew(type1); + temp->elsize = 0; + PyArray_AdaptFlexibleDType(NULL, type2, &temp); + if (temp->elsize > type1->elsize) { + ret = ensure_dtype_nbo(temp); + } + else { + ret = ensure_dtype_nbo(type1); + } + Py_DECREF(temp); + return ret; } break; case NPY_DATETIME: @@ -1088,22 +1195,58 @@ PyArray_PromoteTypes(PyArray_Descr *type1, PyArray_Descr *type2) switch (type_num2) { /* BOOL can convert to almost anything */ case NPY_BOOL: - if (type_num1 != NPY_DATETIME && type_num1 != NPY_TIMEDELTA && + if (type_num2 == NPY_STRING || type_num2 == NPY_UNICODE) { + int char_size = 1; + if (type_num2 == NPY_UNICODE) { + char_size = 4; + } + if (type2->elsize < 5 * char_size) { + PyArray_Descr *ret = NULL; + PyArray_Descr *temp = PyArray_DescrNew(type2); + ret = ensure_dtype_nbo(temp); + ret->elsize = 5 * char_size; + Py_DECREF(temp); + return ret; + } + return ensure_dtype_nbo(type2); + } + else if (type_num1 != NPY_DATETIME && type_num1 != NPY_TIMEDELTA && type_num1 != NPY_VOID) { return ensure_dtype_nbo(type1); } - else { - break; - } + break; case NPY_STRING: /* Allow NUMBER -> STRING */ if (PyTypeNum_ISNUMBER(type_num1)) { - return ensure_dtype_nbo(type2); + PyArray_Descr *ret = NULL; + PyArray_Descr *temp = PyArray_DescrNew(type2); + temp->elsize = 0; + PyArray_AdaptFlexibleDType(NULL, type1, &temp); + if (temp->elsize > type2->elsize) { + ret = ensure_dtype_nbo(temp); + } + else { + ret = ensure_dtype_nbo(type2); + } + Py_DECREF(temp); + return ret; } + break; case NPY_UNICODE: /* Allow NUMBER -> UNICODE */ if (PyTypeNum_ISNUMBER(type_num1)) { - return ensure_dtype_nbo(type2); + PyArray_Descr *ret = NULL; + PyArray_Descr *temp = PyArray_DescrNew(type2); + temp->elsize = 0; + PyArray_AdaptFlexibleDType(NULL, type1, &temp); + if (temp->elsize > type2->elsize) { + ret = ensure_dtype_nbo(temp); + } + else { + ret = ensure_dtype_nbo(type2); + } + Py_DECREF(temp); + return ret; } break; case NPY_TIMEDELTA: @@ -1339,14 +1482,14 @@ static int min_scalar_type_num(char *valueptr, int type_num, } case NPY_FLOAT: { float value = *(float *)valueptr; - if (value > -65000 && value < 65000) { + if ((value > -65000 && value < 65000) || !npy_isfinite(value)) { return NPY_HALF; } break; } case NPY_DOUBLE: { double value = *(double *)valueptr; - if (value > -65000 && value < 65000) { + if ((value > -65000 && value < 65000) || !npy_isfinite(value)) { return NPY_HALF; } else if (value > -3.4e38 && value < 3.4e38) { @@ -1356,7 +1499,7 @@ static int min_scalar_type_num(char *valueptr, int type_num, } case NPY_LONGDOUBLE: { npy_longdouble value = *(npy_longdouble *)valueptr; - if (value > -65000 && value < 65000) { + if ((value > -65000 && value < 65000) || !npy_isfinite(value)) { return NPY_HALF; } else if (value > -3.4e38 && value < 3.4e38) { diff --git a/numpy/core/src/multiarray/ctors.c b/numpy/core/src/multiarray/ctors.c index a47b8625a..3da2dfae7 100644 --- a/numpy/core/src/multiarray/ctors.c +++ b/numpy/core/src/multiarray/ctors.c @@ -26,6 +26,8 @@ #include "array_assign.h" #include "mapping.h" /* for array_item_asarray */ #include "scalarmathmodule.h" /* for npy_mul_with_overflow_intp */ +#include "alloc.h" +#include <assert.h> /* * Reading from a file or a string. @@ -316,7 +318,7 @@ _strided_byte_swap(void *p, npy_intp stride, npy_intp n, int size) case 1: /* no byteswap necessary */ break; case 4: - if (npy_is_aligned(p, sizeof(npy_uint32))) { + if (npy_is_aligned((void*)((npy_intp)p | stride), sizeof(npy_uint32))) { for (a = (char*)p; n > 0; n--, a += stride) { npy_uint32 * a_ = (npy_uint32 *)a; *a_ = npy_bswap4(*a_); @@ -329,7 +331,7 @@ _strided_byte_swap(void *p, npy_intp stride, npy_intp n, int size) } break; case 8: - if (npy_is_aligned(p, sizeof(npy_uint64))) { + if (npy_is_aligned((void*)((npy_intp)p | stride), sizeof(npy_uint64))) { for (a = (char*)p; n > 0; n--, a += stride) { npy_uint64 * a_ = (npy_uint64 *)a; *a_ = npy_bswap8(*a_); @@ -342,7 +344,7 @@ _strided_byte_swap(void *p, npy_intp stride, npy_intp n, int size) } break; case 2: - if (npy_is_aligned(p, sizeof(npy_uint16))) { + if (npy_is_aligned((void*)((npy_intp)p | stride), sizeof(npy_uint16))) { for (a = (char*)p; n > 0; n--, a += stride) { npy_uint16 * a_ = (npy_uint16 *)a; *a_ = npy_bswap2(*a_); @@ -503,15 +505,18 @@ setArrayFromSequence(PyArrayObject *a, PyObject *s, } /* Copy element by element */ else { + PyObject * seq; + seq = PySequence_Fast(s, "Could not convert object to sequence"); + if (seq == NULL) { + goto fail; + } for (i = 0; i < slen; i++) { - PyObject *o = PySequence_GetItem(s, i); - if (o == NULL) { - goto fail; - } + PyObject * o = PySequence_Fast_GET_ITEM(seq, i); if ((PyArray_NDIM(a) - dim) > 1) { PyArrayObject * tmp = (PyArrayObject *)array_item_asarray(dst, i); if (tmp == NULL) { + Py_DECREF(seq); goto fail; } @@ -522,11 +527,12 @@ setArrayFromSequence(PyArrayObject *a, PyObject *s, char * b = (PyArray_BYTES(dst) + i * PyArray_STRIDES(dst)[0]); res = PyArray_DESCR(dst)->f->setitem(o, b, dst); } - Py_DECREF(o); if (res < 0) { + Py_DECREF(seq); goto fail; } } + Py_DECREF(seq); } Py_DECREF(s); @@ -640,6 +646,7 @@ discover_dimensions(PyObject *obj, int *maxndim, npy_intp *d, int check_it, PyObject *e; int r, n, i; Py_buffer buffer_view; + PyObject * seq; if (*maxndim == 0) { return 0; @@ -782,75 +789,63 @@ discover_dimensions(PyObject *obj, int *maxndim, npy_intp *d, int check_it, } } - n = PySequence_Size(obj); - - if (n < 0) { - return -1; + seq = PySequence_Fast(obj, "Could not convert object to sequence"); + if (seq == NULL) { + /* + * PySequence_Check detects whether an old type object is a + * sequence by the presence of the __getitem__ attribute, and + * for new type objects that aren't dictionaries by the + * presence of the __len__ attribute as well. In either case it + * is possible to have an object that tests as a sequence but + * doesn't behave as a sequence and consequently, the + * PySequence_GetItem call can fail. When that happens and the + * object looks like a dictionary, we truncate the dimensions + * and set the object creation flag, otherwise we pass the + * error back up the call chain. + */ + if (PyErr_ExceptionMatches(PyExc_KeyError)) { + PyErr_Clear(); + *maxndim = 0; + *out_is_object = 1; + return 0; + } + else { + return -1; + } } + n = PySequence_Fast_GET_SIZE(seq); d[0] = n; /* 1-dimensional sequence */ if (n == 0 || *maxndim == 1) { *maxndim = 1; + Py_DECREF(seq); return 0; } else { npy_intp dtmp[NPY_MAXDIMS]; int j, maxndim_m1 = *maxndim - 1; + e = PySequence_Fast_GET_ITEM(seq, 0); - if ((e = PySequence_GetItem(obj, 0)) == NULL) { - /* - * PySequence_Check detects whether an old type object is a - * sequence by the presence of the __getitem__ attribute, and - * for new type objects that aren't dictionaries by the - * presence of the __len__ attribute as well. In either case it - * is possible to have an object that tests as a sequence but - * doesn't behave as a sequence and consequently, the - * PySequence_GetItem call can fail. When that happens and the - * object looks like a dictionary, we truncate the dimensions - * and set the object creation flag, otherwise we pass the - * error back up the call chain. - */ - if (PyErr_ExceptionMatches(PyExc_KeyError)) { - PyErr_Clear(); - *maxndim = 0; - *out_is_object = 1; - return 0; - } - else { - return -1; - } - } r = discover_dimensions(e, &maxndim_m1, d + 1, check_it, stop_at_string, stop_at_tuple, out_is_object); - Py_DECREF(e); if (r < 0) { + Py_DECREF(seq); return r; } /* For the dimension truncation check below */ *maxndim = maxndim_m1 + 1; for (i = 1; i < n; ++i) { + e = PySequence_Fast_GET_ITEM(seq, i); /* Get the dimensions of the first item */ - if ((e = PySequence_GetItem(obj, i)) == NULL) { - /* see comment above */ - if (PyErr_ExceptionMatches(PyExc_KeyError)) { - PyErr_Clear(); - *maxndim = 0; - *out_is_object = 1; - return 0; - } - else { - return -1; - } - } r = discover_dimensions(e, &maxndim_m1, dtmp, check_it, stop_at_string, stop_at_tuple, out_is_object); - Py_DECREF(e); if (r < 0) { + Py_DECREF(seq); return r; } @@ -872,6 +867,8 @@ discover_dimensions(PyObject *obj, int *maxndim, npy_intp *d, int check_it, } } + Py_DECREF(seq); + return 0; } @@ -995,7 +992,7 @@ PyArray_NewFromDescr_int(PyTypeObject *subtype, PyArray_Descr *descr, int nd, fa->weakreflist = (PyObject *)NULL; if (nd > 0) { - fa->dimensions = PyDimMem_NEW(3*nd); + fa->dimensions = npy_alloc_cache_dim(2 * nd); if (fa->dimensions == NULL) { PyErr_NoMemory(); goto fail; @@ -1035,10 +1032,10 @@ PyArray_NewFromDescr_int(PyTypeObject *subtype, PyArray_Descr *descr, int nd, * which could also be sub-fields of a VOID array */ if (zeroed || PyDataType_FLAGCHK(descr, NPY_NEEDS_INIT)) { - data = PyDataMem_NEW_ZEROED(sd, 1); + data = npy_alloc_cache_zero(sd); } else { - data = PyDataMem_NEW(sd); + data = npy_alloc_cache(sd); } if (data == NULL) { PyErr_NoMemory(); @@ -1057,12 +1054,12 @@ PyArray_NewFromDescr_int(PyTypeObject *subtype, PyArray_Descr *descr, int nd, fa->data = data; /* - * If the strides were provided to the function, need to - * update the flags to get the right CONTIGUOUS, ALIGN properties + * always update the flags to get the right CONTIGUOUS, ALIGN properties + * not owned data and input strides may not be aligned and on some + * platforms (debian sparc) malloc does not provide enough alignment for + * long double types */ - if (strides != NULL) { - PyArray_UpdateFlags((PyArrayObject *)fa, NPY_ARRAY_UPDATE_ALL); - } + PyArray_UpdateFlags((PyArrayObject *)fa, NPY_ARRAY_UPDATE_ALL); /* * call the __array_finalize__ @@ -1312,7 +1309,9 @@ _array_from_buffer_3118(PyObject *obj, PyObject **out) else { d = view->len; for (k = 0; k < nd; ++k) { - d /= view->shape[k]; + if (view->shape[k] != 0) { + d /= view->shape[k]; + } strides[k] = d; } } @@ -1335,8 +1334,11 @@ _array_from_buffer_3118(PyObject *obj, PyObject **out) r = PyArray_NewFromDescr(&PyArray_Type, descr, nd, shape, strides, view->buf, flags, NULL); - if (PyArray_SetBaseObject((PyArrayObject *)r, memoryview) < 0) { - goto fail; + if (r == NULL || + PyArray_SetBaseObject((PyArrayObject *)r, memoryview) < 0) { + Py_XDECREF(r); + Py_DECREF(memoryview); + return -1; } PyArray_UpdateFlags((PyArrayObject *)r, NPY_ARRAY_UPDATE_ALL); @@ -1382,7 +1384,7 @@ fail: * npy_intp dims[NPY_MAXDIMS]; * * if (PyArray_GetArrayParamsFromObject(op, NULL, 1, &dtype, - * &ndim, &dims, &arr, NULL) < 0) { + * &ndim, dims, &arr, NULL) < 0) { * return NULL; * } * if (arr == NULL) { @@ -1839,7 +1841,7 @@ PyArray_CheckFromAny(PyObject *op, PyArray_Descr *descr, int min_depth, else if (descr && !PyArray_ISNBO(descr->byteorder)) { PyArray_DESCR_REPLACE(descr); } - if (descr) { + if (descr && descr->byteorder != NPY_IGNORE) { descr->byteorder = NPY_NATIVE; } } @@ -2632,9 +2634,7 @@ PyArray_CopyAsFlat(PyArrayObject *dst, PyArrayObject *src, NPY_ORDER order) } } - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; NPY_AUXDATA_FREE(transferdata); NpyIter_Deallocate(dst_iter); @@ -2842,6 +2842,7 @@ PyArray_Arange(double start, double stop, double step, int type_num) PyArray_ArrFuncs *funcs; PyObject *obj; int ret; + NPY_BEGIN_THREADS_DEF; if (_safe_ceil_to_intp((stop - start)/step, &length)) { PyErr_SetString(PyExc_OverflowError, @@ -2889,7 +2890,9 @@ PyArray_Arange(double start, double stop, double step, int type_num) Py_DECREF(range); return NULL; } + NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(range)); funcs->fill(PyArray_DATA(range), length, range); + NPY_END_THREADS; if (PyErr_Occurred()) { goto fail; } @@ -2986,6 +2989,7 @@ PyArray_ArangeObj(PyObject *start, PyObject *stop, PyObject *step, PyArray_Descr npy_intp length; PyArray_Descr *native = NULL; int swap; + NPY_BEGIN_THREADS_DEF; /* Datetime arange is handled specially */ if ((dtype != NULL && (dtype->type_num == NPY_DATETIME || @@ -3102,7 +3106,9 @@ PyArray_ArangeObj(PyObject *start, PyObject *stop, PyObject *step, PyArray_Descr Py_DECREF(range); goto fail; } + NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(range)); funcs->fill(PyArray_DATA(range), length, range); + NPY_END_THREADS; if (PyErr_Occurred()) { goto fail; } @@ -3132,18 +3138,18 @@ static PyArrayObject * array_fromfile_binary(FILE *fp, PyArray_Descr *dtype, npy_intp num, size_t *nread) { PyArrayObject *r; - npy_intp start, numbytes; + npy_off_t start, numbytes; if (num < 0) { int fail = 0; - start = (npy_intp) npy_ftell(fp); + start = npy_ftell(fp); if (start < 0) { fail = 1; } if (npy_fseek(fp, 0, SEEK_END) < 0) { fail = 1; } - numbytes = (npy_intp) npy_ftell(fp); + numbytes = npy_ftell(fp); if (numbytes < 0) { fail = 1; } diff --git a/numpy/core/src/multiarray/datetime.c b/numpy/core/src/multiarray/datetime.c index 5c32c519a..272127f00 100644 --- a/numpy/core/src/multiarray/datetime.c +++ b/numpy/core/src/multiarray/datetime.c @@ -1193,7 +1193,7 @@ get_datetime_conversion_factor(PyArray_DatetimeMetaData *src_meta, } /* If something overflowed, make both num and denom 0 */ - if (denom == 0) { + if (denom == 0 || num == 0) { PyErr_Format(PyExc_OverflowError, "Integer overflow while computing the conversion " "factor between NumPy datetime units %s and %s", diff --git a/numpy/core/src/multiarray/datetime_busdaycal.c b/numpy/core/src/multiarray/datetime_busdaycal.c index 67ab5284c..91ba24c97 100644 --- a/numpy/core/src/multiarray/datetime_busdaycal.c +++ b/numpy/core/src/multiarray/datetime_busdaycal.c @@ -158,12 +158,10 @@ invalid_weekmask_string: } else { int i; - PyObject *f; for (i = 0; i < 7; ++i) { long val; - - f = PySequence_GetItem(obj, i); + PyObject *f = PySequence_GetItem(obj, i); if (f == NULL) { Py_DECREF(obj); return 0; @@ -171,6 +169,7 @@ invalid_weekmask_string: val = PyInt_AsLong(f); if (val == -1 && PyErr_Occurred()) { + Py_DECREF(f); Py_DECREF(obj); return 0; } @@ -184,9 +183,11 @@ invalid_weekmask_string: PyErr_SetString(PyExc_ValueError, "A business day weekmask array must have all " "1's and 0's"); + Py_DECREF(f); Py_DECREF(obj); return 0; } + Py_DECREF(f); } goto finish; diff --git a/numpy/core/src/multiarray/datetime_strings.c b/numpy/core/src/multiarray/datetime_strings.c index e74da0384..54587cb5c 100644 --- a/numpy/core/src/multiarray/datetime_strings.c +++ b/numpy/core/src/multiarray/datetime_strings.c @@ -1554,6 +1554,9 @@ array_datetime_as_string(PyObject *NPY_UNUSED(self), PyObject *args, op[0] = (PyArrayObject *)PyArray_FromAny(arr_in, NULL, 0, 0, 0, NULL); + if (op[0] == NULL) { + goto fail; + } if (PyArray_DESCR(op[0])->type_num != NPY_DATETIME) { PyErr_SetString(PyExc_TypeError, "input must have type NumPy datetime"); diff --git a/numpy/core/src/multiarray/descriptor.c b/numpy/core/src/multiarray/descriptor.c index 10d4023d5..8b55c9fbd 100644 --- a/numpy/core/src/multiarray/descriptor.c +++ b/numpy/core/src/multiarray/descriptor.c @@ -63,7 +63,7 @@ _arraydescr_fromctypes(PyObject *obj) /* derived type */ PyObject *newtup; PyArray_Descr *derived; - newtup = Py_BuildValue("NO", newdescr, length); + newtup = Py_BuildValue("NN", newdescr, length); ret = PyArray_DescrConverter(newtup, &derived); Py_DECREF(newtup); if (ret == NPY_SUCCEED) { @@ -286,6 +286,8 @@ _convert_from_tuple(PyObject *obj) */ PyArray_Dims shape = {NULL, -1}; PyArray_Descr *newdescr; + npy_intp items; + int i; if (!(PyArray_IntpConverter(val, &shape)) || (shape.len > NPY_MAXDIMS)) { PyDimMem_FREE(shape.ptr); @@ -310,28 +312,75 @@ _convert_from_tuple(PyObject *obj) PyDimMem_FREE(shape.ptr); goto fail; } - newdescr->elsize = type->elsize; - newdescr->elsize *= PyArray_MultiplyList(shape.ptr, shape.len); - PyDimMem_FREE(shape.ptr); + + /* validate and set shape */ + for (i=0; i < shape.len; i++) { + if (shape.ptr[i] < 0) { + PyErr_SetString(PyExc_ValueError, + "invalid shape in fixed-type tuple: " + "dimension smaller then zero."); + PyDimMem_FREE(shape.ptr); + goto fail; + } + if (shape.ptr[i] > NPY_MAX_INT) { + PyErr_SetString(PyExc_ValueError, + "invalid shape in fixed-type tuple: " + "dimension does not fit into a C int."); + PyDimMem_FREE(shape.ptr); + goto fail; + } + } + items = PyArray_OverflowMultiplyList(shape.ptr, shape.len); + if ((items < 0) || (items > (NPY_MAX_INT / type->elsize))) { + PyErr_SetString(PyExc_ValueError, + "invalid shape in fixed-type tuple: dtype size in " + "bytes must fit into a C int."); + PyDimMem_FREE(shape.ptr); + goto fail; + } + newdescr->elsize = type->elsize * items; + if (newdescr->elsize == -1) { + PyDimMem_FREE(shape.ptr); + goto fail; + } + newdescr->subarray = PyArray_malloc(sizeof(PyArray_ArrayDescr)); + if (newdescr->subarray == NULL) { + Py_DECREF(newdescr); + PyErr_NoMemory(); + goto fail; + } newdescr->flags = type->flags; + newdescr->alignment = type->alignment; newdescr->subarray->base = type; type = NULL; Py_XDECREF(newdescr->fields); Py_XDECREF(newdescr->names); newdescr->fields = NULL; newdescr->names = NULL; - /* Force subarray->shape to always be a tuple */ - if (PyTuple_Check(val)) { - Py_INCREF(val); - newdescr->subarray->shape = val; - } else { - newdescr->subarray->shape = Py_BuildValue("(O)", val); - if (newdescr->subarray->shape == NULL) { - Py_DECREF(newdescr); + + /* + * Create a new subarray->shape tuple (it can be an arbitrary + * sequence of integer like objects, neither of which is safe. + */ + newdescr->subarray->shape = PyTuple_New(shape.len); + if (newdescr->subarray->shape == NULL) { + PyDimMem_FREE(shape.ptr); + goto fail; + } + for (i=0; i < shape.len; i++) { + PyTuple_SET_ITEM(newdescr->subarray->shape, i, + PyInt_FromLong((long)shape.ptr[i])); + + if (PyTuple_GET_ITEM(newdescr->subarray->shape, i) == NULL) { + Py_DECREF(newdescr->subarray->shape); + newdescr->subarray->shape = NULL; + PyDimMem_FREE(shape.ptr); goto fail; } } + + PyDimMem_FREE(shape.ptr); type = newdescr; } return type; @@ -361,7 +410,8 @@ _convert_from_array_descr(PyObject *obj, int align) PyObject *nameslist; PyArray_Descr *new; PyArray_Descr *conv; - char dtypeflags = 0; + /* Types with fields need the Python C API for field access */ + char dtypeflags = NPY_NEEDS_PYAPI; int maxalign = 0; n = PyList_GET_SIZE(obj); @@ -550,7 +600,8 @@ _convert_from_list(PyObject *obj, int align) PyObject *nameslist = NULL; int ret; int maxalign = 0; - char dtypeflags = 0; + /* Types with fields need the Python C API for field access */ + char dtypeflags = NPY_NEEDS_PYAPI; n = PyList_GET_SIZE(obj); /* @@ -657,6 +708,7 @@ _convert_from_commastring(PyObject *obj, int align) if (!PyList_Check(listobj) || PyList_GET_SIZE(listobj) < 1) { PyErr_SetString(PyExc_RuntimeError, "_commastring is not returning a list with len >= 1"); + Py_DECREF(listobj); return NULL; } if (PyList_GET_SIZE(listobj) == 1) { @@ -885,7 +937,8 @@ _convert_from_dict(PyObject *obj, int align) int n, i; int totalsize, itemsize; int maxalign = 0; - char dtypeflags = 0; + /* Types with fields need the Python C API for field access */ + char dtypeflags = NPY_NEEDS_PYAPI; int has_out_of_order_fields = 0; fields = PyDict_New(); @@ -1528,6 +1581,10 @@ PyArray_DescrNew(PyArray_Descr *base) Py_XINCREF(newdescr->names); if (newdescr->subarray) { newdescr->subarray = PyArray_malloc(sizeof(PyArray_ArrayDescr)); + if (newdescr->subarray == NULL) { + Py_DECREF(newdescr); + return (PyArray_Descr *)PyErr_NoMemory(); + } memcpy(newdescr->subarray, base->subarray, sizeof(PyArray_ArrayDescr)); Py_INCREF(newdescr->subarray->shape); Py_INCREF(newdescr->subarray->base); @@ -1641,12 +1698,14 @@ arraydescr_protocol_typestr_get(PyArray_Descr *self) static PyObject * arraydescr_typename_get(PyArray_Descr *self) { - int len; + static const char np_prefix[] = "numpy."; + const int np_prefix_len = sizeof(np_prefix) - 1; PyTypeObject *typeobj = self->typeobj; PyObject *res; char *s; - /* fixme: not reentrant */ - static int prefix_len = 0; + int len; + int prefix_len; + int suffix_len; if (PyTypeNum_ISUSERDEF(self->type_num)) { s = strrchr(typeobj->tp_name, '.'); @@ -1659,14 +1718,31 @@ arraydescr_typename_get(PyArray_Descr *self) return res; } else { - if (prefix_len == 0) { - prefix_len = strlen("numpy."); - } + /* + * NumPy type or subclass + * + * res is derived from typeobj->tp_name with the following rules: + * - if starts with "numpy.", that prefix is removed + * - if ends with "_", that suffix is removed + */ len = strlen(typeobj->tp_name); - if (*(typeobj->tp_name + (len-1)) == '_') { - len -= 1; + + if (! strncmp(typeobj->tp_name, np_prefix, np_prefix_len)) { + prefix_len = np_prefix_len; + } + else { + prefix_len = 0; } + + if (typeobj->tp_name[len - 1] == '_') { + suffix_len = 1; + } + else { + suffix_len = 0; + } + len -= prefix_len; + len -= suffix_len; res = PyUString_FromStringAndSize(typeobj->tp_name+prefix_len, len); } if (PyTypeNum_ISFLEXIBLE(self->type_num) && self->elsize != 0) { @@ -2677,7 +2753,7 @@ PyArray_DescrNewByteorder(PyArray_Descr *self, char newendian) if (endian != NPY_IGNORE) { if (newendian == NPY_SWAP) { /* swap byteorder */ - if PyArray_ISNBO(endian) { + if (PyArray_ISNBO(endian)) { endian = NPY_OPPBYTE; } else { diff --git a/numpy/core/src/multiarray/dtype_transfer.c b/numpy/core/src/multiarray/dtype_transfer.c index 3bd362c24..7a7379ad5 100644 --- a/numpy/core/src/multiarray/dtype_transfer.c +++ b/numpy/core/src/multiarray/dtype_transfer.c @@ -151,7 +151,7 @@ typedef struct { } _strided_zero_pad_data; /* zero-padded data copy function */ -NpyAuxData *_strided_zero_pad_data_clone(NpyAuxData *data) +static NpyAuxData *_strided_zero_pad_data_clone(NpyAuxData *data) { _strided_zero_pad_data *newdata = (_strided_zero_pad_data *)PyArray_malloc( @@ -258,7 +258,7 @@ typedef struct { } _align_wrap_data; /* transfer data free function */ -void _align_wrap_data_free(NpyAuxData *data) +static void _align_wrap_data_free(NpyAuxData *data) { _align_wrap_data *d = (_align_wrap_data *)data; NPY_AUXDATA_FREE(d->wrappeddata); @@ -268,7 +268,7 @@ void _align_wrap_data_free(NpyAuxData *data) } /* transfer data copy function */ -NpyAuxData *_align_wrap_data_clone(NpyAuxData *data) +static NpyAuxData *_align_wrap_data_clone(NpyAuxData *data) { _align_wrap_data *d = (_align_wrap_data *)data; _align_wrap_data *newdata; @@ -485,7 +485,7 @@ typedef struct { } _wrap_copy_swap_data; /* wrap copy swap data free function */ -void _wrap_copy_swap_data_free(NpyAuxData *data) +static void _wrap_copy_swap_data_free(NpyAuxData *data) { _wrap_copy_swap_data *d = (_wrap_copy_swap_data *)data; Py_DECREF(d->arr); @@ -493,7 +493,7 @@ void _wrap_copy_swap_data_free(NpyAuxData *data) } /* wrap copy swap data copy function */ -NpyAuxData *_wrap_copy_swap_data_clone(NpyAuxData *data) +static NpyAuxData *_wrap_copy_swap_data_clone(NpyAuxData *data) { _wrap_copy_swap_data *newdata = (_wrap_copy_swap_data *)PyArray_malloc(sizeof(_wrap_copy_swap_data)); @@ -572,7 +572,7 @@ typedef struct { } _strided_cast_data; /* strided cast data free function */ -void _strided_cast_data_free(NpyAuxData *data) +static void _strided_cast_data_free(NpyAuxData *data) { _strided_cast_data *d = (_strided_cast_data *)data; Py_DECREF(d->aip); @@ -581,7 +581,7 @@ void _strided_cast_data_free(NpyAuxData *data) } /* strided cast data copy function */ -NpyAuxData *_strided_cast_data_clone(NpyAuxData *data) +static NpyAuxData *_strided_cast_data_clone(NpyAuxData *data) { _strided_cast_data *newdata = (_strided_cast_data *)PyArray_malloc(sizeof(_strided_cast_data)); @@ -716,7 +716,7 @@ typedef struct { } _strided_datetime_cast_data; /* strided datetime cast data free function */ -void _strided_datetime_cast_data_free(NpyAuxData *data) +static void _strided_datetime_cast_data_free(NpyAuxData *data) { _strided_datetime_cast_data *d = (_strided_datetime_cast_data *)data; PyArray_free(d->tmp_buffer); @@ -724,7 +724,7 @@ void _strided_datetime_cast_data_free(NpyAuxData *data) } /* strided datetime cast data copy function */ -NpyAuxData *_strided_datetime_cast_data_clone(NpyAuxData *data) +static NpyAuxData *_strided_datetime_cast_data_clone(NpyAuxData *data) { _strided_datetime_cast_data *newdata = (_strided_datetime_cast_data *)PyArray_malloc( @@ -1547,7 +1547,7 @@ typedef struct { } _one_to_n_data; /* transfer data free function */ -void _one_to_n_data_free(NpyAuxData *data) +static void _one_to_n_data_free(NpyAuxData *data) { _one_to_n_data *d = (_one_to_n_data *)data; NPY_AUXDATA_FREE(d->data); @@ -1556,7 +1556,7 @@ void _one_to_n_data_free(NpyAuxData *data) } /* transfer data copy function */ -NpyAuxData *_one_to_n_data_clone(NpyAuxData *data) +static NpyAuxData *_one_to_n_data_clone(NpyAuxData *data) { _one_to_n_data *d = (_one_to_n_data *)data; _one_to_n_data *newdata; @@ -1750,7 +1750,7 @@ typedef struct { } _n_to_n_data; /* transfer data free function */ -void _n_to_n_data_free(NpyAuxData *data) +static void _n_to_n_data_free(NpyAuxData *data) { _n_to_n_data *d = (_n_to_n_data *)data; NPY_AUXDATA_FREE(d->data); @@ -1758,7 +1758,7 @@ void _n_to_n_data_free(NpyAuxData *data) } /* transfer data copy function */ -NpyAuxData *_n_to_n_data_clone(NpyAuxData *data) +static NpyAuxData *_n_to_n_data_clone(NpyAuxData *data) { _n_to_n_data *d = (_n_to_n_data *)data; _n_to_n_data *newdata; @@ -1929,7 +1929,7 @@ typedef struct { } _subarray_broadcast_data; /* transfer data free function */ -void _subarray_broadcast_data_free(NpyAuxData *data) +static void _subarray_broadcast_data_free(NpyAuxData *data) { _subarray_broadcast_data *d = (_subarray_broadcast_data *)data; NPY_AUXDATA_FREE(d->data); @@ -1939,7 +1939,7 @@ void _subarray_broadcast_data_free(NpyAuxData *data) } /* transfer data copy function */ -NpyAuxData *_subarray_broadcast_data_clone( NpyAuxData *data) +static NpyAuxData *_subarray_broadcast_data_clone( NpyAuxData *data) { _subarray_broadcast_data *d = (_subarray_broadcast_data *)data; _subarray_broadcast_data *newdata; @@ -2381,7 +2381,7 @@ typedef struct { } _field_transfer_data; /* transfer data free function */ -void _field_transfer_data_free(NpyAuxData *data) +static void _field_transfer_data_free(NpyAuxData *data) { _field_transfer_data *d = (_field_transfer_data *)data; npy_intp i, field_count; @@ -2397,7 +2397,7 @@ void _field_transfer_data_free(NpyAuxData *data) } /* transfer data copy function */ -NpyAuxData *_field_transfer_data_clone(NpyAuxData *data) +static NpyAuxData *_field_transfer_data_clone(NpyAuxData *data) { _field_transfer_data *d = (_field_transfer_data *)data; _field_transfer_data *newdata; @@ -2997,7 +2997,7 @@ typedef struct { } _masked_wrapper_transfer_data; /* transfer data free function */ -void _masked_wrapper_transfer_data_free(NpyAuxData *data) +static void _masked_wrapper_transfer_data_free(NpyAuxData *data) { _masked_wrapper_transfer_data *d = (_masked_wrapper_transfer_data *)data; NPY_AUXDATA_FREE(d->transferdata); @@ -3006,7 +3006,7 @@ void _masked_wrapper_transfer_data_free(NpyAuxData *data) } /* transfer data copy function */ -NpyAuxData *_masked_wrapper_transfer_data_clone(NpyAuxData *data) +static NpyAuxData *_masked_wrapper_transfer_data_clone(NpyAuxData *data) { _masked_wrapper_transfer_data *d = (_masked_wrapper_transfer_data *)data; _masked_wrapper_transfer_data *newdata; @@ -3040,7 +3040,7 @@ NpyAuxData *_masked_wrapper_transfer_data_clone(NpyAuxData *data) return (NpyAuxData *)newdata; } -void _strided_masked_wrapper_decsrcref_transfer_function( +static void _strided_masked_wrapper_decsrcref_transfer_function( char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_bool *mask, npy_intp mask_stride, @@ -3060,14 +3060,16 @@ void _strided_masked_wrapper_decsrcref_transfer_function( while (N > 0) { /* Skip masked values, still calling decsrcref for move_references */ - mask = npy_memchr((char *)mask, 0, mask_stride, N, &subloopsize, 1); + mask = (npy_bool*)npy_memchr((char *)mask, 0, mask_stride, N, + &subloopsize, 1); decsrcref_stransfer(NULL, 0, src, src_stride, subloopsize, src_itemsize, decsrcref_transferdata); dst += subloopsize * dst_stride; src += subloopsize * src_stride; N -= subloopsize; /* Process unmasked values */ - mask = npy_memchr((char *)mask, 0, mask_stride, N, &subloopsize, 0); + mask = (npy_bool*)npy_memchr((char *)mask, 0, mask_stride, N, + &subloopsize, 0); unmasked_stransfer(dst, dst_stride, src, src_stride, subloopsize, src_itemsize, unmasked_transferdata); dst += subloopsize * dst_stride; @@ -3076,7 +3078,7 @@ void _strided_masked_wrapper_decsrcref_transfer_function( } } -void _strided_masked_wrapper_transfer_function( +static void _strided_masked_wrapper_transfer_function( char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_bool *mask, npy_intp mask_stride, @@ -3095,12 +3097,14 @@ void _strided_masked_wrapper_transfer_function( while (N > 0) { /* Skip masked values */ - mask = npy_memchr((char *)mask, 0, mask_stride, N, &subloopsize, 1); + mask = (npy_bool*)npy_memchr((char *)mask, 0, mask_stride, N, + &subloopsize, 1); dst += subloopsize * dst_stride; src += subloopsize * src_stride; N -= subloopsize; /* Process unmasked values */ - mask = npy_memchr((char *)mask, 0, mask_stride, N, &subloopsize, 0); + mask = (npy_bool*)npy_memchr((char *)mask, 0, mask_stride, N, + &subloopsize, 0); unmasked_stransfer(dst, dst_stride, src, src_stride, subloopsize, src_itemsize, unmasked_transferdata); dst += subloopsize * dst_stride; @@ -3168,7 +3172,7 @@ typedef struct { } _dst_memset_zero_data; /* zero-padded data copy function */ -NpyAuxData *_dst_memset_zero_data_clone(NpyAuxData *data) +static NpyAuxData *_dst_memset_zero_data_clone(NpyAuxData *data) { _dst_memset_zero_data *newdata = (_dst_memset_zero_data *)PyArray_malloc( diff --git a/numpy/core/src/multiarray/einsum.c.src b/numpy/core/src/multiarray/einsum.c.src index 7a94c9305..b3148f573 100644 --- a/numpy/core/src/multiarray/einsum.c.src +++ b/numpy/core/src/multiarray/einsum.c.src @@ -22,6 +22,7 @@ #include <ctype.h> #include "convert.h" +#include "common.h" #ifdef NPY_HAVE_SSE_INTRINSICS #define EINSUM_USE_SSE1 1 @@ -64,13 +65,6 @@ #endif /**********************************************/ -typedef enum { - BROADCAST_NONE, - BROADCAST_LEFT, - BROADCAST_RIGHT, - BROADCAST_MIDDLE -} EINSUM_BROADCAST; - /**begin repeat * #name = byte, short, int, long, longlong, * ubyte, ushort, uint, ulong, ulonglong, @@ -1802,11 +1796,10 @@ parse_operand_subscripts(char *subscripts, int length, char *out_label_counts, int *out_min_label, int *out_max_label, - int *out_num_labels, - EINSUM_BROADCAST *out_broadcast) + int *out_num_labels) { int i, idim, ndim_left, label; - int left_labels = 0, right_labels = 0, ellipsis = 0; + int ellipsis = 0; /* Process the labels from the end until the ellipsis */ idim = ndim-1; @@ -1828,7 +1821,6 @@ parse_operand_subscripts(char *subscripts, int length, (*out_num_labels)++; } out_label_counts[label]++; - right_labels = 1; } else { PyErr_Format(PyExc_ValueError, @@ -1897,7 +1889,6 @@ parse_operand_subscripts(char *subscripts, int length, (*out_num_labels)++; } out_label_counts[label]++; - left_labels = 1; } else { PyErr_Format(PyExc_ValueError, @@ -1947,19 +1938,6 @@ parse_operand_subscripts(char *subscripts, int length, } } - if (!ellipsis) { - *out_broadcast = BROADCAST_NONE; - } - else if (left_labels && right_labels) { - *out_broadcast = BROADCAST_MIDDLE; - } - else if (!left_labels) { - *out_broadcast = BROADCAST_RIGHT; - } - else { - *out_broadcast = BROADCAST_LEFT; - } - return 1; } @@ -1972,11 +1950,10 @@ static int parse_output_subscripts(char *subscripts, int length, int ndim_broadcast, const char *label_counts, - char *out_labels, - EINSUM_BROADCAST *out_broadcast) + char *out_labels) { int i, nlabels, label, idim, ndim, ndim_left; - int left_labels = 0, right_labels = 0, ellipsis = 0; + int ellipsis = 0; /* Count the labels, making sure they're all unique and valid */ nlabels = 0; @@ -2031,7 +2008,6 @@ parse_output_subscripts(char *subscripts, int length, "too many output subscripts"); return -1; } - right_labels = 1; } /* The end of the ellipsis */ else if (label == '.') { @@ -2081,7 +2057,6 @@ parse_output_subscripts(char *subscripts, int length, "too many subscripts for the output"); return -1; } - left_labels = 1; } else { PyErr_SetString(PyExc_ValueError, @@ -2097,19 +2072,6 @@ parse_output_subscripts(char *subscripts, int length, out_labels[idim++] = 0; } - if (!ellipsis) { - *out_broadcast = BROADCAST_NONE; - } - else if (left_labels && right_labels) { - *out_broadcast = BROADCAST_MIDDLE; - } - else if (!left_labels) { - *out_broadcast = BROADCAST_RIGHT; - } - else { - *out_broadcast = BROADCAST_LEFT; - } - return ndim; } @@ -2328,136 +2290,44 @@ get_combined_dims_view(PyArrayObject *op, int iop, char *labels) static int prepare_op_axes(int ndim, int iop, char *labels, int *axes, - int ndim_iter, char *iter_labels, EINSUM_BROADCAST broadcast) + int ndim_iter, char *iter_labels) { int i, label, ibroadcast; - /* Regular broadcasting */ - if (broadcast == BROADCAST_RIGHT) { - /* broadcast dimensions get placed in rightmost position */ - ibroadcast = ndim-1; - for (i = ndim_iter-1; i >= 0; --i) { - label = iter_labels[i]; - /* - * If it's an unlabeled broadcast dimension, choose - * the next broadcast dimension from the operand. - */ - if (label == 0) { - while (ibroadcast >= 0 && labels[ibroadcast] != 0) { - --ibroadcast; - } - /* - * If we used up all the operand broadcast dimensions, - * extend it with a "newaxis" - */ - if (ibroadcast < 0) { - axes[i] = -1; - } - /* Otherwise map to the broadcast axis */ - else { - axes[i] = ibroadcast; - --ibroadcast; - } - } - /* It's a labeled dimension, find the matching one */ - else { - char *match = memchr(labels, label, ndim); - /* If the op doesn't have the label, broadcast it */ - if (match == NULL) { - axes[i] = -1; - } - /* Otherwise use it */ - else { - axes[i] = match - labels; - } + ibroadcast = ndim-1; + for (i = ndim_iter-1; i >= 0; --i) { + label = iter_labels[i]; + /* + * If it's an unlabeled broadcast dimension, choose + * the next broadcast dimension from the operand. + */ + if (label == 0) { + while (ibroadcast >= 0 && labels[ibroadcast] != 0) { + --ibroadcast; } - } - } - /* Reverse broadcasting */ - else if (broadcast == BROADCAST_LEFT) { - /* broadcast dimensions get placed in leftmost position */ - ibroadcast = 0; - for (i = 0; i < ndim_iter; ++i) { - label = iter_labels[i]; /* - * If it's an unlabeled broadcast dimension, choose - * the next broadcast dimension from the operand. + * If we used up all the operand broadcast dimensions, + * extend it with a "newaxis" */ - if (label == 0) { - while (ibroadcast < ndim && labels[ibroadcast] != 0) { - ++ibroadcast; - } - /* - * If we used up all the operand broadcast dimensions, - * extend it with a "newaxis" - */ - if (ibroadcast >= ndim) { - axes[i] = -1; - } - /* Otherwise map to the broadcast axis */ - else { - axes[i] = ibroadcast; - ++ibroadcast; - } + if (ibroadcast < 0) { + axes[i] = -1; } - /* It's a labeled dimension, find the matching one */ + /* Otherwise map to the broadcast axis */ else { - char *match = memchr(labels, label, ndim); - /* If the op doesn't have the label, broadcast it */ - if (match == NULL) { - axes[i] = -1; - } - /* Otherwise use it */ - else { - axes[i] = match - labels; - } + axes[i] = ibroadcast; + --ibroadcast; } } - } - /* Middle or None broadcasting */ - else { - /* broadcast dimensions get placed in leftmost position */ - ibroadcast = 0; - for (i = 0; i < ndim_iter; ++i) { - label = iter_labels[i]; - /* - * If it's an unlabeled broadcast dimension, choose - * the next broadcast dimension from the operand. - */ - if (label == 0) { - while (ibroadcast < ndim && labels[ibroadcast] != 0) { - ++ibroadcast; - } - /* - * If we used up all the operand broadcast dimensions, - * it's an error - */ - if (ibroadcast >= ndim) { - PyErr_Format(PyExc_ValueError, - "operand %d did not have enough dimensions " - "to match the broadcasting, and couldn't be " - "extended because einstein sum subscripts " - "were specified at both the start and end", - iop); - return 0; - } - /* Otherwise map to the broadcast axis */ - else { - axes[i] = ibroadcast; - ++ibroadcast; - } + /* It's a labeled dimension, find the matching one */ + else { + char *match = memchr(labels, label, ndim); + /* If the op doesn't have the label, broadcast it */ + if (match == NULL) { + axes[i] = -1; } - /* It's a labeled dimension, find the matching one */ + /* Otherwise use it */ else { - char *match = memchr(labels, label, ndim); - /* If the op doesn't have the label, broadcast it */ - if (match == NULL) { - axes[i] = -1; - } - /* Otherwise use it */ - else { - axes[i] = match - labels; - } + axes[i] = match - labels; } } } @@ -2737,7 +2607,6 @@ PyArray_EinsteinSum(char *subscripts, npy_intp nop, char output_labels[NPY_MAXDIMS], *iter_labels; int idim, ndim_output, ndim_broadcast, ndim_iter; - EINSUM_BROADCAST broadcast[NPY_MAXARGS]; PyArrayObject *op[NPY_MAXARGS], *ret = NULL; PyArray_Descr *op_dtypes_array[NPY_MAXARGS], **op_dtypes; @@ -2783,8 +2652,7 @@ PyArray_EinsteinSum(char *subscripts, npy_intp nop, if (!parse_operand_subscripts(subscripts, length, PyArray_NDIM(op_in[iop]), iop, op_labels[iop], label_counts, - &min_label, &max_label, &num_labels, - &broadcast[iop])) { + &min_label, &max_label, &num_labels)) { return NULL; } @@ -2845,7 +2713,7 @@ PyArray_EinsteinSum(char *subscripts, npy_intp nop, /* Parse the output subscript string */ ndim_output = parse_output_subscripts(outsubscripts, length, ndim_broadcast, label_counts, - output_labels, &broadcast[nop]); + output_labels); } else { if (subscripts[0] != '-' || subscripts[1] != '>') { @@ -2859,7 +2727,7 @@ PyArray_EinsteinSum(char *subscripts, npy_intp nop, /* Parse the output subscript string */ ndim_output = parse_output_subscripts(subscripts, strlen(subscripts), ndim_broadcast, label_counts, - output_labels, &broadcast[nop]); + output_labels); } if (ndim_output < 0) { return NULL; @@ -2961,7 +2829,7 @@ PyArray_EinsteinSum(char *subscripts, npy_intp nop, op_axes[iop] = op_axes_arrays[iop]; if (!prepare_op_axes(PyArray_NDIM(op[iop]), iop, op_labels[iop], - op_axes[iop], ndim_iter, iter_labels, broadcast[iop])) { + op_axes[iop], ndim_iter, iter_labels)) { goto fail; } } @@ -3102,7 +2970,6 @@ PyArray_EinsteinSum(char *subscripts, npy_intp nop, char **dataptr; npy_intp *stride; npy_intp *countptr; - int needs_api = NpyIter_IterationNeedsAPI(iter); NPY_BEGIN_THREADS_DEF; iternext = NpyIter_GetIterNext(iter, NULL); @@ -3115,19 +2982,15 @@ PyArray_EinsteinSum(char *subscripts, npy_intp nop, stride = NpyIter_GetInnerStrideArray(iter); countptr = NpyIter_GetInnerLoopSizePtr(iter); - if (!needs_api) { - NPY_BEGIN_THREADS; - } + NPY_BEGIN_THREADS_NDITER(iter); NPY_EINSUM_DBG_PRINT("Einsum loop\n"); do { sop(nop, dataptr, stride, *countptr); } while(iternext(iter)); - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; /* If the API was needed, it may have thrown an error */ - if (needs_api && PyErr_Occurred()) { + if (NpyIter_IterationNeedsAPI(iter) && PyErr_Occurred()) { Py_DECREF(ret); ret = NULL; } diff --git a/numpy/core/src/multiarray/getset.c b/numpy/core/src/multiarray/getset.c index 6ad4cc13a..5374f42e7 100644 --- a/numpy/core/src/multiarray/getset.c +++ b/numpy/core/src/multiarray/getset.c @@ -267,6 +267,7 @@ array_interface_get(PyArrayObject *self) } if (array_might_be_written(self) < 0) { + Py_DECREF(dict); return NULL; } @@ -868,10 +869,7 @@ array_flat_set(PyArrayObject *self, PyObject *val) } while(selfit->index < selfit->size) { - memmove(selfit->dataptr, arrit->dataptr, PyArray_DESCR(self)->elsize); - if (swap) { - copyswap(selfit->dataptr, NULL, swap, self); - } + copyswap(selfit->dataptr, arrit->dataptr, swap, self); PyArray_ITER_NEXT(selfit); PyArray_ITER_NEXT(arrit); if (arrit->index == arrit->size) { diff --git a/numpy/core/src/multiarray/item_selection.c b/numpy/core/src/multiarray/item_selection.c index 5538627dd..b2bf17f4c 100644 --- a/numpy/core/src/multiarray/item_selection.c +++ b/numpy/core/src/multiarray/item_selection.c @@ -22,6 +22,7 @@ #include "item_selection.h" #include "npy_sort.h" #include "npy_partition.h" +#include "npy_binsearch.h" /*NUMPY_API * Take @@ -128,12 +129,15 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, func = PyArray_DESCR(self)->f->fasttake; if (func == NULL) { + NPY_BEGIN_THREADS_DEF; + NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(self)); switch(clipmode) { case NPY_RAISE: for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { tmp = ((npy_intp *)(PyArray_DATA(indices)))[j]; - if (check_and_adjust_index(&tmp, max_item, axis) < 0) { + if (check_and_adjust_index(&tmp, max_item, axis, + _save) < 0) { goto fail; } tmp_src = src + tmp * chunk; @@ -215,8 +219,10 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, } break; } + NPY_END_THREADS; } else { + /* no gil release, need it for error reporting */ err = func(dest, src, (npy_intp *)(PyArray_DATA(indices)), max_item, n, m, nelem, clipmode); if (err) { @@ -299,7 +305,7 @@ PyArray_PutTo(PyArrayObject *self, PyObject* values0, PyObject *indices0, for (i = 0; i < ni; i++) { src = PyArray_BYTES(values) + chunk*(i % nv); tmp = ((npy_intp *)(PyArray_DATA(indices)))[i]; - if (check_and_adjust_index(&tmp, max_item, 0) < 0) { + if (check_and_adjust_index(&tmp, max_item, 0, NULL) < 0) { goto fail; } PyArray_Item_INCREF(src, PyArray_DESCR(self)); @@ -344,12 +350,14 @@ PyArray_PutTo(PyArrayObject *self, PyObject* values0, PyObject *indices0, } } else { + NPY_BEGIN_THREADS_DEF; + NPY_BEGIN_THREADS_THRESHOLDED(ni); switch(clipmode) { case NPY_RAISE: for (i = 0; i < ni; i++) { src = PyArray_BYTES(values) + chunk * (i % nv); tmp = ((npy_intp *)(PyArray_DATA(indices)))[i]; - if (check_and_adjust_index(&tmp, max_item, 0) < 0) { + if (check_and_adjust_index(&tmp, max_item, 0, _save) < 0) { goto fail; } memmove(dest + tmp * chunk, src, chunk); @@ -386,6 +394,7 @@ PyArray_PutTo(PyArrayObject *self, PyObject* values0, PyObject *indices0, } break; } + NPY_END_THREADS; } finish: @@ -481,6 +490,8 @@ PyArray_PutMask(PyArrayObject *self, PyObject* values0, PyObject* mask0) } } else { + NPY_BEGIN_THREADS_DEF; + NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(self)); func = PyArray_DESCR(self)->f->fastputmask; if (func == NULL) { for (i = 0; i < ni; i++) { @@ -494,6 +505,7 @@ PyArray_PutMask(PyArrayObject *self, PyObject* values0, PyObject* mask0) else { func(dest, PyArray_DATA(mask), ni, PyArray_DATA(values), nv); } + NPY_END_THREADS; } Py_XDECREF(values); @@ -1257,7 +1269,7 @@ PyArray_Partition(PyArrayObject *op, PyArrayObject * ktharray, int axis, NPY_SEL PyArray_PartitionFunc * part = get_partition_func(PyArray_TYPE(op), which); n = PyArray_NDIM(op); - if ((n == 0)) { + if (n == 0) { return 0; } if (axis < 0) { @@ -1866,196 +1878,6 @@ PyArray_LexSort(PyObject *sort_keys, int axis) } -/** @brief Use bisection of sorted array to find first entries >= keys. - * - * For each key use bisection to find the first index i s.t. key <= arr[i]. - * When there is no such index i, set i = len(arr). Return the results in ret. - * Both arr and key must be of the same comparable type. - * - * @param arr 1d, strided, sorted array to be searched. - * @param key contiguous array of keys. - * @param ret contiguous array of intp for returned indices. - * @return void - */ -static void -local_search_left(PyArrayObject *arr, PyArrayObject *key, PyArrayObject *ret) -{ - PyArray_CompareFunc *compare = PyArray_DESCR(key)->f->compare; - npy_intp nelts = PyArray_DIMS(arr)[PyArray_NDIM(arr) - 1]; - npy_intp nkeys = PyArray_SIZE(key); - char *parr = PyArray_DATA(arr); - char *pkey = PyArray_DATA(key); - npy_intp *pret = (npy_intp *)PyArray_DATA(ret); - int elsize = PyArray_DESCR(key)->elsize; - npy_intp arrstride = *PyArray_STRIDES(arr); - npy_intp i; - - for (i = 0; i < nkeys; ++i) { - npy_intp imin = 0; - npy_intp imax = nelts; - while (imin < imax) { - npy_intp imid = imin + ((imax - imin) >> 1); - if (compare(parr + arrstride*imid, pkey, key) < 0) { - imin = imid + 1; - } - else { - imax = imid; - } - } - *pret = imin; - pret += 1; - pkey += elsize; - } -} - - -/** @brief Use bisection of sorted array to find first entries > keys. - * - * For each key use bisection to find the first index i s.t. key < arr[i]. - * When there is no such index i, set i = len(arr). Return the results in ret. - * Both arr and key must be of the same comparable type. - * - * @param arr 1d, strided, sorted array to be searched. - * @param key contiguous array of keys. - * @param ret contiguous array of intp for returned indices. - * @return void - */ -static void -local_search_right(PyArrayObject *arr, PyArrayObject *key, PyArrayObject *ret) -{ - PyArray_CompareFunc *compare = PyArray_DESCR(key)->f->compare; - npy_intp nelts = PyArray_DIMS(arr)[PyArray_NDIM(arr) - 1]; - npy_intp nkeys = PyArray_SIZE(key); - char *parr = PyArray_DATA(arr); - char *pkey = PyArray_DATA(key); - npy_intp *pret = (npy_intp *)PyArray_DATA(ret); - int elsize = PyArray_DESCR(key)->elsize; - npy_intp arrstride = *PyArray_STRIDES(arr); - npy_intp i; - - for(i = 0; i < nkeys; ++i) { - npy_intp imin = 0; - npy_intp imax = nelts; - while (imin < imax) { - npy_intp imid = imin + ((imax - imin) >> 1); - if (compare(parr + arrstride*imid, pkey, key) <= 0) { - imin = imid + 1; - } - else { - imax = imid; - } - } - *pret = imin; - pret += 1; - pkey += elsize; - } -} - -/** @brief Use bisection of sorted array to find first entries >= keys. - * - * For each key use bisection to find the first index i s.t. key <= arr[i]. - * When there is no such index i, set i = len(arr). Return the results in ret. - * Both arr and key must be of the same comparable type. - * - * @param arr 1d, strided array to be searched. - * @param key contiguous array of keys. - * @param sorter 1d, strided array of intp that sorts arr. - * @param ret contiguous array of intp for returned indices. - * @return int - */ -static int -local_argsearch_left(PyArrayObject *arr, PyArrayObject *key, - PyArrayObject *sorter, PyArrayObject *ret) -{ - PyArray_CompareFunc *compare = PyArray_DESCR(key)->f->compare; - npy_intp nelts = PyArray_DIMS(arr)[PyArray_NDIM(arr) - 1]; - npy_intp nkeys = PyArray_SIZE(key); - char *parr = PyArray_DATA(arr); - char *pkey = PyArray_DATA(key); - char *psorter = PyArray_DATA(sorter); - npy_intp *pret = (npy_intp *)PyArray_DATA(ret); - int elsize = PyArray_DESCR(key)->elsize; - npy_intp arrstride = *PyArray_STRIDES(arr); - npy_intp sorterstride = *PyArray_STRIDES(sorter); - npy_intp i; - - for (i = 0; i < nkeys; ++i) { - npy_intp imin = 0; - npy_intp imax = nelts; - while (imin < imax) { - npy_intp imid = imin + ((imax - imin) >> 1); - npy_intp indx = *(npy_intp *)(psorter + sorterstride * imid); - - if (indx < 0 || indx >= nelts) { - return -1; - } - if (compare(parr + arrstride*indx, pkey, key) < 0) { - imin = imid + 1; - } - else { - imax = imid; - } - } - *pret = imin; - pret += 1; - pkey += elsize; - } - return 0; -} - - -/** @brief Use bisection of sorted array to find first entries > keys. - * - * For each key use bisection to find the first index i s.t. key < arr[i]. - * When there is no such index i, set i = len(arr). Return the results in ret. - * Both arr and key must be of the same comparable type. - * - * @param arr 1d, strided array to be searched. - * @param key contiguous array of keys. - * @param sorter 1d, strided array of intp that sorts arr. - * @param ret contiguous array of intp for returned indices. - * @return int - */ -static int -local_argsearch_right(PyArrayObject *arr, PyArrayObject *key, - PyArrayObject *sorter, PyArrayObject *ret) -{ - PyArray_CompareFunc *compare = PyArray_DESCR(key)->f->compare; - npy_intp nelts = PyArray_DIMS(arr)[PyArray_NDIM(arr) - 1]; - npy_intp nkeys = PyArray_SIZE(key); - char *parr = PyArray_DATA(arr); - char *pkey = PyArray_DATA(key); - char *psorter = PyArray_DATA(sorter); - npy_intp *pret = (npy_intp *)PyArray_DATA(ret); - int elsize = PyArray_DESCR(key)->elsize; - npy_intp arrstride = *PyArray_STRIDES(arr); - npy_intp sorterstride = *PyArray_STRIDES(sorter); - npy_intp i; - - for(i = 0; i < nkeys; ++i) { - npy_intp imin = 0; - npy_intp imax = nelts; - while (imin < imax) { - npy_intp imid = imin + ((imax - imin) >> 1); - npy_intp indx = *(npy_intp *)(psorter + sorterstride * imid); - - if (indx < 0 || indx >= nelts) { - return -1; - } - if (compare(parr + arrstride*indx, pkey, key) <= 0) { - imin = imid + 1; - } - else { - imax = imid; - } - } - *pret = imin; - pret += 1; - pkey += elsize; - } - return 0; -} - /*NUMPY_API * * Search the sorted array op1 for the location of the items in op2. The @@ -2096,6 +1918,8 @@ PyArray_SearchSorted(PyArrayObject *op1, PyObject *op2, PyArrayObject *ret = NULL; PyArray_Descr *dtype; int ap1_flags = NPY_ARRAY_NOTSWAPPED | NPY_ARRAY_ALIGNED; + PyArray_BinSearchFunc *binsearch = NULL; + PyArray_ArgBinSearchFunc *argbinsearch = NULL; NPY_BEGIN_THREADS_DEF; /* Find common type */ @@ -2103,40 +1927,54 @@ PyArray_SearchSorted(PyArrayObject *op1, PyObject *op2, if (dtype == NULL) { return NULL; } + /* refs to dtype we own = 1 */ + + /* Look for binary search function */ + if (perm) { + argbinsearch = get_argbinsearch_func(dtype, side); + } + else { + binsearch = get_binsearch_func(dtype, side); + } + if (binsearch == NULL && argbinsearch == NULL) { + PyErr_SetString(PyExc_TypeError, "compare not supported for type"); + /* refs to dtype we own = 1 */ + Py_DECREF(dtype); + /* refs to dtype we own = 0 */ + return NULL; + } /* need ap2 as contiguous array and of right type */ + /* refs to dtype we own = 1 */ Py_INCREF(dtype); + /* refs to dtype we own = 2 */ ap2 = (PyArrayObject *)PyArray_CheckFromAny(op2, dtype, 0, 0, NPY_ARRAY_CARRAY_RO | NPY_ARRAY_NOTSWAPPED, NULL); + /* refs to dtype we own = 1, array creation steals one even on failure */ if (ap2 == NULL) { Py_DECREF(dtype); + /* refs to dtype we own = 0 */ return NULL; } /* * If the needle (ap2) is larger than the haystack (op1) we copy the - * haystack to a continuous array for improved cache utilization. + * haystack to a contiguous array for improved cache utilization. */ if (PyArray_SIZE(ap2) > PyArray_SIZE(op1)) { ap1_flags |= NPY_ARRAY_CARRAY_RO; } - ap1 = (PyArrayObject *)PyArray_CheckFromAny((PyObject *)op1, dtype, 1, 1, ap1_flags, NULL); + /* refs to dtype we own = 0, array creation steals one even on failure */ if (ap1 == NULL) { goto fail; } - /* check that comparison function exists */ - if (PyArray_DESCR(ap2)->f->compare == NULL) { - PyErr_SetString(PyExc_TypeError, - "compare not supported for type"); - goto fail; - } if (perm) { - /* need ap3 as contiguous array and of right type */ + /* need ap3 as a 1D aligned, not swapped, array of right type */ ap3 = (PyArrayObject *)PyArray_CheckFromAny(perm, NULL, 1, 1, NPY_ARRAY_ALIGNED | NPY_ARRAY_NOTSWAPPED, @@ -2167,7 +2005,7 @@ PyArray_SearchSorted(PyArrayObject *op1, PyObject *op2, } } - /* ret is a contiguous array of intp type to hold returned indices */ + /* ret is a contiguous array of intp type to hold returned indexes */ ret = (PyArrayObject *)PyArray_New(Py_TYPE(ap2), PyArray_NDIM(ap2), PyArray_DIMS(ap2), NPY_INTP, NULL, NULL, 0, 0, (PyObject *)ap2); @@ -2176,33 +2014,32 @@ PyArray_SearchSorted(PyArrayObject *op1, PyObject *op2, } if (ap3 == NULL) { - if (side == NPY_SEARCHLEFT) { - NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(ap2)); - local_search_left(ap1, ap2, ret); - NPY_END_THREADS_DESCR(PyArray_DESCR(ap2)); - } - else if (side == NPY_SEARCHRIGHT) { - NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(ap2)); - local_search_right(ap1, ap2, ret); - NPY_END_THREADS_DESCR(PyArray_DESCR(ap2)); - } + /* do regular binsearch */ + NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(ap2)); + binsearch((const char *)PyArray_DATA(ap1), + (const char *)PyArray_DATA(ap2), + (char *)PyArray_DATA(ret), + PyArray_SIZE(ap1), PyArray_SIZE(ap2), + PyArray_STRIDES(ap1)[0], PyArray_DESCR(ap2)->elsize, + NPY_SIZEOF_INTP, ap2); + NPY_END_THREADS_DESCR(PyArray_DESCR(ap2)); } else { - int err=0; - - if (side == NPY_SEARCHLEFT) { - NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(ap2)); - err = local_argsearch_left(ap1, ap2, sorter, ret); - NPY_END_THREADS_DESCR(PyArray_DESCR(ap2)); - } - else if (side == NPY_SEARCHRIGHT) { - NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(ap2)); - err = local_argsearch_right(ap1, ap2, sorter, ret); - NPY_END_THREADS_DESCR(PyArray_DESCR(ap2)); - } - if (err < 0) { + /* do binsearch with a sorter array */ + int error = 0; + NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(ap2)); + error = argbinsearch((const char *)PyArray_DATA(ap1), + (const char *)PyArray_DATA(ap2), + (const char *)PyArray_DATA(sorter), + (char *)PyArray_DATA(ret), + PyArray_SIZE(ap1), PyArray_SIZE(ap2), + PyArray_STRIDES(ap1)[0], + PyArray_DESCR(ap2)->elsize, + PyArray_STRIDES(sorter)[0], NPY_SIZEOF_INTP, ap2); + NPY_END_THREADS_DESCR(PyArray_DESCR(ap2)); + if (error < 0) { PyErr_SetString(PyExc_ValueError, - "Sorter index out of range."); + "Sorter index out of range."); goto fail; } Py_DECREF(ap3); @@ -2398,41 +2235,51 @@ PyArray_Compress(PyArrayObject *self, PyObject *condition, int axis, } /* - * count number of nonzero bytes in 16 byte block + * count number of nonzero bytes in 48 byte block * w must be aligned to 8 bytes * * even though it uses 64 bit types its faster than the bytewise sum on 32 bit * but a 32 bit type version would make it even faster on these platforms */ -static NPY_INLINE int -count_nonzero_bytes_128(const npy_uint64 * w) +static NPY_INLINE npy_intp +count_nonzero_bytes_384(const npy_uint64 * w) { const npy_uint64 w1 = w[0]; const npy_uint64 w2 = w[1]; + const npy_uint64 w3 = w[2]; + const npy_uint64 w4 = w[3]; + const npy_uint64 w5 = w[4]; + const npy_uint64 w6 = w[5]; + npy_intp r; + + /* + * last part of sideways add popcount, first three bisections can be + * skipped as we are dealing with bytes. + * multiplication equivalent to (x + (x>>8) + (x>>16) + (x>>24)) & 0xFF + * multiplication overflow well defined for unsigned types. + * w1 + w2 guaranteed to not overflow as we only have 0 and 1 data. + */ + r = ((w1 + w2 + w3 + w4 + w5 + w6) * 0x0101010101010101ULL) >> 56ULL; /* * bytes not exclusively 0 or 1, sum them individually. * should only happen if one does weird stuff with views or external * buffers. + * Doing this after the optimistic computation allows saving registers and + * better pipelining */ - if (NPY_UNLIKELY(((w1 | w2) & 0xFEFEFEFEFEFEFEFEULL) != 0)) { + if (NPY_UNLIKELY( + ((w1 | w2 | w3 | w4 | w5 | w6) & 0xFEFEFEFEFEFEFEFEULL) != 0)) { /* reload from pointer to avoid a unnecessary stack spill with gcc */ const char * c = (const char *)w; npy_uintp i, count = 0; - for (i = 0; i < 16; i++) { + for (i = 0; i < 48; i++) { count += (c[i] != 0); } return count; } - /* - * last part of sideways add popcount, first three bisections can be - * skipped as we are dealing with bytes. - * multiplication equivalent to (x + (x>>8) + (x>>16) + (x>>24)) & 0xFF - * multiplication overflow well defined for unsigned types. - * w1 + w2 guaranteed to not overflow as we only have 0 and 1 data. - */ - return ((w1 + w2) * 0x0101010101010101ULL) >> 56ULL; + return r; } /* @@ -2448,6 +2295,7 @@ count_boolean_trues(int ndim, char *data, npy_intp *ashape, npy_intp *astrides) npy_intp shape[NPY_MAXDIMS], strides[NPY_MAXDIMS]; npy_intp i, coord[NPY_MAXDIMS]; npy_intp count = 0; + NPY_BEGIN_THREADS_DEF; /* Use raw iteration with no heap memory allocation */ if (PyArray_PrepareOneRawArrayIter( @@ -2463,6 +2311,8 @@ count_boolean_trues(int ndim, char *data, npy_intp *ashape, npy_intp *astrides) return 0; } + NPY_BEGIN_THREADS_THRESHOLDED(shape[0]); + /* Special case for contiguous inner loop */ if (strides[0] == 1) { NPY_RAW_ITER_START(idim, ndim, coord, shape) { @@ -2471,9 +2321,9 @@ count_boolean_trues(int ndim, char *data, npy_intp *ashape, npy_intp *astrides) const char *e = data + shape[0]; if (NPY_CPU_HAVE_UNALIGNED_ACCESS || npy_is_aligned(d, sizeof(npy_uint64))) { - npy_uintp stride = 2 * sizeof(npy_uint64); + npy_uintp stride = 6 * sizeof(npy_uint64); for (; d < e - (shape[0] % stride); d += stride) { - count += count_nonzero_bytes_128((const npy_uint64 *)d); + count += count_nonzero_bytes_384((const npy_uint64 *)d); } } for (; d < e; ++d) { @@ -2492,6 +2342,8 @@ count_boolean_trues(int ndim, char *data, npy_intp *ashape, npy_intp *astrides) } NPY_RAW_ITER_ONE_NEXT(idim, ndim, coord, shape, data, strides); } + NPY_END_THREADS; + return count; } @@ -2512,6 +2364,7 @@ PyArray_CountNonzero(PyArrayObject *self) NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *strideptr, *innersizeptr; + NPY_BEGIN_THREADS_DEF; /* Special low-overhead version specific to the boolean type */ if (PyArray_DESCR(self)->type_num == NPY_BOOL) { @@ -2561,6 +2414,9 @@ PyArray_CountNonzero(PyArrayObject *self) NpyIter_Deallocate(iter); return -1; } + + NPY_BEGIN_THREADS_NDITER(iter); + dataptr = NpyIter_GetDataPtrArray(iter); strideptr = NpyIter_GetInnerStrideArray(iter); innersizeptr = NpyIter_GetInnerLoopSizePtr(iter); @@ -2580,6 +2436,8 @@ PyArray_CountNonzero(PyArrayObject *self) } while(iternext(iter)); + NPY_END_THREADS; + NpyIter_Deallocate(iter); return PyErr_Occurred() ? -1 : nonzero_count; @@ -2598,10 +2456,7 @@ PyArray_Nonzero(PyArrayObject *self) PyObject *ret_tuple; npy_intp ret_dims[2]; PyArray_NonzeroFunc *nonzero = PyArray_DESCR(self)->f->nonzero; - char *data; - npy_intp stride, count; npy_intp nonzero_count; - npy_intp *multi_index; NpyIter *iter; NpyIter_IterNextFunc *iternext; @@ -2628,23 +2483,51 @@ PyArray_Nonzero(PyArrayObject *self) /* If it's a one-dimensional result, don't use an iterator */ if (ndim <= 1) { - npy_intp j; + npy_intp * multi_index = (npy_intp *)PyArray_DATA(ret); + char * data = PyArray_BYTES(self); + npy_intp stride = (ndim == 0) ? 0 : PyArray_STRIDE(self, 0); + npy_intp count = (ndim == 0) ? 1 : PyArray_DIM(self, 0); + NPY_BEGIN_THREADS_DEF; - multi_index = (npy_intp *)PyArray_DATA(ret); - data = PyArray_BYTES(self); - stride = (ndim == 0) ? 0 : PyArray_STRIDE(self, 0); - count = (ndim == 0) ? 1 : PyArray_DIM(self, 0); + /* nothing to do */ + if (nonzero_count == 0) { + goto finish; + } + NPY_BEGIN_THREADS_THRESHOLDED(count); + + /* avoid function call for bool */ if (PyArray_ISBOOL(self)) { - /* avoid function call for bool */ - for (j = 0; j < count; ++j) { - if (*data != 0) { - *multi_index++ = j; + /* + * use fast memchr variant for sparse data, see gh-4370 + * the fast bool count is followed by this sparse path is faster + * than combining the two loops, even for larger arrays + */ + if (((double)nonzero_count / count) <= 0.1) { + npy_intp subsize; + npy_intp j = 0; + while (1) { + npy_memchr(data + j * stride, 0, stride, count - j, + &subsize, 1); + j += subsize; + if (j >= count) { + break; + } + *multi_index++ = j++; + } + } + else { + npy_intp j; + for (j = 0; j < count; ++j) { + if (*data != 0) { + *multi_index++ = j; + } + data += stride; } - data += stride; } } else { + npy_intp j; for (j = 0; j < count; ++j) { if (nonzero(data, self)) { *multi_index++ = j; @@ -2653,6 +2536,8 @@ PyArray_Nonzero(PyArrayObject *self) } } + NPY_END_THREADS; + goto finish; } @@ -2672,6 +2557,8 @@ PyArray_Nonzero(PyArrayObject *self) } if (NpyIter_GetIterSize(iter) != 0) { + npy_intp * multi_index; + NPY_BEGIN_THREADS_DEF; /* Get the pointers for inner loop iteration */ iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { @@ -2685,6 +2572,9 @@ PyArray_Nonzero(PyArrayObject *self) Py_DECREF(ret); return NULL; } + + NPY_BEGIN_THREADS_NDITER(iter); + dataptr = NpyIter_GetDataPtrArray(iter); multi_index = (npy_intp *)PyArray_DATA(ret); @@ -2707,6 +2597,8 @@ PyArray_Nonzero(PyArrayObject *self) } } while(iternext(iter)); } + + NPY_END_THREADS; } NpyIter_Deallocate(iter); @@ -2732,7 +2624,7 @@ finish: else { for (i = 0; i < ndim; ++i) { PyArrayObject *view; - stride = ndim*NPY_SIZEOF_INTP; + npy_intp stride = ndim * NPY_SIZEOF_INTP; view = (PyArrayObject *)PyArray_New(Py_TYPE(self), 1, &nonzero_count, @@ -2775,7 +2667,7 @@ PyArray_MultiIndexGetItem(PyArrayObject *self, npy_intp *multi_index) npy_intp shapevalue = shape[idim]; npy_intp ind = multi_index[idim]; - if (check_and_adjust_index(&ind, shapevalue, idim) < 0) { + if (check_and_adjust_index(&ind, shapevalue, idim, NULL) < 0) { return NULL; } data += ind * strides[idim]; @@ -2804,7 +2696,7 @@ PyArray_MultiIndexSetItem(PyArrayObject *self, npy_intp *multi_index, npy_intp shapevalue = shape[idim]; npy_intp ind = multi_index[idim]; - if (check_and_adjust_index(&ind, shapevalue, idim) < 0) { + if (check_and_adjust_index(&ind, shapevalue, idim, NULL) < 0) { return -1; } data += ind * strides[idim]; diff --git a/numpy/core/src/multiarray/iterators.c b/numpy/core/src/multiarray/iterators.c index b8e7c5366..81c6b2a8e 100644 --- a/numpy/core/src/multiarray/iterators.c +++ b/numpy/core/src/multiarray/iterators.c @@ -71,7 +71,7 @@ parse_index_entry(PyObject *op, npy_intp *step_size, *n_steps = SINGLE_INDEX; *step_size = 0; if (check_index) { - if (check_and_adjust_index(&i, max, axis) < 0) { + if (check_and_adjust_index(&i, max, axis, NULL) < 0) { goto fail; } } @@ -668,7 +668,7 @@ iter_subscript_int(PyArrayIterObject *self, PyArrayObject *ind) itemsize = PyArray_DESCR(self->ao)->elsize; if (PyArray_NDIM(ind) == 0) { num = *((npy_intp *)PyArray_DATA(ind)); - if (check_and_adjust_index(&num, self->size, -1) < 0) { + if (check_and_adjust_index(&num, self->size, -1, NULL) < 0) { PyArray_ITER_RESET(self); return NULL; } @@ -702,7 +702,7 @@ iter_subscript_int(PyArrayIterObject *self, PyArrayObject *ind) swap = (PyArray_ISNOTSWAPPED(ret) != PyArray_ISNOTSWAPPED(self->ao)); while (counter--) { num = *((npy_intp *)(ind_it->dataptr)); - if (check_and_adjust_index(&num, self->size, -1) < 0) { + if (check_and_adjust_index(&num, self->size, -1, NULL) < 0) { Py_DECREF(ind_it); Py_DECREF(ret); PyArray_ITER_RESET(self); @@ -926,7 +926,7 @@ iter_ass_sub_int(PyArrayIterObject *self, PyArrayObject *ind, copyswap = PyArray_DESCR(self->ao)->f->copyswap; if (PyArray_NDIM(ind) == 0) { num = *((npy_intp *)PyArray_DATA(ind)); - if (check_and_adjust_index(&num, self->size, -1) < 0) { + if (check_and_adjust_index(&num, self->size, -1, NULL) < 0) { return -1; } PyArray_ITER_GOTO1D(self, num); @@ -940,7 +940,7 @@ iter_ass_sub_int(PyArrayIterObject *self, PyArrayObject *ind, counter = ind_it->size; while (counter--) { num = *((npy_intp *)(ind_it->dataptr)); - if (check_and_adjust_index(&num, self->size, -1) < 0) { + if (check_and_adjust_index(&num, self->size, -1, NULL) < 0) { Py_DECREF(ind_it); return -1; } @@ -1017,7 +1017,7 @@ iter_ass_subscript(PyArrayIterObject *self, PyObject *ind, PyObject *val) PyErr_Clear(); } else { - if (check_and_adjust_index(&start, self->size, -1) < 0) { + if (check_and_adjust_index(&start, self->size, -1, NULL) < 0) { goto finish; } retval = 0; @@ -1489,6 +1489,10 @@ PyArray_MultiIterFromObjects(PyObject **mps, int n, int nadd, ...) } else { multi->iters[i] = (PyArrayIterObject *)PyArray_IterNew(arr); + if (multi->iters[i] == NULL) { + err = 1; + break; + } Py_DECREF(arr); } } @@ -1549,6 +1553,10 @@ PyArray_MultiIterNew(int n, ...) } else { multi->iters[i] = (PyArrayIterObject *)PyArray_IterNew(arr); + if (multi->iters[i] == NULL) { + err = 1; + break; + } Py_DECREF(arr); } } diff --git a/numpy/core/src/multiarray/lowlevel_strided_loops.c.src b/numpy/core/src/multiarray/lowlevel_strided_loops.c.src index 638ae4d1e..38e7656f3 100644 --- a/numpy/core/src/multiarray/lowlevel_strided_loops.c.src +++ b/numpy/core/src/multiarray/lowlevel_strided_loops.c.src @@ -189,9 +189,10 @@ static void * specialized copy and swap for source stride 0, * interestingly unrolling here is like above is only marginally profitable for * small types and detrimental for >= 8byte moves on x86 + * but it profits from vectorization enabled with -O3 */ #if (@src_contig@ == 0) && @is_aligned@ -static void +static NPY_GCC_OPT_3 void @prefix@_@oper@_size@elsize@_srcstride0(char *dst, npy_intp dst_stride, char *src, npy_intp NPY_UNUSED(src_stride), @@ -792,7 +793,7 @@ NPY_NO_EXPORT PyArray_StridedUnaryOp * #endif -static void +static NPY_GCC_OPT_3 void @prefix@_cast_@name1@_to_@name2@( char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, @@ -1353,3 +1354,414 @@ PyArray_TransferMaskedStridedToNDim(npy_intp ndim, } } } + + +/***************************************************************************/ +/****************** MapIter (Advanced indexing) Get/Set ********************/ +/***************************************************************************/ + +/**begin repeat + * #name = set, get# + * #isget = 0, 1# + */ + +/* + * Advanded indexing iteration of arrays when there is a single indexing + * array which has the same memory order as the value array and both + * can be trivally iterated (single stride, aligned, no casting necessary). + */ +NPY_NO_EXPORT int +mapiter_trivial_@name@(PyArrayObject *self, PyArrayObject *ind, + PyArrayObject *result) +{ + char *base_ptr, *ind_ptr, *result_ptr; + npy_intp self_stride, ind_stride, result_stride; + npy_intp fancy_dim = PyArray_DIM(self, 0); + + npy_intp itersize; + + int is_aligned = PyArray_ISALIGNED(self) && PyArray_ISALIGNED(result); + int needs_api = PyDataType_REFCHK(PyArray_DESCR(self)); + + PyArray_CopySwapFunc *copyswap = PyArray_DESCR(self)->f->copyswap; + NPY_BEGIN_THREADS_DEF; + + base_ptr = PyArray_BYTES(self); + self_stride = PyArray_STRIDE(self, 0); + + PyArray_PREPARE_TRIVIAL_PAIR_ITERATION(ind, result, itersize, + ind_ptr, result_ptr, + ind_stride, result_stride) + + if (!needs_api) { + NPY_BEGIN_THREADS_THRESHOLDED(PyArray_SIZE(ind)); + } +#if !@isget@ + /* Check the indices beforehand */ + while (itersize--) { + npy_intp indval = *((npy_intp*)ind_ptr); + if (check_and_adjust_index(&indval, fancy_dim, 1, _save) < 0 ) { + return -1; + } + ind_ptr += ind_stride; + } + + /* + * Reset the ind_ptr and itersize, due to broadcasting it is always + * the size of ind. + */ + ind_ptr = PyArray_BYTES(ind); + itersize = PyArray_SIZE(ind); +#endif + + /* Optimization for aligned types that do not need the api */ + switch ((is_aligned && !needs_api) ? PyArray_ITEMSIZE(self) : 0) { + +/**begin repeat1 + * #elsize = 1, 2, 4, 8, 0# + * #copytype = npy_uint8, npy_uint16, npy_uint32, npy_uint64, 0# + */ + +#if @elsize@ + case @elsize@: +#else + default: +#endif + while (itersize--) { + char * self_ptr; + npy_intp indval = *((npy_intp*)ind_ptr); + assert(npy_is_aligned(ind_ptr, _ALIGN(npy_intp))); +#if @isget@ + if (check_and_adjust_index(&indval, fancy_dim, 1, _save) < 0 ) { + return -1; + } +#else + if (indval < 0) { + indval += fancy_dim; + } +#endif + self_ptr = base_ptr + indval * self_stride; + +#if @isget@ +#if @elsize@ + assert(npy_is_aligned(result_ptr, _ALIGN(@copytype@))); + assert(npy_is_aligned(self_ptr, _ALIGN(@copytype@))); + *(@copytype@ *)result_ptr = *(@copytype@ *)self_ptr; +#else + copyswap(result_ptr, self_ptr, 0, self); +#endif + +#else /* !@isget@ */ +#if @elsize@ + assert(npy_is_aligned(result_ptr, _ALIGN(@copytype@))); + assert(npy_is_aligned(self_ptr, _ALIGN(@copytype@))); + *(@copytype@ *)self_ptr = *(@copytype@ *)result_ptr; +#else + copyswap(self_ptr, result_ptr, 0, self); +#endif +#endif + + ind_ptr += ind_stride; + result_ptr += result_stride; + } + break; + +/**end repeat1**/ + } + + NPY_END_THREADS; + + return 0; +} + + +/* + * General advanced indexing iteration. + */ +NPY_NO_EXPORT int +mapiter_@name@(PyArrayMapIterObject *mit) +{ + npy_intp *counter, count; + int i, is_aligned; + + /* Cached mit info */ + int numiter = mit->numiter; + int needs_api = mit->needs_api; + /* Constant information */ + npy_intp fancy_dims[NPY_MAXDIMS]; + npy_intp fancy_strides[NPY_MAXDIMS]; +#if @isget@ + int iteraxis; +#endif + + char *baseoffset = mit->baseoffset; + char **outer_ptrs = mit->outer_ptrs; + npy_intp *outer_strides = mit->outer_strides; + PyArrayObject *array= mit->array; + + /* Fill constant information */ +#if @isget@ + iteraxis = mit->iteraxes[0]; +#endif + for (i = 0; i < numiter; i++) { + fancy_dims[i] = mit->fancy_dims[i]; + fancy_strides[i] = mit->fancy_strides[i]; + } + + /* + * Alignment information (swapping is never needed, since we buffer), + * could also check extra_op is buffered, but it should rarely matter. + */ + + is_aligned = PyArray_ISALIGNED(array) && PyArray_ISALIGNED(mit->extra_op); + + if (mit->size == 0) { + return 0; + } + + if (mit->subspace_iter == NULL) { + /* + * Item by item copy situation, the operand is buffered + * so use copyswap. + */ + PyArray_CopySwapFunc *copyswap = PyArray_DESCR(array)->f->copyswap; + + /* We have only one iterator handling everything */ + counter = NpyIter_GetInnerLoopSizePtr(mit->outer); + + /************ Optimized inner loops without subspace *************/ + +/**begin repeat1 + * #one_iter = 1, 0# + * #numiter = 1, numiter# + */ + +#if @one_iter@ + if (numiter == 1) { +#else + else { +#endif + NPY_BEGIN_THREADS_DEF; + if (!needs_api) { + NPY_BEGIN_THREADS; + } + + /* Optimization for aligned types that do not need the api */ + switch ((is_aligned && !needs_api) ? PyArray_ITEMSIZE(array) : 0) { + +/**begin repeat2 + * #elsize = 1, 2, 4, 8, 0# + * #copytype = npy_uint8, npy_uint16, npy_uint32, npy_uint64, 0# + */ + +#if @elsize@ + case @elsize@: +#else + default: +#endif + /* Outer iteration (safe because mit->size != 0) */ + do { +#if !@isget@ + /* + * When the API is needed the casting might fail + * TODO: (only if buffering is enabled). + */ + if (needs_api && PyErr_Occurred()) { + return -1; + } +#endif + count = *counter; + while (count--) { + char * self_ptr = baseoffset; + for (i=0; i < @numiter@; i++) { + npy_intp indval = *((npy_intp*)outer_ptrs[i]); + assert(npy_is_aligned(outer_ptrs[i], + _ALIGN(npy_intp))); + +#if @isget@ && @one_iter@ + if (check_and_adjust_index(&indval, fancy_dims[i], + iteraxis, _save) < 0 ) { + return -1; + } +#else + if (indval < 0) { + indval += fancy_dims[i]; + } +#endif + self_ptr += indval * fancy_strides[i]; + + /* advance indexing arrays */ + outer_ptrs[i] += outer_strides[i]; + } + +#if @isget@ +#if @elsize@ + assert(npy_is_aligned(outer_ptrs[i], _ALIGN(@copytype@))); + assert(npy_is_aligned(self_ptr, _ALIGN(@copytype@))); + *(@copytype@ *)(outer_ptrs[i]) = *(@copytype@ *)self_ptr; +#else + copyswap(outer_ptrs[i], self_ptr, 0, array); +#endif +#else /* !@isget@ */ +#if @elsize@ + assert(npy_is_aligned(outer_ptrs[i], _ALIGN(@copytype@))); + assert(npy_is_aligned(self_ptr, _ALIGN(@copytype@))); + *(@copytype@ *)self_ptr = *(@copytype@ *)(outer_ptrs[i]); +#else + copyswap(self_ptr, outer_ptrs[i], 0, array); +#endif +#endif + /* advance extra operand */ + outer_ptrs[i] += outer_strides[i]; + } + } while (mit->outer_next(mit->outer)); + + break; + +/**end repeat2**/ + } + NPY_END_THREADS; + } +/**end repeat1**/ + } + + /******************* Nested Iteration Situation *******************/ + else { + char *subspace_baseptrs[2]; + char **subspace_ptrs = mit->subspace_ptrs; + npy_intp *subspace_strides = mit->subspace_strides; + int skip = 0; + + /* Use strided transfer functions for the inner loop */ + PyArray_StridedUnaryOp *stransfer = NULL; + NpyAuxData *transferdata = NULL; + npy_intp fixed_strides[2]; + +#if @isget@ + npy_intp src_itemsize = PyArray_ITEMSIZE(array); +#else + npy_intp src_itemsize = PyArray_ITEMSIZE(mit->extra_op); +#endif + + /* + * Get a dtype transfer function, since there are no + * buffers, this is safe. + */ + NpyIter_GetInnerFixedStrideArray(mit->subspace_iter, fixed_strides); + + if (PyArray_GetDTypeTransferFunction(is_aligned, +#if @isget@ + fixed_strides[0], fixed_strides[1], + PyArray_DESCR(array), PyArray_DESCR(mit->extra_op), +#else + fixed_strides[1], fixed_strides[0], + PyArray_DESCR(mit->extra_op), PyArray_DESCR(array), +#endif + 0, + &stransfer, &transferdata, + &needs_api) != NPY_SUCCEED) { + return -1; + } + + counter = NpyIter_GetInnerLoopSizePtr(mit->subspace_iter); + if (*counter == PyArray_SIZE(mit->subspace)) { + skip = 1; + } + +/**begin repeat1 + * #one_iter = 1, 0# + * #numiter = 1, numiter# + */ + +#if @one_iter@ + if (numiter == 1) { +#else + else { +#endif + NPY_BEGIN_THREADS_DEF; + if (!needs_api) { + NPY_BEGIN_THREADS; + } + + /* Outer iteration (safe because mit->size != 0) */ + do { + char * self_ptr = baseoffset; + for (i=0; i < @numiter@; i++) { + npy_intp indval = *((npy_intp*)outer_ptrs[i]); + +#if @isget@ && @one_iter@ + if (check_and_adjust_index(&indval, fancy_dims[i], + iteraxis, _save) < 0 ) { + NPY_AUXDATA_FREE(transferdata); + return -1; + } +#else + if (indval < 0) { + indval += fancy_dims[i]; + } +#endif + + self_ptr += indval * fancy_strides[i]; + } + + /* + * Resetting is slow, so skip if the subspace iteration has + * only a single inner loop. + */ + if (!skip) { + char * errmsg = NULL; + subspace_baseptrs[0] = self_ptr; + subspace_baseptrs[1] = mit->extra_op_ptrs[0]; + + /* (can't really fail, since no buffering necessary) */ + if (!NpyIter_ResetBasePointers(mit->subspace_iter, + subspace_baseptrs, + &errmsg)) { + NPY_END_THREADS; + PyErr_SetString(PyExc_ValueError, errmsg); + NPY_AUXDATA_FREE(transferdata); + return -1; + } + } + else { + subspace_ptrs[0] = self_ptr; + subspace_ptrs[1] = mit->extra_op_ptrs[0]; + } + +#if !@isget@ + /* + * When the API is needed the casting might fail + * TODO: Could only check if casting is unsafe, or even just + * not at all... + */ + if (needs_api && PyErr_Occurred()) { + NPY_AUXDATA_FREE(transferdata); + return -1; + } +#endif + + do { + +#if @isget@ + stransfer(subspace_ptrs[1], subspace_strides[1], + subspace_ptrs[0], subspace_strides[0], + *counter, src_itemsize, transferdata); +#else + stransfer(subspace_ptrs[0], subspace_strides[0], + subspace_ptrs[1], subspace_strides[1], + *counter, src_itemsize, transferdata); +#endif + } while (mit->subspace_next(mit->subspace_iter)); + + mit->extra_op_next(mit->extra_op_iter); + } while (mit->outer_next(mit->outer)); + NPY_END_THREADS; + } +/**end repeat1**/ + + NPY_AUXDATA_FREE(transferdata); + } + return 0; +} + +/**end repeat**/ diff --git a/numpy/core/src/multiarray/mapping.c b/numpy/core/src/multiarray/mapping.c index 6bc4fb42d..1255b15ea 100644 --- a/numpy/core/src/multiarray/mapping.c +++ b/numpy/core/src/multiarray/mapping.c @@ -18,14 +18,26 @@ #include "lowlevel_strided_loops.h" #include "item_selection.h" -#define SOBJ_NOTFANCY 0 -#define SOBJ_ISFANCY 1 -#define SOBJ_BADARRAY 2 -#define SOBJ_TOOMANY 3 -#define SOBJ_LISTTUP 4 -static PyObject * -array_subscript_simple(PyArrayObject *self, PyObject *op, int check_index); +#define HAS_INTEGER 1 +#define HAS_NEWAXIS 2 +#define HAS_SLICE 4 +#define HAS_ELLIPSIS 8 +/* HAS_FANCY can be mixed with HAS_0D_BOOL, be careful when to use & or == */ +#define HAS_FANCY 16 +#define HAS_BOOL 32 +/* NOTE: Only set if it is neither fancy nor purely integer index! */ +#define HAS_SCALAR_ARRAY 64 +/* + * Indicate that this is a fancy index that comes from a 0d boolean. + * This means that the index does not operate along a real axis. The + * corresponding index type is just HAS_FANCY. + */ +#define HAS_0D_BOOL (HAS_FANCY | 128) + + +static int +_nonzero_indices(PyObject *myBool, PyArrayObject **arrays); /****************************************************************************** *** IMPLEMENT MAPPING PROTOCOL *** @@ -42,137 +54,12 @@ array_length(PyArrayObject *self) } } -/* Get array item as scalar type */ -NPY_NO_EXPORT PyObject * -array_item_asscalar(PyArrayObject *self, npy_intp i) -{ - char *item; - npy_intp dim0; - - /* Bounds check and get the data pointer */ - dim0 = PyArray_DIM(self, 0); - if (i < 0) { - i += dim0; - } - if (i < 0 || i >= dim0) { - PyErr_SetString(PyExc_IndexError, "index out of bounds"); - return NULL; - } - item = PyArray_BYTES(self) + i * PyArray_STRIDE(self, 0); - return PyArray_Scalar(item, PyArray_DESCR(self), (PyObject *)self); -} - -/* Get array item as ndarray type */ -NPY_NO_EXPORT PyObject * -array_item_asarray(PyArrayObject *self, npy_intp i) -{ - char *item; - PyArrayObject *ret; - npy_intp dim0; - - if(PyArray_NDIM(self) == 0) { - PyErr_SetString(PyExc_IndexError, - "0-d arrays can't be indexed"); - return NULL; - } - - /* Bounds check and get the data pointer */ - dim0 = PyArray_DIM(self, 0); - if (check_and_adjust_index(&i, dim0, 0) < 0) { - return NULL; - } - item = PyArray_BYTES(self) + i * PyArray_STRIDE(self, 0); - - /* Create the view array */ - Py_INCREF(PyArray_DESCR(self)); - ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self), - PyArray_DESCR(self), - PyArray_NDIM(self)-1, - PyArray_DIMS(self)+1, - PyArray_STRIDES(self)+1, item, - PyArray_FLAGS(self), - (PyObject *)self); - if (ret == NULL) { - return NULL; - } - - /* Set the base object */ - Py_INCREF(self); - if (PyArray_SetBaseObject(ret, (PyObject *)self) < 0) { - Py_DECREF(ret); - return NULL; - } - - PyArray_UpdateFlags(ret, NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS); - return (PyObject *)ret; -} - -/* Get array item at given index */ -NPY_NO_EXPORT PyObject * -array_item(PyArrayObject *self, Py_ssize_t _i) -{ - /* Workaround Python 2.4: Py_ssize_t not the same as npyint_p */ - npy_intp i = _i; - - if (PyArray_NDIM(self) == 1) { - return array_item_asscalar(self, (npy_intp) i); - } - else { - return array_item_asarray(self, (npy_intp) i); - } -} - -NPY_NO_EXPORT int -array_ass_item_object(PyArrayObject *self, npy_intp i, PyObject *v) -{ - PyArrayObject *tmp; - char *item; - npy_intp dim0; - int ret; - - if (v == NULL) { - PyErr_SetString(PyExc_ValueError, - "can't delete array elements"); - return -1; - } - - if (PyArray_FailUnlessWriteable(self, "assignment destination") < 0) { - return -1; - } - - if (PyArray_NDIM(self) == 0) { - PyErr_SetString(PyExc_IndexError, - "0-d arrays can't be indexed"); - return -1; - } - - - /* For multi-dimensional arrays, use CopyObject */ - if (PyArray_NDIM(self) > 1) { - tmp = (PyArrayObject *)array_item_asarray(self, i); - if(tmp == NULL) { - return -1; - } - ret = PyArray_CopyObject(tmp, v); - Py_DECREF(tmp); - return ret; - } - - /* Bounds check and get the data pointer */ - dim0 = PyArray_DIM(self, 0); - if (check_and_adjust_index(&i, dim0, 0) < 0) { - return -1; - } - item = PyArray_BYTES(self) + i * PyArray_STRIDE(self, 0); - - return PyArray_SETITEM(self, item, v); -} /* -------------------------------------------------------------- */ /*NUMPY_API * -*/ + */ NPY_NO_EXPORT void PyArray_MapIterSwapAxes(PyArrayMapIterObject *mit, PyArrayObject **ret, int getmap) { @@ -225,7 +112,7 @@ PyArray_MapIterSwapAxes(PyArrayMapIterObject *mit, PyArrayObject **ret, int getm * For setting the array the tuple for transpose is * (n2,...,n1+n2-1,0,...,n2-1,n1+n2,...n3-1) */ - n1 = mit->iters[0]->nd_m1 + 1; + n1 = mit->nd_fancy; n2 = mit->consec; /* axes to insert at */ n3 = mit->nd; @@ -249,364 +136,789 @@ PyArray_MapIterSwapAxes(PyArrayMapIterObject *mit, PyArrayObject **ret, int getm *ret = (PyArrayObject *)new; } -static PyObject * -PyArray_GetMap(PyArrayMapIterObject *mit) + +/** + * Prepare an npy_index_object from the python slicing object. + * + * This function handles all index preparations with the exception + * of field access. It fills the array of index_info structs correctly. + * It already handles the boolean array special case for fancy indexing, + * i.e. if the index type is boolean, it is exactly one matching boolean + * array. If the index type is fancy, the boolean array is already + * converted to integer arrays. There is (as before) no checking of the + * boolean dimension. + * + * Checks everything but the bounds. + * + * @param the array being indexed + * @param the index object + * @param index info struct being filled (size of NPY_MAXDIMS * 2 + 1) + * @param number of indices found + * @param dimension of the indexing result + * @param dimension of the fancy/advanced indices part + * @param whether to allow the boolean special case + * + * @returns the index_type or -1 on failure and fills the number of indices. + */ +NPY_NO_EXPORT int +prepare_index(PyArrayObject *self, PyObject *index, + npy_index_info *indices, + int *num, int *ndim, int *out_fancy_ndim, int allow_boolean) { + int new_ndim, fancy_ndim, used_ndim, index_ndim; + int curr_idx, get_idx; - PyArrayObject *ret, *temp; - PyArrayIterObject *it; - npy_intp counter; - int swap; - PyArray_CopySwapFunc *copyswap; + npy_intp i, n; - /* Unbound map iterator --- Bind should have been called */ - if (mit->ait == NULL) { - return NULL; - } + npy_bool make_tuple = 0; + PyObject *obj = NULL; + PyArrayObject *arr; - /* This relies on the map iterator object telling us the shape - of the new array in nd and dimensions. - */ - temp = mit->ait->ao; - Py_INCREF(PyArray_DESCR(temp)); - ret = (PyArrayObject *) - PyArray_NewFromDescr(Py_TYPE(temp), - PyArray_DESCR(temp), - mit->nd, mit->dimensions, - NULL, NULL, - PyArray_ISFORTRAN(temp), - (PyObject *)temp); - if (ret == NULL) { - return NULL; - } + int index_type = 0; + int ellipsis_pos = -1; /* - * Now just iterate through the new array filling it in - * with the next object from the original array as - * defined by the mapping iterator + * The index might be a multi-dimensional index, but not yet a tuple + * this makes it a tuple in that case. + * + * TODO: Refactor into its own function. */ + if (!PyTuple_CheckExact(index) + /* Next three are just to avoid slow checks */ +#if !defined(NPY_PY3K) + && (!PyInt_CheckExact(index)) +#else + && (!PyLong_CheckExact(index)) +#endif + && (index != Py_None) + && (!PySlice_Check(index)) + && (!PyArray_Check(index)) + && (PySequence_Check(index))) { + /* + * Sequences < NPY_MAXDIMS with any slice objects + * or newaxis, Ellipsis or other arrays or sequences + * embedded, are considered equivalent to an indexing + * tuple. (`a[[[1,2], [3,4]]] == a[[1,2], [3,4]]`) + */ - if ((it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ret)) == NULL) { - Py_DECREF(ret); - return NULL; - } - counter = it->size; - swap = (PyArray_ISNOTSWAPPED(temp) != PyArray_ISNOTSWAPPED(ret)); - copyswap = PyArray_DESCR(ret)->f->copyswap; - PyArray_MapIterReset(mit); - while (counter--) { - copyswap(it->dataptr, mit->dataptr, swap, ret); - PyArray_MapIterNext(mit); - PyArray_ITER_NEXT(it); - } - Py_DECREF(it); + if (PyTuple_Check(index)) { + /* If it is already a tuple, make it an exact tuple anyway */ + n = 0; + make_tuple = 1; + } + n = PySequence_Size(index); + if (n < 0 || n >= NPY_MAXDIMS) { + n = 0; + } + for (i = 0; i < n; i++) { + PyObject *tmp_obj = PySequence_GetItem(index, i); + if (tmp_obj == NULL) { + make_tuple = 1; + break; + } + if (PyArray_Check(tmp_obj) || PySequence_Check(tmp_obj) + || PySlice_Check(tmp_obj) || tmp_obj == Py_Ellipsis + || tmp_obj == Py_None) { + make_tuple = 1; + Py_DECREF(tmp_obj); + break; + } + Py_DECREF(tmp_obj); + } - /* check for consecutive axes */ - if ((mit->subspace != NULL) && (mit->consec)) { - PyArray_MapIterSwapAxes(mit, &ret, 1); + if (make_tuple) { + /* We want to interpret it as a tuple, so make it one */ + index = PySequence_Tuple(index); + if (index == NULL) { + return -1; + } + } } - return (PyObject *)ret; -} -NPY_NO_EXPORT int -array_ass_item(PyArrayObject *self, Py_ssize_t i, PyObject *v) -{ - return array_ass_item_object(self, (npy_intp) i, v); -} - -static int -PyArray_SetMap(PyArrayMapIterObject *mit, PyObject *op) -{ - PyArrayObject *arr = NULL; - PyArrayIterObject *it; - npy_intp counter; - int swap; - PyArray_CopySwapFunc *copyswap; - PyArray_Descr *descr; - - /* Unbound Map Iterator */ - if (mit->ait == NULL) { - return -1; - } - descr = PyArray_DESCR(mit->ait->ao); - Py_INCREF(descr); - arr = (PyArrayObject *)PyArray_FromAny(op, descr, - 0, 0, NPY_ARRAY_FORCECAST, NULL); - if (arr == NULL) { - return -1; + /* If the index is not a tuple, handle it the same as (index,) */ + if (!PyTuple_CheckExact(index)) { + obj = index; + index_ndim = 1; } - if ((mit->subspace != NULL) && (mit->consec)) { - PyArray_MapIterSwapAxes(mit, &arr, 0); - if (arr == NULL) { - return -1; + else { + n = PyTuple_GET_SIZE(index); + if (n > NPY_MAXDIMS * 2) { + PyErr_SetString(PyExc_IndexError, + "too many indices for array"); + goto fail; } + index_ndim = (int)n; + obj = NULL; } - /* Be sure values array is "broadcastable" - to shape of mit->dimensions, mit->nd */ + /* + * Parse all indices into the `indices` array of index_info structs + */ + used_ndim = 0; + new_ndim = 0; + fancy_ndim = 0; + get_idx = 0; + curr_idx = 0; + + while (get_idx < index_ndim) { + if (curr_idx > NPY_MAXDIMS * 2) { + PyErr_SetString(PyExc_IndexError, + "too many indices for array"); + goto failed_building_indices; + } - if ((it = (PyArrayIterObject *)\ - PyArray_BroadcastToShape((PyObject *)arr, - mit->dimensions, mit->nd))==NULL) { - Py_DECREF(arr); - return -1; - } + /* Check for single index. obj is already set then. */ + if ((curr_idx != 0) || (obj == NULL)) { + obj = PyTuple_GET_ITEM(index, get_idx++); + } + else { + /* only one loop */ + get_idx += 1; + } + + /**** Try the cascade of possible indices ****/ + + /* Index is an ellipsis (`...`) */ + if (obj == Py_Ellipsis) { + /* + * If there is more then one Ellipsis, it is replaced. Deprecated, + * since it is hard to imagine anyone using two Ellipsis and + * actually planning on all but the first being automatically + * replaced with a slice. + */ + if (index_type & HAS_ELLIPSIS) { + if (DEPRECATE( + "an index can only have a single Ellipsis (`...`); " + "replace all but one with slices (`:`).") < 0) { + goto failed_building_indices; + } + index_type |= HAS_SLICE; - counter = mit->size; - swap = (PyArray_ISNOTSWAPPED(mit->ait->ao) != - (PyArray_ISNOTSWAPPED(arr))); - copyswap = PyArray_DESCR(arr)->f->copyswap; - PyArray_MapIterReset(mit); - /* Need to decref arrays with objects in them */ - if (PyDataType_FLAGCHK(descr, NPY_ITEM_HASOBJECT)) { - while (counter--) { - PyArray_Item_INCREF(it->dataptr, PyArray_DESCR(arr)); - PyArray_Item_XDECREF(mit->dataptr, PyArray_DESCR(arr)); - memmove(mit->dataptr, it->dataptr, PyArray_ITEMSIZE(arr)); - /* ignored unless VOID array with object's */ - if (swap) { - copyswap(mit->dataptr, NULL, swap, arr); + indices[curr_idx].type = HAS_SLICE; + indices[curr_idx].object = PySlice_New(NULL, NULL, NULL); + + if (indices[curr_idx].object == NULL) { + goto failed_building_indices; + } + + used_ndim += 1; + new_ndim += 1; + curr_idx += 1; + continue; } - PyArray_MapIterNext(mit); - PyArray_ITER_NEXT(it); + index_type |= HAS_ELLIPSIS; + + indices[curr_idx].type = HAS_ELLIPSIS; + indices[curr_idx].object = NULL; + /* number of slices it is worth, won't update if it is 0: */ + indices[curr_idx].value = 0; + + ellipsis_pos = curr_idx; + /* the used and new ndim will be found later */ + used_ndim += 0; + new_ndim += 0; + curr_idx += 1; + continue; } - Py_DECREF(arr); - Py_DECREF(it); - return 0; - } - else { - while(counter--) { - memmove(mit->dataptr, it->dataptr, PyArray_ITEMSIZE(arr)); - if (swap) { - copyswap(mit->dataptr, NULL, swap, arr); - } - PyArray_MapIterNext(mit); - PyArray_ITER_NEXT(it); + + /* Index is np.newaxis/None */ + else if (obj == Py_None) { + index_type |= HAS_NEWAXIS; + + indices[curr_idx].type = HAS_NEWAXIS; + indices[curr_idx].object = NULL; + + used_ndim += 0; + new_ndim += 1; + curr_idx += 1; + continue; } - Py_DECREF(arr); - Py_DECREF(it); - return 0; - } -} -NPY_NO_EXPORT int -count_new_axes_0d(PyObject *tuple) -{ - int i, argument_count; - int ellipsis_count = 0; - int newaxis_count = 0; + /* Index is a slice object. */ + else if (PySlice_Check(obj)) { + index_type |= HAS_SLICE; - argument_count = PyTuple_GET_SIZE(tuple); - for (i = 0; i < argument_count; ++i) { - PyObject *arg = PyTuple_GET_ITEM(tuple, i); - if (arg == Py_Ellipsis && !ellipsis_count) { - ellipsis_count++; + Py_INCREF(obj); + indices[curr_idx].object = obj; + indices[curr_idx].type = HAS_SLICE; + used_ndim += 1; + new_ndim += 1; + curr_idx += 1; + continue; } - else if (arg == Py_None) { - newaxis_count++; + + /* + * Special case to allow 0-d boolean indexing with scalars. + * Should be removed after boolean as integer deprecation. + * Since this is always an error if it was not a boolean, we can + * allow the 0-d special case before the rest. + */ + else if (PyArray_NDIM(self) != 0) { + /* + * Single integer index, there are two cases here. + * It could be an array, a 0-d array is handled + * a bit weird however, so need to special case it. + */ +#if !defined(NPY_PY3K) + if (PyInt_CheckExact(obj) || !PyArray_Check(obj)) { +#else + if (PyLong_CheckExact(obj) || !PyArray_Check(obj)) { +#endif + i = PyArray_PyIntAsIntp(obj); + if ((i == -1) && PyErr_Occurred()) { + PyErr_Clear(); + } + else { + index_type |= HAS_INTEGER; + indices[curr_idx].object = NULL; + indices[curr_idx].value = i; + indices[curr_idx].type = HAS_INTEGER; + used_ndim += 1; + new_ndim += 0; + curr_idx += 1; + continue; + } + } } - else { - break; + + /* + * At this point, we must have an index array (or array-like). + * It might still be a (purely) bool special case, a 0-d integer + * array (an array scalar) or something invalid. + */ + + if (!PyArray_Check(obj)) { + PyArrayObject *tmp_arr; + tmp_arr = (PyArrayObject *)PyArray_FromAny(obj, NULL, 0, 0, 0, NULL); + if (tmp_arr == NULL) { + /* TODO: Should maybe replace the error here? */ + goto failed_building_indices; + } + + /* + * For example an empty list can be cast to an integer array, + * however it will default to a float one. + */ + if (PyArray_SIZE(tmp_arr) == 0) { + PyArray_Descr *indtype = PyArray_DescrFromType(NPY_INTP); + + arr = (PyArrayObject *)PyArray_FromArray(tmp_arr, indtype, + NPY_ARRAY_FORCECAST); + Py_DECREF(tmp_arr); + if (arr == NULL) { + goto failed_building_indices; + } + } + /* + * Special case to allow 0-d boolean indexing with + * scalars. Should be removed after boolean-array + * like as integer-array like deprecation. + * (does not cover ufunc.at, because it does not use the + * boolean special case, but that should not matter...) + * Since all but strictly boolean indices are invalid, + * there is no need for any further conversion tries. + */ + else if (PyArray_NDIM(self) == 0) { + arr = tmp_arr; + } + else { + /* + * These Checks can be removed after deprecation, since + * they should then be either correct already or error out + * later just like a normal array. + */ + if (PyArray_ISBOOL(tmp_arr)) { + if (DEPRECATE_FUTUREWARNING( + "in the future, boolean array-likes will be " + "handled as a boolean array index") < 0) { + Py_DECREF(tmp_arr); + goto failed_building_indices; + } + if (PyArray_NDIM(tmp_arr) == 0) { + /* + * Need to raise an error here, since the + * DeprecationWarning before was not triggered. + * TODO: A `False` triggers a Deprecation *not* a + * a FutureWarning. + */ + PyErr_SetString(PyExc_IndexError, + "in the future, 0-d boolean arrays will be " + "interpreted as a valid boolean index"); + Py_DECREF(tmp_arr); + goto failed_building_indices; + } + else { + arr = tmp_arr; + } + } + /* + * Note: Down the road, the integers will be cast to intp. + * The user has to make sure they can be safely cast. + * If not, we might index wrong instead of an giving + * an error. + */ + else if (!PyArray_ISINTEGER(tmp_arr)) { + if (PyArray_NDIM(tmp_arr) == 0) { + /* match integer deprecation warning */ + if (DEPRECATE( + "using a non-integer number instead of an " + "integer will result in an error in the " + "future") < 0) { + + /* The error message raised in the future */ + PyErr_SetString(PyExc_IndexError, + "only integers, slices (`:`), ellipsis (`...`), " + "numpy.newaxis (`None`) and integer or boolean " + "arrays are valid indices"); + Py_DECREF((PyObject *)tmp_arr); + goto failed_building_indices; + } + } + else { + if (DEPRECATE( + "non integer (and non boolean) array-likes " + "will not be accepted as indices in the " + "future") < 0) { + + /* Error message to be raised in the future */ + PyErr_SetString(PyExc_IndexError, + "non integer (and non boolean) array-likes will " + "not be accepted as indices in the future"); + Py_DECREF((PyObject *)tmp_arr); + goto failed_building_indices; + } + } + } + + arr = (PyArrayObject *)PyArray_FromArray(tmp_arr, + PyArray_DescrFromType(NPY_INTP), + NPY_ARRAY_FORCECAST); + + if (arr == NULL) { + /* Since this will be removed, handle this later */ + PyErr_Clear(); + arr = tmp_arr; + } + else { + Py_DECREF((PyObject *)tmp_arr); + } + } } - } - if (i < argument_count) { - PyErr_SetString(PyExc_IndexError, - "0-d arrays can only use a single ()" - " or a list of newaxes (and a single ...)" - " as an index"); - return -1; - } - if (newaxis_count > NPY_MAXDIMS) { - PyErr_SetString(PyExc_IndexError, "too many dimensions"); - return -1; - } - return newaxis_count; -} + else { + Py_INCREF(obj); + arr = (PyArrayObject *)obj; + } + + /* Check if the array is valid and fill the information */ + if (PyArray_ISBOOL(arr)) { + /* + * There are two types of boolean indices (which are equivalent, + * for the most part though). A single boolean index of matching + * dimensionality and size is a boolean index. + * If this is not the case, it is instead expanded into (multiple) + * integer array indices. + */ + PyArrayObject *nonzero_result[NPY_MAXDIMS]; + + if ((index_ndim == 1) && allow_boolean) { + /* + * If ndim and size match, this can be optimized as a single + * boolean index. The size check is necessary only to support + * old non-matching sizes by using fancy indexing instead. + * The reason for that is that fancy indexing uses nonzero, + * and only the result of nonzero is checked for legality. + */ + if ((PyArray_NDIM(arr) == PyArray_NDIM(self)) + && PyArray_SIZE(arr) == PyArray_SIZE(self)) { + + index_type = HAS_BOOL; + indices[curr_idx].type = HAS_BOOL; + indices[curr_idx].object = (PyObject *)arr; + + /* keep track anyway, just to be complete */ + used_ndim = PyArray_NDIM(self); + fancy_ndim = PyArray_NDIM(self); + curr_idx += 1; + break; + } + } -NPY_NO_EXPORT PyObject * -add_new_axes_0d(PyArrayObject *arr, int newaxis_count) -{ - PyArrayObject *ret; - npy_intp dimensions[NPY_MAXDIMS]; - int i; + if (PyArray_NDIM(arr) == 0) { + /* + * TODO, WARNING: This code block cannot be used due to + * FutureWarnings at this time. So instead + * just raise an IndexError. + */ + PyErr_SetString(PyExc_IndexError, + "in the future, 0-d boolean arrays will be " + "interpreted as a valid boolean index"); + Py_DECREF((PyObject *)arr); + goto failed_building_indices; + /* + * This can actually be well defined. A new axis is added, + * but at the same time no axis is "used". So if we have True, + * we add a new axis (a bit like with np.newaxis). If it is + * False, we add a new axis, but this axis has 0 entries. + */ + + index_type |= HAS_FANCY; + indices[curr_idx].type = HAS_0D_BOOL; + + /* TODO: This can't fail, right? Is there a faster way? */ + if (PyObject_IsTrue((PyObject *)arr)) { + n = 1; + } + else { + n = 0; + } + indices[curr_idx].object = PyArray_Zeros(1, &n, + PyArray_DescrFromType(NPY_INTP), 0); + Py_DECREF(arr); - for (i = 0; i < newaxis_count; ++i) { - dimensions[i] = 1; - } - Py_INCREF(PyArray_DESCR(arr)); - ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(arr), - PyArray_DESCR(arr), - newaxis_count, dimensions, - NULL, PyArray_DATA(arr), - PyArray_FLAGS(arr), - (PyObject *)arr); - if (ret == NULL) { - return NULL; - } + if (indices[curr_idx].object == NULL) { + goto failed_building_indices; + } - Py_INCREF(arr); - if (PyArray_SetBaseObject(ret, (PyObject *)arr) < 0) { - Py_DECREF(ret); - return NULL; - } + used_ndim += 0; + if (fancy_ndim < 1) { + fancy_ndim = 1; + } + curr_idx += 1; + continue; + } - return (PyObject *)ret; -} + /* Convert the boolean array into multiple integer ones */ + n = _nonzero_indices((PyObject *)arr, nonzero_result); + Py_DECREF(arr); + if (n < 0) { + goto failed_building_indices; + } -/* This checks the args for any fancy indexing objects */ + /* Check that we will not run out of indices to store new ones */ + if (curr_idx + n >= NPY_MAXDIMS * 2) { + PyErr_SetString(PyExc_IndexError, + "too many indices for array"); + for (i=0; i < n; i++) { + Py_DECREF(nonzero_result[i]); + } + goto failed_building_indices; + } -static int -fancy_indexing_check(PyObject *args) -{ - int i, n; - int retval = SOBJ_NOTFANCY; + /* Add the arrays from the nonzero result to the index */ + index_type |= HAS_FANCY; + for (i=0; i < n; i++) { + indices[curr_idx].type = HAS_FANCY; + indices[curr_idx].object = (PyObject *)nonzero_result[i]; - if (PyTuple_Check(args)) { - n = PyTuple_GET_SIZE(args); - if (n >= NPY_MAXDIMS) { - return SOBJ_TOOMANY; - } - for (i = 0; i < n; i++) { - PyObject *obj = PyTuple_GET_ITEM(args,i); - if (PyArray_Check(obj)) { - int type_num = PyArray_DESCR((PyArrayObject *)obj)->type_num; - if (PyTypeNum_ISINTEGER(type_num) || - PyTypeNum_ISBOOL(type_num)) { - retval = SOBJ_ISFANCY; + used_ndim += 1; + curr_idx += 1; + } + + /* All added indices have 1 dimension */ + if (fancy_ndim < 1) { + fancy_ndim = 1; + } + continue; + } + + /* Normal case of an integer array */ + else if (PyArray_ISINTEGER(arr)) { + if (PyArray_NDIM(arr) == 0) { + /* + * A 0-d integer array is an array scalar and can + * be dealt with the HAS_SCALAR_ARRAY flag. + * We could handle 0-d arrays early on, but this makes + * sure that array-likes or odder arrays are always + * handled right. + */ + i = PyArray_PyIntAsIntp((PyObject *)arr); + Py_DECREF(arr); + if ((i == -1) && PyErr_Occurred()) { + goto failed_building_indices; } else { - retval = SOBJ_BADARRAY; - break; + index_type |= (HAS_INTEGER | HAS_SCALAR_ARRAY); + indices[curr_idx].object = NULL; + indices[curr_idx].value = i; + indices[curr_idx].type = HAS_INTEGER; + used_ndim += 1; + new_ndim += 0; + curr_idx += 1; + continue; } } - else if (PySequence_Check(obj)) { - retval = SOBJ_ISFANCY; + + index_type |= HAS_FANCY; + indices[curr_idx].type = HAS_FANCY; + indices[curr_idx].object = (PyObject *)arr; + + used_ndim += 1; + if (fancy_ndim < PyArray_NDIM(arr)) { + fancy_ndim = PyArray_NDIM(arr); } + curr_idx += 1; + continue; } - } - else if (PyArray_Check(args)) { - int type_num = PyArray_DESCR((PyArrayObject *)args)->type_num; - if (PyTypeNum_ISINTEGER(type_num) || PyTypeNum_ISBOOL(type_num)) { - return SOBJ_ISFANCY; + + /* + * The array does not have a valid type. + */ + if ((PyObject *)arr == obj) { + /* The input was an array already */ + PyErr_SetString(PyExc_IndexError, + "arrays used as indices must be of integer (or boolean) type"); } else { - return SOBJ_BADARRAY; + /* The input was not an array, so give a general error message */ + PyErr_SetString(PyExc_IndexError, + "only integers, slices (`:`), ellipsis (`...`), " + "numpy.newaxis (`None`) and integer or boolean " + "arrays are valid indices"); } + Py_DECREF(arr); + goto failed_building_indices; + } + + /* + * Compare dimension of the index to the real ndim. this is + * to find the ellipsis value or append an ellipsis if necessary. + */ + if (used_ndim < PyArray_NDIM(self)) { + if (index_type & HAS_ELLIPSIS) { + indices[ellipsis_pos].value = PyArray_NDIM(self) - used_ndim; + used_ndim = PyArray_NDIM(self); + new_ndim += indices[ellipsis_pos].value; + } + else { + /* + * There is no ellipsis yet, but it is not a full index + * so we append an ellipsis to the end. + */ + index_type |= HAS_ELLIPSIS; + indices[curr_idx].object = NULL; + indices[curr_idx].type = HAS_ELLIPSIS; + indices[curr_idx].value = PyArray_NDIM(self) - used_ndim; + ellipsis_pos = curr_idx; + + used_ndim = PyArray_NDIM(self); + new_ndim += indices[curr_idx].value; + curr_idx += 1; + } + } + else if (used_ndim > PyArray_NDIM(self)) { + PyErr_SetString(PyExc_IndexError, + "too many indices for array"); + goto failed_building_indices; } - else if (PySequence_Check(args)) { + else if (index_ndim == 0) { /* - * Sequences < NPY_MAXDIMS with any slice objects - * or newaxis, or Ellipsis is considered standard - * as long as there are also no Arrays and or additional - * sequences embedded. + * 0-d index into 0-d array, i.e. array[()] + * We consider this an integer index. Which means it will return + * the scalar. + * This makes sense, because then array[...] gives + * an array and array[()] gives the scalar. */ - retval = SOBJ_ISFANCY; - n = PySequence_Size(args); - if (n < 0 || n >= NPY_MAXDIMS) { - return SOBJ_ISFANCY; + used_ndim = 0; + index_type = HAS_INTEGER; + } + + /* HAS_SCALAR_ARRAY requires cleaning up the index_type */ + if (index_type & HAS_SCALAR_ARRAY) { + /* clear as info is unnecessary and makes life harder later */ + if (index_type & HAS_FANCY) { + index_type -= HAS_SCALAR_ARRAY; } - for (i = 0; i < n; i++) { - PyObject *obj = PySequence_GetItem(args, i); - if (obj == NULL) { - return SOBJ_ISFANCY; - } - if (PyArray_Check(obj)) { - int type_num = PyArray_DESCR((PyArrayObject *)obj)->type_num; - if (PyTypeNum_ISINTEGER(type_num) || - PyTypeNum_ISBOOL(type_num)) { - retval = SOBJ_LISTTUP; - } - else { - retval = SOBJ_BADARRAY; - } - } - else if (PySequence_Check(obj)) { - retval = SOBJ_LISTTUP; - } - else if (PySlice_Check(obj) || obj == Py_Ellipsis || - obj == Py_None) { - retval = SOBJ_NOTFANCY; - } - Py_DECREF(obj); - if (retval > SOBJ_ISFANCY) { - return retval; - } + /* A full integer index sees array scalars as part of itself */ + else if (index_type == (HAS_INTEGER | HAS_SCALAR_ARRAY)) { + index_type -= HAS_SCALAR_ARRAY; } } - return retval; + + /* + * At this point indices are all set correctly, no bounds checking + * has been made and the new array may still have more dimensions + * then is possible. + * + * Check this now so we do not have to worry about it later. + * It can happen for fancy indexing or with newaxis. + * This means broadcasting errors in the case of too many dimensions + * take less priority. + */ + if (index_type & (HAS_NEWAXIS | HAS_FANCY)) { + if (new_ndim + fancy_ndim > NPY_MAXDIMS) { + PyErr_Format(PyExc_IndexError, + "number of dimensions must be within [0, %d], " + "indexing result would have %d", + NPY_MAXDIMS, (new_ndim + fancy_ndim)); + goto failed_building_indices; + } + } + + *num = curr_idx; + *ndim = new_ndim + fancy_ndim; + *out_fancy_ndim = fancy_ndim; + + if (make_tuple) { + Py_DECREF(index); + } + + return index_type; + + failed_building_indices: + for (i=0; i < curr_idx; i++) { + Py_XDECREF(indices[i].object); + } + fail: + if (make_tuple) { + Py_DECREF(index); + } + return -1; } -/* - * Called when treating array object like a mapping -- called first from - * Python when using a[object] unless object is a standard slice object - * (not an extended one). + +/** + * Get pointer for an integer index. * - * There are two situations: + * For a purely integer index, set ptr to the memory address. + * Returns 0 on success, -1 on failure. + * The caller must ensure that the index is a full integer + * one. * - * 1 - the subscript is a standard view and a reference to the - * array can be returned + * @param Array being indexed + * @param result pointer + * @param parsed index information + * @param number of indices * - * 2 - the subscript uses Boolean masks or integer indexing and - * therefore a new array is created and returned. + * @return 0 on success -1 on failure */ +static int +get_item_pointer(PyArrayObject *self, char **ptr, + npy_index_info *indices, int index_num) { + int i; + *ptr = PyArray_BYTES(self); + for (i=0; i < index_num; i++) { + if ((check_and_adjust_index(&(indices[i].value), + PyArray_DIMS(self)[i], i, NULL)) < 0) { + return -1; + } + *ptr += PyArray_STRIDE(self, i) * indices[i].value; + } + return 0; +} -NPY_NO_EXPORT PyObject * -array_subscript_simple(PyArrayObject *self, PyObject *op, int check_index) -{ - npy_intp dimensions[NPY_MAXDIMS], strides[NPY_MAXDIMS]; - npy_intp offset; - int nd; - PyArrayObject *ret; - npy_intp value; - if (!(PyArray_Check(op) && (PyArray_SIZE((PyArrayObject*)op) > 1))) { - value = PyArray_PyIntAsIntp(op); +/** + * Get view into an array using all non-array indices. + * + * For any index, get a view of the subspace into the original + * array. If there are no fancy indices, this is the result of + * the indexing operation. + * Ensure_array allows to fetch a safe subspace view for advanced + * indexing. + * + * @param Array being indexed + * @param resulting array (new reference) + * @param parsed index information + * @param number of indices + * @param Whether result should inherit the type from self + * + * @return 0 on success -1 on failure + */ +static int +get_view_from_index(PyArrayObject *self, PyArrayObject **view, + npy_index_info *indices, int index_num, int ensure_array) { + npy_intp new_strides[NPY_MAXDIMS]; + npy_intp new_shape[NPY_MAXDIMS]; + int i, j; + int new_dim = 0; + int orig_dim = 0; + char *data_ptr = PyArray_BYTES(self); + + /* for slice parsing */ + npy_intp start, stop, step, n_steps; + + for (i=0; i < index_num; i++) { + switch (indices[i].type) { + case HAS_INTEGER: + if ((check_and_adjust_index(&indices[i].value, + PyArray_DIMS(self)[orig_dim], orig_dim, + NULL)) < 0) { + return -1; + } + data_ptr += PyArray_STRIDE(self, orig_dim) * indices[i].value; - if (value == -1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) { - /* Operand is not an integer type */ - PyErr_Clear(); - } - else { - PyErr_SetString(PyExc_IndexError, - "cannot convert index to integer"); - return NULL; - } - } - else { - return array_item_asarray(self, value); - } - } + new_dim += 0; + orig_dim += 1; + break; + case HAS_ELLIPSIS: + for (j=0; j < indices[i].value; j++) { + new_strides[new_dim] = PyArray_STRIDE(self, orig_dim); + new_shape[new_dim] = PyArray_DIMS(self)[orig_dim]; + new_dim += 1; + orig_dim += 1; + } + break; + case HAS_SLICE: + if (slice_GetIndices((PySliceObject *)indices[i].object, + PyArray_DIMS(self)[orig_dim], + &start, &stop, &step, &n_steps) < 0) { + if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_IndexError, "invalid slice"); + } + return -1; + } + if (n_steps <= 0) { + /* TODO: Always points to start then, could change that */ + n_steps = 0; + step = 1; + start = 0; + } - /* Standard (view-based) Indexing */ - nd = parse_index(self, op, dimensions, - strides, &offset, check_index); - if (nd == -1) { - return NULL; + data_ptr += PyArray_STRIDE(self, orig_dim) * start; + new_strides[new_dim] = PyArray_STRIDE(self, orig_dim) * step; + new_shape[new_dim] = n_steps; + new_dim += 1; + orig_dim += 1; + break; + case HAS_NEWAXIS: + new_strides[new_dim] = 0; + new_shape[new_dim] = 1; + new_dim += 1; + break; + /* Fancy and 0-d boolean indices are ignored here */ + case HAS_0D_BOOL: + break; + default: + new_dim += 0; + orig_dim += 1; + break; + } } - /* Create a view using the indexing result */ + /* Create the new view and set the base array */ Py_INCREF(PyArray_DESCR(self)); - ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self), + *view = (PyArrayObject *)PyArray_NewFromDescr( + ensure_array ? &PyArray_Type : Py_TYPE(self), PyArray_DESCR(self), - nd, dimensions, - strides, PyArray_BYTES(self) + offset, + new_dim, new_shape, + new_strides, data_ptr, PyArray_FLAGS(self), - (PyObject *)self); - if (ret == NULL) { - return NULL; + ensure_array ? NULL : (PyObject *)self); + if (*view == NULL) { + return -1; } + Py_INCREF(self); - if (PyArray_SetBaseObject(ret, (PyObject *)self) < 0) { - Py_DECREF(ret); - return NULL; + if (PyArray_SetBaseObject(*view, (PyObject *)self) < 0) { + Py_DECREF(*view); + return -1; } - PyArray_UpdateFlags(ret, NPY_ARRAY_UPDATE_ALL); - return (PyObject *)ret; + return 0; } + /* * Implements boolean indexing. This produces a one-dimensional * array which picks out all of the elements of 'self' for which @@ -626,36 +938,15 @@ array_boolean_subscript(PyArrayObject *self, PyArray_Descr *dtype; PyArrayObject *ret; int needs_api = 0; - npy_intp bmask_size; - - if (PyArray_DESCR(bmask)->type_num != NPY_BOOL) { - PyErr_SetString(PyExc_TypeError, - "NumPy boolean array indexing requires a boolean index"); - return NULL; - } - - if (PyArray_NDIM(bmask) != PyArray_NDIM(self)) { - PyErr_SetString(PyExc_ValueError, - "The boolean mask assignment indexing array " - "must have the same number of dimensions as " - "the array being indexed"); - return NULL; - } - size = count_boolean_trues(PyArray_NDIM(bmask), PyArray_DATA(bmask), PyArray_DIMS(bmask), PyArray_STRIDES(bmask)); - /* Correction factor for broadcasting 'bmask' to 'self' */ - bmask_size = PyArray_SIZE(bmask); - if (bmask_size > 0) { - size *= PyArray_SIZE(self) / bmask_size; - } /* Allocate the output of the boolean indexing */ dtype = PyArray_DESCR(self); Py_INCREF(dtype); - ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self), dtype, 1, &size, - NULL, NULL, 0, (PyObject *)self); + ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, 1, &size, + NULL, NULL, 0, NULL); if (ret == NULL) { return NULL; } @@ -679,6 +970,7 @@ array_boolean_subscript(PyArrayObject *self, npy_intp self_stride, bmask_stride, subloopsize; char *self_data; char *bmask_data; + NPY_BEGIN_THREADS_DEF; /* Set up the iterator */ flags = NPY_ITER_EXTERNAL_LOOP | NPY_ITER_REFS_OK; @@ -713,6 +1005,9 @@ array_boolean_subscript(PyArrayObject *self, NPY_AUXDATA_FREE(transferdata); return NULL; } + + NPY_BEGIN_THREADS_NDITER(iter); + innerstrides = NpyIter_GetInnerStrideArray(iter); dataptrs = NpyIter_GetDataPtrArray(iter); @@ -740,10 +1035,34 @@ array_boolean_subscript(PyArrayObject *self, } } while (iternext(iter)); + NPY_END_THREADS; + NpyIter_Deallocate(iter); NPY_AUXDATA_FREE(transferdata); } + if (!PyArray_CheckExact(self)) { + PyArrayObject *tmp = ret; + + Py_INCREF(dtype); + ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self), dtype, 1, + &size, PyArray_STRIDES(ret), PyArray_BYTES(ret), + 0, (PyObject *)self); + + if (ret == NULL) { + Py_DECREF(tmp); + return NULL; + } + + if (PyArray_SetBaseObject(ret, (PyObject *)tmp) < 0) { + Py_DECREF(ret); + return NULL; + } + if (_IsWriteable(ret)) { + PyArray_ENABLEFLAGS(ret, NPY_ARRAY_WRITEABLE); + } + } + return ret; } @@ -760,7 +1079,7 @@ array_boolean_subscript(PyArrayObject *self, * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int -array_ass_boolean_subscript(PyArrayObject *self, +array_assign_boolean_subscript(PyArrayObject *self, PyArrayObject *bmask, PyArrayObject *v, NPY_ORDER order) { npy_intp size, src_itemsize, v_stride; @@ -834,6 +1153,7 @@ array_ass_boolean_subscript(PyArrayObject *self, npy_intp self_stride, bmask_stride, subloopsize; char *self_data; char *bmask_data; + NPY_BEGIN_THREADS_DEF; /* Set up the iterator */ flags = NPY_ITER_EXTERNAL_LOOP | NPY_ITER_REFS_OK; @@ -852,6 +1172,9 @@ array_ass_boolean_subscript(PyArrayObject *self, NpyIter_Deallocate(iter); return -1; } + + NPY_BEGIN_THREADS_NDITER(iter); + innerstrides = NpyIter_GetInnerStrideArray(iter); dataptrs = NpyIter_GetDataPtrArray(iter); @@ -893,119 +1216,96 @@ array_ass_boolean_subscript(PyArrayObject *self, } } while (iternext(iter)); + NPY_END_THREADS; + NPY_AUXDATA_FREE(transferdata); NpyIter_Deallocate(iter); } + if (needs_api) { + /* + * FIXME?: most assignment operations stop after the first occurrence + * of an error. Boolean does not currently, but should at least + * report the error. (This is only relevant for things like str->int + * casts which call into python) + */ + if (PyErr_Occurred()) { + return -1; + } + } + return 0; } -/* Check if ind is a tuple and if it has as many elements as arr has axes. */ -static NPY_INLINE int -_is_full_index(PyObject *ind, PyArrayObject *arr) -{ - return PyTuple_Check(ind) && (PyTuple_GET_SIZE(ind) == PyArray_NDIM(arr)); -} - /* - * Returns 0 if tuple-object seq is not a tuple of integers. - * If the return value is positive, vals will be filled with the elements - * from the tuple. + * C-level integer indexing always returning an array and never a scalar. + * Works also for subclasses, but it will not be called on one from the + * Python API. + * + * This function does not accept negative indices because it is called by + * PySequence_GetItem (through array_item) and that converts them to + * positive indices. */ -static int -_tuple_of_integers(PyObject *seq, npy_intp *vals, int maxvals) +NPY_NO_EXPORT PyObject * +array_item_asarray(PyArrayObject *self, npy_intp i) { - int i; - PyObject *obj; - npy_intp temp; + npy_index_info indices[2]; + PyObject *result; - for(i=0; i<maxvals; i++) { - obj = PyTuple_GET_ITEM(seq, i); - if ((PyArray_Check(obj) && PyArray_NDIM((PyArrayObject *)obj) > 0) - || PyList_Check(obj)) { - return 0; - } - temp = PyArray_PyIntAsIntp(obj); - if (error_converting(temp)) { - PyErr_Clear(); - return 0; - } - vals[i] = temp; + if (PyArray_NDIM(self) == 0) { + PyErr_SetString(PyExc_IndexError, + "too many indices for array"); + return NULL; + } + if (i < 0) { + /* This is an error, but undo PySequence_GetItem fix for message */ + i -= PyArray_DIM(self, 0); } - return 1; -} - -/* return TRUE if ellipses are found else return FALSE */ -static npy_bool -_check_ellipses(PyObject *op) -{ - if ((op == Py_Ellipsis) || PyString_Check(op) || PyUnicode_Check(op)) { - return NPY_TRUE; - } - else if (PyBool_Check(op) || PyArray_IsScalar(op, Bool) || - (PyArray_Check(op) && - (PyArray_DIMS((PyArrayObject *)op)==0) && - PyArray_ISBOOL((PyArrayObject *)op))) { - return NPY_TRUE; - } - else if (PySequence_Check(op)) { - Py_ssize_t n, i; - PyObject *temp; - - n = PySequence_Size(op); - i = 0; - while (i < n) { - temp = PySequence_GetItem(op, i); - if (temp == Py_Ellipsis) { - Py_DECREF(temp); - return NPY_TRUE; - } - Py_DECREF(temp); - i++; - } + indices[0].value = i; + indices[0].type = HAS_INTEGER; + indices[1].value = PyArray_NDIM(self) - 1; + indices[1].type = HAS_ELLIPSIS; + if (get_view_from_index(self, (PyArrayObject **)&result, + indices, 2, 0) < 0) { + return NULL; } - return NPY_FALSE; + return result; } + +/* + * Python C-Api level item subscription (implementation for PySequence_GetItem) + * + * Negative indices are not accepted because PySequence_GetItem converts + * them to positive indices before calling this. + */ NPY_NO_EXPORT PyObject * -array_subscript_fancy(PyArrayObject *self, PyObject *op, int fancy) - { - int oned; - PyObject *other; - PyArrayMapIterObject *mit; +array_item(PyArrayObject *self, Py_ssize_t i) +{ + if (PyArray_NDIM(self) == 1) { + char *item; + npy_index_info index; - oned = ((PyArray_NDIM(self) == 1) && - !(PyTuple_Check(op) && PyTuple_GET_SIZE(op) > 1)); + if (i < 0) { + /* This is an error, but undo PySequence_GetItem fix for message */ + i -= PyArray_DIM(self, 0); + } - /* wrap arguments into a mapiter object */ - mit = (PyArrayMapIterObject *) PyArray_MapIterNew(op, oned, fancy); - if (mit == NULL) { - return NULL; - } - if (oned) { - PyArrayIterObject *it; - PyObject *rval; - it = (PyArrayIterObject *) PyArray_IterNew((PyObject *)self); - if (it == NULL) { - Py_DECREF(mit); + index.value = i; + index.type = HAS_INTEGER; + if (get_item_pointer(self, &item, &index, 1) < 0) { return NULL; } - rval = iter_subscript(it, mit->indexobj); - Py_DECREF(it); - Py_DECREF(mit); - return rval; + return PyArray_Scalar(item, PyArray_DESCR(self), (PyObject *)self); } - if (PyArray_MapIterBind(mit, self) != 0) { - Py_DECREF(mit); - return NULL; + else { + return array_item_asarray(self, i); } - other = (PyObject *)PyArray_GetMap(mit); - Py_DECREF(mit); - return other; } + /* make sure subscript always returns an array object */ NPY_NO_EXPORT PyObject * array_subscript_asarray(PyArrayObject *self, PyObject *op) @@ -1013,317 +1313,421 @@ array_subscript_asarray(PyArrayObject *self, PyObject *op) return PyArray_EnsureAnyArray(array_subscript(self, op)); } + +/* + * General function for indexing a NumPy array with a Python object. + */ NPY_NO_EXPORT PyObject * -array_subscript_fromobject(PyArrayObject *self, PyObject *op) +array_subscript(PyArrayObject *self, PyObject *op) { - int fancy; - npy_intp vals[NPY_MAXDIMS]; - - /* Integer index */ - if (PyArray_IsIntegerScalar(op) || (PyIndex_Check(op) && - !PySequence_Check(op))) { - npy_intp value = PyArray_PyIntAsIntp(op); - if (value == -1 && PyErr_Occurred()) { - /* fail on error */ - PyErr_SetString(PyExc_IndexError, - "cannot convert index to integer"); + int index_type; + int index_num; + int i, ndim, fancy_ndim, fancy; + /* + * Index info array. We can have twice as many indices as dimensions + * (because of None). The + 1 is to not need to check as much. + */ + npy_index_info indices[NPY_MAXDIMS * 2 + 1]; + + PyArrayObject *view = NULL; + PyObject *result = NULL; + + PyArrayMapIterObject * mit = NULL; + + /* Check for multiple field access */ + if (PyDataType_HASFIELDS(PyArray_DESCR(self))) { + /* Check for single field access */ + /* + * TODO: Moving this code block into the HASFIELDS, means that + * string integers temporarily work as indices. + */ + if (PyString_Check(op) || PyUnicode_Check(op)) { + PyObject *temp, *obj; + + if (PyDataType_HASFIELDS(PyArray_DESCR(self))) { + obj = PyDict_GetItem(PyArray_DESCR(self)->fields, op); + if (obj != NULL) { + PyArray_Descr *descr; + int offset; + PyObject *title; + + if (PyArg_ParseTuple(obj, "Oi|O", &descr, &offset, &title)) { + Py_INCREF(descr); + return PyArray_GetField(self, descr, offset); + } + } + } + + temp = op; + if (PyUnicode_Check(op)) { + temp = PyUnicode_AsUnicodeEscapeString(op); + } + PyErr_Format(PyExc_ValueError, + "field named %s not found", + PyBytes_AsString(temp)); + if (temp != op) { + Py_DECREF(temp); + } return NULL; } - else { - return array_item(self, (Py_ssize_t) value); - } - } - /* optimization for a tuple of integers */ - if (PyArray_NDIM(self) > 1 && _is_full_index(op, self)) { - int ret = _tuple_of_integers(op, vals, PyArray_NDIM(self)); - - if (ret > 0) { - int idim, ndim = PyArray_NDIM(self); - npy_intp *shape = PyArray_DIMS(self); - npy_intp *strides = PyArray_STRIDES(self); - char *item = PyArray_BYTES(self); - for (idim = 0; idim < ndim; idim++) { - npy_intp v = vals[idim]; - if (check_and_adjust_index(&v, shape[idim], idim) < 0) { - return NULL; + + else if (PySequence_Check(op) && !PyTuple_Check(op)) { + int seqlen, i; + PyObject *obj; + seqlen = PySequence_Size(op); + for (i = 0; i < seqlen; i++) { + obj = PySequence_GetItem(op, i); + if (!PyString_Check(obj) && !PyUnicode_Check(obj)) { + Py_DECREF(obj); + break; } - item += v * strides[idim]; + Py_DECREF(obj); + } + /* + * Extract multiple fields if all elements in sequence + * are either string or unicode (i.e. no break occurred). + */ + fancy = ((seqlen > 0) && (i == seqlen)); + if (fancy) { + PyObject *_numpy_internal; + _numpy_internal = PyImport_ImportModule("numpy.core._internal"); + if (_numpy_internal == NULL) { + return NULL; + } + obj = PyObject_CallMethod(_numpy_internal, + "_index_fields", "OO", self, op); + Py_DECREF(_numpy_internal); + if (obj == NULL) { + return NULL; + } + PyArray_ENABLEFLAGS((PyArrayObject*)obj, NPY_ARRAY_WARN_ON_WRITE); + return obj; } - return PyArray_Scalar(item, PyArray_DESCR(self), (PyObject *)self); } } - /* Check for single field access */ - if (PyString_Check(op) || PyUnicode_Check(op)) { - PyObject *temp, *obj; + /* Prepare the indices */ + index_type = prepare_index(self, op, indices, &index_num, + &ndim, &fancy_ndim, 1); - if (PyDataType_HASFIELDS(PyArray_DESCR(self))) { - obj = PyDict_GetItem(PyArray_DESCR(self)->fields, op); - if (obj != NULL) { - PyArray_Descr *descr; - int offset; - PyObject *title; + if (index_type < 0) { + return NULL; + } - if (PyArg_ParseTuple(obj, "Oi|O", &descr, &offset, &title)) { - Py_INCREF(descr); - return PyArray_GetField(self, descr, offset); - } - } + /* Full integer index */ + else if (index_type == HAS_INTEGER) { + char *item; + if (get_item_pointer(self, &item, indices, index_num) < 0) { + goto finish; } + result = (PyObject *) PyArray_Scalar(item, PyArray_DESCR(self), + (PyObject *)self); + /* Because the index is full integer, we do not need to decref */ + return result; + } - temp = op; - if (PyUnicode_Check(op)) { - temp = PyUnicode_AsUnicodeEscapeString(op); - } - PyErr_Format(PyExc_ValueError, - "field named %s not found", - PyBytes_AsString(temp)); - if (temp != op) { - Py_DECREF(temp); - } - return NULL; + /* Single boolean array */ + else if (index_type == HAS_BOOL) { + result = (PyObject *)array_boolean_subscript(self, + (PyArrayObject *)indices[0].object, + NPY_CORDER); + goto finish; } - /* Check for multiple field access */ - if (PyDataType_HASFIELDS(PyArray_DESCR(self)) && - PySequence_Check(op) && - !PyTuple_Check(op)) { - int seqlen, i; - PyObject *obj; - seqlen = PySequence_Size(op); - for (i = 0; i < seqlen; i++) { - obj = PySequence_GetItem(op, i); - if (!PyString_Check(obj) && !PyUnicode_Check(obj)) { - Py_DECREF(obj); - break; - } - Py_DECREF(obj); + /* If it is only a single ellipsis, just return a view */ + else if (index_type == HAS_ELLIPSIS) { + /* + * TODO: Should this be a view or not? The only reason not would be + * optimization (i.e. of array[...] += 1) I think. + * Before, it was just self for a single ellipsis. + */ + result = PyArray_View(self, NULL, NULL); + /* A single ellipsis, so no need to decref */ + return result; + } + + /* + * View based indexing. + * There are two cases here. First we need to create a simple view, + * second we need to create a (possibly invalid) view for the + * subspace to the fancy index. This procedure is identical. + */ + + else if (index_type & (HAS_SLICE | HAS_NEWAXIS | + HAS_ELLIPSIS | HAS_INTEGER)) { + if (get_view_from_index(self, &view, indices, index_num, + (index_type & HAS_FANCY)) < 0) { + goto finish; } + /* - * Extract multiple fields if all elements in sequence - * are either string or unicode (i.e. no break occurred). + * There is a scalar array, so we need to force a copy to simulate + * fancy indexing. */ - fancy = ((seqlen > 0) && (i == seqlen)); - if (fancy) { - PyObject *_numpy_internal; - _numpy_internal = PyImport_ImportModule("numpy.core._internal"); - if (_numpy_internal == NULL) { - return NULL; - } - obj = PyObject_CallMethod(_numpy_internal, - "_index_fields", "OO", self, op); - Py_DECREF(_numpy_internal); - if (obj == NULL) { - return NULL; - } - PyArray_ENABLEFLAGS((PyArrayObject*)obj, NPY_ARRAY_WARN_ON_WRITE); - return obj; + if (index_type & HAS_SCALAR_ARRAY) { + result = PyArray_NewCopy(view, NPY_KEEPORDER); + goto finish; } } - /* Check for Ellipsis index */ - if (op == Py_Ellipsis) { - Py_INCREF(self); - return (PyObject *)self; + /* If there is no fancy indexing, we have the result */ + if (!(index_type & HAS_FANCY)) { + result = (PyObject *)view; + Py_INCREF(result); + goto finish; } - if (PyArray_NDIM(self) == 0) { - int nd; - /* Check for None index */ - if (op == Py_None) { - return add_new_axes_0d(self, 1); - } - /* Check for (empty) tuple index */ - if (PyTuple_Check(op)) { - if (0 == PyTuple_GET_SIZE(op)) { - Py_INCREF(self); - return (PyObject *)self; - } - nd = count_new_axes_0d(op); - if (nd == -1) { - return NULL; - } - return add_new_axes_0d(self, nd); - } - /* Allow Boolean mask selection also */ - if ((PyArray_Check(op) && (PyArray_DIMS((PyArrayObject *)op)==0) - && PyArray_ISBOOL((PyArrayObject *)op))) { - if (PyObject_IsTrue(op)) { - Py_INCREF(self); - return (PyObject *)self; + /* + * Special case for very simple 1-d fancy indexing, which however + * is quite common. This saves not only a lot of setup time in the + * iterator, but also is faster (must be exactly fancy because + * we don't support 0-d booleans here) + */ + if (index_type == HAS_FANCY && index_num == 1) { + /* The array being indexed has one dimension and it is a fancy index */ + PyArrayObject *ind = (PyArrayObject*)indices[0].object; + + /* Check if the index is simple enough */ + if (PyArray_TRIVIALLY_ITERABLE(ind) && + /* Check if the type is equivalent to INTP */ + PyArray_ITEMSIZE(ind) == sizeof(npy_intp) && + PyArray_DESCR(ind)->kind == 'i' && + PyArray_ISALIGNED(ind) && + PyDataType_ISNOTSWAPPED(PyArray_DESCR(ind))) { + + Py_INCREF(PyArray_DESCR(self)); + result = PyArray_NewFromDescr(&PyArray_Type, + PyArray_DESCR(self), + PyArray_NDIM(ind), + PyArray_SHAPE(ind), + NULL, NULL, + /* Same order as indices */ + PyArray_ISFORTRAN(ind) ? + NPY_ARRAY_F_CONTIGUOUS : 0, + NULL); + if (result == NULL) { + goto finish; } - else { - npy_intp oned = 0; - Py_INCREF(PyArray_DESCR(self)); - return PyArray_NewFromDescr(Py_TYPE(self), - PyArray_DESCR(self), - 1, &oned, - NULL, NULL, - NPY_ARRAY_DEFAULT, - NULL); + + if (mapiter_trivial_get(self, ind, (PyArrayObject *)result) < 0) { + Py_DECREF(result); + result = NULL; + goto finish; } + + goto wrap_out_array; } - PyErr_SetString(PyExc_IndexError, - "0-dimensional arrays can't be indexed"); - return NULL; } - fancy = fancy_indexing_check(op); - if (fancy != SOBJ_NOTFANCY) { - return array_subscript_fancy(self, op, fancy); + /* fancy indexing has to be used. And view is the subspace. */ + mit = (PyArrayMapIterObject *)PyArray_MapIterNew(indices, index_num, + index_type, + ndim, fancy_ndim, + self, view, 0, + NPY_ITER_READONLY, + NPY_ITER_WRITEONLY, + NULL, PyArray_DESCR(self)); + if (mit == NULL) { + goto finish; } - else { - return array_subscript_simple(self, op, 1); + + if (mit->numiter > 1) { + /* + * If it is one, the inner loop checks indices, otherwise + * check indices beforehand, because it is much faster if + * broadcasting occurs and most likely no big overhead + */ + if (PyArray_MapIterCheckIndices(mit) < 0) { + goto finish; + } } -} -NPY_NO_EXPORT PyObject * -array_subscript(PyArrayObject *self, PyObject *op) -{ - int fancy; - PyObject *ret = NULL; - if (!PyArray_Check(op)) { - ret = array_subscript_fromobject(self, op); + /* Reset the outer iterator */ + if (NpyIter_Reset(mit->outer, NULL) < 0) { + goto finish; } - /* Boolean indexing special case */ - /* The SIZE check is to ensure old behaviour for non-matching arrays. */ - else if (PyArray_ISBOOL((PyArrayObject *)op) - && (PyArray_NDIM(self) == PyArray_NDIM((PyArrayObject *)op)) - && (PyArray_SIZE((PyArrayObject *)op) == PyArray_SIZE(self))) { - return (PyObject *)array_boolean_subscript(self, - (PyArrayObject *)op, NPY_CORDER); + if (mapiter_get(mit) < 0) { + goto finish; } - /* Error case when indexing 0-dim array with non-boolean. */ - else if (PyArray_NDIM(self) == 0) { - PyErr_SetString(PyExc_IndexError, - "0-dimensional arrays can't be indexed"); - return NULL; + + result = (PyObject *)mit->extra_op; + Py_INCREF(result); + + if (mit->consec) { + PyArray_MapIterSwapAxes(mit, (PyArrayObject **)&result, 1); } - else { - fancy = fancy_indexing_check(op); - if (fancy != SOBJ_NOTFANCY) { - ret = array_subscript_fancy(self, op, fancy); - } - else { - ret = array_subscript_simple(self, op, 1); + wrap_out_array: + if (!PyArray_CheckExact(self)) { + /* + * Need to create a new array as if the old one never existed. + */ + PyArrayObject *tmp_arr = (PyArrayObject *)result; + + Py_INCREF(PyArray_DESCR(tmp_arr)); + result = PyArray_NewFromDescr(Py_TYPE(self), + PyArray_DESCR(tmp_arr), + PyArray_NDIM(tmp_arr), + PyArray_SHAPE(tmp_arr), + PyArray_STRIDES(tmp_arr), + PyArray_BYTES(tmp_arr), + 0, /* TODO: Flags? */ + (PyObject *)self); + + if (result == NULL) { + Py_DECREF(tmp_arr); + goto finish; } - } - if (ret == NULL) { - return NULL; + if (PyArray_SetBaseObject((PyArrayObject *)result, + (PyObject *)tmp_arr) < 0) { + Py_DECREF(result); + result = NULL; + goto finish; + } + if (_IsWriteable(result)) { + PyArray_ENABLEFLAGS(result, NPY_ARRAY_WRITEABLE); + } } - if (PyArray_Check(ret) && PyArray_NDIM((PyArrayObject *)ret) == 0 - && !_check_ellipses(op)) { - return PyArray_Return((PyArrayObject *)ret); + finish: + Py_XDECREF(mit); + Py_XDECREF(view); + /* Clean up indices */ + for (i=0; i < index_num; i++) { + Py_XDECREF(indices[i].object); } - return ret; + return result; } + /* - * Another assignment hacked by using CopyObject. - * This only works if subscript returns a standard view. - * Again there are two cases. In the first case, PyArray_CopyObject - * can be used. In the second case, a new indexing function has to be - * used. + * Python C-Api level item assignment (implementation for PySequence_SetItem) + * + * Negative indices are not accepted because PySequence_SetItem converts + * them to positive indices before calling this. */ - -static int -array_ass_sub_simple(PyArrayObject *self, PyObject *ind, PyObject *op) +NPY_NO_EXPORT int +array_assign_item(PyArrayObject *self, Py_ssize_t i, PyObject *op) { - int ret; - PyArrayObject *tmp; - npy_intp value; + npy_index_info indices[2]; - value = PyArray_PyIntAsIntp(ind); - if (value == -1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) { - /* Operand is not an integer type */ - PyErr_Clear(); - } - else { - return -1; - } + if (op == NULL) { + PyErr_SetString(PyExc_ValueError, + "cannot delete array elements"); + return -1; } - else { - return array_ass_item_object(self, value, op); + if (PyArray_FailUnlessWriteable(self, "assignment destination") < 0) { + return -1; + } + if (PyArray_NDIM(self) == 0) { + PyErr_SetString(PyExc_IndexError, + "too many indices for array"); + return -1; } - /* Rest of standard (view-based) indexing */ - if (PyArray_CheckExact(self)) { - tmp = (PyArrayObject *)array_subscript_simple(self, ind, 1); - if (tmp == NULL) { + if (i < 0) { + /* This is an error, but undo PySequence_SetItem fix for message */ + i -= PyArray_DIM(self, 0); + } + + indices[0].value = i; + indices[0].type = HAS_INTEGER; + if (PyArray_NDIM(self) == 1) { + char *item; + if (get_item_pointer(self, &item, indices, 1) < 0) { + return -1; + } + if (PyArray_SETITEM(self, item, op) < 0) { return -1; } } else { - PyObject *tmp0; - - /* - * Note: this code path should never be reached with an index that - * produces scalars -- those are handled earlier in array_ass_sub - */ + PyArrayObject *view; - tmp0 = PyObject_GetItem((PyObject *)self, ind); - if (tmp0 == NULL) { + indices[1].value = PyArray_NDIM(self) - 1; + indices[1].type = HAS_ELLIPSIS; + if (get_view_from_index(self, &view, indices, 2, 0) < 0) { return -1; } - if (!PyArray_Check(tmp0)) { - PyErr_SetString(PyExc_RuntimeError, - "Getitem not returning array"); - Py_DECREF(tmp0); + if (PyArray_CopyObject(view, op) < 0) { + Py_DECREF(view); return -1; } - tmp = (PyArrayObject *)tmp0; + Py_DECREF(view); } - - ret = PyArray_CopyObject(tmp, op); - Py_DECREF(tmp); - return ret; + return 0; } -static int -array_ass_sub_fancy(PyArrayObject *self, PyObject *ind, PyObject *op, int fancy) + +/* + * This fallback takes the old route of `arr.flat[index] = values` + * for one dimensional `arr`. The route can sometimes fail slightly + * differently (ValueError instead of IndexError), in which case we + * warn users about the change. But since it does not actually care *at all* + * about shapes, it should only fail for out of bound indexes or + * casting errors. + */ +NPY_NO_EXPORT int +attempt_1d_fallback(PyArrayObject *self, PyObject *ind, PyObject *op) { - int oned, ret; - PyArrayMapIterObject *mit; - oned = ((PyArray_NDIM(self) == 1) && - !(PyTuple_Check(ind) && PyTuple_GET_SIZE(ind) > 1)); - mit = (PyArrayMapIterObject *) PyArray_MapIterNew(ind, oned, fancy); - if (mit == NULL) { - return -1; - } - if (oned) { - PyArrayIterObject *it; - int rval; + PyObject *err = PyErr_Occurred(); + PyArrayIterObject *self_iter = NULL; - it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self); - if (it == NULL) { - Py_DECREF(mit); - return -1; - } - rval = iter_ass_subscript(it, mit->indexobj, op); - Py_DECREF(it); - Py_DECREF(mit); - return rval; + Py_INCREF(err); + PyErr_Clear(); + + self_iter = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self); + if (self_iter == NULL) { + goto fail; } - if (PyArray_MapIterBind(mit, self) != 0) { - Py_DECREF(mit); + if (iter_ass_subscript(self_iter, ind, op) < 0) { + goto fail; + } + + Py_XDECREF((PyObject *)self_iter); + Py_DECREF(err); + + if (DEPRECATE( + "assignment will raise an error in the future, most likely " + "because your index result shape does not match the value array " + "shape. You can use `arr.flat[index] = values` to keep the old " + "behaviour.") < 0) { return -1; } - ret = PyArray_SetMap(mit, op); - Py_DECREF(mit); - return ret; + return 0; + + fail: + if (!PyErr_ExceptionMatches(err)) { + PyObject *err, *val, *tb; + PyErr_Fetch(&err, &val, &tb); + DEPRECATE_FUTUREWARNING( + "assignment exception type will change in the future"); + PyErr_Restore(err, val, tb); + } + + Py_XDECREF((PyObject *)self_iter); + Py_DECREF(err); + return -1; } +/* + * General assignment with python indexing objects. + */ static int -array_ass_sub(PyArrayObject *self, PyObject *ind, PyObject *op) +array_assign_subscript(PyArrayObject *self, PyObject *ind, PyObject *op) { - int fancy; - npy_intp vals[NPY_MAXDIMS]; + int index_type; + int index_num; + int i, ndim, fancy_ndim; + PyArray_Descr *descr = PyArray_DESCR(self); + PyArrayObject *view = NULL; + PyArrayObject *tmp_arr = NULL; + npy_index_info indices[NPY_MAXDIMS * 2 + 1]; + + PyArrayMapIterObject *mit = NULL; if (op == NULL) { PyErr_SetString(PyExc_ValueError, @@ -1334,24 +1738,9 @@ array_ass_sub(PyArrayObject *self, PyObject *ind, PyObject *op) return -1; } - /* Integer index */ - if (PyArray_IsIntegerScalar(ind) || (PyIndex_Check(ind) && - !PySequence_Check(ind))) { - npy_intp value = PyArray_PyIntAsIntp(ind); - if (value == -1 && PyErr_Occurred()) { - /* fail on error */ - PyErr_SetString(PyExc_IndexError, - "cannot convert index to integer"); - return -1; - } - else { - return array_ass_item_object(self, value, op); - } - } - /* Single field access */ - if (PyString_Check(ind) || PyUnicode_Check(ind)) { - if (PyDataType_HASFIELDS(PyArray_DESCR(self))) { + if (PyDataType_HASFIELDS(PyArray_DESCR(self))) { + if (PyString_Check(ind) || PyUnicode_Check(ind)) { PyObject *obj; obj = PyDict_GetItem(PyArray_DESCR(self)->fields, ind); @@ -1365,138 +1754,298 @@ array_ass_sub(PyArrayObject *self, PyObject *ind, PyObject *op) return PyArray_SetField(self, descr, offset, op); } } - } #if defined(NPY_PY3K) - PyErr_Format(PyExc_ValueError, + PyErr_Format(PyExc_ValueError, "field named %S not found", ind); #else - PyErr_Format(PyExc_ValueError, + PyErr_Format(PyExc_ValueError, "field named %s not found", PyString_AsString(ind)); #endif + return -1; + } + } + + + /* Prepare the indices */ + index_type = prepare_index(self, ind, indices, &index_num, + &ndim, &fancy_ndim, 1); + + if (index_type < 0) { return -1; } - /* Ellipsis index */ - if (ind == Py_Ellipsis || - (PyTuple_Check(ind) && 1 == PyTuple_GET_SIZE(ind) && - Py_Ellipsis == PyTuple_GET_ITEM(ind, 0))) { - /* - * Doing "a[...] += 1" triggers assigning an array to itself, - * so this check is needed. - */ - if ((PyObject *)self == op) { - return 0; + /* Full integer index */ + if (index_type == HAS_INTEGER) { + char *item; + if (get_item_pointer(self, &item, indices, index_num) < 0) { + return -1; } - else { - return PyArray_CopyObject(self, op); + if (PyArray_SETITEM(self, item, op) < 0) { + return -1; } + /* integers do not store objects in indices */ + return 0; } - if (PyArray_NDIM(self) == 0) { - /* - * Several different exceptions to the 0-d no-indexing rule - * - * 1) ellipses or tuple with ellipses (handled above generally) - * 2) empty tuple - * 3) Using newaxis (None) - * 4) Boolean mask indexing - */ - - /* Check for None or empty tuple */ - if (ind == Py_None || (PyTuple_Check(ind) && - (0 == PyTuple_GET_SIZE(ind) || - count_new_axes_0d(ind) > 0))) { - return PyArray_SETITEM(self, PyArray_DATA(self), op); - } - /* Check for boolean index */ - if (PyBool_Check(ind) || PyArray_IsScalar(ind, Bool) || - (PyArray_Check(ind) && - (PyArray_NDIM((PyArrayObject *)ind)==0) && - PyArray_ISBOOL((PyArrayObject *)ind))) { - if (PyObject_IsTrue(ind)) { - return PyArray_CopyObject(self, op); + /* Single boolean array */ + if (index_type == HAS_BOOL) { + if (!PyArray_Check(op)) { + Py_INCREF(PyArray_DESCR(self)); + tmp_arr = (PyArrayObject *)PyArray_FromAny(op, + PyArray_DESCR(self), 0, 0, + NPY_ARRAY_FORCECAST, NULL); + if (tmp_arr == NULL) { + goto fail; } - else { /* False: don't do anything */ - return 0; + } + else { + Py_INCREF(op); + tmp_arr = (PyArrayObject *)op; + } + + if (array_assign_boolean_subscript(self, + (PyArrayObject *)indices[0].object, + tmp_arr, NPY_CORDER) < 0) { + /* + * Deprecated case. The old boolean indexing seemed to have some + * check to allow wrong dimensional boolean arrays in all cases. + */ + if (PyArray_NDIM(tmp_arr) > 1) { + if (attempt_1d_fallback(self, indices[0].object, tmp_arr) < 0) { + goto fail; + } + goto success; } + goto fail; } - PyErr_SetString(PyExc_IndexError, - "0-dimensional arrays can't be indexed"); - return -1; + goto success; } - /* Integer-tuple index */ - if (_is_full_index(ind, self)) { - int ret = _tuple_of_integers(ind, vals, PyArray_NDIM(self)); - if (ret > 0) { - int idim, ndim = PyArray_NDIM(self); - npy_intp *shape = PyArray_DIMS(self); - npy_intp *strides = PyArray_STRIDES(self); - char *item = PyArray_BYTES(self); - for (idim = 0; idim < ndim; idim++) { - npy_intp v = vals[idim]; - if (check_and_adjust_index(&v, shape[idim], idim) < 0) { - return -1; - } - item += v * strides[idim]; - } - return PyArray_SETITEM(self, item, op); + /* + * Single ellipsis index, no need to create a new view. + * Note that here, we do *not* go through self.__getitem__ for subclasses + * (defchar array failed then, due to uninitialized values...) + */ + else if (index_type == HAS_ELLIPSIS) { + if ((PyObject *)self == op) { + /* + * CopyObject does not handle this case gracefully and + * there is nothing to do. Removing the special case + * will cause segfaults, though it is unclear what exactly + * happens. + */ + return 0; } + /* we can just use self, but incref for error handling */ + Py_INCREF((PyObject *)self); + view = self; } - /* Boolean indexing special case */ - if (PyArray_Check(ind) && - (PyArray_TYPE((PyArrayObject *)ind) == NPY_BOOL) && - (PyArray_NDIM(self) == PyArray_NDIM((PyArrayObject *)ind)) && - (PyArray_SIZE(self) == PyArray_SIZE((PyArrayObject *)ind))) { - int retcode; - PyArrayObject *op_arr; - PyArray_Descr *dtype = NULL; + /* + * WARNING: There is a huge special case here. If this is not a + * base class array, we have to get the view through its + * very own index machinery. + * Many subclasses should probably call __setitem__ + * with a base class ndarray view to avoid this. + */ + else if (!(index_type & (HAS_FANCY | HAS_SCALAR_ARRAY)) + && !PyArray_CheckExact(self)) { + view = (PyArrayObject *)PyObject_GetItem((PyObject *)self, ind); + if (view == NULL) { + goto fail; + } + if (!PyArray_Check(view)) { + PyErr_SetString(PyExc_RuntimeError, + "Getitem not returning array"); + goto fail; + } + } - if (!PyArray_Check(op)) { - dtype = PyArray_DTYPE(self); - Py_INCREF(dtype); - op_arr = (PyArrayObject *)PyArray_FromAny(op, dtype, 0, 0, 0, NULL); - if (op_arr == NULL) { - return -1; - } + /* + * View based indexing. + * There are two cases here. First we need to create a simple view, + * second we need to create a (possibly invalid) view for the + * subspace to the fancy index. This procedure is identical. + */ + else if (index_type & (HAS_SLICE | HAS_NEWAXIS | + HAS_ELLIPSIS | HAS_INTEGER)) { + if (get_view_from_index(self, &view, indices, index_num, + (index_type & HAS_FANCY)) < 0) { + goto fail; + } + } + else { + view = NULL; + } + + /* If there is no fancy indexing, we have the array to assign to */ + if (!(index_type & HAS_FANCY)) { + if (PyArray_CopyObject(view, op) < 0) { + goto fail; + } + goto success; + } + + if (!PyArray_Check(op)) { + /* + * If the array is of object converting the values to an array + * might not be legal even though normal assignment works. + * So allocate a temporary array of the right size and use the + * normal assignment to handle this case. + */ + if (PyDataType_REFCHK(descr) && PySequence_Check(op)) { + tmp_arr = NULL; } else { - op_arr = op; - Py_INCREF(op_arr); + /* There is nothing fancy possible, so just make an array */ + Py_INCREF(descr); + tmp_arr = (PyArrayObject *)PyArray_FromAny(op, descr, 0, 0, + NPY_ARRAY_FORCECAST, NULL); + if (tmp_arr == NULL) { + goto fail; + } } + } + else { + Py_INCREF(op); + tmp_arr = (PyArrayObject *)op; + } - if (PyArray_NDIM(op_arr) < 2) { - retcode = array_ass_boolean_subscript(self, - (PyArrayObject *)ind, - op_arr, NPY_CORDER); - Py_DECREF(op_arr); - return retcode; + /* + * Special case for very simple 1-d fancy indexing, which however + * is quite common. This saves not only a lot of setup time in the + * iterator, but also is faster (must be exactly fancy because + * we don't support 0-d booleans here) + */ + if (index_type == HAS_FANCY && + index_num == 1 && tmp_arr) { + /* The array being indexed has one dimension and it is a fancy index */ + PyArrayObject *ind = (PyArrayObject*)indices[0].object; + + /* Check if the type is equivalent */ + if (PyArray_EquivTypes(PyArray_DESCR(self), + PyArray_DESCR(tmp_arr)) && + /* + * Either they are equivalent, or the values must + * be a scalar + */ + (PyArray_EQUIVALENTLY_ITERABLE(ind, tmp_arr) || + (PyArray_NDIM(tmp_arr) == 0 && + PyArray_TRIVIALLY_ITERABLE(tmp_arr))) && + /* Check if the type is equivalent to INTP */ + PyArray_ITEMSIZE(ind) == sizeof(npy_intp) && + PyArray_DESCR(ind)->kind == 'i' && + PyArray_ISALIGNED(ind) && + PyDataType_ISNOTSWAPPED(PyArray_DESCR(ind))) { + + /* trivial_set checks the index for us */ + if (mapiter_trivial_set(self, ind, tmp_arr) < 0) { + goto fail; + } + goto success; } + } + + /* + * NOTE: If tmp_arr was not allocated yet, mit should + * handle the allocation. + * The NPY_ITER_READWRITE is necessary for automatic + * allocation. Readwrite would not allow broadcasting + * correctly, but such an operand always has the full + * size anyway. + */ + mit = (PyArrayMapIterObject *)PyArray_MapIterNew(indices, + index_num, index_type, + ndim, fancy_ndim, self, + view, 0, + NPY_ITER_WRITEONLY, + ((tmp_arr == NULL) ? + NPY_ITER_READWRITE : + NPY_ITER_READONLY), + tmp_arr, descr); + + if (mit == NULL) { /* - * Assigning from multi-dimensional 'op' in this case seems - * inconsistent, so falling through to old code for backwards - * compatibility. + * This is a deprecated special case to allow non-matching shapes + * for the index and value arrays. */ - Py_DECREF(op_arr); + if (index_type != HAS_FANCY || index_num != 1) { + /* This is not a "flat like" 1-d special case */ + goto fail; + } + if (attempt_1d_fallback(self, indices[0].object, op) < 0) { + goto fail; + } + goto success; + } + + if (tmp_arr == NULL) { + /* Fill extra op */ + + if (PyArray_CopyObject(mit->extra_op, op) < 0) { + /* + * This is a deprecated special case to allow non-matching shapes + * for the index and value arrays. + */ + if (index_type != HAS_FANCY || index_num != 1) { + /* This is not a "flat like" 1-d special case */ + goto fail; + } + if (attempt_1d_fallback(self, indices[0].object, op) < 0) { + goto fail; + } + goto success; + } } - fancy = fancy_indexing_check(ind); - if (fancy != SOBJ_NOTFANCY) { - return array_ass_sub_fancy(self, ind, op, fancy); + /* Can now reset the outer iterator (delayed bufalloc) */ + if (NpyIter_Reset(mit->outer, NULL) < 0) { + goto fail; } - else { - return array_ass_sub_simple(self, ind, op); + + if (PyArray_MapIterCheckIndices(mit) < 0) { + goto fail; } + + /* + * Could add a casting check, but apparently most assignments do + * not care about safe casting. + */ + + if (mapiter_set(mit) < 0) { + goto fail; + } + + Py_DECREF(mit); + goto success; + + /* Clean up temporary variables and indices */ + fail: + Py_XDECREF((PyObject *)view); + Py_XDECREF((PyObject *)tmp_arr); + Py_XDECREF((PyObject *)mit); + for (i=0; i < index_num; i++) { + Py_XDECREF(indices[i].object); + } + return -1; + + success: + Py_XDECREF((PyObject *)view); + Py_XDECREF((PyObject *)tmp_arr); + for (i=0; i < index_num; i++) { + Py_XDECREF(indices[i].object); + } + return 0; } + NPY_NO_EXPORT PyMappingMethods array_as_mapping = { (lenfunc)array_length, /*mp_length*/ (binaryfunc)array_subscript, /*mp_subscript*/ - (objobjargproc)array_ass_sub, /*mp_ass_subscript*/ + (objobjargproc)array_assign_subscript, /*mp_ass_subscript*/ }; /****************** End of Mapping Protocol ******************************/ @@ -1513,9 +2062,11 @@ NPY_NO_EXPORT PyMappingMethods array_as_mapping = { /* * This function takes a Boolean array and constructs index objects and * iterators as if nonzero(Bool) had been called + * + * Must not be called on a 0-d array. */ static int -_nonzero_indices(PyObject *myBool, PyArrayIterObject **iters) +_nonzero_indices(PyObject *myBool, PyArrayObject **arrays) { PyArray_Descr *typecode; PyArrayObject *ba = NULL, *new = NULL; @@ -1524,6 +2075,8 @@ _nonzero_indices(PyObject *myBool, PyArrayIterObject **iters) npy_bool *ptr; npy_intp coords[NPY_MAXDIMS], dims_m1[NPY_MAXDIMS]; npy_intp *dptr[NPY_MAXDIMS]; + static npy_intp one = 1; + NPY_BEGIN_THREADS_DEF; typecode=PyArray_DescrFromType(NPY_BOOL); ba = (PyArrayObject *)PyArray_FromAny(myBool, typecode, 0, 0, @@ -1533,26 +2086,17 @@ _nonzero_indices(PyObject *myBool, PyArrayIterObject **iters) } nd = PyArray_NDIM(ba); - if (nd == 0) { - PyErr_SetString(PyExc_IndexError, - "only scalars can be indexed by 0-dimensional " - "boolean arrays"); - goto fail; - } - for (j = 0; j < nd; j++) { - iters[j] = NULL; + arrays[j] = NULL; } size = PyArray_SIZE(ba); ptr = (npy_bool *)PyArray_DATA(ba); - count = 0; - /* pre-determine how many nonzero entries there are */ - for (i = 0; i < size; i++) { - if (*(ptr++)) { - count++; - } - } + /* + * pre-determine how many nonzero entries there are, + * ignore dimensionality of input as its a CARRAY + */ + count = count_boolean_trues(1, (char*)ptr, &size, &one); /* create count-sized index arrays for each dimension */ for (j = 0; j < nd; j++) { @@ -1562,26 +2106,21 @@ _nonzero_indices(PyObject *myBool, PyArrayIterObject **iters) if (new == NULL) { goto fail; } - iters[j] = (PyArrayIterObject *) - PyArray_IterNew((PyObject *)new); - Py_DECREF(new); - if (iters[j] == NULL) { - goto fail; - } - dptr[j] = (npy_intp *)PyArray_DATA(iters[j]->ao); + arrays[j] = new; + + dptr[j] = (npy_intp *)PyArray_DATA(new); coords[j] = 0; dims_m1[j] = PyArray_DIMS(ba)[j]-1; } - ptr = (npy_bool *)PyArray_DATA(ba); if (count == 0) { goto finish; } /* - * Loop through the Boolean array and copy coordinates * for non-zero entries */ + NPY_BEGIN_THREADS_THRESHOLDED(size); for (i = 0; i < size; i++) { if (*(ptr++)) { for (j = 0; j < nd; j++) { @@ -1599,6 +2138,7 @@ _nonzero_indices(PyObject *myBool, PyArrayIterObject **iters) } } } + NPY_END_THREADS; finish: Py_DECREF(ba); @@ -1606,551 +2146,1100 @@ _nonzero_indices(PyObject *myBool, PyArrayIterObject **iters) fail: for (j = 0; j < nd; j++) { - Py_XDECREF(iters[j]); + Py_XDECREF(arrays[j]); } Py_XDECREF(ba); return -1; } -/* convert an indexing object to an INTP indexing array iterator - if possible -- otherwise, it is a Slice, Ellipsis or None object - and has to be interpreted on bind to a particular - array so leave it NULL for now. -*/ -static int -_convert_obj(PyObject *obj, PyArrayIterObject **iter) -{ - PyArray_Descr *indtype; - PyObject *arr; - - if (PySlice_Check(obj) || (obj == Py_Ellipsis) || (obj == Py_None)) { - return 0; - } - else if (PyArray_Check(obj) && PyArray_ISBOOL((PyArrayObject *)obj)) { - return _nonzero_indices(obj, iter); - } - else { - indtype = PyArray_DescrFromType(NPY_INTP); - arr = PyArray_FromAny(obj, indtype, 0, 0, NPY_ARRAY_FORCECAST, NULL); - if (arr == NULL) { - return -1; - } - *iter = (PyArrayIterObject *)PyArray_IterNew(arr); - Py_DECREF(arr); - if (*iter == NULL) { - return -1; - } - } - return 1; -} /* Reset the map iterator to the beginning */ NPY_NO_EXPORT void PyArray_MapIterReset(PyArrayMapIterObject *mit) { - int i,j; npy_intp coord[NPY_MAXDIMS]; - PyArrayIterObject *it; - PyArray_CopySwapFunc *copyswap; + npy_intp indval; + char *baseptrs[2]; + int i; - mit->index = 0; + if (mit->size == 0) { + return; + } - if (mit->numiter > 0) { - copyswap = PyArray_DESCR(mit->iters[0]->ao)->f->copyswap; + NpyIter_Reset(mit->outer, NULL); + if (mit->extra_op_iter) { + NpyIter_Reset(mit->extra_op_iter, NULL); + + baseptrs[1] = mit->extra_op_ptrs[0]; } - if (mit->subspace != NULL) { - memcpy(coord, mit->bscoord, sizeof(npy_intp)*PyArray_NDIM(mit->ait->ao)); - PyArray_ITER_RESET(mit->subspace); - for (i = 0; i < mit->numiter; i++) { - it = mit->iters[i]; - PyArray_ITER_RESET(it); - j = mit->iteraxes[i]; - copyswap(coord+j,it->dataptr, !PyArray_ISNOTSWAPPED(it->ao), - it->ao); + baseptrs[0] = mit->baseoffset; + + for (i = 0; i < mit->numiter; i++) { + indval = *((npy_intp*)mit->outer_ptrs[i]); + if (indval < 0) { + indval += mit->fancy_dims[i]; } - PyArray_ITER_GOTO(mit->ait, coord); - mit->subspace->dataptr = mit->ait->dataptr; - mit->dataptr = mit->subspace->dataptr; + baseptrs[0] += indval * mit->fancy_strides[i]; + } + mit->dataptr = baseptrs[0]; + + if (mit->subspace_iter) { + NpyIter_ResetBasePointers(mit->subspace_iter, baseptrs, NULL); + mit->iter_count = *NpyIter_GetInnerLoopSizePtr(mit->subspace_iter); } else { - for (i = 0; i < mit->numiter; i++) { - it = mit->iters[i]; - if (it->size != 0) { - PyArray_ITER_RESET(it); - copyswap(coord+i,it->dataptr, !PyArray_ISNOTSWAPPED(it->ao), - it->ao); - } - else { - coord[i] = 0; - } - } - PyArray_ITER_GOTO(mit->ait, coord); - mit->dataptr = mit->ait->dataptr; + mit->iter_count = *NpyIter_GetInnerLoopSizePtr(mit->outer); } + return; } + /*NUMPY_API * This function needs to update the state of the map iterator * and point mit->dataptr to the memory-location of the next object + * + * Note that this function never handles an extra operand but provides + * compatibility for an old (exposed) API. */ NPY_NO_EXPORT void PyArray_MapIterNext(PyArrayMapIterObject *mit) { - int i, j; - npy_intp coord[NPY_MAXDIMS]; - PyArrayIterObject *it; - PyArray_CopySwapFunc *copyswap; + int i; + char *baseptr; + npy_intp indval; - mit->index += 1; - if (mit->index >= mit->size) { - return; - } + if (mit->subspace_iter) { + if (--mit->iter_count > 0) { + mit->subspace_ptrs[0] += mit->subspace_strides[0]; + mit->dataptr = mit->subspace_ptrs[0]; + return; + } + else if (mit->subspace_next(mit->subspace_iter)) { + mit->iter_count = *NpyIter_GetInnerLoopSizePtr(mit->subspace_iter); + mit->dataptr = mit->subspace_ptrs[0]; + } + else { + if (!mit->outer_next(mit->outer)) { + return; + } - if (mit->numiter > 0) { - copyswap = PyArray_DESCR(mit->iters[0]->ao)->f->copyswap; - } + baseptr = mit->baseoffset; - /* Sub-space iteration */ - if (mit->subspace != NULL) { - PyArray_ITER_NEXT(mit->subspace); - if (mit->subspace->index >= mit->subspace->size) { - /* reset coord to coordinates of beginning of the subspace */ - memcpy(coord, mit->bscoord, - sizeof(npy_intp)*PyArray_NDIM(mit->ait->ao)); - PyArray_ITER_RESET(mit->subspace); for (i = 0; i < mit->numiter; i++) { - it = mit->iters[i]; - PyArray_ITER_NEXT(it); - j = mit->iteraxes[i]; - copyswap(coord+j,it->dataptr, !PyArray_ISNOTSWAPPED(it->ao), - it->ao); + indval = *((npy_intp*)mit->outer_ptrs[i]); + if (indval < 0) { + indval += mit->fancy_dims[i]; + } + baseptr += indval * mit->fancy_strides[i]; } - PyArray_ITER_GOTO(mit->ait, coord); - mit->subspace->dataptr = mit->ait->dataptr; + NpyIter_ResetBasePointers(mit->subspace_iter, &baseptr, NULL); + mit->iter_count = *NpyIter_GetInnerLoopSizePtr(mit->subspace_iter); + + mit->dataptr = mit->subspace_ptrs[0]; } - mit->dataptr = mit->subspace->dataptr; } else { - for (i = 0; i < mit->numiter; i++) { - it = mit->iters[i]; - PyArray_ITER_NEXT(it); - copyswap(coord+i,it->dataptr, - !PyArray_ISNOTSWAPPED(it->ao), - it->ao); + if (--mit->iter_count > 0) { + baseptr = mit->baseoffset; + + for (i = 0; i < mit->numiter; i++) { + mit->outer_ptrs[i] += mit->outer_strides[i]; + + indval = *((npy_intp*)mit->outer_ptrs[i]); + if (indval < 0) { + indval += mit->fancy_dims[i]; + } + baseptr += indval * mit->fancy_strides[i]; + } + + mit->dataptr = baseptr; + return; + } + else { + if (!mit->outer_next(mit->outer)) { + return; + } + mit->iter_count = *NpyIter_GetInnerLoopSizePtr(mit->outer); + baseptr = mit->baseoffset; + + for (i = 0; i < mit->numiter; i++) { + indval = *((npy_intp*)mit->outer_ptrs[i]); + if (indval < 0) { + indval += mit->fancy_dims[i]; + } + baseptr += indval * mit->fancy_strides[i]; + } + + mit->dataptr = baseptr; } - PyArray_ITER_GOTO(mit->ait, coord); - mit->dataptr = mit->ait->dataptr; } - return; } -/* - * Bind a mapiteration to a particular array - * - * Determine if subspace iteration is necessary. If so, - * 1) Fill in mit->iteraxes - * 2) Create subspace iterator - * 3) Update nd, dimensions, and size. + +/** + * Fill information about the iterator. The MapIterObject does not + * need to have any information set for this function to work. + * (PyArray_MapIterSwapAxes requires also nd and nd_fancy info) * - * Subspace iteration is necessary if: PyArray_NDIM(arr) > mit->numiter + * Sets the following information: + * * mit->consec: The axis where the fancy indices need transposing to. + * * mit->iteraxes: The axis which the fancy index corresponds to. + * * mit-> fancy_dims: the dimension of `arr` along the indexed dimension + * for each fancy index. + * * mit->fancy_strides: the strides for the dimension being indexed + * by each fancy index. + * * mit->dimensions: Broadcast dimension of the fancy indices and + * the subspace iteration dimension. * - * Need to check for index-errors somewhere. + * @param MapIterObject + * @param The parsed indices object + * @param Number of indices + * @param The array that is being iterated * - * Let's do it at bind time and also convert all <0 values to >0 here - * as well. + * @return 0 on success -1 on failure */ -NPY_NO_EXPORT int -PyArray_MapIterBind(PyArrayMapIterObject *mit, PyArrayObject *arr) +static int +mapiter_fill_info(PyArrayMapIterObject *mit, npy_index_info *indices, + int index_num, PyArrayObject *arr) { - int subnd; - PyObject *sub, *obj = NULL; - int i, j, n, curraxis, ellipexp, noellip, newaxes; - PyArrayIterObject *it; - npy_intp dimsize; - npy_intp *indptr; - - subnd = PyArray_NDIM(arr) - mit->numiter; - if (subnd < 0) { - PyErr_SetString(PyExc_IndexError, - "too many indices for array"); - return -1; + int j = 0, i; + int curr_dim = 0; + /* dimension of index result (up to first fancy index) */ + int result_dim = 0; + /* -1 init; 0 found fancy; 1 fancy stopped; 2 found not consecutive fancy */ + int consec_status = -1; + int axis, broadcast_axis; + npy_intp dimension; + PyObject *errmsg, *tmp; + + for (i = 0; i < mit->nd_fancy; i++) { + mit->dimensions[i] = 1; + } + + mit->consec = 0; + for (i = 0; i < index_num; i++) { + /* integer and fancy indexes are transposed together */ + if (indices[i].type & (HAS_FANCY | HAS_INTEGER)) { + /* there was no previous fancy index, so set consec */ + if (consec_status == -1) { + mit->consec = result_dim; + consec_status = 0; + } + /* there was already a non-fancy index after a fancy one */ + else if (consec_status == 1) { + consec_status = 2; + mit->consec = 0; + } + } + else { + /* consec_status == 0 means there was a fancy index before */ + if (consec_status == 0) { + consec_status = 1; + } + } + + /* (iterating) fancy index, store the iterator */ + if (indices[i].type == HAS_FANCY) { + mit->fancy_strides[j] = PyArray_STRIDE(arr, curr_dim); + mit->fancy_dims[j] = PyArray_DIM(arr, curr_dim); + mit->iteraxes[j++] = curr_dim++; + + /* Check broadcasting */ + broadcast_axis = mit->nd_fancy; + /* Fill from back, we know how many dims there are */ + for (axis = PyArray_NDIM((PyArrayObject *)indices[i].object) - 1; + axis >= 0; axis--) { + broadcast_axis--; + dimension = PyArray_DIM((PyArrayObject *)indices[i].object, axis); + + /* If it is 1, we can broadcast */ + if (dimension != 1) { + if (dimension != mit->dimensions[broadcast_axis]) { + if (mit->dimensions[broadcast_axis] != 1) { + goto broadcast_error; + } + mit->dimensions[broadcast_axis] = dimension; + } + } + } + } + else if (indices[i].type == HAS_0D_BOOL) { + mit->fancy_strides[j] = 0; + mit->fancy_dims[j] = 1; + /* Does not exist */ + mit->iteraxes[j++] = -1; + } + + /* advance curr_dim for non-fancy indices */ + else if (indices[i].type == HAS_ELLIPSIS) { + curr_dim += indices[i].value; + result_dim += indices[i].value; + } + else if (indices[i].type != HAS_NEWAXIS){ + curr_dim += 1; + result_dim += 1; + } + else { + result_dim += 1; + } } - mit->ait = (PyArrayIterObject *)PyArray_IterNew((PyObject *)arr); - if (mit->ait == NULL) { - return -1; + /* Fill dimension of subspace */ + if (mit->subspace) { + for (i = 0; i < PyArray_NDIM(mit->subspace); i++) { + mit->dimensions[mit->nd_fancy + i] = PyArray_DIM(mit->subspace, i); + } } + return 0; + + broadcast_error: /* - * all indexing arrays have been converted to 0 - * therefore we can extract the subspace with a simple - * getitem call which will use view semantics, but - * without index checking since all original normal - * indexes are checked later as fancy ones. - * - * But, be sure to do it with a true array. + * Attempt to set a meaningful exception. Could also find out + * if a boolean index was converted. */ - if (PyArray_CheckExact(arr)) { - sub = array_subscript_simple(arr, mit->indexobj, 0); + errmsg = PyUString_FromString("shape mismatch: indexing arrays could not " + "be broadcast together with shapes "); + if (errmsg == NULL) { + return -1; } - else { - Py_INCREF(arr); - obj = PyArray_EnsureArray((PyObject *)arr); - if (obj == NULL) { + + for (i = 0; i < index_num; i++) { + if (indices[i].type != HAS_FANCY) { + continue; + } + tmp = convert_shape_to_string( + PyArray_NDIM((PyArrayObject *)indices[i].object), + PyArray_SHAPE((PyArrayObject *)indices[i].object), + " "); + if (tmp == NULL) { + return -1; + } + PyUString_ConcatAndDel(&errmsg, tmp); + if (errmsg == NULL) { return -1; } - sub = array_subscript_simple((PyArrayObject *)obj, mit->indexobj, 0); - Py_DECREF(obj); } - if (sub == NULL) { - return -1; + PyErr_SetObject(PyExc_IndexError, errmsg); + Py_DECREF(errmsg); + return -1; +} + + +/* + * Check whether the fancy indices are out of bounds. + * Returns 0 on success and -1 on failure. + * (Gets operands from the outer iterator, but iterates them independently) + */ +NPY_NO_EXPORT int +PyArray_MapIterCheckIndices(PyArrayMapIterObject *mit) +{ + PyArrayObject *op; + NpyIter *op_iter; + NpyIter_IterNextFunc *op_iternext; + npy_intp outer_dim, indval; + int outer_axis; + npy_intp itersize, iterstride; + char **iterptr; + PyArray_Descr *intp_type; + int i; + NPY_BEGIN_THREADS_DEF; + + if (mit->size == 0) { + /* All indices got broadcast away, do *not* check as it always was */ + return 0; } - subnd = PyArray_NDIM(sub); - /* no subspace iteration needed. Finish up and Return */ - if (subnd == 0) { - n = PyArray_NDIM(arr); - for (i = 0; i < n; i++) { - mit->iteraxes[i] = i; + intp_type = PyArray_DescrFromType(NPY_INTP); + + NPY_BEGIN_THREADS; + + for (i=0; i < mit->numiter; i++) { + op = NpyIter_GetOperandArray(mit->outer)[i]; + + outer_dim = mit->fancy_dims[i]; + outer_axis = mit->iteraxes[i]; + + /* See if it is possible to just trivially iterate the array */ + if (PyArray_TRIVIALLY_ITERABLE(op) && + /* Check if the type is equivalent to INTP */ + PyArray_ITEMSIZE(op) == sizeof(npy_intp) && + PyArray_DESCR(op)->kind == 'i' && + PyArray_ISALIGNED(op) && + PyDataType_ISNOTSWAPPED(PyArray_DESCR(op))) { + char *data; + npy_intp stride; + /* release GIL if it was taken by nditer below */ + if (_save == NULL) { + NPY_BEGIN_THREADS; + } + + PyArray_PREPARE_TRIVIAL_ITERATION(op, itersize, data, stride); + + while (itersize--) { + indval = *((npy_intp*)data); + if (check_and_adjust_index(&indval, + outer_dim, outer_axis, _save) < 0) { + return -1; + } + data += stride; + } + /* GIL retake at end of function or if nditer path required */ + continue; } - Py_DECREF(sub); - goto finish; + + /* Use NpyIter if the trivial iteration is not possible */ + NPY_END_THREADS; + op_iter = NpyIter_New(op, + NPY_ITER_BUFFERED | NPY_ITER_NBO | NPY_ITER_ALIGNED | + NPY_ITER_EXTERNAL_LOOP | NPY_ITER_GROWINNER | + NPY_ITER_READONLY, + NPY_KEEPORDER, NPY_SAME_KIND_CASTING, intp_type); + + if (op_iter == NULL) { + Py_DECREF(intp_type); + return -1; + } + + op_iternext = NpyIter_GetIterNext(op_iter, NULL); + if (op_iternext == NULL) { + Py_DECREF(intp_type); + NpyIter_Deallocate(op_iter); + return -1; + } + + NPY_BEGIN_THREADS_NDITER(op_iter); + iterptr = NpyIter_GetDataPtrArray(op_iter); + iterstride = NpyIter_GetInnerStrideArray(op_iter)[0]; + do { + itersize = *NpyIter_GetInnerLoopSizePtr(op_iter); + while (itersize--) { + indval = *((npy_intp*)*iterptr); + if (check_and_adjust_index(&indval, + outer_dim, outer_axis, _save) < 0) { + Py_DECREF(intp_type); + NpyIter_Deallocate(op_iter); + return -1; + } + *iterptr += iterstride; + } + } while (op_iternext(op_iter)); + + NPY_END_THREADS; + NpyIter_Deallocate(op_iter); } - mit->subspace = (PyArrayIterObject *)PyArray_IterNew(sub); - Py_DECREF(sub); - if (mit->subspace == NULL) { - return -1; + NPY_END_THREADS; + Py_DECREF(intp_type); + return 0; +} + + +/* + * Create new mapiter. + * + * NOTE: The outer iteration (and subspace if requested buffered) is + * created with DELAY_BUFALLOC. It must be reset before usage! + * + * @param Index information filled by prepare_index. + * @param Number of indices (gotten through prepare_index). + * @param Kind of index (gotten through preprare_index). + * @param NpyIter flags for an extra array. If 0 assume that there is no + * extra operand. NPY_ITER_ALLOCATE can make sense here. + * @param Array being indexed + * @param subspace (result of getting view for the indices) + * @param Subspace iterator flags can be used to enable buffering. + * NOTE: When no subspace is necessary, the extra operand will + * always be buffered! Buffering the subspace when not + * necessary is very slow when the subspace is small. + * @param Subspace operand flags (should just be 0 normally) + * @param Operand iteration flags for the extra operand, this must not be + * 0 if an extra operand should be used, otherwise it must be 0. + * Should be at least READONLY, WRITEONLY or READWRITE. + * @param Extra operand. For getmap, this would be the result, for setmap + * this would be the arrays to get from. Can be NULL, and will be + * allocated in that case. + * The operand has no effect on the shape. + * @param Dtype for the extra operand, borrows the reference and must not + * be NULL (if extra_op_flags is not 0). + * + * @return A new MapIter (PyObject *) or NULL. + */ +NPY_NO_EXPORT PyObject * +PyArray_MapIterNew(npy_index_info *indices , int index_num, int index_type, + int ndim, int fancy_ndim, + PyArrayObject *arr, PyArrayObject *subspace, + npy_uint32 subspace_iter_flags, npy_uint32 subspace_flags, + npy_uint32 extra_op_flags, PyArrayObject *extra_op, + PyArray_Descr *extra_op_dtype) +{ + PyObject *errmsg, *tmp; + /* For shape reporting on error */ + PyArrayObject *original_extra_op = extra_op; + + PyArrayObject *index_arrays[NPY_MAXDIMS]; + PyArray_Descr *dtypes[NPY_MAXDIMS]; + + npy_uint32 op_flags[NPY_MAXDIMS]; + npy_uint32 outer_flags; + + PyArrayMapIterObject *mit; + + int single_op_axis[NPY_MAXDIMS]; + int *op_axes[NPY_MAXDIMS] = {NULL}; + int i, j, dummy_array = 0; + int nops; + int uses_subspace; + + /* create new MapIter object */ + mit = (PyArrayMapIterObject *)PyArray_malloc(sizeof(PyArrayMapIterObject)); + if (mit == NULL) { + return NULL; } + /* set all attributes of mapiter to zero */ + memset(mit, 0, sizeof(PyArrayMapIterObject)); + PyObject_Init((PyObject *)mit, &PyArrayMapIter_Type); - if (mit->nd + subnd > NPY_MAXDIMS) { - PyErr_Format(PyExc_ValueError, - "number of dimensions must be within [0, %d], " - "indexed array has %d", - NPY_MAXDIMS, mit->nd + subnd); - return -1; + Py_INCREF(arr); + mit->array = arr; + Py_XINCREF(subspace); + mit->subspace = subspace; + + /* + * The subspace, the part of the array which is not indexed by + * arrays, needs to be iterated when the size of the subspace + * is larger than 1. If it is one, it has only an effect on the + * result shape. (Optimizes for example np.newaxis usage) + */ + if ((subspace == NULL) || PyArray_SIZE(subspace) == 1) { + uses_subspace = 0; + } + else { + uses_subspace = 1; } - /* Expand dimensions of result */ - for (i = 0; i < subnd; i++) { - mit->dimensions[mit->nd+i] = PyArray_DIMS(mit->subspace->ao)[i]; + /* Fill basic information about the mapiter */ + mit->nd = ndim; + mit->nd_fancy = fancy_ndim; + if (mapiter_fill_info(mit, indices, index_num, arr) < 0) { + Py_DECREF(mit); + return NULL; } - mit->nd += subnd; /* - * Now, we still need to interpret the ellipsis, slice and None - * objects to determine which axes the indexing arrays are - * referring to + * Set iteration information of the indexing arrays. */ - n = PyTuple_GET_SIZE(mit->indexobj); - /* The number of dimensions an ellipsis takes up */ - newaxes = subnd - (PyArray_NDIM(arr) - mit->numiter); - ellipexp = PyArray_NDIM(arr) + newaxes - n + 1; + for (i=0; i < index_num; i++) { + if (indices[i].type & HAS_FANCY) { + index_arrays[mit->numiter] = (PyArrayObject *)indices[i].object; + dtypes[mit->numiter] = PyArray_DescrFromType(NPY_INTP); + + op_flags[mit->numiter] = (NPY_ITER_NBO | + NPY_ITER_ALIGNED | + NPY_ITER_READONLY); + mit->numiter += 1; + } + } + + if (mit->numiter == 0) { + /* + * For MapIterArray, it is possible that there is no fancy index. + * to support this case, add a a dummy iterator. + * Since it is 0-d its transpose, etc. does not matter. + */ + + /* signal necessity to decref... */ + dummy_array = 1; + + index_arrays[0] = (PyArrayObject *)PyArray_Zeros(0, NULL, + PyArray_DescrFromType(NPY_INTP), 0); + if (index_arrays[0] == NULL) { + Py_DECREF(mit); + return NULL; + } + dtypes[0] = PyArray_DescrFromType(NPY_INTP); + op_flags[0] = NPY_ITER_NBO | NPY_ITER_ALIGNED | NPY_ITER_READONLY; + + mit->fancy_dims[0] = 1; + mit->numiter = 1; + } + /* - * Now fill in iteraxes -- remember indexing arrays have been - * converted to 0's in mit->indexobj + * Now there are two general cases how extra_op is used: + * 1. No subspace iteration is necessary, so the extra_op can + * be included into the index iterator (it will be buffered) + * 2. Subspace iteration is necessary, so the extra op is iterated + * independently, and the iteration order is fixed at C (could + * also use Fortran order if the array is Fortran order). + * In this case the subspace iterator is not buffered. + * + * If subspace iteration is necessary and an extra_op was given, + * it may also be necessary to transpose the extra_op (or signal + * the transposing to the advanced iterator). */ - curraxis = 0; - j = 0; - /* Only expand the first ellipsis */ - noellip = 1; - /* count newaxes before iter axes */ - newaxes = 0; - memset(mit->bscoord, 0, sizeof(npy_intp)*PyArray_NDIM(arr)); - for (i = 0; i < n; i++) { + + if (extra_op != NULL) { /* - * We need to fill in the starting coordinates for - * the subspace + * If we have an extra_op given, need to prepare it. + * 1. Subclasses might mess with the shape, so need a baseclass + * 2. Need to make sure the shape is compatible + * 3. May need to remove leading 1s and transpose dimensions. + * Normal assignments allows broadcasting away leading 1s, but + * the transposing code does not like this. */ - obj = PyTuple_GET_ITEM(mit->indexobj, i); - if (PyInt_Check(obj) || PyLong_Check(obj)) { - mit->iteraxes[j++] = curraxis++; - } - else if (noellip && obj == Py_Ellipsis) { - curraxis += ellipexp; - noellip = 0; - } - else if (obj == Py_None) { - if (j == 0) { - newaxes += 1; + if (!PyArray_CheckExact(extra_op)) { + extra_op = (PyArrayObject *)PyArray_View(extra_op, NULL, + &PyArray_Type); + if (extra_op == NULL) { + goto fail; } } else { - npy_intp start = 0; - npy_intp stop, step; - /* Should be slice object or another Ellipsis */ - if (obj == Py_Ellipsis) { - mit->bscoord[curraxis] = 0; + Py_INCREF(extra_op); + } + + if (PyArray_NDIM(extra_op) > mit->nd) { + /* + * Usual assignments allows removal of leading one dimensions. + * (or equivalently adding of one dimensions to the array being + * assigned to). To implement this, reshape the array. + */ + PyArrayObject *tmp_arr; + PyArray_Dims permute; + + permute.len = mit->nd; + permute.ptr = &PyArray_DIMS(extra_op)[ + PyArray_NDIM(extra_op) - mit->nd]; + tmp_arr = (PyArrayObject*)PyArray_Newshape(extra_op, &permute, + NPY_CORDER); + if (tmp_arr == NULL) { + goto broadcast_error; } - else if (!PySlice_Check(obj) || - (slice_GetIndices((PySliceObject *)obj, - PyArray_DIMS(arr)[curraxis], - &start, &stop, &step, - &dimsize) < 0)) { - PyErr_Format(PyExc_ValueError, - "unexpected object " \ - "(%s) in selection position %d", - Py_TYPE(obj)->tp_name, i); - return -1; + Py_DECREF(extra_op); + extra_op = tmp_arr; + } + + /* + * If dimensions need to be prepended (and no swapaxis is needed), + * use op_axes after extra_op is allocated for sure. + */ + if (mit->consec) { + PyArray_MapIterSwapAxes(mit, &extra_op, 0); + if (extra_op == NULL) { + goto fail; + } + } + + if (subspace && !uses_subspace) { + /* + * We are not using the subspace, so its size is 1. + * All dimensions of the extra_op corresponding to the + * subspace must be equal to 1. + */ + if (PyArray_NDIM(subspace) <= PyArray_NDIM(extra_op)) { + j = PyArray_NDIM(subspace); } else { - mit->bscoord[curraxis] = start; + j = PyArray_NDIM(extra_op); + } + for (i = 1; i < j + 1; i++) { + if (PyArray_DIM(extra_op, PyArray_NDIM(extra_op) - i) != 1) { + goto broadcast_error; + } } - curraxis += 1; } } - if (mit->consec) { - mit->consec = mit->iteraxes[0] + newaxes; - } - finish: - /* Here check the indexes (now that we have iteraxes) */ - mit->size = PyArray_OverflowMultiplyList(mit->dimensions, mit->nd); - if (mit->size < 0) { - PyErr_SetString(PyExc_ValueError, - "dimensions too large in fancy indexing"); - return -1; - } - if (mit->ait->size == 0 && mit->size != 0) { - PyErr_SetString(PyExc_IndexError, - "invalid index into a 0-size array"); - return -1; - } + /* + * If subspace is not NULL, NpyIter cannot allocate extra_op for us. + * This is a bit of a kludge. A dummy iterator is created to find + * the correct output shape and stride permutation. + * TODO: This can at least partially be replaced, since the shape + * is found for broadcasting errors. + */ + else if (extra_op_flags && (subspace != NULL)) { + npy_uint32 tmp_op_flags[NPY_MAXDIMS]; + + NpyIter *tmp_iter; + npy_intp stride; + npy_intp strides[NPY_MAXDIMS]; + npy_stride_sort_item strideperm[NPY_MAXDIMS]; + + for (i=0; i < mit->numiter; i++) { + tmp_op_flags[i] = NPY_ITER_READONLY; + } + + Py_INCREF(extra_op_dtype); + mit->extra_op_dtype = extra_op_dtype; + + /* Create an iterator, just to broadcast the arrays?! */ + tmp_iter = NpyIter_MultiNew(mit->numiter, index_arrays, + NPY_ITER_ZEROSIZE_OK | + NPY_ITER_REFS_OK | + NPY_ITER_MULTI_INDEX | + NPY_ITER_DONT_NEGATE_STRIDES, + NPY_KEEPORDER, + NPY_UNSAFE_CASTING, + tmp_op_flags, NULL); + if (tmp_iter == NULL) { + goto fail; + } - for (i = 0; i < mit->numiter; i++) { - npy_intp indval; - it = mit->iters[i]; - PyArray_ITER_RESET(it); - dimsize = PyArray_DIMS(arr)[mit->iteraxes[i]]; - while (it->index < it->size) { - indptr = ((npy_intp *)it->dataptr); - indval = *indptr; - if (check_and_adjust_index(&indval, dimsize, mit->iteraxes[i]) < 0) { - return -1; + if (PyArray_SIZE(subspace) == 1) { + /* + * nditer allows itemsize with npy_intp type, so it works + * here, but it would *not* work directly, since elsize + * is limited to int. + */ + if (!NpyIter_CreateCompatibleStrides(tmp_iter, + extra_op_dtype->elsize * PyArray_SIZE(subspace), + strides)) { + PyErr_SetString(PyExc_ValueError, + "internal error: failed to find output array strides"); + goto fail; } - PyArray_ITER_NEXT(it); } - PyArray_ITER_RESET(it); - } - return 0; -} - + else { + /* Just use C-order strides (TODO: allow also F-order) */ + stride = extra_op_dtype->elsize * PyArray_SIZE(subspace); + for (i=mit->nd_fancy - 1; i >= 0; i--) { + strides[i] = stride; + stride *= mit->dimensions[i]; + } + } + NpyIter_Deallocate(tmp_iter); -NPY_NO_EXPORT PyObject * -PyArray_MapIterNew(PyObject *indexobj, int oned, int fancy) -{ - PyArrayMapIterObject *mit; - PyArray_Descr *indtype; - PyArrayObject *arr = NULL; - int i, n, started, nonindex; + /* shape is set, and strides is set up to mit->nd, set rest */ + PyArray_CreateSortedStridePerm(PyArray_NDIM(subspace), + PyArray_STRIDES(subspace), strideperm); + stride = extra_op_dtype->elsize; + for (i=PyArray_NDIM(subspace) - 1; i >= 0; i--) { + strides[mit->nd_fancy + strideperm[i].perm] = stride; + stride *= PyArray_DIM(subspace, strideperm[i].perm); + } - if (fancy == SOBJ_BADARRAY) { - PyErr_SetString(PyExc_IndexError, - "arrays used as indices must be of " - "integer (or boolean) type"); - return NULL; + /* + * Allocate new array. Note: Always base class, because + * subclasses might mess with the shape. + */ + Py_INCREF(extra_op_dtype); + extra_op = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, + extra_op_dtype, + mit->nd_fancy + PyArray_NDIM(subspace), + mit->dimensions, strides, + NULL, 0, NULL); + if (extra_op == NULL) { + goto fail; + } } - if (fancy == SOBJ_TOOMANY) { - PyErr_SetString(PyExc_IndexError, "too many indices"); - return NULL; + + /* + * The extra op is now either allocated, can be allocated by + * NpyIter (no subspace) or is not used at all. + * + * Need to set the axis remapping for the extra_op. This needs + * to cause ignoring of subspace dimensions and prepending -1 + * for broadcasting. + */ + if (extra_op) { + for (j=0; j < mit->nd - PyArray_NDIM(extra_op); j++) { + single_op_axis[j] = -1; + } + for (i=0; i < PyArray_NDIM(extra_op); i++) { + /* (fills subspace dimensions too, but they are not unused) */ + single_op_axis[j++] = i; + } } - mit = (PyArrayMapIterObject *)PyArray_malloc(sizeof(PyArrayMapIterObject)); - if (mit == NULL) { - return NULL; + /* + * NOTE: If for some reason someone wishes to use REDUCE_OK, be + * careful and fix the error message replacement at the end. + */ + outer_flags = NPY_ITER_ZEROSIZE_OK | + NPY_ITER_REFS_OK | + NPY_ITER_BUFFERED | + NPY_ITER_DELAY_BUFALLOC | + NPY_ITER_GROWINNER; + + /* + * For a single 1-d operand, guarantee iteration order + * (scipy used this). Note that subspace may be used. + */ + if ((mit->numiter == 1) && (PyArray_NDIM(index_arrays[0]) == 1)) { + outer_flags |= NPY_ITER_DONT_NEGATE_STRIDES; } - /* set all attributes of mapiter to zero */ - memset(mit, 0, sizeof(PyArrayMapIterObject)); - PyObject_Init((PyObject *)mit, &PyArrayMapIter_Type); - /* initialize mapiter attributes */ - mit->consec = 1; - if (fancy == SOBJ_LISTTUP) { - PyObject *newobj; - newobj = PySequence_Tuple(indexobj); - if (newobj == NULL) { + /* If external array is iterated, and no subspace is needed */ + nops = mit->numiter; + if (extra_op_flags && !uses_subspace) { + /* + * NOTE: This small limitation should practically not matter. + * (replaces npyiter error) + */ + if (mit->numiter > NPY_MAXDIMS - 1) { + PyErr_Format(PyExc_IndexError, + "when no subspace is given, the number of index " + "arrays cannot be above %d, but %d index arrays found", + NPY_MAXDIMS - 1, mit->numiter); goto fail; } - indexobj = newobj; - mit->indexobj = indexobj; + + nops += 1; + index_arrays[mit->numiter] = extra_op; + + Py_INCREF(extra_op_dtype); + dtypes[mit->numiter] = extra_op_dtype; + op_flags[mit->numiter] = (extra_op_flags | + NPY_ITER_ALLOCATE | + NPY_ITER_NO_SUBTYPE); + + if (extra_op) { + /* Use the axis remapping */ + op_axes[mit->numiter] = single_op_axis; + mit->outer = NpyIter_AdvancedNew(nops, index_arrays, outer_flags, + NPY_KEEPORDER, NPY_UNSAFE_CASTING, op_flags, dtypes, + mit->nd_fancy, op_axes, mit->dimensions, 0); + } + else { + mit->outer = NpyIter_MultiNew(nops, index_arrays, outer_flags, + NPY_KEEPORDER, NPY_UNSAFE_CASTING, op_flags, dtypes); + } + } else { - Py_INCREF(indexobj); - mit->indexobj = indexobj; + /* TODO: Maybe add test for the CORDER, and maybe also allow F */ + mit->outer = NpyIter_MultiNew(nops, index_arrays, outer_flags, + NPY_CORDER, NPY_UNSAFE_CASTING, op_flags, dtypes); } - - if (oned) { - return (PyObject *)mit; + /* NpyIter cleanup and information: */ + for (i=0; i < nops; i++) { + Py_DECREF(dtypes[i]); + } + if (dummy_array) { + Py_DECREF(index_arrays[0]); + } + if (mit->outer == NULL) { + goto fail; + } + if (!uses_subspace) { + NpyIter_EnableExternalLoop(mit->outer); } - /* - * Must have some kind of fancy indexing if we are here - * indexobj is either a list, an arrayobject, or a tuple - * (with at least 1 list or arrayobject or Bool object) - */ - /* convert all inputs to iterators */ - if (PyArray_Check(indexobj) && PyArray_ISBOOL(indexobj) - && !PyArray_IsZeroDim(indexobj)) { - mit->numiter = _nonzero_indices(indexobj, mit->iters); - if (mit->numiter < 0) { + mit->outer_next = NpyIter_GetIterNext(mit->outer, NULL); + if (mit->outer_next == NULL) { + goto fail; + } + mit->outer_ptrs = NpyIter_GetDataPtrArray(mit->outer); + if (!uses_subspace) { + mit->outer_strides = NpyIter_GetInnerStrideArray(mit->outer); + } + if (NpyIter_IterationNeedsAPI(mit->outer)) { + mit->needs_api = 1; + /* We may be doing a cast for the buffer, and that may have failed */ + if (PyErr_Occurred()) { goto fail; } - mit->nd = 1; - mit->dimensions[0] = mit->iters[0]->dims_m1[0]+1; - Py_DECREF(mit->indexobj); - mit->indexobj = PyTuple_New(mit->numiter); - if (mit->indexobj == NULL) { - goto fail; + } + + /* Get the allocated extra_op */ + if (extra_op_flags) { + if (extra_op == NULL) { + mit->extra_op = NpyIter_GetOperandArray(mit->outer)[mit->numiter]; } - for (i = 0; i < mit->numiter; i++) { - PyTuple_SET_ITEM(mit->indexobj, i, PyInt_FromLong(0)); + else { + mit->extra_op = extra_op; } + Py_INCREF(mit->extra_op); } - else if (PyArray_Check(indexobj) || !PyTuple_Check(indexobj)) { - mit->numiter = 1; - indtype = PyArray_DescrFromType(NPY_INTP); - arr = (PyArrayObject *)PyArray_FromAny(indexobj, indtype, 0, 0, - NPY_ARRAY_FORCECAST, NULL); - if (arr == NULL) { + + /* + * If extra_op is being tracked but subspace is used, we need + * to create a dedicated iterator for the outer iteration of + * the extra operand. + */ + if (extra_op_flags && uses_subspace) { + op_axes[0] = single_op_axis; + mit->extra_op_iter = NpyIter_AdvancedNew(1, &extra_op, + NPY_ITER_ZEROSIZE_OK | + NPY_ITER_REFS_OK | + NPY_ITER_GROWINNER, + NPY_CORDER, + NPY_NO_CASTING, + &extra_op_flags, + NULL, + mit->nd_fancy, op_axes, + mit->dimensions, 0); + + if (mit->extra_op_iter == NULL) { goto fail; } - mit->iters[0] = (PyArrayIterObject *)PyArray_IterNew((PyObject *)arr); - if (mit->iters[0] == NULL) { - Py_DECREF(arr); + + mit->extra_op_next = NpyIter_GetIterNext(mit->extra_op_iter, NULL); + if (mit->extra_op_next == NULL) { goto fail; } - mit->nd = PyArray_NDIM(arr); - memcpy(mit->dimensions, PyArray_DIMS(arr), mit->nd*sizeof(npy_intp)); - mit->size = PyArray_SIZE(arr); - Py_DECREF(arr); - Py_DECREF(mit->indexobj); - mit->indexobj = Py_BuildValue("(N)", PyInt_FromLong(0)); + mit->extra_op_ptrs = NpyIter_GetDataPtrArray(mit->extra_op_iter); + } + + /* Get the full dimension information */ + if (subspace != NULL) { + mit->baseoffset = PyArray_BYTES(subspace); } else { - /* must be a tuple */ - PyObject *obj; - PyArrayIterObject **iterp; - PyObject *new; - int numiters, j, n2; + mit->baseoffset = PyArray_BYTES(arr); + } + + /* Calculate total size of the MapIter */ + mit->size = PyArray_OverflowMultiplyList(mit->dimensions, mit->nd); + if (mit->size < 0) { + PyErr_SetString(PyExc_ValueError, + "advanced indexing operation result is too large"); + goto fail; + } + + /* Can now return early if no subspace is being used */ + if (!uses_subspace) { + Py_XDECREF(extra_op); + return (PyObject *)mit; + } + + /* Fill in the last bit of mapiter information needed */ + + /* + * Now just need to create the correct subspace iterator. + */ + index_arrays[0] = subspace; + dtypes[0] = NULL; + op_flags[0] = subspace_flags; + op_axes[0] = NULL; + + if (extra_op_flags) { + /* We should iterate the extra_op as well */ + nops = 2; + index_arrays[1] = extra_op; + + op_axes[1] = &single_op_axis[mit->nd_fancy]; + /* - * Make a copy of the tuple -- we will be replacing - * index objects with 0's + * Buffering is never used here, but in case someone plugs it in + * somewhere else, set the type correctly then. */ - n = PyTuple_GET_SIZE(indexobj); - n2 = n; - new = PyTuple_New(n2); - if (new == NULL) { - goto fail; + if ((subspace_iter_flags & NPY_ITER_BUFFERED)) { + dtypes[1] = extra_op_dtype; } - started = 0; - nonindex = 0; - j = 0; - for (i = 0; i < n; i++) { - obj = PyTuple_GET_ITEM(indexobj,i); - iterp = mit->iters + mit->numiter; - if ((numiters=_convert_obj(obj, iterp)) < 0) { - Py_DECREF(new); - goto fail; - } - if (numiters > 0) { - started = 1; - if (nonindex) { - mit->consec = 0; - } - mit->numiter += numiters; - if (numiters == 1) { - PyTuple_SET_ITEM(new,j++, PyInt_FromLong(0)); - } - else { - /* - * we need to grow the new indexing object and fill - * it with 0s for each of the iterators produced - */ - int k; - n2 += numiters - 1; - if (_PyTuple_Resize(&new, n2) < 0) { - goto fail; - } - for (k = 0; k < numiters; k++) { - PyTuple_SET_ITEM(new, j++, PyInt_FromLong(0)); - } - } - } - else { - if (started) { - nonindex = 1; - } - Py_INCREF(obj); - PyTuple_SET_ITEM(new,j++,obj); - } + else { + dtypes[1] = NULL; } - Py_DECREF(mit->indexobj); - mit->indexobj = new; + op_flags[1] = extra_op_flags; + } + else { + nops = 1; + } + + mit->subspace_iter = NpyIter_AdvancedNew(nops, index_arrays, + NPY_ITER_ZEROSIZE_OK | + NPY_ITER_REFS_OK | + NPY_ITER_GROWINNER | + NPY_ITER_EXTERNAL_LOOP | + NPY_ITER_DELAY_BUFALLOC | + subspace_iter_flags, + (nops == 1 ? NPY_CORDER : NPY_KEEPORDER), + NPY_UNSAFE_CASTING, + op_flags, dtypes, + PyArray_NDIM(subspace), op_axes, + &mit->dimensions[mit->nd_fancy], 0); + + if (mit->subspace_iter == NULL) { + goto fail; + } + + mit->subspace_next = NpyIter_GetIterNext(mit->subspace_iter, NULL); + if (mit->subspace_next == NULL) { + goto fail; + } + mit->subspace_ptrs = NpyIter_GetDataPtrArray(mit->subspace_iter); + mit->subspace_strides = NpyIter_GetInnerStrideArray(mit->subspace_iter); + + if (NpyIter_IterationNeedsAPI(mit->outer)) { + mit->needs_api = 1; /* - * Store the number of iterators actually converted - * These will be mapped to actual axes at bind time + * NOTE: In this case, need to call PyErr_Occurred() after + * basepointer resetting (buffer allocation) */ - if (PyArray_Broadcast((PyArrayMultiIterObject *)mit) < 0) { - goto fail; - } } + Py_XDECREF(extra_op); return (PyObject *)mit; - fail: + fail: + /* + * Check whether the operand could not be broadcast and replace the error + * in that case. This should however normally be found early with a + * direct goto to broadcast_error + */ + if (extra_op == NULL) { + goto finish; + } + + j = mit->nd; + for (i = PyArray_NDIM(extra_op) - 1; i >= 0; i--) { + j--; + if ((PyArray_DIM(extra_op, i) != 1) && + /* (j < 0 is currently impossible, extra_op is reshaped) */ + j >= 0 && + PyArray_DIM(extra_op, i) != mit->dimensions[j]) { + /* extra_op cannot be broadcast to the indexing result */ + goto broadcast_error; + } + } + goto finish; + + broadcast_error: + errmsg = PyUString_FromString("shape mismatch: value array " + "of shape "); + if (errmsg == NULL) { + goto finish; + } + + /* Report the shape of the original array if it exists */ + if (original_extra_op == NULL) { + original_extra_op = extra_op; + } + + tmp = convert_shape_to_string(PyArray_NDIM(original_extra_op), + PyArray_DIMS(original_extra_op), " "); + if (tmp == NULL) { + goto finish; + } + PyUString_ConcatAndDel(&errmsg, tmp); + if (errmsg == NULL) { + goto finish; + } + + tmp = PyUString_FromString("could not be broadcast to indexing " + "result of shape "); + PyUString_ConcatAndDel(&errmsg, tmp); + if (errmsg == NULL) { + goto finish; + } + + tmp = convert_shape_to_string(mit->nd, mit->dimensions, ""); + if (tmp == NULL) { + goto finish; + } + PyUString_ConcatAndDel(&errmsg, tmp); + if (errmsg == NULL) { + goto finish; + } + + PyErr_SetObject(PyExc_ValueError, errmsg); + Py_DECREF(errmsg); + + finish: + Py_XDECREF(extra_op); Py_DECREF(mit); return NULL; } + /*NUMPY_API -*/ + * + * Use advanced indexing to iterate an array. Please note + * that most of this public API is currently not guaranteed + * to stay the same between versions. If you plan on using + * it, please consider adding more utility functions here + * to accommodate new features. + */ NPY_NO_EXPORT PyObject * PyArray_MapIterArray(PyArrayObject * a, PyObject * index) { - PyArrayMapIterObject * mit; - int fancy = fancy_indexing_check(index); + PyArrayMapIterObject * mit = NULL; + PyArrayObject *subspace = NULL; + npy_index_info indices[NPY_MAXDIMS * 2 + 1]; + int i, index_num, ndim, fancy_ndim, index_type; - /* - * MapIterNew supports a special mode that allows more efficient 1-d iteration, - * but clients that want to make use of this need to use a different API just - * for the one-d cases. For the public interface this is confusing, so we - * unconditionally disable the 1-d optimized mode, and use the generic - * implementation in all cases. - */ - int oned = 0; + index_type = prepare_index(a, index, indices, &index_num, + &ndim, &fancy_ndim, 0); - mit = (PyArrayMapIterObject *) PyArray_MapIterNew(index, oned, fancy); - if (mit == NULL) { + if (index_type < 0) { return NULL; } - if (PyArray_MapIterBind(mit, a) != 0) { - Py_DECREF(mit); - return NULL; + /* If it is not a pure fancy index, need to get the subspace */ + if (index_type != HAS_FANCY) { + if (get_view_from_index(a, &subspace, indices, index_num, 1) < 0) { + goto fail; + } + } + + mit = (PyArrayMapIterObject *)PyArray_MapIterNew(indices, index_num, + index_type, ndim, + fancy_ndim, + a, subspace, 0, + NPY_ITER_READWRITE, + 0, NULL, NULL); + if (mit == NULL) { + goto fail; + } + + /* Required for backward compatibility */ + mit->ait = (PyArrayIterObject *)PyArray_IterNew((PyObject *)a); + if (mit->ait == NULL) { + goto fail; + } + + if (PyArray_MapIterCheckIndices(mit) < 0) { + goto fail; } + + Py_XDECREF(subspace); PyArray_MapIterReset(mit); - return mit; + + for (i=0; i < index_num; i++) { + Py_XDECREF(indices[i].object); + } + + return (PyObject *)mit; + + fail: + Py_XDECREF(subspace); + Py_XDECREF((PyObject *)mit); + for (i=0; i < index_num; i++) { + Py_XDECREF(indices[i].object); + } + return NULL; } -#undef SOBJ_NOTFANCY -#undef SOBJ_ISFANCY -#undef SOBJ_BADARRAY -#undef SOBJ_TOOMANY -#undef SOBJ_LISTTUP +#undef HAS_INTEGER +#undef HAS_NEWAXIS +#undef HAS_SLICE +#undef HAS_ELLIPSIS +#undef HAS_FANCY +#undef HAS_BOOL +#undef HAS_SCALAR_ARRAY +#undef HAS_0D_BOOL + static void arraymapiter_dealloc(PyArrayMapIterObject *mit) { - int i; - Py_XDECREF(mit->indexobj); + Py_XDECREF(mit->array); Py_XDECREF(mit->ait); Py_XDECREF(mit->subspace); - for (i = 0; i < mit->numiter; i++) { - Py_XDECREF(mit->iters[i]); + Py_XDECREF(mit->extra_op); + Py_XDECREF(mit->extra_op_dtype); + if (mit->outer != NULL) { + NpyIter_Deallocate(mit->outer); + } + if (mit->subspace_iter != NULL) { + NpyIter_Deallocate(mit->subspace_iter); + } + if (mit->extra_op_iter != NULL) { + NpyIter_Deallocate(mit->extra_op_iter); } PyArray_free(mit); } @@ -2162,9 +3251,9 @@ arraymapiter_dealloc(PyArrayMapIterObject *mit) * This was the orginal intention, but currently that does not work. * Do not expose the MapIter_Type to Python. * - * It's not very useful anyway, since mapiter(indexobj); mapiter.bind(a); - * mapiter is equivalent to a[indexobj].flat but the latter gets to use - * slice syntax. + * The original mapiter(indexobj); mapiter.bind(a); idea is now fully + * removed. This is not very useful anyway, since mapiter is equivalent + * to a[indexobj].flat but the latter gets to use slice syntax. */ NPY_NO_EXPORT PyTypeObject PyArrayMapIter_Type = { #if defined(NPY_PY3K) @@ -2174,7 +3263,7 @@ NPY_NO_EXPORT PyTypeObject PyArrayMapIter_Type = { 0, /* ob_size */ #endif "numpy.mapiter", /* tp_name */ - sizeof(PyArrayIterObject), /* tp_basicsize */ + sizeof(PyArrayMapIterObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)arraymapiter_dealloc, /* tp_dealloc */ @@ -2223,7 +3312,7 @@ NPY_NO_EXPORT PyTypeObject PyArrayMapIter_Type = { 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ +#if PY_VERSION_HEX >= 0x02060000 0, /* tp_version_tag */ +#endif }; - -/** END of Subscript Iterator **/ diff --git a/numpy/core/src/multiarray/mapping.h b/numpy/core/src/multiarray/mapping.h index 224e28412..f59f6bb22 100644 --- a/numpy/core/src/multiarray/mapping.h +++ b/numpy/core/src/multiarray/mapping.h @@ -7,6 +7,25 @@ extern NPY_NO_EXPORT PyMappingMethods array_as_mapping; NPY_NO_EXPORT PyMappingMethods array_as_mapping; #endif + +/* + * Struct into which indices are parsed. + * I.e. integer ones should only be parsed once, slices and arrays + * need to be validated later and for the ellipsis we need to find how + * many slices it represents. + */ +typedef struct { + /* + * Object of index: slice, array, or NULL. Owns a reference. + */ + PyObject *object; + /* Value of an integer index or number of slices an Ellipsis is worth */ + npy_intp value; + /* kind of index, see constants in mapping.c */ + int type; +} npy_index_info; + + NPY_NO_EXPORT Py_ssize_t array_length(PyArrayObject *self); @@ -26,13 +45,7 @@ NPY_NO_EXPORT PyObject * array_subscript(PyArrayObject *self, PyObject *op); NPY_NO_EXPORT int -array_ass_item(PyArrayObject *self, Py_ssize_t i, PyObject *v); - -NPY_NO_EXPORT PyObject * -add_new_axes_0d(PyArrayObject *, int); - -NPY_NO_EXPORT int -count_new_axes_0d(PyObject *tuple); +array_assign_item(PyArrayObject *self, Py_ssize_t i, PyObject *v); /* * Prototypes for Mapping calls --- not part of the C-API @@ -45,9 +58,16 @@ NPY_NO_EXPORT void PyArray_MapIterNext(PyArrayMapIterObject *mit); NPY_NO_EXPORT int -PyArray_MapIterBind(PyArrayMapIterObject *, PyArrayObject *); +PyArray_MapIterCheckIndices(PyArrayMapIterObject *mit); -NPY_NO_EXPORT PyObject* -PyArray_MapIterNew(PyObject *, int, int); +NPY_NO_EXPORT void +PyArray_MapIterSwapAxes(PyArrayMapIterObject *mit, PyArrayObject **ret, int getmap); +NPY_NO_EXPORT PyObject* +PyArray_MapIterNew(npy_index_info *indices , int index_num, int index_type, + int ndim, int fancy_ndim, + PyArrayObject *arr, PyArrayObject *subspace, + npy_uint32 subspace_iter_flags, npy_uint32 subspace_flags, + npy_uint32 extra_op_flags, PyArrayObject *extra_op, + PyArray_Descr *extra_op_dtype); #endif diff --git a/numpy/core/src/multiarray/methods.c b/numpy/core/src/multiarray/methods.c index 37b7d3c18..5fab174ba 100644 --- a/numpy/core/src/multiarray/methods.c +++ b/numpy/core/src/multiarray/methods.c @@ -65,8 +65,9 @@ get_forwarding_ndarray_method(const char *name) "NumPy internal error: could not find function " "numpy.core._methods.%s", name); } - - Py_INCREF(callable); + else { + Py_INCREF(callable); + } Py_DECREF(module_methods); return callable; } @@ -351,9 +352,9 @@ array_swapaxes(PyArrayObject *self, PyObject *args) } -/* steals typed reference */ /*NUMPY_API Get a subset of bytes from each element of the array + steals reference to typed, must not be NULL */ NPY_NO_EXPORT PyObject * PyArray_GetField(PyArrayObject *self, PyArray_Descr *typed, int offset) @@ -409,6 +410,7 @@ array_getfield(PyArrayObject *self, PyObject *args, PyObject *kwds) /*NUMPY_API Set a subset of bytes from each element of the array + steals reference to dtype, must not be NULL */ NPY_NO_EXPORT int PyArray_SetField(PyArrayObject *self, PyArray_Descr *dtype, @@ -542,7 +544,7 @@ array_tolist(PyArrayObject *self, PyObject *args) static PyObject * -array_tostring(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_tobytes(PyArrayObject *self, PyObject *args, PyObject *kwds) { NPY_ORDER order = NPY_CORDER; static char *kwlist[] = {"order", NULL}; @@ -588,7 +590,7 @@ array_tofile(PyArrayObject *self, PyObject *args, PyObject *kwds) own = 0; } - fd = npy_PyFile_Dup(file, "wb", &orig_pos); + fd = npy_PyFile_Dup2(file, "wb", &orig_pos); if (fd == NULL) { PyErr_SetString(PyExc_IOError, "first argument must be a string or open file"); @@ -597,7 +599,7 @@ array_tofile(PyArrayObject *self, PyObject *args, PyObject *kwds) if (PyArray_ToFile(self, fd, sep, format) < 0) { goto fail; } - if (npy_PyFile_DupClose(file, fd, orig_pos) < 0) { + if (npy_PyFile_DupClose2(file, fd, orig_pos) < 0) { goto fail; } if (own && npy_PyFile_CloseFile(file) < 0) { @@ -647,7 +649,7 @@ array_toscalar(PyArrayObject *self, PyObject *args) return NULL; } - if (check_and_adjust_index(&value, size, -1) < 0) { + if (check_and_adjust_index(&value, size, -1, NULL) < 0) { return NULL; } @@ -724,7 +726,7 @@ array_setscalar(PyArrayObject *self, PyObject *args) return NULL; } - if (check_and_adjust_index(&value, size, -1) < 0) { + if (check_and_adjust_index(&value, size, -1, NULL) < 0) { return NULL; } @@ -1457,7 +1459,7 @@ array_deepcopy(PyArrayObject *self, PyObject *args) Py_DECREF(deepcopy); Py_DECREF(it); } - return PyArray_Return(ret); + return (PyObject*)ret; } /* Convert Array to flat list (using getitem) */ @@ -1712,6 +1714,9 @@ array_setstate(PyArrayObject *self, PyObject *args) if (nd > 0) { fa->dimensions = PyDimMem_NEW(3*nd); + if (fa->dimensions == NULL) { + return PyErr_NoMemory(); + } fa->strides = PyArray_DIMS(self) + nd; memcpy(PyArray_DIMS(self), dimensions, sizeof(npy_intp)*nd); _array_fill_strides(PyArray_STRIDES(self), dimensions, nd, @@ -1820,6 +1825,7 @@ PyArray_Dump(PyObject *self, PyObject *file, int protocol) if (PyBytes_Check(file) || PyUnicode_Check(file)) { file = npy_PyFile_OpenFile(file, "wb"); if (file == NULL) { + Py_DECREF(cpick); return -1; } } @@ -2456,6 +2462,9 @@ NPY_NO_EXPORT PyMethodDef array_methods[] = { {"take", (PyCFunction)array_take, METH_VARARGS | METH_KEYWORDS, NULL}, + {"tobytes", + (PyCFunction)array_tobytes, + METH_VARARGS | METH_KEYWORDS, NULL}, {"tofile", (PyCFunction)array_tofile, METH_VARARGS | METH_KEYWORDS, NULL}, @@ -2463,7 +2472,7 @@ NPY_NO_EXPORT PyMethodDef array_methods[] = { (PyCFunction)array_tolist, METH_VARARGS, NULL}, {"tostring", - (PyCFunction)array_tostring, + (PyCFunction)array_tobytes, METH_VARARGS | METH_KEYWORDS, NULL}, {"trace", (PyCFunction)array_trace, diff --git a/numpy/core/src/multiarray/multiarray_tests.c.src b/numpy/core/src/multiarray/multiarray_tests.c.src index 9f327b24e..bd0366bd5 100644 --- a/numpy/core/src/multiarray/multiarray_tests.c.src +++ b/numpy/core/src/multiarray/multiarray_tests.c.src @@ -690,6 +690,139 @@ get_buffer_info(PyObject *NPY_UNUSED(self), PyObject *args) #undef GET_PYBUF_FLAG +/* + * Test C-api level item getting. + */ +static PyObject * +array_indexing(PyObject *NPY_UNUSED(self), PyObject *args) +{ + int mode; + Py_ssize_t i; + PyObject *arr, *op = NULL; + + if (!PyArg_ParseTuple(args, "iOn|O", &mode, &arr, &i, &op)) { + return NULL; + } + + if (mode == 0) { + return PySequence_GetItem(arr, i); + } + if (mode == 1) { + if (PySequence_SetItem(arr, i, op) < 0) { + return NULL; + } + Py_RETURN_NONE; + } + + PyErr_SetString(PyExc_ValueError, + "invalid mode. 0: item 1: assign"); + return NULL; +} + + +/* + * Test nditer of too large arrays using remove axis, etc. + */ +static PyObject * +test_nditer_too_large(PyObject *NPY_UNUSED(self), PyObject *args) { + NpyIter *iter; + PyObject *array_tuple, *arr; + PyArrayObject *arrays[NPY_MAXARGS]; + npy_uint32 op_flags[NPY_MAXARGS]; + Py_ssize_t nop; + int i, axis, mode; + + npy_intp index[NPY_MAXARGS] = {0}; + char *msg; + + if (!PyArg_ParseTuple(args, "Oii", &array_tuple, &axis, &mode)) { + return NULL; + } + + if (!PyTuple_CheckExact(array_tuple)) { + PyErr_SetString(PyExc_ValueError, "tuple required as first argument"); + return NULL; + } + nop = PyTuple_Size(array_tuple); + if (nop > NPY_MAXARGS) { + PyErr_SetString(PyExc_ValueError, "tuple must be smaller then maxargs"); + return NULL; + } + + for (i=0; i < nop; i++) { + arr = PyTuple_GET_ITEM(array_tuple, i); + if (!PyArray_CheckExact(arr)) { + PyErr_SetString(PyExc_ValueError, "require base class ndarray"); + return NULL; + } + arrays[i] = (PyArrayObject *)arr; + op_flags[i] = NPY_ITER_READONLY; + } + + iter = NpyIter_MultiNew(nop, arrays, NPY_ITER_MULTI_INDEX | NPY_ITER_RANGED, + NPY_KEEPORDER, NPY_NO_CASTING, op_flags, NULL); + + if (iter == NULL) { + return NULL; + } + + /* Remove an axis (negative, do not remove any) */ + if (axis >= 0) { + if (!NpyIter_RemoveAxis(iter, axis)) { + goto fail; + } + } + + switch (mode) { + /* Test IterNext getting */ + case 0: + if (NpyIter_GetIterNext(iter, NULL) == NULL) { + goto fail; + } + break; + case 1: + if (NpyIter_GetIterNext(iter, &msg) == NULL) { + PyErr_SetString(PyExc_ValueError, msg); + goto fail; + } + break; + /* Test Multi Index removal */ + case 2: + if (!NpyIter_RemoveMultiIndex(iter)) { + goto fail; + } + break; + /* Test GotoMultiIndex (just 0 hardcoded) */ + case 3: + if (!NpyIter_GotoMultiIndex(iter, index)) { + goto fail; + } + break; + /* Test setting iterrange (hardcoded range of 0, 1) */ + case 4: + if (!NpyIter_ResetToIterIndexRange(iter, 0, 1, NULL)) { + goto fail; + } + break; + case 5: + if (!NpyIter_ResetToIterIndexRange(iter, 0, 1, &msg)) { + PyErr_SetString(PyExc_ValueError, msg); + goto fail; + } + break; + /* Do nothing */ + default: + break; + } + + NpyIter_Deallocate(iter); + Py_RETURN_NONE; + fail: + NpyIter_Deallocate(iter); + return NULL; +} + + static PyMethodDef Multiarray_TestsMethods[] = { {"test_neighborhood_iterator", test_neighborhood_iterator, @@ -714,6 +847,12 @@ static PyMethodDef Multiarray_TestsMethods[] = { {"get_buffer_info", get_buffer_info, METH_VARARGS, NULL}, + {"array_indexing", + array_indexing, + METH_VARARGS, NULL}, + {"test_nditer_too_large", + test_nditer_too_large, + METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} /* Sentinel */ }; diff --git a/numpy/core/src/multiarray/multiarraymodule.c b/numpy/core/src/multiarray/multiarraymodule.c index 23cb7e368..682705a1b 100644 --- a/numpy/core/src/multiarray/multiarraymodule.c +++ b/numpy/core/src/multiarray/multiarraymodule.c @@ -20,6 +20,7 @@ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE +#include <numpy/npy_common.h> #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" @@ -1007,8 +1008,15 @@ PyArray_MatrixProduct2(PyObject *op1, PyObject *op2, PyArrayObject* out) axis = PyArray_NDIM(ap1)-1; it1 = (PyArrayIterObject *) PyArray_IterAllButAxis((PyObject *)ap1, &axis); + if (it1 == NULL) { + goto fail; + } it2 = (PyArrayIterObject *) PyArray_IterAllButAxis((PyObject *)ap2, &matchDim); + if (it2 == NULL) { + Py_DECREF(it1); + goto fail; + } NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(ap2)); while (it1->index < it1->size) { while (it2->index < it2->size) { @@ -1393,7 +1401,9 @@ array_putmask(PyObject *NPY_UNUSED(module), PyObject *args, PyObject *kwds) static int _equivalent_fields(PyObject *field1, PyObject *field2) { - int same, val; + Py_ssize_t ppos; + PyObject *key; + PyObject *tuple1, *tuple2; if (field1 == field2) { return 1; @@ -1401,20 +1411,33 @@ _equivalent_fields(PyObject *field1, PyObject *field2) { if (field1 == NULL || field2 == NULL) { return 0; } -#if defined(NPY_PY3K) - val = PyObject_RichCompareBool(field1, field2, Py_EQ); - if (val != 1 || PyErr_Occurred()) { -#else - val = PyObject_Compare(field1, field2); - if (val != 0 || PyErr_Occurred()) { -#endif - same = 0; + + if (PyDict_Size(field1) != PyDict_Size(field2)) { + return 0; } - else { - same = 1; + + /* Iterate over all the fields and compare for equivalency */ + ppos = 0; + while (PyDict_Next(field1, &ppos, &key, &tuple1)) { + if ((tuple2 = PyDict_GetItem(field2, key)) == NULL) { + return 0; + } + /* Compare the dtype of the field for equivalency */ + if (!PyArray_CanCastTypeTo((PyArray_Descr *)PyTuple_GET_ITEM(tuple1, 0), + (PyArray_Descr *)PyTuple_GET_ITEM(tuple2, 0), + NPY_EQUIV_CASTING)) { + return 0; + } + /* Compare the byte position of the field */ + if (PyObject_RichCompareBool(PyTuple_GET_ITEM(tuple1, 1), + PyTuple_GET_ITEM(tuple2, 1), + Py_EQ) != 1) { + PyErr_Clear(); + return 0; + } } - PyErr_Clear(); - return same; + + return 1; } /* @@ -1517,7 +1540,7 @@ PyArray_EquivTypenums(int typenum1, int typenum2) * NPY_RELAXED_STRIDES_CHECKING: If the strides logic is changed, the * order specific stride setting is not necessary. */ -static PyObject * +static NPY_STEALS_REF_TO_ARG(1) PyObject * _prepend_ones(PyArrayObject *arr, int nd, int ndmin, NPY_ORDER order) { npy_intp newdims[NPY_MAXDIMS]; @@ -1633,7 +1656,7 @@ _array_fromobject(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kws) } else { ret = (PyArrayObject *)PyArray_NewCopy(oparr, order); - if (oldtype == type) { + if (oldtype == type || ret == NULL) { goto finish; } Py_INCREF(oldtype); @@ -1992,7 +2015,7 @@ array_fromfile(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *keywds) Py_INCREF(file); own = 0; } - fp = npy_PyFile_Dup(file, "rb", &orig_pos); + fp = npy_PyFile_Dup2(file, "rb", &orig_pos); if (fp == NULL) { PyErr_SetString(PyExc_IOError, "first argument must be an open file"); @@ -2004,7 +2027,7 @@ array_fromfile(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *keywds) } ret = PyArray_FromFile(fp, type, (npy_intp) nin, sep); - if (npy_PyFile_DupClose(file, fp, orig_pos) < 0) { + if (npy_PyFile_DupClose2(file, fp, orig_pos) < 0) { goto fail; } if (own && npy_PyFile_CloseFile(file) < 0) { @@ -2085,15 +2108,16 @@ static PyObject * array_matrixproduct(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject* kwds) { int errval; - static PyObject *cached_npy_dot = NULL; + static PyUFuncObject *cached_npy_dot = NULL; PyObject *override = NULL; PyObject *v, *a, *o = NULL; char* kwlist[] = {"a", "b", "out", NULL }; PyObject *module; - + if (cached_npy_dot == NULL) { module = PyImport_ImportModule("numpy.core.multiarray"); - cached_npy_dot = PyDict_GetItemString(PyModule_GetDict(module), "dot"); + cached_npy_dot = (PyUFuncObject*)PyDict_GetItemString( + PyModule_GetDict(module), "dot"); Py_INCREF(cached_npy_dot); Py_DECREF(module); @@ -2291,7 +2315,7 @@ einsum_sub_op_from_lists(PyObject *args, /* Set the operands to NULL */ for (i = 0; i < nop; ++i) { - op[nop] = NULL; + op[i] = NULL; } /* Get the operands and build the subscript string */ @@ -2679,6 +2703,28 @@ array_set_datetimeparse_function(PyObject *NPY_UNUSED(self), return NULL; } +/* + * inner loop with constant size memcpy arguments + * this allows the compiler to replace function calls while still handling the + * alignment requirements of the platform. + */ +#define INNER_WHERE_LOOP(size) \ + do { \ + npy_intp i; \ + for (i = 0; i < n; i++) { \ + if (*csrc) { \ + memcpy(dst, xsrc, size); \ + } \ + else { \ + memcpy(dst, ysrc, size); \ + } \ + dst += size; \ + xsrc += xstride; \ + ysrc += ystride; \ + csrc += cstride; \ + } \ + } while(0) + /*NUMPY_API * Where @@ -2686,9 +2732,8 @@ array_set_datetimeparse_function(PyObject *NPY_UNUSED(self), NPY_NO_EXPORT PyObject * PyArray_Where(PyObject *condition, PyObject *x, PyObject *y) { - PyArrayObject *arr; - PyObject *tup = NULL, *obj = NULL; - PyObject *ret = NULL, *zero = NULL; + PyArrayObject *arr, *ax, *ay; + PyObject *ret = NULL; arr = (PyArrayObject *)PyArray_FromAny(condition, NULL, 0, 0, 0, NULL); if (arr == NULL) { @@ -2706,26 +2751,132 @@ PyArray_Where(PyObject *condition, PyObject *x, PyObject *y) return NULL; } - - zero = PyInt_FromLong((long) 0); - obj = PyArray_EnsureAnyArray(PyArray_GenericBinaryFunction(arr, zero, - n_ops.not_equal)); - Py_DECREF(zero); - Py_DECREF(arr); - if (obj == NULL) { - return NULL; + ax = (PyArrayObject*)PyArray_FromAny(x, NULL, 0, 0, 0 ,NULL); + ay = (PyArrayObject*)PyArray_FromAny(y, NULL, 0, 0, 0 ,NULL); + if (ax == NULL || ay == NULL) { + goto fail; } - tup = Py_BuildValue("(OO)", y, x); - if (tup == NULL) { - Py_DECREF(obj); - return NULL; + else { + npy_uint32 flags = NPY_ITER_EXTERNAL_LOOP | NPY_ITER_BUFFERED | + NPY_ITER_REFS_OK | NPY_ITER_ZEROSIZE_OK; + PyArrayObject * op_in[4] = { + NULL, arr, ax, ay + }; + npy_uint32 op_flags[4] = { + NPY_ITER_WRITEONLY | NPY_ITER_ALLOCATE, + NPY_ITER_READONLY, NPY_ITER_READONLY, NPY_ITER_READONLY + }; + PyArray_Descr * common_dt = PyArray_ResultType(2, &op_in[0] + 2, + 0, NULL); + PyArray_Descr * op_dt[4] = {common_dt, PyArray_DescrFromType(NPY_BOOL), + common_dt, common_dt}; + NpyIter * iter; + int needs_api; + NPY_BEGIN_THREADS_DEF; + + if (common_dt == NULL || op_dt[1] == NULL) { + Py_XDECREF(op_dt[1]); + Py_XDECREF(common_dt); + goto fail; + } + iter = NpyIter_MultiNew(4, op_in, flags, + NPY_KEEPORDER, NPY_UNSAFE_CASTING, + op_flags, op_dt); + Py_DECREF(op_dt[1]); + Py_DECREF(common_dt); + if (iter == NULL) { + goto fail; + } + + needs_api = NpyIter_IterationNeedsAPI(iter); + + /* Get the result from the iterator object array */ + ret = (PyObject*)NpyIter_GetOperandArray(iter)[0]; + + NPY_BEGIN_THREADS_NDITER(iter); + + if (NpyIter_GetIterSize(iter) != 0) { + NpyIter_IterNextFunc *iternext = NpyIter_GetIterNext(iter, NULL); + npy_intp * innersizeptr = NpyIter_GetInnerLoopSizePtr(iter); + char **dataptrarray = NpyIter_GetDataPtrArray(iter); + + do { + PyArray_Descr * dtx = NpyIter_GetDescrArray(iter)[2]; + PyArray_Descr * dty = NpyIter_GetDescrArray(iter)[3]; + int axswap = PyDataType_ISBYTESWAPPED(dtx); + int ayswap = PyDataType_ISBYTESWAPPED(dty); + PyArray_CopySwapFunc *copyswapx = dtx->f->copyswap; + PyArray_CopySwapFunc *copyswapy = dty->f->copyswap; + int native = (axswap == ayswap) && (axswap == 0) && !needs_api; + npy_intp n = (*innersizeptr); + npy_intp itemsize = NpyIter_GetDescrArray(iter)[0]->elsize; + npy_intp cstride = NpyIter_GetInnerStrideArray(iter)[1]; + npy_intp xstride = NpyIter_GetInnerStrideArray(iter)[2]; + npy_intp ystride = NpyIter_GetInnerStrideArray(iter)[3]; + char * dst = dataptrarray[0]; + char * csrc = dataptrarray[1]; + char * xsrc = dataptrarray[2]; + char * ysrc = dataptrarray[3]; + + /* constant sizes so compiler replaces memcpy */ + if (native && itemsize == 16) { + INNER_WHERE_LOOP(16); + } + else if (native && itemsize == 8) { + INNER_WHERE_LOOP(8); + } + else if (native && itemsize == 4) { + INNER_WHERE_LOOP(4); + } + else if (native && itemsize == 2) { + INNER_WHERE_LOOP(2); + } + else if (native && itemsize == 1) { + INNER_WHERE_LOOP(1); + } + else { + /* copyswap is faster than memcpy even if we are native */ + npy_intp i; + for (i = 0; i < n; i++) { + if (*csrc) { + copyswapx(dst, xsrc, axswap, ret); + } + else { + copyswapy(dst, ysrc, ayswap, ret); + } + dst += itemsize; + xsrc += xstride; + ysrc += ystride; + csrc += cstride; + } + } + } while (iternext(iter)); + } + + NPY_END_THREADS; + + Py_INCREF(ret); + Py_DECREF(arr); + Py_DECREF(ax); + Py_DECREF(ay); + + if (NpyIter_Deallocate(iter) != NPY_SUCCEED) { + Py_DECREF(ret); + return NULL; + } + + return ret; } - ret = PyArray_Choose((PyArrayObject *)obj, tup, NULL, NPY_RAISE); - Py_DECREF(obj); - Py_DECREF(tup); - return ret; + + fail: + Py_DECREF(arr); + Py_XDECREF(ax); + Py_XDECREF(ay); + return NULL; } +#undef INNER_WHERE_LOOP + static PyObject * array_where(PyObject *NPY_UNUSED(ignored), PyObject *args) { @@ -2858,8 +3009,8 @@ static PyObject * array_result_type(PyObject *NPY_UNUSED(dummy), PyObject *args) { npy_intp i, len, narr = 0, ndtypes = 0; - PyArrayObject *arr[NPY_MAXARGS]; - PyArray_Descr *dtypes[NPY_MAXARGS]; + PyArrayObject **arr = NULL; + PyArray_Descr **dtypes = NULL; PyObject *ret = NULL; len = PyTuple_GET_SIZE(args); @@ -2869,25 +3020,21 @@ array_result_type(PyObject *NPY_UNUSED(dummy), PyObject *args) goto finish; } + arr = PyArray_malloc(2 * len * sizeof(void *)); + if (arr == NULL) { + return PyErr_NoMemory(); + } + dtypes = (PyArray_Descr**)&arr[len]; + for (i = 0; i < len; ++i) { PyObject *obj = PyTuple_GET_ITEM(args, i); if (PyArray_Check(obj)) { - if (narr == NPY_MAXARGS) { - PyErr_SetString(PyExc_ValueError, - "too many arguments"); - goto finish; - } Py_INCREF(obj); arr[narr] = (PyArrayObject *)obj; ++narr; } else if (PyArray_IsScalar(obj, Generic) || PyArray_IsPythonNumber(obj)) { - if (narr == NPY_MAXARGS) { - PyErr_SetString(PyExc_ValueError, - "too many arguments"); - goto finish; - } arr[narr] = (PyArrayObject *)PyArray_FromAny(obj, NULL, 0, 0, 0, NULL); if (arr[narr] == NULL) { @@ -2896,11 +3043,6 @@ array_result_type(PyObject *NPY_UNUSED(dummy), PyObject *args) ++narr; } else { - if (ndtypes == NPY_MAXARGS) { - PyErr_SetString(PyExc_ValueError, - "too many arguments"); - goto finish; - } if (!PyArray_DescrConverter(obj, &dtypes[ndtypes])) { goto finish; } @@ -2917,6 +3059,7 @@ finish: for (i = 0; i < ndtypes; ++i) { Py_DECREF(dtypes[i]); } + PyArray_free(arr); return ret; } @@ -3397,7 +3540,8 @@ _vec_string(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *kwds) #ifndef __NPY_PRIVATE_NO_SIGNAL -NPY_SIGJMP_BUF _NPY_SIGINT_BUF; +static NPY_TLS int sigint_buf_init = 0; +static NPY_TLS NPY_SIGJMP_BUF _NPY_SIGINT_BUF; /*NUMPY_API */ @@ -3405,7 +3549,17 @@ NPY_NO_EXPORT void _PyArray_SigintHandler(int signum) { PyOS_setsig(signum, SIG_IGN); - NPY_SIGLONGJMP(_NPY_SIGINT_BUF, signum); + /* + * jump buffer may be unitialized as SIGINT allowing functions are usually + * run in other threads than the master thread that receives the signal + */ + if (sigint_buf_init > 0) { + NPY_SIGLONGJMP(_NPY_SIGINT_BUF, signum); + } + /* + * sending SIGINT to the worker threads to cancel them is job of the + * application + */ } /*NUMPY_API @@ -3413,6 +3567,7 @@ _PyArray_SigintHandler(int signum) NPY_NO_EXPORT void* _PyArray_GetSigintBuf(void) { + sigint_buf_init = 1; return (void *)&_NPY_SIGINT_BUF; } @@ -3462,122 +3617,6 @@ test_interrupt(PyObject *NPY_UNUSED(self), PyObject *args) return PyInt_FromLong(a); } -/* malloc/free/realloc hook */ -NPY_NO_EXPORT PyDataMem_EventHookFunc *_PyDataMem_eventhook; -NPY_NO_EXPORT void *_PyDataMem_eventhook_user_data; - -/*NUMPY_API - * Sets the allocation event hook for numpy array data. - * Takes a PyDataMem_EventHookFunc *, which has the signature: - * void hook(void *old, void *new, size_t size, void *user_data). - * Also takes a void *user_data, and void **old_data. - * - * Returns a pointer to the previous hook or NULL. If old_data is - * non-NULL, the previous user_data pointer will be copied to it. - * - * If not NULL, hook will be called at the end of each PyDataMem_NEW/FREE/RENEW: - * result = PyDataMem_NEW(size) -> (*hook)(NULL, result, size, user_data) - * PyDataMem_FREE(ptr) -> (*hook)(ptr, NULL, 0, user_data) - * result = PyDataMem_RENEW(ptr, size) -> (*hook)(ptr, result, size, user_data) - * - * When the hook is called, the GIL will be held by the calling - * thread. The hook should be written to be reentrant, if it performs - * operations that might cause new allocation events (such as the - * creation/descruction numpy objects, or creating/destroying Python - * objects which might cause a gc) - */ -NPY_NO_EXPORT PyDataMem_EventHookFunc * -PyDataMem_SetEventHook(PyDataMem_EventHookFunc *newhook, - void *user_data, void **old_data) -{ - PyGILState_STATE gilstate = PyGILState_Ensure(); - PyDataMem_EventHookFunc *temp = _PyDataMem_eventhook; - _PyDataMem_eventhook = newhook; - if (old_data != NULL) { - *old_data = _PyDataMem_eventhook_user_data; - } - _PyDataMem_eventhook_user_data = user_data; - PyGILState_Release(gilstate); - return temp; -} - -/*NUMPY_API - * Allocates memory for array data. - */ -NPY_NO_EXPORT void * -PyDataMem_NEW(size_t size) -{ - void *result; - - result = malloc(size); - if (_PyDataMem_eventhook != NULL) { - PyGILState_STATE gilstate = PyGILState_Ensure(); - if (_PyDataMem_eventhook != NULL) { - (*_PyDataMem_eventhook)(NULL, result, size, - _PyDataMem_eventhook_user_data); - } - PyGILState_Release(gilstate); - } - return result; -} - -/*NUMPY_API - * Allocates zeroed memory for array data. - */ -NPY_NO_EXPORT void * -PyDataMem_NEW_ZEROED(size_t size, size_t elsize) -{ - void *result; - - result = calloc(size, elsize); - if (_PyDataMem_eventhook != NULL) { - PyGILState_STATE gilstate = PyGILState_Ensure(); - if (_PyDataMem_eventhook != NULL) { - (*_PyDataMem_eventhook)(NULL, result, size * elsize, - _PyDataMem_eventhook_user_data); - } - PyGILState_Release(gilstate); - } - return result; -} - -/*NUMPY_API - * Free memory for array data. - */ -NPY_NO_EXPORT void -PyDataMem_FREE(void *ptr) -{ - free(ptr); - if (_PyDataMem_eventhook != NULL) { - PyGILState_STATE gilstate = PyGILState_Ensure(); - if (_PyDataMem_eventhook != NULL) { - (*_PyDataMem_eventhook)(ptr, NULL, 0, - _PyDataMem_eventhook_user_data); - } - PyGILState_Release(gilstate); - } -} - -/*NUMPY_API - * Reallocate/resize memory for array data. - */ -NPY_NO_EXPORT void * -PyDataMem_RENEW(void *ptr, size_t size) -{ - void *result; - - result = realloc(ptr, size); - if (_PyDataMem_eventhook != NULL) { - PyGILState_STATE gilstate = PyGILState_Ensure(); - if (_PyDataMem_eventhook != NULL) { - (*_PyDataMem_eventhook)(ptr, result, size, - _PyDataMem_eventhook_user_data); - } - PyGILState_Release(gilstate); - } - return result; -} - static PyObject * array_may_share_memory(PyObject *NPY_UNUSED(ignored), PyObject *args) { @@ -4017,7 +4056,6 @@ PyMODINIT_FUNC initmultiarray(void) { if (!d) { goto err; } - PyArray_Type.tp_free = PyObject_Free; if (PyType_Ready(&PyArray_Type) < 0) { return RETVAL; } diff --git a/numpy/core/src/multiarray/multiarraymodule_onefile.c b/numpy/core/src/multiarray/multiarraymodule_onefile.c index 9410263e4..2d05c20ef 100644 --- a/numpy/core/src/multiarray/multiarraymodule_onefile.c +++ b/numpy/core/src/multiarray/multiarraymodule_onefile.c @@ -21,6 +21,7 @@ #include "descriptor.c" #include "flagsobject.c" +#include "alloc.c" #include "ctors.c" #include "iterators.c" #include "mapping.c" diff --git a/numpy/core/src/multiarray/nditer_api.c b/numpy/core/src/multiarray/nditer_api.c index 905a19d55..17108f02c 100644 --- a/numpy/core/src/multiarray/nditer_api.c +++ b/numpy/core/src/multiarray/nditer_api.c @@ -14,6 +14,7 @@ /* Indicate that this .c file is allowed to include the header */ #define NPY_ITERATOR_IMPLEMENTATION_CODE #include "nditer_impl.h" +#include "scalarmathmodule.h" /* Internal helper functions private to this file */ static npy_intp @@ -127,13 +128,23 @@ NpyIter_RemoveAxis(NpyIter *iter, int axis) perm[idim] = p; } - /* Adjust the iteration size */ - NIT_ITERSIZE(iter) /= NAD_SHAPE(axisdata_del); - /* Shift all the axisdata structures by one */ axisdata = NIT_INDEX_AXISDATA(axisdata_del, 1); memmove(axisdata_del, axisdata, (ndim-1-xdim)*sizeof_axisdata); + /* Adjust the iteration size and reset iterend */ + NIT_ITERSIZE(iter) = 1; + axisdata = NIT_AXISDATA(iter); + for (idim = 0; idim < ndim-1; ++idim) { + if (npy_mul_with_overflow_intp(&NIT_ITERSIZE(iter), + NIT_ITERSIZE(iter), NAD_SHAPE(axisdata))) { + NIT_ITERSIZE(iter) = -1; + break; + } + NIT_ADVANCE_AXISDATA(axisdata, 1); + } + NIT_ITEREND(iter) = NIT_ITERSIZE(iter); + /* Shrink the iterator */ NIT_NDIM(iter) = ndim - 1; /* If it is now 0-d fill the singleton dimension */ @@ -166,6 +177,11 @@ NpyIter_RemoveMultiIndex(NpyIter *iter) itflags = NIT_ITFLAGS(iter); if (itflags&NPY_ITFLAG_HASMULTIINDEX) { + if (NIT_ITERSIZE(iter) < 0) { + PyErr_SetString(PyExc_ValueError, "iterator is too large"); + return NPY_FAIL; + } + NIT_ITFLAGS(iter) = itflags & ~NPY_ITFLAG_HASMULTIINDEX; npyiter_coalesce_axes(iter); } @@ -349,6 +365,15 @@ NpyIter_ResetToIterIndexRange(NpyIter *iter, } if (istart < 0 || iend > NIT_ITERSIZE(iter)) { + if (NIT_ITERSIZE(iter) < 0) { + if (errmsg == NULL) { + PyErr_SetString(PyExc_ValueError, "iterator is too large"); + } + else { + *errmsg = "iterator is too large"; + } + return NPY_FAIL; + } if (errmsg == NULL) { PyErr_Format(PyExc_ValueError, "Out-of-bounds range [%d, %d) passed to " @@ -454,6 +479,10 @@ NpyIter_GotoMultiIndex(NpyIter *iter, npy_intp *multi_index) } if (iterindex < NIT_ITERSTART(iter) || iterindex >= NIT_ITEREND(iter)) { + if (NIT_ITERSIZE(iter) < 0) { + PyErr_SetString(PyExc_ValueError, "iterator is too large"); + return NPY_FAIL; + } PyErr_SetString(PyExc_IndexError, "Iterator GotoMultiIndex called with a multi-index outside the " "restricted iteration range"); @@ -574,6 +603,10 @@ NpyIter_GotoIterIndex(NpyIter *iter, npy_intp iterindex) } if (iterindex < NIT_ITERSTART(iter) || iterindex >= NIT_ITEREND(iter)) { + if (NIT_ITERSIZE(iter) < 0) { + PyErr_SetString(PyExc_ValueError, "iterator is too large"); + return NPY_FAIL; + } PyErr_SetString(PyExc_IndexError, "Iterator GotoIterIndex called with an iterindex outside the " "iteration range."); @@ -752,8 +785,8 @@ NpyIter_IsFirstVisit(NpyIter *iter, int iop) if (itflags&NPY_ITFLAG_BUFFER) { NpyIter_BufferData *bufferdata = NIT_BUFFERDATA(iter); /* The outer reduce loop */ - if (NBF_REDUCE_OUTERSTRIDES(bufferdata)[iop] == 0 && - NBF_REDUCE_POS(bufferdata) != 0) { + if (NBF_REDUCE_POS(bufferdata) != 0 && + NBF_REDUCE_OUTERSTRIDES(bufferdata)[iop] == 0) { return 0; } } @@ -1298,21 +1331,20 @@ NpyIter_GetInnerFixedStrideArray(NpyIter *iter, npy_intp *out_strides) out_strides[iop] = stride; } /* - * Otherwise it's a fixed stride if the stride is 0 - * for all inner dimensions of the reduction double loop + * Otherwise it's guaranteed to be a fixed stride if the + * stride is 0 for all the dimensions. */ else { NpyIter_AxisData *axisdata = axisdata0; - int idim, - reduce_outerdim = NBF_REDUCE_OUTERDIM(data); - for (idim = 0; idim < reduce_outerdim; ++idim) { + int idim; + for (idim = 0; idim < ndim; ++idim) { if (NAD_STRIDES(axisdata)[iop] != 0) { break; } NIT_ADVANCE_AXISDATA(axisdata, 1); } /* If all the strides were 0, the stride won't change */ - if (idim == reduce_outerdim) { + if (idim == ndim) { out_strides[iop] = stride; } else { @@ -1377,7 +1409,8 @@ NpyIter_DebugPrint(NpyIter *iter) NpyIter_AxisData *axisdata; npy_intp sizeof_axisdata; - PyGILState_STATE gilstate = PyGILState_Ensure(); + NPY_ALLOW_C_API_DEF + NPY_ALLOW_C_API printf("\n------ BEGIN ITERATOR DUMP ------\n"); printf("| Iterator Address: %p\n", (void *)iter); @@ -1598,7 +1631,7 @@ NpyIter_DebugPrint(NpyIter *iter) printf("------- END ITERATOR DUMP -------\n"); fflush(stdout); - PyGILState_Release(gilstate); + NPY_DISABLE_C_API } NPY_NO_EXPORT void diff --git a/numpy/core/src/multiarray/nditer_constr.c b/numpy/core/src/multiarray/nditer_constr.c index 964b51e22..b7f700e60 100644 --- a/numpy/core/src/multiarray/nditer_constr.c +++ b/numpy/core/src/multiarray/nditer_constr.c @@ -261,6 +261,12 @@ NpyIter_AdvancedNew(int nop, PyArrayObject **op_in, npy_uint32 flags, buffersize = NIT_ITERSIZE(iter); } NBF_BUFFERSIZE(bufferdata) = buffersize; + + /* + * Initialize for use in FirstVisit, which may be called before + * the buffers are filled and the reduce pos is updated. + */ + NBF_REDUCE_POS(bufferdata) = 0; } /* @@ -1255,54 +1261,6 @@ npyiter_casting_to_string(NPY_CASTING casting) } } -static PyObject * -npyiter_shape_string(npy_intp n, npy_intp *vals, char *ending) -{ - npy_intp i; - PyObject *ret, *tmp; - - /* - * Negative dimension indicates "newaxis", which can - * be discarded for printing if it's a leading dimension. - * Find the first non-"newaxis" dimension. - */ - i = 0; - while (i < n && vals[i] < 0) { - ++i; - } - - if (i == n) { - return PyUString_FromFormat("()%s", ending); - } - else { - ret = PyUString_FromFormat("(%" NPY_INTP_FMT, vals[i++]); - if (ret == NULL) { - return NULL; - } - } - - for (; i < n; ++i) { - if (vals[i] < 0) { - tmp = PyUString_FromString(",newaxis"); - } - else { - tmp = PyUString_FromFormat(",%" NPY_INTP_FMT, vals[i]); - } - if (tmp == NULL) { - Py_DECREF(ret); - return NULL; - } - - PyUString_ConcatAndDel(&ret, tmp); - if (ret == NULL) { - return NULL; - } - } - - tmp = PyUString_FromFormat(")%s", ending); - PyUString_ConcatAndDel(&ret, tmp); - return ret; -} static int npyiter_check_casting(int nop, PyArrayObject **op, @@ -1704,8 +1662,21 @@ npyiter_fill_axisdata(NpyIter *iter, npy_uint32 flags, npyiter_opitflags *op_itf for (idim = 0; idim < ndim; ++idim) { if (npy_mul_with_overflow_intp(&NIT_ITERSIZE(iter), NIT_ITERSIZE(iter), broadcast_shape[idim])) { - PyErr_SetString(PyExc_ValueError, "iterator is too large"); - return 0; + if ((itflags & NPY_ITFLAG_HASMULTIINDEX) && + !(itflags & NPY_ITFLAG_HASINDEX) && + !(itflags & NPY_ITFLAG_BUFFER)) { + /* + * If RemoveAxis may be called, the size check is delayed + * until either the multi index is removed, or GetIterNext + * is called. + */ + NIT_ITERSIZE(iter) = -1; + break; + } + else { + PyErr_SetString(PyExc_ValueError, "iterator is too large"); + return 0; + } } } /* The range defaults to everything */ @@ -1727,7 +1698,7 @@ broadcast_error: { } for (iop = 0; iop < nop; ++iop) { if (op[iop] != NULL) { - tmp = npyiter_shape_string(PyArray_NDIM(op[iop]), + tmp = convert_shape_to_string(PyArray_NDIM(op[iop]), PyArray_DIMS(op[iop]), " "); if (tmp == NULL) { @@ -1751,7 +1722,7 @@ broadcast_error: { return 0; } - tmp = npyiter_shape_string(ndim, itershape, ""); + tmp = convert_shape_to_string(ndim, itershape, ""); if (tmp == NULL) { Py_DECREF(errmsg); return 0; @@ -1774,7 +1745,7 @@ broadcast_error: { int *axes = op_axes[iop]; tmpstr = (axes == NULL) ? " " : "->"; - tmp = npyiter_shape_string(PyArray_NDIM(op[iop]), + tmp = convert_shape_to_string(PyArray_NDIM(op[iop]), PyArray_DIMS(op[iop]), tmpstr); if (tmp == NULL) { @@ -1796,7 +1767,7 @@ broadcast_error: { remdims[idim] = -1; } } - tmp = npyiter_shape_string(ndim, remdims, " "); + tmp = convert_shape_to_string(ndim, remdims, " "); if (tmp == NULL) { return 0; } @@ -1818,7 +1789,7 @@ broadcast_error: { return 0; } - tmp = npyiter_shape_string(ndim, itershape, ""); + tmp = convert_shape_to_string(ndim, itershape, ""); if (tmp == NULL) { Py_DECREF(errmsg); return 0; @@ -1854,7 +1825,7 @@ operand_different_than_broadcast: { } /* Operand shape */ - tmp = npyiter_shape_string(PyArray_NDIM(op[iop]), + tmp = convert_shape_to_string(PyArray_NDIM(op[iop]), PyArray_DIMS(op[iop]), ""); if (tmp == NULL) { return 0; @@ -1887,7 +1858,7 @@ operand_different_than_broadcast: { return 0; } - tmp = npyiter_shape_string(ndim, remdims, "]"); + tmp = convert_shape_to_string(ndim, remdims, "]"); if (tmp == NULL) { return 0; } @@ -1907,7 +1878,7 @@ operand_different_than_broadcast: { } /* Broadcast shape */ - tmp = npyiter_shape_string(ndim, broadcast_shape, ""); + tmp = convert_shape_to_string(ndim, broadcast_shape, ""); if (tmp == NULL) { return 0; } diff --git a/numpy/core/src/multiarray/nditer_pywrap.c b/numpy/core/src/multiarray/nditer_pywrap.c index b3eda8669..7e40377b2 100644 --- a/numpy/core/src/multiarray/nditer_pywrap.c +++ b/numpy/core/src/multiarray/nditer_pywrap.c @@ -37,12 +37,16 @@ struct NewNpyArrayIterObject_tag { char writeflags[NPY_MAXARGS]; }; -void npyiter_cache_values(NewNpyArrayIterObject *self) +static int npyiter_cache_values(NewNpyArrayIterObject *self) { NpyIter *iter = self->iter; /* iternext and get_multi_index functions */ self->iternext = NpyIter_GetIterNext(iter, NULL); + if (self->iternext == NULL) { + return -1; + } + if (NpyIter_HasMultiIndex(iter) && !NpyIter_HasDelayedBufAlloc(iter)) { self->get_multi_index = NpyIter_GetGetMultiIndex(iter, NULL); } @@ -67,6 +71,7 @@ void npyiter_cache_values(NewNpyArrayIterObject *self) /* The read/write settings */ NpyIter_GetReadFlags(iter, self->readflags); NpyIter_GetWriteFlags(iter, self->writeflags); + return 0; } static PyObject * @@ -803,7 +808,9 @@ npyiter_init(NewNpyArrayIterObject *self, PyObject *args, PyObject *kwds) } /* Cache some values for the member functions to use */ - npyiter_cache_values(self); + if (npyiter_cache_values(self) < 0) { + goto fail; + } if (NpyIter_GetIterSize(self->iter) == 0) { self->started = 1; @@ -1068,7 +1075,10 @@ NpyIter_NestedIters(PyObject *NPY_UNUSED(self), } /* Cache some values for the member functions to use */ - npyiter_cache_values(iter); + if (npyiter_cache_values(iter) < 0) { + Py_DECREF(ret); + goto fail; + } if (NpyIter_GetIterSize(iter->iter) == 0) { iter->started = 1; @@ -1242,7 +1252,10 @@ npyiter_copy(NewNpyArrayIterObject *self) } /* Cache some values for the member functions to use */ - npyiter_cache_values(iter); + if (npyiter_cache_values(iter) < 0) { + Py_DECREF(iter); + return NULL; + } iter->started = self->started; iter->finished = self->finished; @@ -1287,7 +1300,9 @@ npyiter_remove_axis(NewNpyArrayIterObject *self, PyObject *args) return NULL; } /* RemoveAxis invalidates cached values */ - npyiter_cache_values(self); + if (npyiter_cache_values(self) < 0) { + return NULL; + } /* RemoveAxis also resets the iterator */ if (NpyIter_GetIterSize(self->iter) == 0) { self->started = 1; @@ -1532,6 +1547,9 @@ static PyObject *npyiter_multi_index_get(NewNpyArrayIterObject *self) ndim = NpyIter_GetNDim(self->iter); self->get_multi_index(self->iter, multi_index); ret = PyTuple_New(ndim); + if (ret == NULL) { + return NULL; + } for (idim = 0; idim < ndim; ++idim) { PyTuple_SET_ITEM(ret, idim, PyInt_FromLong(multi_index[idim])); @@ -1590,6 +1608,7 @@ npyiter_multi_index_set(NewNpyArrayIterObject *self, PyObject *value) PyObject *v = PySequence_GetItem(value, idim); multi_index[idim] = PyInt_AsLong(v); if (multi_index[idim]==-1 && PyErr_Occurred()) { + Py_XDECREF(v); return -1; } } @@ -2003,9 +2022,12 @@ npyiter_seq_item(NewNpyArrayIterObject *self, Py_ssize_t i) ret_ndim, &innerloopsize, &innerstride, dataptr, self->writeflags[i] ? NPY_ARRAY_WRITEABLE : 0, NULL); + if (ret == NULL) { + return NULL; + } Py_INCREF(self); if (PyArray_SetBaseObject(ret, (PyObject *)self) < 0) { - Py_DECREF(ret); + Py_XDECREF(ret); return NULL; } diff --git a/numpy/core/src/multiarray/nditer_templ.c.src b/numpy/core/src/multiarray/nditer_templ.c.src index 59aae244b..8976b132e 100644 --- a/numpy/core/src/multiarray/nditer_templ.c.src +++ b/numpy/core/src/multiarray/nditer_templ.c.src @@ -347,6 +347,16 @@ NpyIter_GetIterNext(NpyIter *iter, char **errmsg) int ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); + if (NIT_ITERSIZE(iter) < 0) { + if (errmsg == NULL) { + PyErr_SetString(PyExc_ValueError, "iterator is too large"); + } + else { + *errmsg = "iterator is too large"; + } + return NULL; + } + /* * When there is just one iteration and buffering is disabled * the iternext function is very simple. diff --git a/numpy/core/src/multiarray/number.c b/numpy/core/src/multiarray/number.c index 483a22776..a26a93c1d 100644 --- a/numpy/core/src/multiarray/number.c +++ b/numpy/core/src/multiarray/number.c @@ -115,7 +115,7 @@ has_ufunc_attr(PyObject * obj) { NPY_NO_EXPORT int needs_right_binop_forward(PyObject *self, PyObject *other, - char *right_name, int inplace_op) + const char *right_name, int inplace_op) { if (other == NULL || self == NULL || @@ -127,7 +127,7 @@ needs_right_binop_forward(PyObject *self, PyObject *other, */ return 0; } - if (!inplace_op && PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) || + if ((!inplace_op && PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) || !PyArray_Check(self)) { /* * Bail out if Python would already have called the right-hand @@ -146,7 +146,8 @@ needs_right_binop_forward(PyObject *self, PyObject *other, #define GIVE_UP_IF_HAS_RIGHT_BINOP(m1, m2, left_name, right_name, inplace) \ do { \ - if (needs_right_binop_forward(m1, m2, right_name, inplace)) { \ + if (needs_right_binop_forward((PyObject *)m1, m2, right_name, \ + inplace)) { \ Py_INCREF(Py_NotImplemented); \ return Py_NotImplemented; \ } \ @@ -390,32 +391,41 @@ is_scalar_with_conversion(PyObject *o2, double* out_exponent) *out_exponent = PyFloat_AsDouble(o2); return NPY_FLOAT_SCALAR; } - if ((PyArray_IsZeroDim(o2) && - ((PyArray_ISINTEGER((PyArrayObject *)o2) || - (optimize_fpexps && PyArray_ISFLOAT((PyArrayObject *)o2))))) || - PyArray_IsScalar(o2, Integer) || - (optimize_fpexps && PyArray_IsScalar(o2, Floating))) { - temp = Py_TYPE(o2)->tp_as_number->nb_float(o2); - if (temp != NULL) { + if (PyArray_Check(o2)) { + if ((PyArray_NDIM((PyArrayObject *)o2) == 0) && + ((PyArray_ISINTEGER((PyArrayObject *)o2) || + (optimize_fpexps && PyArray_ISFLOAT((PyArrayObject *)o2))))) { + temp = Py_TYPE(o2)->tp_as_number->nb_float(o2); + if (temp == NULL) { + return NPY_NOSCALAR; + } *out_exponent = PyFloat_AsDouble(o2); Py_DECREF(temp); - if (PyArray_IsZeroDim(o2)) { - if (PyArray_ISINTEGER((PyArrayObject *)o2)) { - return NPY_INTPOS_SCALAR; - } - else { /* ISFLOAT */ - return NPY_FLOAT_SCALAR; - } + if (PyArray_ISINTEGER((PyArrayObject *)o2)) { + return NPY_INTPOS_SCALAR; } - else if PyArray_IsScalar(o2, Integer) { - return NPY_INTPOS_SCALAR; - } - else { /* IsScalar(o2, Floating) */ + else { /* ISFLOAT */ return NPY_FLOAT_SCALAR; } } } - if (PyIndex_Check(o2)) { + else if (PyArray_IsScalar(o2, Integer) || + (optimize_fpexps && PyArray_IsScalar(o2, Floating))) { + temp = Py_TYPE(o2)->tp_as_number->nb_float(o2); + if (temp == NULL) { + return NPY_NOSCALAR; + } + *out_exponent = PyFloat_AsDouble(o2); + Py_DECREF(temp); + + if (PyArray_IsScalar(o2, Integer)) { + return NPY_INTPOS_SCALAR; + } + else { /* IsScalar(o2, Floating) */ + return NPY_FLOAT_SCALAR; + } + } + else if (PyIndex_Check(o2)) { PyObject* value = PyNumber_Index(o2); Py_ssize_t val; if (value==NULL) { diff --git a/numpy/core/src/multiarray/number.h b/numpy/core/src/multiarray/number.h index 63ea40696..4667b6b99 100644 --- a/numpy/core/src/multiarray/number.h +++ b/numpy/core/src/multiarray/number.h @@ -70,7 +70,7 @@ PyArray_GenericAccumulateFunction(PyArrayObject *m1, PyObject *op, int axis, int rtype, PyArrayObject *out); NPY_NO_EXPORT int -needs_right_binop_forward(PyObject *self, PyObject *other, char *right_name, - int is_inplace); +needs_right_binop_forward(PyObject *self, PyObject *other, + const char *right_name, int is_inplace); #endif diff --git a/numpy/core/src/multiarray/numpymemoryview.c b/numpy/core/src/multiarray/numpymemoryview.c index 27c02e592..ccc5f33ed 100644 --- a/numpy/core/src/multiarray/numpymemoryview.c +++ b/numpy/core/src/multiarray/numpymemoryview.c @@ -252,7 +252,6 @@ NPY_NO_EXPORT PyObject * PyMemorySimpleView_FromObject(PyObject *base) { PyMemorySimpleViewObject *mview = NULL; - Py_buffer view; if (Py_TYPE(base)->tp_as_buffer == NULL || Py_TYPE(base)->tp_as_buffer->bf_getbuffer == NULL) { @@ -263,17 +262,19 @@ PyMemorySimpleView_FromObject(PyObject *base) return NULL; } - memset(&view, 0, sizeof(Py_buffer)); - if (PyObject_GetBuffer(base, &view, PyBUF_FULL_RO) < 0) - return NULL; - mview = (PyMemorySimpleViewObject *) PyObject_GC_New(PyMemorySimpleViewObject, &PyMemorySimpleView_Type); if (mview == NULL) { - PyBuffer_Release(&view); return NULL; } - memcpy(&mview->view, &view, sizeof(Py_buffer)); + + memset(&mview->view, 0, sizeof(Py_buffer)); + mview->base = NULL; + if (PyObject_GetBuffer(base, &mview->view, PyBUF_FULL_RO) < 0) { + Py_DECREF(mview); + return NULL; + } + mview->base = base; Py_INCREF(base); diff --git a/numpy/core/src/multiarray/refcount.c b/numpy/core/src/multiarray/refcount.c index b067cd948..eab11e933 100644 --- a/numpy/core/src/multiarray/refcount.c +++ b/numpy/core/src/multiarray/refcount.c @@ -70,7 +70,7 @@ PyArray_Item_XDECREF(char *data, PyArray_Descr *descr) NPY_COPY_PYOBJECT_PTR(&temp, data); Py_XDECREF(temp); } - else if PyDataType_HASFIELDS(descr) { + else if (PyDataType_HASFIELDS(descr)) { PyObject *key, *value, *title = NULL; PyArray_Descr *new; int offset; diff --git a/numpy/core/src/multiarray/scalarapi.c b/numpy/core/src/multiarray/scalarapi.c index 9dfd3c4c8..d71823566 100644 --- a/numpy/core/src/multiarray/scalarapi.c +++ b/numpy/core/src/multiarray/scalarapi.c @@ -275,6 +275,9 @@ PyArray_FromScalar(PyObject *scalar, PyArray_Descr *outcode) /* convert to 0-dim array of scalar typecode */ typecode = PyArray_DescrFromScalar(scalar); + if (typecode == NULL) { + return NULL; + } if ((typecode->type_num == NPY_VOID) && !(((PyVoidScalarObject *)scalar)->flags & NPY_ARRAY_OWNDATA) && outcode == NULL) { @@ -544,6 +547,9 @@ PyArray_DescrFromScalar(PyObject *sc) /* Timedelta */ descr = PyArray_DescrNewFromType(NPY_TIMEDELTA); } + if (descr == NULL) { + return NULL; + } dt_data = &(((PyArray_DatetimeDTypeMetaData *)descr->c_metadata)->meta); memcpy(dt_data, &((PyDatetimeScalarObject *)sc)->obmeta, sizeof(PyArray_DatetimeMetaData)); @@ -628,7 +634,7 @@ PyArray_Scalar(void *data, PyArray_Descr *descr, PyObject *base) copyswap = descr->f->copyswap; type = descr->typeobj; swap = !PyArray_ISNBO(descr->byteorder); - if PyTypeNum_ISSTRING(type_num) { + if (PyTypeNum_ISSTRING(type_num)) { /* Eliminate NULL bytes */ char *dptr = data; @@ -825,8 +831,9 @@ PyArray_Scalar(void *data, PyArray_Descr *descr, PyObject *base) /*NUMPY_API * - *Return either an array or the appropriate Python object if the array - *is 0d and matches a Python type. + * Return either an array or the appropriate Python object if the array + * is 0d and matches a Python type. + * steals reference to mp */ NPY_NO_EXPORT PyObject * PyArray_Return(PyArrayObject *mp) diff --git a/numpy/core/src/multiarray/scalartypes.c.src b/numpy/core/src/multiarray/scalartypes.c.src index 8b7269676..110bef248 100644 --- a/numpy/core/src/multiarray/scalartypes.c.src +++ b/numpy/core/src/multiarray/scalartypes.c.src @@ -128,6 +128,18 @@ gentype_dealloc(PyObject *v) Py_TYPE(v)->tp_free(v); } +static void +gentype_free(PyObject *v) +{ + /* + * have an explicit tp_free to enforce inheritance from it. + * PyObject_Free is also the tp_free of PyBaseObject so python does not + * COPYSLOT it, instead it takes the next parent PyInt which has a + * different allocator + */ + PyObject_Free(v); +} + static PyObject * gentype_power(PyObject *m1, PyObject *m2, PyObject *NPY_UNUSED(m3)) @@ -421,8 +433,7 @@ gentype_format(PyObject *self, PyObject *args) Py_DECREF(dtype); } else { - obj = self; - Py_INCREF(obj); + obj = PyObject_Str(self); } if (obj == NULL) { @@ -965,6 +976,9 @@ static PyObject * dval = (double)(((Py@CHAR@LongDoubleScalarObject *)self)->obval)@POST@; obj = Py@KIND@_FromDouble(dval); + if (obj == NULL) { + return NULL; + } ret = Py_TYPE(obj)->tp_as_number->nb_@name@(obj); Py_DECREF(obj); return ret; @@ -989,6 +1003,9 @@ static PyObject * dval = (double)(((Py@CHAR@LongDoubleScalarObject *)self)->obval)@POST@; obj = Py@KIND@_FromDouble(dval); + if (obj == NULL) { + return NULL; + } ret = Py_TYPE(obj)->tp_as_number->nb_@name@(obj); Py_DECREF(obj); return ret; @@ -1065,7 +1082,11 @@ gentype_richcompare(PyObject *self, PyObject *other, int cmp_op) if (arr == NULL) { return NULL; } - ret = Py_TYPE(arr)->tp_richcompare(arr, other, cmp_op); + /* + * Call via PyObject_RichCompare to ensure that other.__eq__ + * has a chance to run when necessary + */ + ret = PyObject_RichCompare(arr, other, cmp_op); Py_DECREF(arr); return ret; } @@ -1104,6 +1125,21 @@ voidtype_dtypedescr_get(PyVoidScalarObject *self) static PyObject * +inttype_numerator_get(PyObject *self) +{ + Py_INCREF(self); + return self; +} + + +static PyObject * +inttype_denominator_get(PyObject *self) +{ + return PyInt_FromLong(1); +} + + +static PyObject * gentype_data_get(PyObject *self) { #if defined(NPY_PY3K) @@ -1487,9 +1523,9 @@ gentype_wraparray(PyObject *NPY_UNUSED(scalar), PyObject *args) */ /**begin repeat * - * #name = tolist, item, tostring, astype, copy, __deepcopy__, searchsorted, - * view, swapaxes, conj, conjugate, nonzero, flatten, ravel, fill, - * transpose, newbyteorder# + * #name = tolist, item, tostring, tobytes, astype, copy, __deepcopy__, + * searchsorted, view, swapaxes, conj, conjugate, nonzero, flatten, + * ravel, fill, transpose, newbyteorder# */ static PyObject * gentype_@name@(PyObject *self, PyObject *args) @@ -1833,6 +1869,9 @@ static PyMethodDef gentype_methods[] = { {"itemset", (PyCFunction)gentype_itemset, METH_VARARGS, NULL}, + {"tobytes", + (PyCFunction)gentype_tobytes, + METH_VARARGS, NULL}, {"tofile", (PyCFunction)gentype_tofile, METH_VARARGS | METH_KEYWORDS, NULL}, @@ -2044,6 +2083,20 @@ static PyMethodDef voidtype_methods[] = { {NULL, NULL, 0, NULL} }; +static PyGetSetDef inttype_getsets[] = { + {"numerator", + (getter)inttype_numerator_get, + (setter)0, + "numerator of value (the value itself)", + NULL}, + {"denominator", + (getter)inttype_denominator_get, + (setter)0, + "denominator of value (1)", + NULL}, + {NULL, NULL, NULL, NULL, NULL} +}; + /**begin repeat * #name = cfloat,clongdouble# */ @@ -2435,10 +2488,13 @@ object_arrtype_dealloc(PyObject *v) /* We are inheriting from a Python type as well so \ give it first dibs on conversion */ \ sup = (PyTypeObject *)PyTuple_GET_ITEM(type->tp_bases, num); \ - robj = sup->tp_new(type, args, kwds); \ - if (robj != NULL) goto finish; \ - if (PyTuple_GET_SIZE(args)!=1) return NULL; \ - PyErr_Clear(); \ + /* Prevent recursion */ \ + if (thisfunc != sup->tp_new) { \ + robj = sup->tp_new(type, args, kwds); \ + if (robj != NULL) goto finish; \ + if (PyTuple_GET_SIZE(args)!=1) return NULL; \ + PyErr_Clear(); \ + } \ /* now do default conversion */ \ } @@ -2474,6 +2530,9 @@ static PyObject * PyObject *robj; PyArrayObject *arr; PyArray_Descr *typecode = NULL; +#if (@work@ != 0) || (@default@ == 1) + void *thisfunc = (void *)@name@_arrtype_new; +#endif #if !(@default@ == 2) int itemsize; void *dest, *src; @@ -2930,7 +2989,7 @@ long_arrtype_hash(PyObject *obj) * #Char = ,U# * #Word = ,Unsigned# */ -static npy_hash_t +static NPY_INLINE npy_hash_t @char@longlong_arrtype_hash(PyObject *obj) { PyObject * l = PyLong_From@Word@LongLong( @@ -3342,33 +3401,15 @@ gen_arrtype_subscript(PyObject *self, PyObject *key) * the data where N is the number of None's in <???>. */ PyObject *res, *ret; - int N; - if (key == Py_Ellipsis || key == Py_None || - PyTuple_Check(key)) { - res = PyArray_FromScalar(self, NULL); - } - else { + res = PyArray_FromScalar(self, NULL); + + ret = array_subscript((PyArrayObject *)res, key); + Py_DECREF(res); + if (ret == NULL) { PyErr_SetString(PyExc_IndexError, - "invalid index to scalar variable."); - return NULL; + "invalid index to scalar variable."); } - if (key == Py_Ellipsis) { - return res; - } - if (key == Py_None) { - ret = add_new_axes_0d((PyArrayObject *)res, 1); - Py_DECREF(res); - return ret; - } - /* Must be a Tuple */ - N = count_new_axes_0d(key); - if (N < 0) { - Py_DECREF(res); - return NULL; - } - ret = add_new_axes_0d((PyArrayObject *)res, N); - Py_DECREF(res); return ret; } @@ -3985,7 +4026,7 @@ initialize_numeric_types(void) PyGenericArrType_Type.tp_getset = gentype_getsets; PyGenericArrType_Type.tp_new = NULL; PyGenericArrType_Type.tp_alloc = gentype_alloc; - PyGenericArrType_Type.tp_free = PyObject_Free; + PyGenericArrType_Type.tp_free = (freefunc)gentype_free; PyGenericArrType_Type.tp_repr = gentype_repr; PyGenericArrType_Type.tp_str = gentype_str; PyGenericArrType_Type.tp_richcompare = gentype_richcompare; @@ -4009,7 +4050,7 @@ initialize_numeric_types(void) PyBoolArrType_Type.tp_as_number->nb_index = (unaryfunc)bool_index; PyStringArrType_Type.tp_alloc = NULL; - PyStringArrType_Type.tp_free = PyObject_Free; + PyStringArrType_Type.tp_free = NULL; PyStringArrType_Type.tp_repr = stringtype_repr; PyStringArrType_Type.tp_str = stringtype_str; @@ -4022,6 +4063,8 @@ initialize_numeric_types(void) PyVoidArrType_Type.tp_as_mapping = &voidtype_as_mapping; PyVoidArrType_Type.tp_as_sequence = &voidtype_as_sequence; + PyIntegerArrType_Type.tp_getset = inttype_getsets; + /**begin repeat * #NAME= Number, Integer, SignedInteger, UnsignedInteger, Inexact, * Floating, ComplexFloating, Flexible, Character# diff --git a/numpy/core/src/multiarray/sequence.c b/numpy/core/src/multiarray/sequence.c index 310c01084..520732acf 100644 --- a/numpy/core/src/multiarray/sequence.c +++ b/numpy/core/src/multiarray/sequence.c @@ -88,7 +88,7 @@ array_slice(PyArrayObject *self, Py_ssize_t ilow, Py_ssize_t ihigh) static int -array_ass_slice(PyArrayObject *self, Py_ssize_t ilow, +array_assign_slice(PyArrayObject *self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { int ret; PyArrayObject *tmp; @@ -135,8 +135,8 @@ NPY_NO_EXPORT PySequenceMethods array_as_sequence = { (ssizeargfunc)NULL, (ssizeargfunc)array_item, (ssizessizeargfunc)array_slice, - (ssizeobjargproc)array_ass_item, /*sq_ass_item*/ - (ssizessizeobjargproc)array_ass_slice, /*sq_ass_slice*/ + (ssizeobjargproc)array_assign_item, /*sq_ass_item*/ + (ssizessizeobjargproc)array_assign_slice, /*sq_ass_slice*/ (objobjproc) array_contains, /*sq_contains */ (binaryfunc) NULL, /*sg_inplace_concat */ (ssizeargfunc)NULL, diff --git a/numpy/core/src/multiarray/shape.c b/numpy/core/src/multiarray/shape.c index 41c670df4..8b73f4709 100644 --- a/numpy/core/src/multiarray/shape.c +++ b/numpy/core/src/multiarray/shape.c @@ -93,7 +93,8 @@ PyArray_Resize(PyArrayObject *self, PyArray_Dims *newshape, int refcheck, || (PyArray_BASE(self) != NULL) || (((PyArrayObject_fields *)self)->weakreflist != NULL)) { PyErr_SetString(PyExc_ValueError, - "cannot resize an array references or is referenced\n"\ + "cannot resize an array that "\ + "references or is referenced\n"\ "by another array in this way. Use the resize function"); return NULL; } @@ -775,7 +776,8 @@ PyArray_Transpose(PyArrayObject *ap, PyArray_Dims *permute) PyArray_DIMS(ret)[i] = PyArray_DIMS(ap)[permutation[i]]; PyArray_STRIDES(ret)[i] = PyArray_STRIDES(ap)[permutation[i]]; } - PyArray_UpdateFlags(ret, NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS); + PyArray_UpdateFlags(ret, NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS | + NPY_ARRAY_ALIGNED); return (PyObject *)ret; } @@ -783,7 +785,7 @@ PyArray_Transpose(PyArrayObject *ap, PyArray_Dims *permute) * Sorts items so stride is descending, because C-order * is the default in the face of ambiguity. */ -int _npy_stride_sort_item_comparator(const void *a, const void *b) +static int _npy_stride_sort_item_comparator(const void *a, const void *b) { npy_intp astride = ((const npy_stride_sort_item *)a)->stride, bstride = ((const npy_stride_sort_item *)b)->stride; diff --git a/numpy/core/src/npymath/ieee754.c.src b/numpy/core/src/npymath/ieee754.c.src index 4b007f18d..b8f6889e1 100644 --- a/numpy/core/src/npymath/ieee754.c.src +++ b/numpy/core/src/npymath/ieee754.c.src @@ -46,7 +46,7 @@ int _npy_signbit_ld(long double x) * p >= 0, returnx x + nulp * p < 0, returnx x - nulp */ -double _next(double x, int p) +static double _next(double x, int p) { volatile double t; npy_int32 hx, hy, ix; @@ -92,7 +92,7 @@ double _next(double x, int p) return x; } -float _nextf(float x, int p) +static float _nextf(float x, int p) { volatile float t; npy_int32 hx, hy, ix; @@ -133,7 +133,8 @@ float _nextf(float x, int p) return x; } -#ifdef HAVE_LDOUBLE_DOUBLE_DOUBLE_BE +#if defined(HAVE_LDOUBLE_DOUBLE_DOUBLE_BE) || \ + defined(HAVE_LDOUBLE_DOUBLE_DOUBLE_LE) /* * FIXME: this is ugly and untested. The asm part only works with gcc, and we @@ -178,7 +179,7 @@ do { \ (d) = qw_u.value; \ } while (0) -npy_longdouble _nextl(npy_longdouble x, int p) +static npy_longdouble _nextl(npy_longdouble x, int p) { npy_int64 hx,ihx,ilx; npy_uint64 lx; @@ -256,7 +257,7 @@ npy_longdouble _nextl(npy_longdouble x, int p) } } #else -npy_longdouble _nextl(npy_longdouble x, int p) +static npy_longdouble _nextl(npy_longdouble x, int p) { volatile npy_longdouble t; union IEEEl2bitsrep ux; diff --git a/numpy/core/src/npymath/npy_math.c.src b/numpy/core/src/npymath/npy_math.c.src index 61f1d79ab..05af0b132 100644 --- a/numpy/core/src/npymath/npy_math.c.src +++ b/numpy/core/src/npymath/npy_math.c.src @@ -65,14 +65,19 @@ #ifndef HAVE_EXPM1 double npy_expm1(double x) { - const double u = npy_exp(x); - - if (u == 1.0) { + if (npy_isinf(x) && x > 0) { return x; - } else if (u - 1.0 == -1.0) { - return -1; - } else { - return (u - 1.0) * x/npy_log(u); + } + else { + const double u = npy_exp(x); + + if (u == 1.0) { + return x; + } else if (u - 1.0 == -1.0) { + return -1; + } else { + return (u - 1.0) * x/npy_log(u); + } } } #endif @@ -80,13 +85,18 @@ double npy_expm1(double x) #ifndef HAVE_LOG1P double npy_log1p(double x) { - const double u = 1. + x; - const double d = u - 1.; - - if (d == 0) { + if (npy_isinf(x) && x > 0) { return x; - } else { - return npy_log(u) * x / d; + } + else { + const double u = 1. + x; + const double d = u - 1.; + + if (d == 0) { + return x; + } else { + return npy_log(u) * x / d; + } } } #endif @@ -289,7 +299,35 @@ double npy_exp2(double x) #ifndef HAVE_LOG2 double npy_log2(double x) { - return NPY_LOG2E*npy_log(x); +#ifdef HAVE_FREXP + if (!npy_isfinite(x) || x <= 0.) { + /* special value result */ + return npy_log(x); + } + else { + /* + * fallback implementation copied from python3.4 math.log2 + * provides int(log(2**i)) == i for i 1-64 in default rounding mode. + * + * We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when + * x is just greater than 1.0: in that case e is 1, log(m) is negative, + * and we get significant cancellation error from the addition of + * log(m) / log(2) to e. The slight rewrite of the expression below + * avoids this problem. + */ + int e; + double m = frexp(x, &e); + if (x >= 1.0) { + return log(2.0 * m) / log(2.0) + (e - 1); + } + else { + return log(m) / log(2.0) + e; + } + } +#else + /* does not provide int(log(2**i)) == i */ + return NPY_LOG2E * npy_log(x); +#endif } #endif diff --git a/numpy/core/src/npymath/npy_math_private.h b/numpy/core/src/npymath/npy_math_private.h index 2bca6bf60..b3b1690be 100644 --- a/numpy/core/src/npymath/npy_math_private.h +++ b/numpy/core/src/npymath/npy_math_private.h @@ -435,7 +435,8 @@ do { \ typedef npy_uint32 ldouble_sign_t; #endif -#ifndef HAVE_LDOUBLE_DOUBLE_DOUBLE_BE +#if !defined(HAVE_LDOUBLE_DOUBLE_DOUBLE_BE) && \ + !defined(HAVE_LDOUBLE_DOUBLE_DOUBLE_LE) /* Get the sign bit of x. x should be of type IEEEl2bitsrep */ #define GET_LDOUBLE_SIGN(x) \ (((x).a[LDBL_SIGN_INDEX] & LDBL_SIGN_MASK) >> LDBL_SIGN_SHIFT) diff --git a/numpy/core/src/npysort/binsearch.c.src b/numpy/core/src/npysort/binsearch.c.src new file mode 100644 index 000000000..a1a07039a --- /dev/null +++ b/numpy/core/src/npysort/binsearch.c.src @@ -0,0 +1,240 @@ +/* -*- c -*- */ +#define NPY_NO_DEPRECATED_API NPY_API_VERSION + +#include "npy_sort.h" +#include "npysort_common.h" +#include "npy_binsearch.h" + +#define NOT_USED NPY_UNUSED(unused) + +/* + ***************************************************************************** + ** NUMERIC SEARCHES ** + ***************************************************************************** + */ + +/**begin repeat + * + * #TYPE = BOOL, BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, + * LONGLONG, ULONGLONG, HALF, FLOAT, DOUBLE, LONGDOUBLE, + * CFLOAT, CDOUBLE, CLONGDOUBLE, DATETIME, TIMEDELTA# + * #suff = bool, byte, ubyte, short, ushort, int, uint, long, ulong, + * longlong, ulonglong, half, float, double, longdouble, + * cfloat, cdouble, clongdouble, datetime, timedelta# + * #type = npy_bool, npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, + * npy_uint, npy_long, npy_ulong, npy_longlong, npy_ulonglong, + * npy_ushort, npy_float, npy_double, npy_longdouble, npy_cfloat, + * npy_cdouble, npy_clongdouble, npy_datetime, npy_timedelta# + */ + +#define @TYPE@_LTE(a, b) (!@TYPE@_LT((b), (a))) + +/**begin repeat1 + * + * #side = left, right# + * #CMP = LT, LTE# + */ + +NPY_VISIBILITY_HIDDEN void +binsearch_@side@_@suff@(const char *arr, const char *key, char *ret, + npy_intp arr_len, npy_intp key_len, + npy_intp arr_str, npy_intp key_str, npy_intp ret_str, + PyArrayObject *NOT_USED) +{ + npy_intp min_idx = 0; + npy_intp max_idx = arr_len; + @type@ last_key_val = *(const @type@ *)key; + + for (; key_len > 0; key_len--, key += key_str, ret += ret_str) { + const @type@ key_val = *(const @type@ *)key; + /* + * Updating only one of the indices based on the previous key + * gives the search a big boost when keys are sorted, but slightly + * slows down things for purely random ones. + */ + if (@TYPE@_LT(last_key_val, key_val)) { + max_idx = arr_len; + } + else { + min_idx = 0; + max_idx = (max_idx < arr_len) ? (max_idx + 1) : arr_len; + } + + last_key_val = key_val; + + while (min_idx < max_idx) { + const npy_intp mid_idx = min_idx + ((max_idx - min_idx) >> 1); + const @type@ mid_val = *(const @type@ *)(arr + mid_idx*arr_str); + if (@TYPE@_@CMP@(mid_val, key_val)) { + min_idx = mid_idx + 1; + } + else { + max_idx = mid_idx; + } + } + *(npy_intp *)ret = min_idx; + } +} + +NPY_VISIBILITY_HIDDEN int +argbinsearch_@side@_@suff@(const char *arr, const char *key, + const char *sort, char *ret, + npy_intp arr_len, npy_intp key_len, + npy_intp arr_str, npy_intp key_str, + npy_intp sort_str, npy_intp ret_str, + PyArrayObject *NOT_USED) +{ + npy_intp min_idx = 0; + npy_intp max_idx = arr_len; + @type@ last_key_val = *(const @type@ *)key; + + for (; key_len > 0; key_len--, key += key_str, ret += ret_str) { + const @type@ key_val = *(const @type@ *)key; + /* + * Updating only one of the indices based on the previous key + * gives the search a big boost when keys are sorted, but slightly + * slows down things for purely random ones. + */ + if (@TYPE@_LT(last_key_val, key_val)) { + max_idx = arr_len; + } + else { + min_idx = 0; + max_idx = (max_idx < arr_len) ? (max_idx + 1) : arr_len; + } + + last_key_val = key_val; + + while (min_idx < max_idx) { + const npy_intp mid_idx = min_idx + ((max_idx - min_idx) >> 1); + const npy_intp sort_idx = *(npy_intp *)(sort + mid_idx*sort_str); + @type@ mid_val; + + if (sort_idx < 0 || sort_idx >= arr_len) { + return -1; + } + + mid_val = *(const @type@ *)(arr + sort_idx*arr_str); + + if (@TYPE@_@CMP@(mid_val, key_val)) { + min_idx = mid_idx + 1; + } + else { + max_idx = mid_idx; + } + } + *(npy_intp *)ret = min_idx; + } + return 0; +} + +/**end repeat1**/ +/**end repeat**/ + +/* + ***************************************************************************** + ** GENERIC SEARCH ** + ***************************************************************************** + */ + + /**begin repeat + * + * #side = left, right# + * #CMP = <, <=# + */ + +NPY_VISIBILITY_HIDDEN void +npy_binsearch_@side@(const char *arr, const char *key, char *ret, + npy_intp arr_len, npy_intp key_len, + npy_intp arr_str, npy_intp key_str, npy_intp ret_str, + PyArrayObject *cmp) +{ + PyArray_CompareFunc *compare = PyArray_DESCR(cmp)->f->compare; + npy_intp min_idx = 0; + npy_intp max_idx = arr_len; + const char *last_key = key; + + for (; key_len > 0; key_len--, key += key_str, ret += ret_str) { + /* + * Updating only one of the indices based on the previous key + * gives the search a big boost when keys are sorted, but slightly + * slows down things for purely random ones. + */ + if (compare(last_key, key, cmp) @CMP@ 0) { + max_idx = arr_len; + } + else { + min_idx = 0; + max_idx = (max_idx < arr_len) ? (max_idx + 1) : arr_len; + } + + last_key = key; + + while (min_idx < max_idx) { + const npy_intp mid_idx = min_idx + ((max_idx - min_idx) >> 1); + const char *arr_ptr = arr + mid_idx*arr_str; + + if (compare(arr_ptr, key, cmp) @CMP@ 0) { + min_idx = mid_idx + 1; + } + else { + max_idx = mid_idx; + } + } + *(npy_intp *)ret = min_idx; + } +} + +NPY_VISIBILITY_HIDDEN int +npy_argbinsearch_@side@(const char *arr, const char *key, + const char *sort, char *ret, + npy_intp arr_len, npy_intp key_len, + npy_intp arr_str, npy_intp key_str, + npy_intp sort_str, npy_intp ret_str, + PyArrayObject *cmp) +{ + PyArray_CompareFunc *compare = PyArray_DESCR(cmp)->f->compare; + npy_intp min_idx = 0; + npy_intp max_idx = arr_len; + const char *last_key = key; + + for (; key_len > 0; key_len--, key += key_str, ret += ret_str) { + /* + * Updating only one of the indices based on the previous key + * gives the search a big boost when keys are sorted, but slightly + * slows down things for purely random ones. + */ + if (compare(last_key, key, cmp) @CMP@ 0) { + max_idx = arr_len; + } + else { + min_idx = 0; + max_idx = (max_idx < arr_len) ? (max_idx + 1) : arr_len; + } + + last_key = key; + + while (min_idx < max_idx) { + const npy_intp mid_idx = min_idx + ((max_idx - min_idx) >> 1); + const npy_intp sort_idx = *(npy_intp *)(sort + mid_idx*sort_str); + const char *arr_ptr; + + if (sort_idx < 0 || sort_idx >= arr_len) { + return -1; + } + + arr_ptr = arr + sort_idx*arr_str; + + if (compare(arr_ptr, key, cmp) @CMP@ 0) { + min_idx = mid_idx + 1; + } + else { + max_idx = mid_idx; + } + } + *(npy_intp *)ret = min_idx; + } + return 0; +} + +/**end repeat**/ diff --git a/numpy/core/src/npysort/selection.c.src b/numpy/core/src/npysort/selection.c.src index 073b5847f..4167b2694 100644 --- a/numpy/core/src/npysort/selection.c.src +++ b/numpy/core/src/npysort/selection.c.src @@ -69,6 +69,7 @@ static NPY_INLINE void store_pivot(npy_intp pivot, npy_intp kth, * npy_uint, npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_ushort, npy_float, npy_double, npy_longdouble, npy_cfloat, * npy_cdouble, npy_clongdouble# + * #inexact = 0*11, 1*7# */ static npy_intp @@ -322,6 +323,20 @@ int store_pivot(kth, kth, pivots, npiv); return 0; } + else if (@inexact@ && kth == num - 1) { + /* useful to check if NaN present via partition(d, (x, -1)) */ + npy_intp k; + npy_intp maxidx = low; + @type@ maxval = v[IDX(low)]; + for (k = low + 1; k < num; k++) { + if (!@TYPE@_LT(v[IDX(k)], maxval)) { + maxidx = k; + maxval = v[IDX(k)]; + } + } + SWAP(SORTEE(kth), SORTEE(maxidx)); + return 0; + } /* dumb integer msb, float npy_log2 too slow for small parititions */ { @@ -375,7 +390,10 @@ int /* move pivot into position */ SWAP(SORTEE(low), SORTEE(hh)); - store_pivot(hh, kth, pivots, npiv); + /* kth pivot stored later */ + if (hh != kth) { + store_pivot(hh, kth, pivots, npiv); + } if (hh >= kth) high = hh - 1; @@ -385,10 +403,11 @@ int /* two elements */ if (high == low + 1) { - if (@TYPE@_LT(v[IDX(high)], v[IDX(low)])) + if (@TYPE@_LT(v[IDX(high)], v[IDX(low)])) { SWAP(SORTEE(high), SORTEE(low)) - store_pivot(low, kth, pivots, npiv); + } } + store_pivot(kth, kth, pivots, npiv); return 0; } diff --git a/numpy/core/src/private/lowlevel_strided_loops.h b/numpy/core/src/private/lowlevel_strided_loops.h index f2e5d02c3..a6bb4c7eb 100644 --- a/numpy/core/src/private/lowlevel_strided_loops.h +++ b/numpy/core/src/private/lowlevel_strided_loops.h @@ -326,6 +326,20 @@ PyArray_TransferMaskedStridedToNDim(npy_intp ndim, PyArray_MaskedStridedUnaryOp *stransfer, NpyAuxData *data); +NPY_NO_EXPORT int +mapiter_trivial_get(PyArrayObject *self, PyArrayObject *ind, + PyArrayObject *result); + +NPY_NO_EXPORT int +mapiter_trivial_set(PyArrayObject *self, PyArrayObject *ind, + PyArrayObject *result); + +NPY_NO_EXPORT int +mapiter_get(PyArrayMapIterObject *mit); + +NPY_NO_EXPORT int +mapiter_set(PyArrayMapIterObject *mit); + /* * Prepares shape and strides for a simple raw array iteration. * This sorts the strides into FORTRAN order, reverses any negative @@ -654,7 +668,7 @@ npy_bswap8_unaligned(char * x) PyArray_DIMS(arr2), \ PyArray_NDIM(arr1)) && \ (PyArray_FLAGS(arr1)&(NPY_ARRAY_C_CONTIGUOUS| \ - NPY_ARRAY_F_CONTIGUOUS)) == \ + NPY_ARRAY_F_CONTIGUOUS)) & \ (PyArray_FLAGS(arr2)&(NPY_ARRAY_C_CONTIGUOUS| \ NPY_ARRAY_F_CONTIGUOUS)) \ ) @@ -665,12 +679,12 @@ npy_bswap8_unaligned(char * x) PyArray_CHKFLAGS(arr, NPY_ARRAY_F_CONTIGUOUS) \ ) #define PyArray_PREPARE_TRIVIAL_ITERATION(arr, count, data, stride) \ - count = PyArray_SIZE(arr), \ - data = PyArray_BYTES(arr), \ + count = PyArray_SIZE(arr); \ + data = PyArray_BYTES(arr); \ stride = ((PyArray_NDIM(arr) == 0) ? 0 : \ ((PyArray_NDIM(arr) == 1) ? \ PyArray_STRIDE(arr, 0) : \ - PyArray_ITEMSIZE(arr))) \ + PyArray_ITEMSIZE(arr))); #define PyArray_TRIVIALLY_ITERABLE_PAIR(arr1, arr2) (\ diff --git a/numpy/core/src/private/npy_binsearch.h.src b/numpy/core/src/private/npy_binsearch.h.src new file mode 100644 index 000000000..3b2c59487 --- /dev/null +++ b/numpy/core/src/private/npy_binsearch.h.src @@ -0,0 +1,140 @@ +#ifndef __NPY_BINSEARCH_H__ +#define __NPY_BINSEARCH_H__ + +#include "npy_sort.h" +#include <numpy/npy_common.h> +#include <numpy/ndarraytypes.h> + +typedef void (PyArray_BinSearchFunc)(const char*, const char*, char*, + npy_intp, npy_intp, + npy_intp, npy_intp, npy_intp, + PyArrayObject*); + +typedef int (PyArray_ArgBinSearchFunc)(const char*, const char*, + const char*, char*, + npy_intp, npy_intp, npy_intp, + npy_intp, npy_intp, npy_intp, + PyArrayObject*); + +struct binsearch_map { + enum NPY_TYPES typenum; + PyArray_BinSearchFunc *binsearch[NPY_NSEARCHSIDES]; +}; + +struct argbinsearch_map { + enum NPY_TYPES typenum; + PyArray_ArgBinSearchFunc *argbinsearch[NPY_NSEARCHSIDES]; +}; + +/**begin repeat + * + * #side = left, right# + */ + +/**begin repeat1 + * + * #suff = bool, byte, ubyte, short, ushort, int, uint, long, ulong, + * longlong, ulonglong, half, float, double, longdouble, + * cfloat, cdouble, clongdouble, datetime, timedelta# + */ + +NPY_VISIBILITY_HIDDEN void +binsearch_@side@_@suff@(const char *arr, const char *key, char *ret, + npy_intp arr_len, npy_intp key_len, + npy_intp arr_str, npy_intp key_str, npy_intp ret_str, + PyArrayObject *unused); +NPY_VISIBILITY_HIDDEN int +argbinsearch_@side@_@suff@(const char *arr, const char *key, + const char *sort, char *ret, + npy_intp arr_len, npy_intp key_len, + npy_intp arr_str, npy_intp key_str, + npy_intp sort_str, npy_intp ret_str, + PyArrayObject *unused); +/**end repeat1**/ + +NPY_VISIBILITY_HIDDEN void +npy_binsearch_@side@(const char *arr, const char *key, char *ret, + npy_intp arr_len, npy_intp key_len, + npy_intp arr_str, npy_intp key_str, + npy_intp ret_str, PyArrayObject *cmp); +NPY_VISIBILITY_HIDDEN int +npy_argbinsearch_@side@(const char *arr, const char *key, + const char *sort, char *ret, + npy_intp arr_len, npy_intp key_len, + npy_intp arr_str, npy_intp key_str, + npy_intp sort_str, npy_intp ret_str, + PyArrayObject *cmp); +/**end repeat**/ + +/**begin repeat + * + * #arg = , arg# + * #Arg = , Arg# + */ + +static struct @arg@binsearch_map _@arg@binsearch_map[] = { + /* If adding new types, make sure to keep them ordered by type num */ + /**begin repeat1 + * + * #TYPE = BOOL, BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, + * LONGLONG, ULONGLONG, FLOAT, DOUBLE, LONGDOUBLE, + * CFLOAT, CDOUBLE, CLONGDOUBLE, DATETIME, TIMEDELTA, HALF# + * #suff = bool, byte, ubyte, short, ushort, int, uint, long, ulong, + * longlong, ulonglong, float, double, longdouble, + * cfloat, cdouble, clongdouble, datetime, timedelta, half# + */ + {NPY_@TYPE@, + { + &@arg@binsearch_left_@suff@, + &@arg@binsearch_right_@suff@, + }, + }, + /**end repeat1**/ +}; + +static PyArray_@Arg@BinSearchFunc *gen@arg@binsearch_map[] = { + &npy_@arg@binsearch_left, + &npy_@arg@binsearch_right, +}; + +static NPY_INLINE PyArray_@Arg@BinSearchFunc* +get_@arg@binsearch_func(PyArray_Descr *dtype, NPY_SEARCHSIDE side) +{ + static npy_intp num_funcs = sizeof(_@arg@binsearch_map) / + sizeof(_@arg@binsearch_map[0]); + npy_intp min_idx = 0; + npy_intp max_idx = num_funcs; + int type = dtype->type_num; + + if (side >= NPY_NSEARCHSIDES) { + return NULL; + } + + /* + * It seems only fair that a binary search function be searched for + * using a binary search... + */ + while (min_idx < max_idx) { + npy_intp mid_idx = min_idx + ((max_idx - min_idx) >> 1); + + if (_@arg@binsearch_map[mid_idx].typenum < type) { + min_idx = mid_idx + 1; + } + else { + max_idx = mid_idx; + } + } + + if (min_idx < num_funcs && _@arg@binsearch_map[min_idx].typenum == type) { + return _@arg@binsearch_map[min_idx].@arg@binsearch[side]; + } + + if (dtype->f->compare) { + return gen@arg@binsearch_map[side]; + } + + return NULL; +} +/**end repeat**/ + +#endif diff --git a/numpy/core/src/private/npy_config.h b/numpy/core/src/private/npy_config.h index 453dbd065..71d448ee9 100644 --- a/numpy/core/src/private/npy_config.h +++ b/numpy/core/src/private/npy_config.h @@ -10,6 +10,17 @@ #undef HAVE_HYPOT #endif +/* + * largest alignment the copy loops might require + * required as string, void and complex types might get copied using larger + * instructions than required to operate on them. E.g. complex float is copied + * in 8 byte moves but arithmetic on them only loads in 4 byte moves. + * the sparc platform may need that alignment for long doubles. + * amd64 is not harmed much by the bloat as the system provides 16 byte + * alignment by default. + */ +#define NPY_MAX_COPY_ALIGNMENT 16 + /* Safe to use ldexp and frexp for long double for MSVC builds */ #if (NPY_SIZEOF_LONGDOUBLE == NPY_SIZEOF_DOUBLE) || defined(_MSC_VER) #ifdef HAVE_LDEXP diff --git a/numpy/core/src/private/npy_fpmath.h b/numpy/core/src/private/npy_fpmath.h index 8a120cab7..86b9cf3da 100644 --- a/numpy/core/src/private/npy_fpmath.h +++ b/numpy/core/src/private/npy_fpmath.h @@ -29,6 +29,8 @@ #define HAVE_LDOUBLE_INTEL_EXTENDED_16_BYTES_LE #elif defined(NPY_CPU_PPC) || defined(NPY_CPU_PPC64) #define HAVE_LDOUBLE_IEEE_DOUBLE_16_BYTES_BE + #elif defined(NPY_CPU_PPC64LE) + #define HAVE_LDOUBLE_IEEE_DOUBLE_16_BYTES_LE #endif #endif #endif @@ -41,7 +43,8 @@ defined(HAVE_LDOUBLE_INTEL_EXTENDED_16_BYTES_LE) || \ defined(HAVE_LDOUBLE_INTEL_EXTENDED_12_BYTES_LE) || \ defined(HAVE_LDOUBLE_MOTOROLA_EXTENDED_12_BYTES_BE) || \ - defined(HAVE_LDOUBLE_DOUBLE_DOUBLE_BE)) + defined(HAVE_LDOUBLE_DOUBLE_DOUBLE_BE) || \ + defined(HAVE_LDOUBLE_DOUBLE_DOUBLE_LE)) #error No long double representation defined #endif diff --git a/numpy/core/src/private/npy_partition.h.src b/numpy/core/src/private/npy_partition.h.src index c03ecb0de..fd79068f7 100644 --- a/numpy/core/src/private/npy_partition.h.src +++ b/numpy/core/src/private/npy_partition.h.src @@ -41,28 +41,35 @@ * npy_cdouble, npy_clongdouble# */ -int introselect_@suff@(@type@ *v, npy_intp num, - npy_intp kth, - npy_intp * pivots, - npy_intp * npiv, - void *NOT_USED); -int aintroselect_@suff@(@type@ *v, npy_intp* tosort, npy_intp num, - npy_intp kth, - npy_intp * pivots, - npy_intp * npiv, - void *NOT_USED); +NPY_VISIBILITY_HIDDEN int introselect_@suff@(@type@ *v, npy_intp num, + npy_intp kth, + npy_intp * pivots, + npy_intp * npiv, + void *NOT_USED); +NPY_VISIBILITY_HIDDEN int aintroselect_@suff@(@type@ *v, npy_intp* tosort, npy_intp num, + npy_intp kth, + npy_intp * pivots, + npy_intp * npiv, + void *NOT_USED); /**end repeat**/ -int introselect_string(npy_char *vec, npy_intp cnt, npy_intp kth, PyArrayObject *arr); -int aintroselect_string(npy_char *vec, npy_intp *ind, npy_intp cnt, npy_intp kth, void *null); +NPY_VISIBILITY_HIDDEN int introselect_string(npy_char *vec, npy_intp cnt, + npy_intp kth, PyArrayObject *arr); +NPY_VISIBILITY_HIDDEN int aintroselect_string(npy_char *vec, npy_intp *ind, + npy_intp cnt, npy_intp kth, + void *null); -int introselect_unicode(npy_ucs4 *vec, npy_intp cnt, npy_intp kth, PyArrayObject *arr); -int aintroselect_unicode(npy_ucs4 *vec, npy_intp *ind, npy_intp cnt, npy_intp kth, void *null); +NPY_VISIBILITY_HIDDEN int introselect_unicode(npy_ucs4 *vec, npy_intp cnt, + npy_intp kth, PyArrayObject *arr); +NPY_VISIBILITY_HIDDEN int aintroselect_unicode(npy_ucs4 *vec, npy_intp *ind, + npy_intp cnt, npy_intp kth, + void *null); -int npy_introselect(void *base, size_t num, size_t size, size_t kth, npy_comparator cmp); +NPY_VISIBILITY_HIDDEN int npy_introselect(void *base, size_t num, size_t size, + size_t kth, npy_comparator cmp); typedef struct { enum NPY_TYPES typenum; diff --git a/numpy/core/src/private/ufunc_override.h b/numpy/core/src/private/ufunc_override.h index 380aef714..c47c46a66 100644 --- a/numpy/core/src/private/ufunc_override.h +++ b/numpy/core/src/private/ufunc_override.h @@ -3,6 +3,154 @@ #include <npy_config.h> #include "numpy/arrayobject.h" #include "common.h" +#include <string.h> +#include "numpy/ufuncobject.h" + +static void +normalize___call___args(PyUFuncObject *ufunc, PyObject *args, + PyObject **normal_args, PyObject **normal_kwds, + int nin) +{ + /* ufunc.__call__(*args, **kwds) */ + int nargs = PyTuple_GET_SIZE(args); + PyObject *obj; + + *normal_args = PyTuple_GetSlice(args, 0, nin); + + /* If we have more args than nin, they must be the output variables.*/ + if (nargs > nin) { + if ((nargs - nin) == 1) { + obj = PyTuple_GET_ITEM(args, nargs - 1); + PyDict_SetItemString(*normal_kwds, "out", obj); + } + else { + obj = PyTuple_GetSlice(args, nin, nargs); + PyDict_SetItemString(*normal_kwds, "out", obj); + Py_DECREF(obj); + } + } +} + +static void +normalize_reduce_args(PyUFuncObject *ufunc, PyObject *args, + PyObject **normal_args, PyObject **normal_kwds) +{ + /* ufunc.reduce(a[, axis, dtype, out, keepdims]) */ + int nargs = PyTuple_GET_SIZE(args); + int i; + PyObject *obj; + + for (i = 0; i < nargs; i++) { + obj = PyTuple_GET_ITEM(args, i); + if (i == 0) { + *normal_args = PyTuple_GetSlice(args, 0, 1); + } + else if (i == 1) { + /* axis */ + PyDict_SetItemString(*normal_kwds, "axis", obj); + } + else if (i == 2) { + /* dtype */ + PyDict_SetItemString(*normal_kwds, "dtype", obj); + } + else if (i == 3) { + /* out */ + PyDict_SetItemString(*normal_kwds, "out", obj); + } + else { + /* keepdims */ + PyDict_SetItemString(*normal_kwds, "keepdims", obj); + } + } + return; +} + +static void +normalize_accumulate_args(PyUFuncObject *ufunc, PyObject *args, + PyObject **normal_args, PyObject **normal_kwds) +{ + /* ufunc.accumulate(a[, axis, dtype, out]) */ + int nargs = PyTuple_GET_SIZE(args); + int i; + PyObject *obj; + + for (i = 0; i < nargs; i++) { + obj = PyTuple_GET_ITEM(args, i); + if (i == 0) { + *normal_args = PyTuple_GetSlice(args, 0, 1); + } + else if (i == 1) { + /* axis */ + PyDict_SetItemString(*normal_kwds, "axis", obj); + } + else if (i == 2) { + /* dtype */ + PyDict_SetItemString(*normal_kwds, "dtype", obj); + } + else { + /* out */ + PyDict_SetItemString(*normal_kwds, "out", obj); + } + } + return; +} + +static void +normalize_reduceat_args(PyUFuncObject *ufunc, PyObject *args, + PyObject **normal_args, PyObject **normal_kwds) +{ + /* ufunc.reduceat(a, indicies[, axis, dtype, out]) */ + int i; + int nargs = PyTuple_GET_SIZE(args); + PyObject *obj; + + for (i = 0; i < nargs; i++) { + obj = PyTuple_GET_ITEM(args, i); + if (i == 0) { + /* a and indicies */ + *normal_args = PyTuple_GetSlice(args, 0, 2); + } + else if (i == 1) { + /* Handled above, when i == 0. */ + continue; + } + else if (i == 2) { + /* axis */ + PyDict_SetItemString(*normal_kwds, "axis", obj); + } + else if (i == 3) { + /* dtype */ + PyDict_SetItemString(*normal_kwds, "dtype", obj); + } + else { + /* out */ + PyDict_SetItemString(*normal_kwds, "out", obj); + } + } + return; +} + +static void +normalize_outer_args(PyUFuncObject *ufunc, PyObject *args, + PyObject **normal_args, PyObject **normal_kwds) +{ + /* ufunc.outer(A, B) + * This has no kwds so we don't need to do any kwd stuff. + */ + *normal_args = PyTuple_GetSlice(args, 0, 2); + return; +} + +static void +normalize_at_args(PyUFuncObject *ufunc, PyObject *args, + PyObject **normal_args, PyObject **normal_kwds) +{ + /* ufunc.at(a, indices[, b]) */ + int nargs = PyTuple_GET_SIZE(args); + + *normal_args = PyTuple_GetSlice(args, 0, nargs); + return; +} /* * Check a set of args for the `__numpy_ufunc__` method. If more than one of @@ -16,8 +164,8 @@ * result of the operation, if any. If *result is NULL, there is no override. */ static int -PyUFunc_CheckOverride(PyObject *ufunc, char *method, - PyObject *args, PyObject *kwds, +PyUFunc_CheckOverride(PyUFuncObject *ufunc, char *method, + PyObject *args, PyObject *kwds, PyObject **result, int nin) { @@ -35,23 +183,23 @@ PyUFunc_CheckOverride(PyObject *ufunc, char *method, PyObject *normal_args = NULL; /* normal_* holds normalized arguments. */ PyObject *normal_kwds = NULL; - PyObject *with_override[NPY_MAXARGS]; + PyObject *with_override[NPY_MAXARGS]; /* Pos of each override in args */ int with_override_pos[NPY_MAXARGS]; - /* + /* * Check inputs */ if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "Internal Numpy error: call to PyUFunc_CheckOverride " "with non-tuple"); goto fail; } if (PyTuple_GET_SIZE(args) > NPY_MAXARGS) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "Internal Numpy error: too many arguments in call " "to PyUFunc_CheckOverride"); goto fail; @@ -59,7 +207,12 @@ PyUFunc_CheckOverride(PyObject *ufunc, char *method, for (i = 0; i < nargs; ++i) { obj = PyTuple_GET_ITEM(args, i); - if (PyArray_CheckExact(obj) || PyArray_IsAnyScalar(obj)) { + /* + * TODO: could use PyArray_GetAttrString_SuppressException if it + * weren't private to multiarray.so + */ + if (PyArray_CheckExact(obj) || PyArray_IsScalar(obj, Generic) || + _is_basic_python_type(obj)) { continue; } if (PyObject_HasAttrString(obj, "__numpy_ufunc__")) { @@ -75,14 +228,15 @@ PyUFunc_CheckOverride(PyObject *ufunc, char *method, return 0; } - /* - * Normalize ufunc arguments. - */ - normal_args = PyTuple_GetSlice(args, 0, nin); - if (normal_args == NULL) { + method_name = PyUString_FromString(method); + if (method_name == NULL) { goto fail; } + /* + * Normalize ufunc arguments. + */ + /* Build new kwds */ if (kwds && PyDict_CheckExact(kwds)) { normal_kwds = PyDict_Copy(kwds); @@ -94,21 +248,38 @@ PyUFunc_CheckOverride(PyObject *ufunc, char *method, goto fail; } - /* If we have more args than nin, they must be the output variables.*/ - if (nargs > nin) { - if ((nargs - nin) == 1) { - obj = PyTuple_GET_ITEM(args, nargs - 1); - PyDict_SetItemString(normal_kwds, "out", obj); - } - else { - obj = PyTuple_GetSlice(args, nin, nargs); - PyDict_SetItemString(normal_kwds, "out", obj); - Py_DECREF(obj); - } + /* decide what to do based on the method. */ + /* ufunc.__call__ */ + if (strcmp(method, "__call__") == 0) { + normalize___call___args(ufunc, args, &normal_args, &normal_kwds, nin); } - method_name = PyUString_FromString(method); - if (method_name == NULL) { + /* ufunc.reduce */ + else if (strcmp(method, "reduce") == 0) { + normalize_reduce_args(ufunc, args, &normal_args, &normal_kwds); + } + + /* ufunc.accumulate */ + else if (strcmp(method, "accumulate") == 0) { + normalize_accumulate_args(ufunc, args, &normal_args, &normal_kwds); + } + + /* ufunc.reduceat */ + else if (strcmp(method, "reduceat") == 0) { + normalize_reduceat_args(ufunc, args, &normal_args, &normal_kwds); + } + + /* ufunc.outer */ + else if (strcmp(method, "outer") == 0) { + normalize_outer_args(ufunc, args, &normal_args, &normal_kwds); + } + + /* ufunc.at */ + else if (strcmp(method, "at") == 0) { + normalize_at_args(ufunc, args, &normal_args, &normal_kwds); + } + + if (normal_args == NULL) { goto fail; } @@ -138,7 +309,7 @@ PyUFunc_CheckOverride(PyObject *ufunc, char *method, for (j = i + 1; j < noa; j++) { other_obj = with_override[j]; if (PyObject_Type(other_obj) != PyObject_Type(obj) && - PyObject_IsInstance(other_obj, + PyObject_IsInstance(other_obj, PyObject_Type(override_obj))) { override_obj = NULL; break; @@ -155,19 +326,19 @@ PyUFunc_CheckOverride(PyObject *ufunc, char *method, /* Check if there is a method left to call */ if (!override_obj) { /* No acceptable override found. */ - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "__numpy_ufunc__ not implemented for this type."); goto fail; } /* Call the override */ - numpy_ufunc = PyObject_GetAttrString(override_obj, + numpy_ufunc = PyObject_GetAttrString(override_obj, "__numpy_ufunc__"); if (numpy_ufunc == NULL) { goto fail; } - override_args = Py_BuildValue("OOiO", ufunc, method_name, + override_args = Py_BuildValue("OOiO", ufunc, method_name, override_pos, normal_args); if (override_args == NULL) { Py_DECREF(numpy_ufunc); @@ -175,7 +346,7 @@ PyUFunc_CheckOverride(PyObject *ufunc, char *method, } *result = PyObject_Call(numpy_ufunc, override_args, normal_kwds); - + Py_DECREF(numpy_ufunc); Py_DECREF(override_args); @@ -206,5 +377,4 @@ fail: Py_XDECREF(normal_kwds); return 1; } - #endif diff --git a/numpy/core/src/umath/loops.c.src b/numpy/core/src/umath/loops.c.src index 2eef4c94a..035a27fd2 100644 --- a/numpy/core/src/umath/loops.c.src +++ b/numpy/core/src/umath/loops.c.src @@ -5,7 +5,8 @@ #include "Python.h" -#ifdef ENABLE_SEPARATE_COMPILATION +#include "npy_config.h" +#ifdef ENABLE_SEPARATE_COMPILATION #define PY_ARRAY_UNIQUE_SYMBOL _npy_umathmodule_ARRAY_API #define NO_IMPORT_ARRAY #endif @@ -51,6 +52,19 @@ && (steps[0] == steps[2])\ && (steps[0] == 0)) +/* binary loop input and output continous */ +#define IS_BINARY_CONT(tin, tout) (steps[0] == sizeof(tin) && \ + steps[1] == sizeof(tin) && \ + steps[2] == sizeof(tout)) +/* binary loop input and output continous with first scalar */ +#define IS_BINARY_CONT_S1(tin, tout) (steps[0] == 0 && \ + steps[1] == sizeof(tin) && \ + steps[2] == sizeof(tout)) +/* binary loop input and output continous with second scalar */ +#define IS_BINARY_CONT_S2(tin, tout) (steps[0] == sizeof(tin) && \ + steps[1] == 0 && \ + steps[2] == sizeof(tout)) + #define OUTPUT_LOOP\ char *op1 = args[1];\ npy_intp os1 = steps[1];\ @@ -634,32 +648,6 @@ BOOL_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED } /**end repeat**/ - -NPY_NO_EXPORT void -BOOL_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) -{ - BINARY_LOOP { - npy_bool in1 = *((npy_bool *)ip1) != 0; - npy_bool in2 = *((npy_bool *)ip2) != 0; - *((npy_bool *)op1)= (in1 && !in2) || (!in1 && in2); - } -} - -/**begin repeat - * #kind = maximum, minimum# - * #OP = >, <# - **/ -NPY_NO_EXPORT void -BOOL_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) -{ - BINARY_LOOP { - npy_bool in1 = *((npy_bool *)ip1) != 0; - npy_bool in2 = *((npy_bool *)ip2) != 0; - *((npy_bool *)op1) = (in1 @OP@ in2) ? in1 : in2; - } -} -/**end repeat**/ - /**begin repeat * #kind = absolute, logical_not# * #OP = !=, ==# @@ -802,13 +790,45 @@ NPY_NO_EXPORT void * #OP = ==, !=, >, >=, <, <=, &&, ||# */ -NPY_NO_EXPORT void +NPY_NO_EXPORT NPY_GCC_OPT_3 void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { - BINARY_LOOP { - const @type@ in1 = *(@type@ *)ip1; - const @type@ in2 = *(@type@ *)ip2; - *((npy_bool *)op1) = in1 @OP@ in2; + /* + * gcc vectorization of this is not good (PR60575) but manual integer + * vectorization is too tedious to be worthwhile + */ + if (IS_BINARY_CONT(@type@, npy_bool)) { + npy_intp i, n = dimensions[0]; + @type@ * a = (@type@ *)args[0], * b = (@type@ *)args[1]; + npy_bool * o = (npy_bool *)args[2]; + for (i = 0; i < n; i++) { + o[i] = a[i] @OP@ b[i]; + } + } + else if (IS_BINARY_CONT_S1(@type@, npy_bool)) { + npy_intp i, n = dimensions[0]; + @type@ a = *(@type@ *)args[0]; + @type@ * b = (@type@ *)args[1]; + npy_bool * o = (npy_bool *)args[2]; + for (i = 0; i < n; i++) { + o[i] = a @OP@ b[i]; + } + } + else if (IS_BINARY_CONT_S2(@type@, npy_bool)) { + npy_intp i, n = dimensions[0]; + @type@ * a = (@type@ *)args[0]; + @type@ b = *(@type@*)args[1]; + npy_bool * o = (npy_bool *)args[2]; + for (i = 0; i < n; i++) { + o[i] = a[i] @OP@ b; + } + } + else { + BINARY_LOOP { + const @type@ in1 = *(@type@ *)ip1; + const @type@ in2 = *(@type@ *)ip2; + *((npy_bool *)op1) = in1 @OP@ in2; + } } } @@ -1513,13 +1533,18 @@ NPY_NO_EXPORT void /**begin repeat1 * #kind = isnan, isinf, isfinite, signbit# * #func = npy_isnan, npy_isinf, npy_isfinite, npy_signbit# + * #isnan = 1, 0*3# **/ NPY_NO_EXPORT void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { - UNARY_LOOP { - const @type@ in1 = *(@type@ *)ip1; - *((npy_bool *)op1) = @func@(in1) != 0; + char * margs[] = {args[0], args[0], args[1]}; + npy_intp msteps[] = {steps[0], steps[0], steps[1]}; + if (!@isnan@ || !run_binary_simd_not_equal_@TYPE@(margs, dimensions, msteps)) { + UNARY_LOOP { + const @type@ in1 = *(@type@ *)ip1; + *((npy_bool *)op1) = @func@(in1) != 0; + } } } /**end repeat1**/ @@ -1691,9 +1716,11 @@ NPY_NO_EXPORT void NPY_NO_EXPORT void @TYPE@_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { - UNARY_LOOP { - const @type@ in1 = *(@type@ *)ip1; - *((@type@ *)op1) = -in1; + if (!run_unary_simd_negative_@TYPE@(args, dimensions, steps)) { + UNARY_LOOP { + const @type@ in1 = *(@type@ *)ip1; + *((@type@ *)op1) = -in1; + } } } @@ -1790,20 +1817,19 @@ NPY_NO_EXPORT void HALF_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { if (IS_BINARY_REDUCE) { + char *iop1 = args[0]; + float io1 = npy_half_to_float(*(npy_half *)iop1); #if @PW@ - npy_half * iop1 = (npy_half *)args[0]; npy_intp n = dimensions[0]; - *iop1 @OP@= npy_float_to_half(pairwise_sum_HALF((npy_half *)args[1], n, - steps[1] / (npy_intp)sizeof(npy_half))); + io1 @OP@= pairwise_sum_HALF((npy_half *)args[1], n, + steps[1] / (npy_intp)sizeof(npy_half)); #else - char *iop1 = args[0]; - float io1 = npy_half_to_float(*(npy_half *)iop1); BINARY_REDUCE_LOOP_INNER { io1 @OP@= npy_half_to_float(*(npy_half *)ip2); } - *((npy_half *)iop1) = npy_float_to_half(io1); #endif + *((npy_half *)iop1) = npy_float_to_half(io1); } else { BINARY_LOOP { @@ -2132,7 +2158,7 @@ pairwise_sum_@TYPE@(@ftype@ *rr, @ftype@ * ri, @ftype@ * a, npy_uintp n, } else if (n <= PW_BLOCKSIZE) { npy_intp i; - @ftype@ r[8], res; + @ftype@ r[8]; /* * sum a block with 8 accumulators @@ -2510,18 +2536,72 @@ NPY_NO_EXPORT void /**begin repeat * #kind = equal, not_equal, greater, greater_equal, less, less_equal# * #OP = EQ, NE, GT, GE, LT, LE# + * #identity = NPY_TRUE, NPY_FALSE, -1*4# */ NPY_NO_EXPORT void OBJECT_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { + int ret; + PyObject *ret_obj; PyObject *in1 = *(PyObject **)ip1; PyObject *in2 = *(PyObject **)ip2; - int ret = PyObject_RichCompareBool( - in1 ? in1 : Py_None, - in2 ? in2 : Py_None, Py_@OP@); + + in1 = in1 ? in1 : Py_None; + in2 = in2 ? in2 : Py_None; + + /* + * Do not use RichCompareBool because it includes an identity check + * (for == and !=). + * This is wrong for elementwise behaviour, since it means + * that NaN can be equal to NaN and an array is equal to itself. + */ + ret_obj = PyObject_RichCompare(in1, in2, Py_@OP@); + if (ret_obj == NULL) { +#if @identity@ != -1 + if (in1 == in2) { + PyErr_Clear(); + if (DEPRECATE("numpy @kind@ will not check object identity " + "in the future. The comparison error will " + "be raised.") < 0) { + return; + } + *((npy_bool *)op1) = @identity@; + continue; + } +#endif + return; + } + ret = PyObject_IsTrue(ret_obj); + Py_DECREF(ret_obj); if (ret == -1) { +#if @identity@ != -1 + if (in1 == in2) { + PyErr_Clear(); + if (DEPRECATE("numpy @kind@ will not check object identity " + "in the future. The error trying to get the " + "boolean value of the comparison result will " + "be raised.") < 0) { + return; + } + *((npy_bool *)op1) = @identity@; + continue; + } +#endif return; } +#if @identity@ != -1 + if ((in1 == in2) && ((npy_bool)ret != @identity@)) { + if (DEPRECATE_FUTUREWARNING( + "numpy @kind@ will not check object identity " + "in the future. The comparison did not return the " + "same result as suggested by the identity (`is`)) " + "and will change.") < 0) { + return; + } + *((npy_bool *)op1) = @identity@; + continue; + } +#endif *((npy_bool *)op1) = (npy_bool)ret; } } @@ -2537,9 +2617,12 @@ OBJECT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED PyObject **out = (PyObject **)op1; int v; PyObject *ret; - PyObject_Cmp(in1 ? in1 : Py_None, zero, &v); + if (PyObject_Cmp(in1 ? in1 : Py_None, zero, &v) == -1) { + return; + } ret = PyLong_FromLong(v); if (PyErr_Occurred()) { + Py_DECREF(zero); return; } Py_XDECREF(*out); @@ -2554,6 +2637,7 @@ OBJECT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED PyObject *ret = PyInt_FromLong( PyObject_Compare(in1 ? in1 : Py_None, zero)); if (PyErr_Occurred()) { + Py_DECREF(zero); return; } Py_XDECREF(*out); diff --git a/numpy/core/src/umath/loops.h b/numpy/core/src/umath/loops.h deleted file mode 100644 index 62890f370..000000000 --- a/numpy/core/src/umath/loops.h +++ /dev/null @@ -1,2728 +0,0 @@ - -/* - ***************************************************************************** - ** This file was autogenerated from a template DO NOT EDIT!!!! ** - ** Changes should be made to the original source (.src) file ** - ***************************************************************************** - */ - -#line 1 -/* -*- c -*- */ -/* - * vim:syntax=c - */ - -/* - ***************************************************************************** - ** IMPORTANT NOTE for loops.h.src -> loops.h ** - ***************************************************************************** - * The template file loops.h.src is not automatically converted into - * loops.h by the build system. If you edit this file, you must manually - * do the conversion using numpy/distutils/conv_template.py from the - * command line as follows: - * - * $ cd <NumPy source root directory> - * $ python numpy/distutils/conv_template.py numpy/core/src/umath/loops.h.src - * $ - */ - -#ifndef _NPY_UMATH_LOOPS_H_ -#define _NPY_UMATH_LOOPS_H_ - -#define BOOL_invert BOOL_logical_not -#define BOOL_negative BOOL_logical_not -#define BOOL_add BOOL_logical_or -#define BOOL_bitwise_and BOOL_logical_and -#define BOOL_bitwise_or BOOL_logical_or -#define BOOL_bitwise_xor BOOL_logical_xor -#define BOOL_multiply BOOL_logical_and -#define BOOL_subtract BOOL_logical_xor -#define BOOL_fmax BOOL_maximum -#define BOOL_fmin BOOL_minimum - -/* - ***************************************************************************** - ** BOOLEAN LOOPS ** - ***************************************************************************** - */ - -#line 46 - -NPY_NO_EXPORT void -BOOL_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 46 - -NPY_NO_EXPORT void -BOOL_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 55 -NPY_NO_EXPORT void -BOOL_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 55 -NPY_NO_EXPORT void -BOOL_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 63 -NPY_NO_EXPORT void -BOOL_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 63 -NPY_NO_EXPORT void -BOOL_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -BOOL__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -/* - ***************************************************************************** - ** INTEGER LOOPS - ***************************************************************************** - */ - -#line 79 - -#line 85 - -#define BYTE_floor_divide BYTE_divide -#define BYTE_fmax BYTE_maximum -#define BYTE_fmin BYTE_minimum - -NPY_NO_EXPORT void -BYTE__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -BYTE_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -BYTE_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -BYTE_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -BYTE_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -BYTE_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -BYTE_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 117 -NPY_NO_EXPORT void -BYTE_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -BYTE_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -BYTE_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -BYTE_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -BYTE_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -BYTE_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -BYTE_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -BYTE_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -#line 127 -NPY_NO_EXPORT void -BYTE_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -BYTE_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -BYTE_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -BYTE_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -BYTE_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -BYTE_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -BYTE_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -BYTE_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -BYTE_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -BYTE_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -BYTE_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -BYTE_true_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -BYTE_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -BYTE_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 85 - -#define UBYTE_floor_divide UBYTE_divide -#define UBYTE_fmax UBYTE_maximum -#define UBYTE_fmin UBYTE_minimum - -NPY_NO_EXPORT void -UBYTE__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -UBYTE_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -UBYTE_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -UBYTE_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UBYTE_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UBYTE_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UBYTE_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 117 -NPY_NO_EXPORT void -UBYTE_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -UBYTE_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -UBYTE_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -UBYTE_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -UBYTE_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -UBYTE_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -UBYTE_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -UBYTE_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -#line 127 -NPY_NO_EXPORT void -UBYTE_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -UBYTE_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -UBYTE_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -UBYTE_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -UBYTE_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -UBYTE_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -UBYTE_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -UBYTE_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -UBYTE_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -UBYTE_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -UBYTE_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -UBYTE_true_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UBYTE_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UBYTE_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -NPY_NO_EXPORT void -UBYTE_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -BYTE_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UBYTE_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -BYTE_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -BYTE_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UBYTE_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -BYTE_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UBYTE_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 79 - -#line 85 - -#define SHORT_floor_divide SHORT_divide -#define SHORT_fmax SHORT_maximum -#define SHORT_fmin SHORT_minimum - -NPY_NO_EXPORT void -SHORT__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -SHORT_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -SHORT_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -SHORT_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -SHORT_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -SHORT_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -SHORT_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 117 -NPY_NO_EXPORT void -SHORT_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -SHORT_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -SHORT_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -SHORT_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -SHORT_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -SHORT_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -SHORT_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -SHORT_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -#line 127 -NPY_NO_EXPORT void -SHORT_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -SHORT_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -SHORT_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -SHORT_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -SHORT_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -SHORT_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -SHORT_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -SHORT_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -SHORT_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -SHORT_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -SHORT_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -SHORT_true_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -SHORT_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -SHORT_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 85 - -#define USHORT_floor_divide USHORT_divide -#define USHORT_fmax USHORT_maximum -#define USHORT_fmin USHORT_minimum - -NPY_NO_EXPORT void -USHORT__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -USHORT_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -USHORT_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -USHORT_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -USHORT_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -USHORT_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -USHORT_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 117 -NPY_NO_EXPORT void -USHORT_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -USHORT_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -USHORT_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -USHORT_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -USHORT_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -USHORT_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -USHORT_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -USHORT_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -#line 127 -NPY_NO_EXPORT void -USHORT_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -USHORT_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -USHORT_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -USHORT_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -USHORT_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -USHORT_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -USHORT_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -USHORT_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -USHORT_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -USHORT_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -USHORT_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -USHORT_true_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -USHORT_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -USHORT_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -NPY_NO_EXPORT void -USHORT_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -SHORT_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -USHORT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -SHORT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -SHORT_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -USHORT_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -SHORT_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -USHORT_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 79 - -#line 85 - -#define INT_floor_divide INT_divide -#define INT_fmax INT_maximum -#define INT_fmin INT_minimum - -NPY_NO_EXPORT void -INT__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -INT_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -INT_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -INT_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -INT_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -INT_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -INT_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 117 -NPY_NO_EXPORT void -INT_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -INT_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -INT_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -INT_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -INT_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -INT_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -INT_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -INT_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -#line 127 -NPY_NO_EXPORT void -INT_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -INT_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -INT_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -INT_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -INT_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -INT_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -INT_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -INT_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -INT_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -INT_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -INT_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -INT_true_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -INT_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -INT_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 85 - -#define UINT_floor_divide UINT_divide -#define UINT_fmax UINT_maximum -#define UINT_fmin UINT_minimum - -NPY_NO_EXPORT void -UINT__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -UINT_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -UINT_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -UINT_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UINT_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UINT_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UINT_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 117 -NPY_NO_EXPORT void -UINT_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -UINT_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -UINT_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -UINT_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -UINT_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -UINT_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -UINT_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -UINT_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -#line 127 -NPY_NO_EXPORT void -UINT_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -UINT_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -UINT_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -UINT_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -UINT_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -UINT_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -UINT_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -UINT_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -UINT_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -UINT_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -UINT_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -UINT_true_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UINT_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UINT_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -NPY_NO_EXPORT void -UINT_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -INT_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UINT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -INT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -INT_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UINT_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -INT_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -UINT_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 79 - -#line 85 - -#define LONG_floor_divide LONG_divide -#define LONG_fmax LONG_maximum -#define LONG_fmin LONG_minimum - -NPY_NO_EXPORT void -LONG__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -LONG_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -LONG_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -LONG_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONG_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONG_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONG_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 117 -NPY_NO_EXPORT void -LONG_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -LONG_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -LONG_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -LONG_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -LONG_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -LONG_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -LONG_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -LONG_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -#line 127 -NPY_NO_EXPORT void -LONG_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -LONG_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -LONG_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -LONG_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -LONG_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -LONG_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -LONG_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -LONG_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -LONG_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -LONG_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -LONG_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -LONG_true_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONG_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONG_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 85 - -#define ULONG_floor_divide ULONG_divide -#define ULONG_fmax ULONG_maximum -#define ULONG_fmin ULONG_minimum - -NPY_NO_EXPORT void -ULONG__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -ULONG_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -ULONG_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -ULONG_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONG_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONG_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONG_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 117 -NPY_NO_EXPORT void -ULONG_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -ULONG_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -ULONG_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -ULONG_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -ULONG_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -ULONG_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -ULONG_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -ULONG_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -#line 127 -NPY_NO_EXPORT void -ULONG_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -ULONG_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -ULONG_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -ULONG_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -ULONG_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -ULONG_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -ULONG_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -ULONG_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -ULONG_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -ULONG_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -ULONG_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -ULONG_true_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONG_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONG_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -NPY_NO_EXPORT void -ULONG_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONG_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONG_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONG_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONG_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONG_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONG_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONG_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 79 - -#line 85 - -#define LONGLONG_floor_divide LONGLONG_divide -#define LONGLONG_fmax LONGLONG_maximum -#define LONGLONG_fmin LONGLONG_minimum - -NPY_NO_EXPORT void -LONGLONG__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -LONGLONG_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -LONGLONG_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -LONGLONG_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONGLONG_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONGLONG_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONGLONG_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 117 -NPY_NO_EXPORT void -LONGLONG_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -LONGLONG_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -LONGLONG_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -LONGLONG_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -LONGLONG_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -LONGLONG_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -LONGLONG_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -LONGLONG_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -#line 127 -NPY_NO_EXPORT void -LONGLONG_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -LONGLONG_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -LONGLONG_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -LONGLONG_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -LONGLONG_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -LONGLONG_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -LONGLONG_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -LONGLONG_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -LONGLONG_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -LONGLONG_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -LONGLONG_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -LONGLONG_true_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONGLONG_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONGLONG_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 85 - -#define ULONGLONG_floor_divide ULONGLONG_divide -#define ULONGLONG_fmax ULONGLONG_maximum -#define ULONGLONG_fmin ULONGLONG_minimum - -NPY_NO_EXPORT void -ULONGLONG__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -ULONGLONG_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -ULONGLONG_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -ULONGLONG_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONGLONG_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONGLONG_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONGLONG_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 117 -NPY_NO_EXPORT void -ULONGLONG_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -ULONGLONG_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -ULONGLONG_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -ULONGLONG_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -ULONGLONG_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -ULONGLONG_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -ULONGLONG_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 117 -NPY_NO_EXPORT void -ULONGLONG_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -#line 127 -NPY_NO_EXPORT void -ULONGLONG_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -ULONGLONG_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -ULONGLONG_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -ULONGLONG_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -ULONGLONG_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -ULONGLONG_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -ULONGLONG_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 127 -NPY_NO_EXPORT void -ULONGLONG_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -ULONGLONG_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -ULONGLONG_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 138 -NPY_NO_EXPORT void -ULONGLONG_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -ULONGLONG_true_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONGLONG_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONGLONG_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -NPY_NO_EXPORT void -ULONGLONG_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONGLONG_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONGLONG_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONGLONG_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONGLONG_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONGLONG_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONGLONG_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -ULONGLONG_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -/* - ***************************************************************************** - ** FLOAT LOOPS ** - ***************************************************************************** - */ - -#line 187 -NPY_NO_EXPORT void -FLOAT_sqrt(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 187 -NPY_NO_EXPORT void -DOUBLE_sqrt(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 197 - - -#line 204 -NPY_NO_EXPORT void -HALF_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 204 -NPY_NO_EXPORT void -HALF_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 204 -NPY_NO_EXPORT void -HALF_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 204 -NPY_NO_EXPORT void -HALF_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 213 -NPY_NO_EXPORT void -HALF_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -HALF_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -HALF_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -HALF_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -HALF_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -HALF_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -HALF_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -HALF_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -HALF_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -HALF_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -HALF_isnan(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -HALF_isinf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -HALF_isfinite(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -HALF_signbit(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -HALF_copysign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -HALF_nextafter(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -HALF_spacing(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 235 -NPY_NO_EXPORT void -HALF_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 235 -NPY_NO_EXPORT void -HALF_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 243 -NPY_NO_EXPORT void -HALF_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 243 -NPY_NO_EXPORT void -HALF_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -HALF_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -HALF_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -HALF_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -HALF_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - - -NPY_NO_EXPORT void -HALF__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -HALF_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -HALF_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -HALF_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -HALF_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -HALF_modf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#ifdef HAVE_FREXPF -NPY_NO_EXPORT void -HALF_frexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -#endif - -#ifdef HAVE_LDEXPF -NPY_NO_EXPORT void -HALF_ldexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -NPY_NO_EXPORT void -HALF_ldexp_long(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -#endif - -#define HALF_true_divide HALF_divide - - -#line 197 - - -#line 204 -NPY_NO_EXPORT void -FLOAT_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 204 -NPY_NO_EXPORT void -FLOAT_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 204 -NPY_NO_EXPORT void -FLOAT_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 204 -NPY_NO_EXPORT void -FLOAT_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 213 -NPY_NO_EXPORT void -FLOAT_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -FLOAT_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -FLOAT_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -FLOAT_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -FLOAT_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -FLOAT_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -FLOAT_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -FLOAT_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -FLOAT_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -FLOAT_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -FLOAT_isnan(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -FLOAT_isinf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -FLOAT_isfinite(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -FLOAT_signbit(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -FLOAT_copysign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -FLOAT_nextafter(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -FLOAT_spacing(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 235 -NPY_NO_EXPORT void -FLOAT_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 235 -NPY_NO_EXPORT void -FLOAT_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 243 -NPY_NO_EXPORT void -FLOAT_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 243 -NPY_NO_EXPORT void -FLOAT_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -FLOAT_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -FLOAT_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -FLOAT_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -FLOAT_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - - -NPY_NO_EXPORT void -FLOAT__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -FLOAT_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -FLOAT_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -FLOAT_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -FLOAT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -FLOAT_modf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#ifdef HAVE_FREXPF -NPY_NO_EXPORT void -FLOAT_frexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -#endif - -#ifdef HAVE_LDEXPF -NPY_NO_EXPORT void -FLOAT_ldexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -NPY_NO_EXPORT void -FLOAT_ldexp_long(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -#endif - -#define FLOAT_true_divide FLOAT_divide - - -#line 197 - - -#line 204 -NPY_NO_EXPORT void -DOUBLE_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 204 -NPY_NO_EXPORT void -DOUBLE_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 204 -NPY_NO_EXPORT void -DOUBLE_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 204 -NPY_NO_EXPORT void -DOUBLE_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 213 -NPY_NO_EXPORT void -DOUBLE_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -DOUBLE_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -DOUBLE_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -DOUBLE_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -DOUBLE_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -DOUBLE_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -DOUBLE_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -DOUBLE_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -DOUBLE_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -DOUBLE_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -DOUBLE_isnan(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -DOUBLE_isinf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -DOUBLE_isfinite(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -DOUBLE_signbit(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -DOUBLE_copysign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -DOUBLE_nextafter(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -DOUBLE_spacing(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 235 -NPY_NO_EXPORT void -DOUBLE_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 235 -NPY_NO_EXPORT void -DOUBLE_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 243 -NPY_NO_EXPORT void -DOUBLE_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 243 -NPY_NO_EXPORT void -DOUBLE_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -DOUBLE_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -DOUBLE_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -DOUBLE_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -DOUBLE_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - - -NPY_NO_EXPORT void -DOUBLE__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -DOUBLE_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -DOUBLE_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -DOUBLE_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -DOUBLE_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -DOUBLE_modf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#ifdef HAVE_FREXP -NPY_NO_EXPORT void -DOUBLE_frexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -#endif - -#ifdef HAVE_LDEXP -NPY_NO_EXPORT void -DOUBLE_ldexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -NPY_NO_EXPORT void -DOUBLE_ldexp_long(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -#endif - -#define DOUBLE_true_divide DOUBLE_divide - - -#line 197 - - -#line 204 -NPY_NO_EXPORT void -LONGDOUBLE_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 204 -NPY_NO_EXPORT void -LONGDOUBLE_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 204 -NPY_NO_EXPORT void -LONGDOUBLE_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 204 -NPY_NO_EXPORT void -LONGDOUBLE_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 213 -NPY_NO_EXPORT void -LONGDOUBLE_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -LONGDOUBLE_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -LONGDOUBLE_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -LONGDOUBLE_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -LONGDOUBLE_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -LONGDOUBLE_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -LONGDOUBLE_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 213 -NPY_NO_EXPORT void -LONGDOUBLE_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -LONGDOUBLE_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONGDOUBLE_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -LONGDOUBLE_isnan(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -LONGDOUBLE_isinf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -LONGDOUBLE_isfinite(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -LONGDOUBLE_signbit(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -LONGDOUBLE_copysign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -LONGDOUBLE_nextafter(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 227 -NPY_NO_EXPORT void -LONGDOUBLE_spacing(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 235 -NPY_NO_EXPORT void -LONGDOUBLE_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 235 -NPY_NO_EXPORT void -LONGDOUBLE_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 243 -NPY_NO_EXPORT void -LONGDOUBLE_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 243 -NPY_NO_EXPORT void -LONGDOUBLE_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -LONGDOUBLE_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONGDOUBLE_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONGDOUBLE_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -LONGDOUBLE_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - - -NPY_NO_EXPORT void -LONGDOUBLE__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -LONGDOUBLE_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONGDOUBLE_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -LONGDOUBLE_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -LONGDOUBLE_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -LONGDOUBLE_modf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#ifdef HAVE_FREXPL -NPY_NO_EXPORT void -LONGDOUBLE_frexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -#endif - -#ifdef HAVE_LDEXPL -NPY_NO_EXPORT void -LONGDOUBLE_ldexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -NPY_NO_EXPORT void -LONGDOUBLE_ldexp_long(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -#endif - -#define LONGDOUBLE_true_divide LONGDOUBLE_divide - - - - -/* - ***************************************************************************** - ** COMPLEX LOOPS ** - ***************************************************************************** - */ - -#define CGE(xr,xi,yr,yi) (xr > yr || (xr == yr && xi >= yi)); -#define CLE(xr,xi,yr,yi) (xr < yr || (xr == yr && xi <= yi)); -#define CGT(xr,xi,yr,yi) (xr > yr || (xr == yr && xi > yi)); -#define CLT(xr,xi,yr,yi) (xr < yr || (xr == yr && xi < yi)); -#define CEQ(xr,xi,yr,yi) (xr == yr && xi == yi); -#define CNE(xr,xi,yr,yi) (xr != yr || xi != yi); - -#line 316 - -#line 322 -NPY_NO_EXPORT void -CFLOAT_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 322 -NPY_NO_EXPORT void -CFLOAT_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -NPY_NO_EXPORT void -CFLOAT_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CFLOAT_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CFLOAT_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CFLOAT_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CFLOAT_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CFLOAT_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CFLOAT_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CFLOAT_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CFLOAT_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 349 -NPY_NO_EXPORT void -CFLOAT_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 349 -NPY_NO_EXPORT void -CFLOAT_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -CFLOAT_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CFLOAT_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -#line 363 -NPY_NO_EXPORT void -CFLOAT_isnan(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 363 -NPY_NO_EXPORT void -CFLOAT_isinf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 363 -NPY_NO_EXPORT void -CFLOAT_isfinite(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -CFLOAT_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -CFLOAT_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -CFLOAT__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -CFLOAT_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CFLOAT_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CFLOAT__arg(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CFLOAT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 392 -NPY_NO_EXPORT void -CFLOAT_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 392 -NPY_NO_EXPORT void -CFLOAT_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 400 -NPY_NO_EXPORT void -CFLOAT_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 400 -NPY_NO_EXPORT void -CFLOAT_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#define CFLOAT_true_divide CFLOAT_divide - - -#line 316 - -#line 322 -NPY_NO_EXPORT void -CDOUBLE_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 322 -NPY_NO_EXPORT void -CDOUBLE_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -NPY_NO_EXPORT void -CDOUBLE_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CDOUBLE_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CDOUBLE_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CDOUBLE_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CDOUBLE_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CDOUBLE_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CDOUBLE_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CDOUBLE_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CDOUBLE_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 349 -NPY_NO_EXPORT void -CDOUBLE_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 349 -NPY_NO_EXPORT void -CDOUBLE_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -CDOUBLE_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CDOUBLE_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -#line 363 -NPY_NO_EXPORT void -CDOUBLE_isnan(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 363 -NPY_NO_EXPORT void -CDOUBLE_isinf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 363 -NPY_NO_EXPORT void -CDOUBLE_isfinite(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -CDOUBLE_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -CDOUBLE_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -CDOUBLE__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -CDOUBLE_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CDOUBLE_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CDOUBLE__arg(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CDOUBLE_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 392 -NPY_NO_EXPORT void -CDOUBLE_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 392 -NPY_NO_EXPORT void -CDOUBLE_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 400 -NPY_NO_EXPORT void -CDOUBLE_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 400 -NPY_NO_EXPORT void -CDOUBLE_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#define CDOUBLE_true_divide CDOUBLE_divide - - -#line 316 - -#line 322 -NPY_NO_EXPORT void -CLONGDOUBLE_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 322 -NPY_NO_EXPORT void -CLONGDOUBLE_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -NPY_NO_EXPORT void -CLONGDOUBLE_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CLONGDOUBLE_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CLONGDOUBLE_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CLONGDOUBLE_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CLONGDOUBLE_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CLONGDOUBLE_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CLONGDOUBLE_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CLONGDOUBLE_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 340 -NPY_NO_EXPORT void -CLONGDOUBLE_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 349 -NPY_NO_EXPORT void -CLONGDOUBLE_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 349 -NPY_NO_EXPORT void -CLONGDOUBLE_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -CLONGDOUBLE_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CLONGDOUBLE_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -#line 363 -NPY_NO_EXPORT void -CLONGDOUBLE_isnan(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 363 -NPY_NO_EXPORT void -CLONGDOUBLE_isinf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 363 -NPY_NO_EXPORT void -CLONGDOUBLE_isfinite(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -CLONGDOUBLE_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -CLONGDOUBLE_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -CLONGDOUBLE__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -CLONGDOUBLE_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CLONGDOUBLE_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CLONGDOUBLE__arg(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -CLONGDOUBLE_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 392 -NPY_NO_EXPORT void -CLONGDOUBLE_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 392 -NPY_NO_EXPORT void -CLONGDOUBLE_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 400 -NPY_NO_EXPORT void -CLONGDOUBLE_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 400 -NPY_NO_EXPORT void -CLONGDOUBLE_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#define CLONGDOUBLE_true_divide CLONGDOUBLE_divide - - - -#undef CGE -#undef CLE -#undef CGT -#undef CLT -#undef CEQ -#undef CNE - -/* - ***************************************************************************** - ** DATETIME LOOPS ** - ***************************************************************************** - */ - -NPY_NO_EXPORT void -TIMEDELTA_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -TIMEDELTA_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -TIMEDELTA_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 433 - -NPY_NO_EXPORT void -DATETIME__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -#line 441 -NPY_NO_EXPORT void -DATETIME_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 441 -NPY_NO_EXPORT void -DATETIME_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 441 -NPY_NO_EXPORT void -DATETIME_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 441 -NPY_NO_EXPORT void -DATETIME_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 441 -NPY_NO_EXPORT void -DATETIME_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 441 -NPY_NO_EXPORT void -DATETIME_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 449 -NPY_NO_EXPORT void -DATETIME_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 449 -NPY_NO_EXPORT void -DATETIME_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - -#line 433 - -NPY_NO_EXPORT void -TIMEDELTA__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -#line 441 -NPY_NO_EXPORT void -TIMEDELTA_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 441 -NPY_NO_EXPORT void -TIMEDELTA_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 441 -NPY_NO_EXPORT void -TIMEDELTA_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 441 -NPY_NO_EXPORT void -TIMEDELTA_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 441 -NPY_NO_EXPORT void -TIMEDELTA_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 441 -NPY_NO_EXPORT void -TIMEDELTA_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -#line 449 -NPY_NO_EXPORT void -TIMEDELTA_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 449 -NPY_NO_EXPORT void -TIMEDELTA_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - - - -NPY_NO_EXPORT void -DATETIME_Mm_M_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); - -NPY_NO_EXPORT void -DATETIME_mM_M_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -TIMEDELTA_mm_m_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -DATETIME_Mm_M_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -DATETIME_MM_m_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -TIMEDELTA_mm_m_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -TIMEDELTA_mq_m_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -TIMEDELTA_qm_m_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -TIMEDELTA_md_m_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -TIMEDELTA_dm_m_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -TIMEDELTA_mq_m_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -TIMEDELTA_md_m_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -NPY_NO_EXPORT void -TIMEDELTA_mm_d_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -/* Special case equivalents to above functions */ - -#define TIMEDELTA_mq_m_true_divide TIMEDELTA_mq_m_divide -#define TIMEDELTA_md_m_true_divide TIMEDELTA_md_m_divide -#define TIMEDELTA_mm_d_true_divide TIMEDELTA_mm_d_divide -#define TIMEDELTA_mq_m_floor_divide TIMEDELTA_mq_m_divide -#define TIMEDELTA_md_m_floor_divide TIMEDELTA_md_m_divide -/* #define TIMEDELTA_mm_d_floor_divide TIMEDELTA_mm_d_divide */ -#define TIMEDELTA_fmin TIMEDELTA_minimum -#define TIMEDELTA_fmax TIMEDELTA_maximum -#define DATETIME_fmin DATETIME_minimum -#define DATETIME_fmax DATETIME_maximum - -/* - ***************************************************************************** - ** OBJECT LOOPS ** - ***************************************************************************** - */ - -#line 517 -NPY_NO_EXPORT void -OBJECT_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 517 -NPY_NO_EXPORT void -OBJECT_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 517 -NPY_NO_EXPORT void -OBJECT_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 517 -NPY_NO_EXPORT void -OBJECT_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 517 -NPY_NO_EXPORT void -OBJECT_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -#line 517 -NPY_NO_EXPORT void -OBJECT_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - - -NPY_NO_EXPORT void -OBJECT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); - -/* - ***************************************************************************** - ** END LOOPS ** - ***************************************************************************** - */ - -#endif diff --git a/numpy/core/src/umath/loops.h.src b/numpy/core/src/umath/loops.h.src index a8a58c5de..fdc9230de 100644 --- a/numpy/core/src/umath/loops.h.src +++ b/numpy/core/src/umath/loops.h.src @@ -3,20 +3,6 @@ * vim:syntax=c */ -/* - ***************************************************************************** - ** IMPORTANT NOTE for loops.h.src -> loops.h ** - ***************************************************************************** - * The template file loops.h.src is not automatically converted into - * loops.h by the build system. If you edit this file, you must manually - * do the conversion using numpy/distutils/conv_template.py from the - * command line as follows: - * - * $ cd <NumPy source root directory> - * $ python numpy/distutils/conv_template.py numpy/core/src/umath/loops.h.src - * $ - */ - #ifndef _NPY_UMATH_LOOPS_H_ #define _NPY_UMATH_LOOPS_H_ @@ -25,12 +11,16 @@ #define BOOL_add BOOL_logical_or #define BOOL_bitwise_and BOOL_logical_and #define BOOL_bitwise_or BOOL_logical_or +#define BOOL_logical_xor BOOL_not_equal #define BOOL_bitwise_xor BOOL_logical_xor #define BOOL_multiply BOOL_logical_and #define BOOL_subtract BOOL_logical_xor +#define BOOL_maximum BOOL_logical_or +#define BOOL_minimum BOOL_logical_and #define BOOL_fmax BOOL_maximum #define BOOL_fmin BOOL_minimum + /* ***************************************************************************** ** BOOLEAN LOOPS ** @@ -39,26 +29,7 @@ /**begin repeat * #kind = equal, not_equal, greater, greater_equal, less, less_equal, - * logical_and, logical_or, logical_xor, add, bitwise_or, - * bitwise_xor, bitwise_and, fmax, fmin, invert, multiply, negative, - * subtract# - **/ - -NPY_NO_EXPORT void -BOOL_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -/**end repeat**/ - -/**begin repeat - * #kind = maximum, minimum# - * #OP = >, <# - **/ -NPY_NO_EXPORT void -BOOL_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); -/**end repeat**/ - -/**begin repeat - * #kind = absolute, logical_not# - * #OP = !=, ==# + * logical_and, logical_or, absolute, logical_not# **/ NPY_NO_EXPORT void BOOL_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); diff --git a/numpy/core/src/umath/simd.inc.src b/numpy/core/src/umath/simd.inc.src index 3a7c4f75b..7944d5f47 100644 --- a/numpy/core/src/umath/simd.inc.src +++ b/numpy/core/src/umath/simd.inc.src @@ -84,34 +84,6 @@ #define LOOP_BLOCKED_END\ for (; i < n; i++) -/* fanout two bits to two bytes */ -static const npy_int16 fanout_2[] = { - 0x0000, - 0x0001, - 0x0100, - 0x0101, -}; - -/* fanout four bits to four bytes */ -static const npy_int32 fanout_4[] = { - 0x00000000, - 0x00000001, - 0x00000100, - 0x00000101, - 0x00010000, - 0x00010001, - 0x00010100, - 0x00010101, - 0x01000000, - 0x01000001, - 0x01000100, - 0x01000101, - 0x01010000, - 0x01010001, - 0x01010100, - 0x01010101 -}; - /* * Dispatcher functions @@ -133,10 +105,10 @@ static const npy_int32 fanout_4[] = { */ /**begin repeat1 - * #func = sqrt, absolute, minimum, maximum# - * #check = IS_BLOCKABLE_UNARY, IS_BLOCKABLE_UNARY, IS_BLOCKABLE_REDUCE, IS_BLOCKABLE_REDUCE# - * #name = unary, unary, unary_reduce, unary_reduce# - * #minmax = 0, 0, 1, 1# + * #func = sqrt, absolute, negative, minimum, maximum# + * #check = IS_BLOCKABLE_UNARY*3, IS_BLOCKABLE_REDUCE*2 # + * #name = unary*3, unary_reduce*2# + * #minmax = 0*3, 1*2# */ #if @vector@ && defined NPY_HAVE_SSE2_INTRINSICS @@ -274,10 +246,15 @@ run_binary_simd_@kind@_@TYPE@(char **args, npy_intp *dimensions, npy_intp *steps * # kind = logical_or, logical_and# */ +#if defined NPY_HAVE_SSE2_INTRINSICS static void sse2_binary_@kind@_BOOL(npy_bool * op, npy_bool * ip1, npy_bool * ip2, npy_intp n); +static void +sse2_reduce_@kind@_BOOL(npy_bool * op, npy_bool * ip, npy_intp n); +#endif + static NPY_INLINE int run_binary_simd_@kind@_BOOL(char **args, npy_intp *dimensions, npy_intp *steps) { @@ -292,9 +269,6 @@ run_binary_simd_@kind@_BOOL(char **args, npy_intp *dimensions, npy_intp *steps) } -static void -sse2_reduce_@kind@_BOOL(npy_bool * op, npy_bool * ip, npy_intp n); - static NPY_INLINE int run_reduce_simd_@kind@_BOOL(char **args, npy_intp *dimensions, npy_intp *steps) { @@ -314,8 +288,10 @@ run_reduce_simd_@kind@_BOOL(char **args, npy_intp *dimensions, npy_intp *steps) * # kind = absolute, logical_not# */ +#if defined NPY_HAVE_SSE2_INTRINSICS static void sse2_@kind@_BOOL(npy_bool *, npy_bool *, const npy_intp n); +#endif static NPY_INLINE int run_unary_simd_@kind@_BOOL(char **args, npy_intp *dimensions, npy_intp *steps) @@ -377,8 +353,8 @@ static NPY_INLINE npy_double sse2_horizontal_@VOP@___m128d(__m128d v) * #vsuf = ps, pd# * #vsufs = ss, sd# * #nan = NPY_NANF, NPY_NAN# - * #mtype = npy_int32, npy_int16# - * #fanout = fanout_4, fanout_2# + * #double = 0, 1# + * #cast = _mm_castps_si128, _mm_castpd_si128# */ @@ -504,10 +480,34 @@ sse2_binary_scalar2_@kind@_@TYPE@(@type@ * op, @type@ * ip1, @type@ * ip2, npy_i /**end repeat1**/ +/* + * compress 4 vectors to 4/8 bytes in op with filled with 0 or 1 + * the last vector is passed as a pointer as MSVC 2010 is unable to ignore the + * calling convention leading to C2719 on 32 bit, see #4795 + */ +static NPY_INLINE void +sse2_compress4_to_byte_@TYPE@(@vtype@ r1, @vtype@ r2, @vtype@ r3, @vtype@ * r4, + npy_bool * op) +{ + const __m128i mask = @vpre@_set1_epi8(0x1); + __m128i ir1 = @vpre@_packs_epi32(@cast@(r1), @cast@(r2)); + __m128i ir2 = @vpre@_packs_epi32(@cast@(r3), @cast@(*r4)); + __m128i rr = @vpre@_packs_epi16(ir1, ir2); +#if @double@ + rr = @vpre@_packs_epi16(rr, rr); + rr = @vpre@_and_si128(rr, mask); + @vpre@_storel_epi64((__m128i*)op, rr); +#else + rr = @vpre@_and_si128(rr, mask); + @vpre@_storeu_si128((__m128i*)op, rr); +#endif +} + /**begin repeat1 * #kind = equal, not_equal, less, less_equal, greater, greater_equal# * #OP = ==, !=, <, <=, >, >=# * #VOP = cmpeq, cmpneq, cmplt, cmple, cmpgt, cmpge# + * #neq = 0, 1, 0*4# */ /* sets invalid fpu flag on QNaN for consistency with packed compare */ @@ -525,19 +525,39 @@ sse2_ordered_cmp_@kind@_@TYPE@(const @type@ a, const @type@ b) static void sse2_binary_@kind@_@TYPE@(npy_bool * op, @type@ * ip1, @type@ * ip2, npy_intp n) { - npy_bool * r; LOOP_BLOCK_ALIGN_VAR(ip1, @type@, 16) { op[i] = sse2_ordered_cmp_@kind@_@TYPE@(ip1[i], ip2[i]); } - r = &op[i]; - LOOP_BLOCKED(@type@, 16) { - @vtype@ a = @vpre@_load_@vsuf@(&ip1[i]); - @vtype@ b = @vpre@_loadu_@vsuf@(&ip2[i]); - @vtype@ c = @vpre@_@VOP@_@vsuf@(a, b); - @mtype@ ir = @fanout@[@vpre@_movemask_@vsuf@(c)]; - /* may be unaligned */ - memcpy(r, &ir, sizeof(ir)); - r += sizeof(ir); + /* isnan special unary case */ + if (@neq@ && ip1 == ip2) { + LOOP_BLOCKED(@type@, 64) { + @vtype@ a = @vpre@_load_@vsuf@(&ip1[i + 0 * 16 / sizeof(@type@)]); + @vtype@ b = @vpre@_load_@vsuf@(&ip1[i + 1 * 16 / sizeof(@type@)]); + @vtype@ c = @vpre@_load_@vsuf@(&ip1[i + 2 * 16 / sizeof(@type@)]); + @vtype@ d = @vpre@_load_@vsuf@(&ip1[i + 3 * 16 / sizeof(@type@)]); + @vtype@ r1 = @vpre@_@VOP@_@vsuf@(a, a); + @vtype@ r2 = @vpre@_@VOP@_@vsuf@(b, b); + @vtype@ r3 = @vpre@_@VOP@_@vsuf@(c, c); + @vtype@ r4 = @vpre@_@VOP@_@vsuf@(d, d); + sse2_compress4_to_byte_@TYPE@(r1, r2, r3, &r4, &op[i]); + } + } + else { + LOOP_BLOCKED(@type@, 64) { + @vtype@ a1 = @vpre@_load_@vsuf@(&ip1[i + 0 * 16 / sizeof(@type@)]); + @vtype@ b1 = @vpre@_load_@vsuf@(&ip1[i + 1 * 16 / sizeof(@type@)]); + @vtype@ c1 = @vpre@_load_@vsuf@(&ip1[i + 2 * 16 / sizeof(@type@)]); + @vtype@ d1 = @vpre@_load_@vsuf@(&ip1[i + 3 * 16 / sizeof(@type@)]); + @vtype@ a2 = @vpre@_loadu_@vsuf@(&ip2[i + 0 * 16 / sizeof(@type@)]); + @vtype@ b2 = @vpre@_loadu_@vsuf@(&ip2[i + 1 * 16 / sizeof(@type@)]); + @vtype@ c2 = @vpre@_loadu_@vsuf@(&ip2[i + 2 * 16 / sizeof(@type@)]); + @vtype@ d2 = @vpre@_loadu_@vsuf@(&ip2[i + 3 * 16 / sizeof(@type@)]); + @vtype@ r1 = @vpre@_@VOP@_@vsuf@(a1, a2); + @vtype@ r2 = @vpre@_@VOP@_@vsuf@(b1, b2); + @vtype@ r3 = @vpre@_@VOP@_@vsuf@(c1, c2); + @vtype@ r4 = @vpre@_@VOP@_@vsuf@(d1, d2); + sse2_compress4_to_byte_@TYPE@(r1, r2, r3, &r4, &op[i]); + } } LOOP_BLOCKED_END { op[i] = sse2_ordered_cmp_@kind@_@TYPE@(ip1[i], ip2[i]); @@ -548,19 +568,20 @@ sse2_binary_@kind@_@TYPE@(npy_bool * op, @type@ * ip1, @type@ * ip2, npy_intp n) static void sse2_binary_scalar1_@kind@_@TYPE@(npy_bool * op, @type@ * ip1, @type@ * ip2, npy_intp n) { - npy_bool * r; - @vtype@ a = @vpre@_set1_@vsuf@(ip1[0]); + @vtype@ s = @vpre@_set1_@vsuf@(ip1[0]); LOOP_BLOCK_ALIGN_VAR(ip2, @type@, 16) { op[i] = sse2_ordered_cmp_@kind@_@TYPE@(ip1[0], ip2[i]); } - r = &op[i]; - LOOP_BLOCKED(@type@, 16) { - @vtype@ b = @vpre@_load_@vsuf@(&ip2[i]); - @vtype@ c = @vpre@_@VOP@_@vsuf@(a, b); - @mtype@ ir = @fanout@[@vpre@_movemask_@vsuf@(c)]; - /* may be unaligned */ - memcpy(r, &ir, sizeof(ir)); - r += sizeof(ir); + LOOP_BLOCKED(@type@, 64) { + @vtype@ a = @vpre@_load_@vsuf@(&ip2[i + 0 * 16 / sizeof(@type@)]); + @vtype@ b = @vpre@_load_@vsuf@(&ip2[i + 1 * 16 / sizeof(@type@)]); + @vtype@ c = @vpre@_load_@vsuf@(&ip2[i + 2 * 16 / sizeof(@type@)]); + @vtype@ d = @vpre@_load_@vsuf@(&ip2[i + 3 * 16 / sizeof(@type@)]); + @vtype@ r1 = @vpre@_@VOP@_@vsuf@(s, a); + @vtype@ r2 = @vpre@_@VOP@_@vsuf@(s, b); + @vtype@ r3 = @vpre@_@VOP@_@vsuf@(s, c); + @vtype@ r4 = @vpre@_@VOP@_@vsuf@(s, d); + sse2_compress4_to_byte_@TYPE@(r1, r2, r3, &r4, &op[i]); } LOOP_BLOCKED_END { op[i] = sse2_ordered_cmp_@kind@_@TYPE@(ip1[0], ip2[i]); @@ -571,19 +592,20 @@ sse2_binary_scalar1_@kind@_@TYPE@(npy_bool * op, @type@ * ip1, @type@ * ip2, npy static void sse2_binary_scalar2_@kind@_@TYPE@(npy_bool * op, @type@ * ip1, @type@ * ip2, npy_intp n) { - npy_bool * r; - @vtype@ b = @vpre@_set1_@vsuf@(ip2[0]); + @vtype@ s = @vpre@_set1_@vsuf@(ip2[0]); LOOP_BLOCK_ALIGN_VAR(ip1, @type@, 16) { op[i] = sse2_ordered_cmp_@kind@_@TYPE@(ip1[i], ip2[0]); } - r = &op[i]; - LOOP_BLOCKED(@type@, 16) { - @vtype@ a = @vpre@_load_@vsuf@(&ip1[i]); - @vtype@ c = @vpre@_@VOP@_@vsuf@(a, b); - @mtype@ ir = @fanout@[@vpre@_movemask_@vsuf@(c)]; - /* may be unaligned */ - memcpy(r, &ir, sizeof(ir)); - r += sizeof(ir); + LOOP_BLOCKED(@type@, 64) { + @vtype@ a = @vpre@_load_@vsuf@(&ip1[i + 0 * 16 / sizeof(@type@)]); + @vtype@ b = @vpre@_load_@vsuf@(&ip1[i + 1 * 16 / sizeof(@type@)]); + @vtype@ c = @vpre@_load_@vsuf@(&ip1[i + 2 * 16 / sizeof(@type@)]); + @vtype@ d = @vpre@_load_@vsuf@(&ip1[i + 3 * 16 / sizeof(@type@)]); + @vtype@ r1 = @vpre@_@VOP@_@vsuf@(a, s); + @vtype@ r2 = @vpre@_@VOP@_@vsuf@(b, s); + @vtype@ r3 = @vpre@_@VOP@_@vsuf@(c, s); + @vtype@ r4 = @vpre@_@VOP@_@vsuf@(d, s); + sse2_compress4_to_byte_@TYPE@(r1, r2, r3, &r4, &op[i]); } LOOP_BLOCKED_END { op[i] = sse2_ordered_cmp_@kind@_@TYPE@(ip1[i], ip2[0]); @@ -617,41 +639,56 @@ sse2_sqrt_@TYPE@(@type@ * op, @type@ * ip, const npy_intp n) } +static NPY_INLINE +@type@ scalar_abs_@type@(@type@ v) +{ + /* add 0 to clear -0.0 */ + return (v > 0 ? v: -v) + 0; +} + +static NPY_INLINE +@type@ scalar_neg_@type@(@type@ v) +{ + return -v; +} + +/**begin repeat1 + * #kind = absolute, negative# + * #VOP = andnot, xor# + * #scalar = scalar_abs, scalar_neg# + **/ static void -sse2_absolute_@TYPE@(@type@ * op, @type@ * ip, const npy_intp n) +sse2_@kind@_@TYPE@(@type@ * op, @type@ * ip, const npy_intp n) { /* * get 0x7FFFFFFF mask (everything but signbit set) - * float & ~mask will remove the sign + * float & ~mask will remove the sign, float ^ mask flips the sign * this is equivalent to how the compiler implements fabs on amd64 */ const @vtype@ mask = @vpre@_set1_@vsuf@(-0.@c@); /* align output to 16 bytes */ LOOP_BLOCK_ALIGN_VAR(op, @type@, 16) { - const @type@ tmp = ip[i] > 0 ? ip[i]: -ip[i]; - /* add 0 to clear -0.0 */ - op[i] = tmp + 0; + op[i] = @scalar@_@type@(ip[i]); } assert(n < (16 / sizeof(@type@)) || npy_is_aligned(&op[i], 16)); if (npy_is_aligned(&ip[i], 16)) { LOOP_BLOCKED(@type@, 16) { @vtype@ a = @vpre@_load_@vsuf@(&ip[i]); - @vpre@_store_@vsuf@(&op[i], @vpre@_andnot_@vsuf@(mask, a)); + @vpre@_store_@vsuf@(&op[i], @vpre@_@VOP@_@vsuf@(mask, a)); } } else { LOOP_BLOCKED(@type@, 16) { @vtype@ a = @vpre@_loadu_@vsuf@(&ip[i]); - @vpre@_store_@vsuf@(&op[i], @vpre@_andnot_@vsuf@(mask, a)); + @vpre@_store_@vsuf@(&op[i], @vpre@_@VOP@_@vsuf@(mask, a)); } } LOOP_BLOCKED_END { - const @type@ tmp = ip[i] > 0 ? ip[i]: -ip[i]; - /* add 0 to clear -0.0 */ - op[i] = tmp + 0; + op[i] = @scalar@_@type@(ip[i]); } } +/**end repeat1**/ /**begin repeat1 diff --git a/numpy/core/src/umath/test_rational.c.src b/numpy/core/src/umath/test_rational.c.src index d8f90f9e5..5ce792266 100644 --- a/numpy/core/src/umath/test_rational.c.src +++ b/numpy/core/src/umath/test_rational.c.src @@ -846,7 +846,6 @@ npyrational_compare(const void* d0, const void* d1, void* arr) { data = (rational*)data_; \ best_i = 0; \ best_r = data[0]; \ - i; \ for (i = 1; i < n; i++) { \ if (rational_##op(data[i],best_r)) { \ best_i = i; \ @@ -1240,8 +1239,9 @@ PyMODINIT_FUNC inittest_rational(void) { } \ if (sizeof(_types)/sizeof(int)!=ufunc->nargs) { \ PyErr_Format(PyExc_AssertionError, \ - "ufunc %s takes %d arguments, our loop takes %ld", \ - #name, ufunc->nargs, sizeof(_types)/sizeof(int)); \ + "ufunc %s takes %d arguments, our loop takes %lu", \ + #name, ufunc->nargs, (unsigned long) \ + (sizeof(_types)/sizeof(int))); \ Py_DECREF(ufunc); \ goto fail; \ } \ diff --git a/numpy/core/src/umath/ufunc_object.c b/numpy/core/src/umath/ufunc_object.c index 5b881c0c7..45966902b 100644 --- a/numpy/core/src/umath/ufunc_object.c +++ b/numpy/core/src/umath/ufunc_object.c @@ -73,7 +73,7 @@ static int _does_loop_use_arrays(void *data); static int -_extract_pyvals(PyObject *ref, char *name, int *bufsize, +_extract_pyvals(PyObject *ref, const char *name, int *bufsize, int *errmask, PyObject **errobj); static int @@ -237,7 +237,7 @@ static int PyUFunc_NUM_NODEFAULTS = 0; #endif static PyObject * -_get_global_ext_obj(char * name) +get_global_ext_obj(void) { PyObject *thedict; PyObject *ref = NULL; @@ -259,12 +259,12 @@ _get_global_ext_obj(char * name) static int -_get_bufsize_errmask(PyObject * extobj, char * ufunc_name, +_get_bufsize_errmask(PyObject * extobj, const char *ufunc_name, int *buffersize, int *errormask) { /* Get the buffersize and errormask */ if (extobj == NULL) { - extobj = _get_global_ext_obj(ufunc_name); + extobj = get_global_ext_obj(); } if (_extract_pyvals(extobj, ufunc_name, buffersize, errormask, NULL) < 0) { @@ -430,7 +430,7 @@ _find_array_prepare(PyObject *args, PyObject *kwds, * if an error handling method is 'call' */ static int -_extract_pyvals(PyObject *ref, char *name, int *bufsize, +_extract_pyvals(PyObject *ref, const char *name, int *bufsize, int *errmask, PyObject **errobj) { PyObject *retval; @@ -518,41 +518,41 @@ _extract_pyvals(PyObject *ref, char *name, int *bufsize, NPY_NO_EXPORT int PyUFunc_GetPyValues(char *name, int *bufsize, int *errmask, PyObject **errobj) { - PyObject *ref = _get_global_ext_obj(name); + PyObject *ref = get_global_ext_obj(); return _extract_pyvals(ref, name, bufsize, errmask, errobj); } -#define _GETATTR_(str, rstr) do {if (strcmp(name, #str) == 0) \ +#define GETATTR(str, rstr) do {if (strcmp(name, #str) == 0) \ return PyObject_HasAttrString(op, "__" #rstr "__");} while (0); static int -_has_reflected_op(PyObject *op, char *name) +_has_reflected_op(PyObject *op, const char *name) { - _GETATTR_(add, radd); - _GETATTR_(subtract, rsub); - _GETATTR_(multiply, rmul); - _GETATTR_(divide, rdiv); - _GETATTR_(true_divide, rtruediv); - _GETATTR_(floor_divide, rfloordiv); - _GETATTR_(remainder, rmod); - _GETATTR_(power, rpow); - _GETATTR_(left_shift, rlshift); - _GETATTR_(right_shift, rrshift); - _GETATTR_(bitwise_and, rand); - _GETATTR_(bitwise_xor, rxor); - _GETATTR_(bitwise_or, ror); + GETATTR(add, radd); + GETATTR(subtract, rsub); + GETATTR(multiply, rmul); + GETATTR(divide, rdiv); + GETATTR(true_divide, rtruediv); + GETATTR(floor_divide, rfloordiv); + GETATTR(remainder, rmod); + GETATTR(power, rpow); + GETATTR(left_shift, rlshift); + GETATTR(right_shift, rrshift); + GETATTR(bitwise_and, rand); + GETATTR(bitwise_xor, rxor); + GETATTR(bitwise_or, ror); /* Comparisons */ - _GETATTR_(equal, eq); - _GETATTR_(not_equal, ne); - _GETATTR_(greater, lt); - _GETATTR_(less, gt); - _GETATTR_(greater_equal, le); - _GETATTR_(less_equal, ge); + GETATTR(equal, eq); + GETATTR(not_equal, ne); + GETATTR(greater, lt); + GETATTR(less, gt); + GETATTR(greater_equal, le); + GETATTR(less_equal, ge); return 0; } -#undef _GETATTR_ +#undef GETATTR /* Return the position of next non-white-space char in the string */ @@ -779,7 +779,7 @@ static int get_ufunc_arguments(PyUFuncObject *ufunc, int i, nargs, nin = ufunc->nin; PyObject *obj, *context; PyObject *str_key_obj = NULL; - char *ufunc_name; + const char *ufunc_name; int type_num; int any_flexible = 0, any_object = 0, any_flexible_userloops = 0; @@ -1153,9 +1153,7 @@ trivial_two_operand_loop(PyArrayObject **op, innerloop(data, count, stride, innerloopdata); - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; } static void @@ -1186,9 +1184,7 @@ trivial_three_operand_loop(PyArrayObject **op, innerloop(data, count, stride, innerloopdata); - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; } /* @@ -1270,7 +1266,6 @@ iterator_loop(PyUFuncObject *ufunc, npy_uint32 op_flags[NPY_MAXARGS]; NpyIter *iter; char *baseptrs[NPY_MAXARGS]; - int needs_api; NpyIter_IterNextFunc *iternext; char **dataptr; @@ -1325,8 +1320,6 @@ iterator_loop(PyUFuncObject *ufunc, return -1; } - needs_api = NpyIter_IterationNeedsAPI(iter); - /* Copy any allocated outputs */ op_it = NpyIter_GetOperandArray(iter); for (i = nin; i < nop; ++i) { @@ -1370,9 +1363,7 @@ iterator_loop(PyUFuncObject *ufunc, stride = NpyIter_GetInnerStrideArray(iter); count_ptr = NpyIter_GetInnerLoopSizePtr(iter); - if (!needs_api) { - NPY_BEGIN_THREADS; - } + NPY_BEGIN_THREADS_NDITER(iter); /* Execute the loop */ do { @@ -1380,9 +1371,7 @@ iterator_loop(PyUFuncObject *ufunc, innerloop(dataptr, count_ptr, stride, innerloopdata); } while (iternext(iter)); - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; } NpyIter_Deallocate(iter); @@ -1579,8 +1568,6 @@ execute_fancy_ufunc_loop(PyUFuncObject *ufunc, PyArrayObject **op_it; npy_uint32 iter_flags; - NPY_BEGIN_THREADS_DEF; - if (wheremask != NULL) { if (nop + 1 > NPY_MAXARGS) { PyErr_SetString(PyExc_ValueError, @@ -1669,6 +1656,7 @@ execute_fancy_ufunc_loop(PyUFuncObject *ufunc, NpyAuxData *innerloopdata; npy_intp fixed_strides[2*NPY_MAXARGS]; PyArray_Descr **iter_dtypes; + NPY_BEGIN_THREADS_DEF; /* Validate that the prepare_ufunc_output didn't mess with pointers */ for (i = nin; i < nop; ++i) { @@ -1708,9 +1696,7 @@ execute_fancy_ufunc_loop(PyUFuncObject *ufunc, strides = NpyIter_GetInnerStrideArray(iter); countptr = NpyIter_GetInnerLoopSizePtr(iter); - if (!needs_api) { - NPY_BEGIN_THREADS; - } + NPY_BEGIN_THREADS_NDITER(iter); NPY_UF_DBG_PRINT("Actual inner loop:\n"); /* Execute the loop */ @@ -1721,9 +1707,7 @@ execute_fancy_ufunc_loop(PyUFuncObject *ufunc, *countptr, innerloopdata); } while (iternext(iter)); - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; NPY_AUXDATA_FREE(innerloopdata); } @@ -1777,8 +1761,8 @@ make_arr_prep_args(npy_intp nin, PyObject *args, PyObject *kwds) * may be null, in which case the thread global one is fetched * - ufunc_name: name of ufunc */ -static int -_check_ufunc_fperr(int errmask, PyObject *extobj, char* ufunc_name) { +static int +_check_ufunc_fperr(int errmask, PyObject *extobj, const char *ufunc_name) { int fperr; PyObject *errobj = NULL; int ret; @@ -1794,7 +1778,7 @@ _check_ufunc_fperr(int errmask, PyObject *extobj, char* ufunc_name) { /* Get error object globals */ if (extobj == NULL) { - extobj = _get_global_ext_obj(ufunc_name); + extobj = get_global_ext_obj(); } if (_extract_pyvals(extobj, ufunc_name, NULL, NULL, &errobj) < 0) { @@ -1816,7 +1800,7 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, { int nin, nout; int i, j, idim, nop; - char *ufunc_name; + const char *ufunc_name; int retval = -1, subok = 1; int needs_api = 0; @@ -2167,6 +2151,11 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, */ inner_strides = (npy_intp *)PyArray_malloc( NPY_SIZEOF_INTP * (nop+core_dim_ixs_size)); + if (inner_strides == NULL) { + PyErr_NoMemory(); + retval = -1; + goto fail; + } /* Copy the strides after the first nop */ idim = nop; for (i = 0; i < nop; ++i) { @@ -2241,7 +2230,6 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, /* Get the variables needed for the loop */ iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { - NpyIter_Deallocate(iter); retval = -1; goto fail; } @@ -2273,11 +2261,13 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, PyErr_Format(PyExc_ValueError, "ufunc %s ", ufunc_name); + retval = -1; goto fail; default: PyErr_Format(PyExc_ValueError, "ufunc %s has an invalid identity for reduction", ufunc_name); + retval = -1; goto fail; } } @@ -2335,7 +2325,7 @@ PyUFunc_GenericFunction(PyUFuncObject *ufunc, { int nin, nout; int i, nop; - char *ufunc_name; + const char *ufunc_name; int retval = -1, subok = 1; int need_fancy = 0; @@ -2438,7 +2428,7 @@ PyUFunc_GenericFunction(PyUFuncObject *ufunc, */ if (nin == 2 && nout == 1 && dtypes[1]->type_num == NPY_OBJECT) { PyObject *_obj = PyTuple_GET_ITEM(args, 1); - if (!PyArray_CheckExact(_obj)) { + if (!PyArray_Check(_obj)) { double self_prio, other_prio; self_prio = PyArray_GetPriority(PyTuple_GET_ITEM(args, 0), NPY_SCALAR_PRIORITY); @@ -2650,7 +2640,7 @@ reduce_type_resolver(PyUFuncObject *ufunc, PyArrayObject *arr, int i, retcode; PyArrayObject *op[3] = {arr, arr, NULL}; PyArray_Descr *dtypes[3] = {NULL, NULL, NULL}; - char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; + const char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; PyObject *type_tup = NULL; *out_dtype = NULL; @@ -2742,9 +2732,7 @@ reduce_loop(NpyIter *iter, char **dataptrs, npy_intp *strides, return -1; } - if (!needs_api) { - NPY_BEGIN_THREADS; - } + NPY_BEGIN_THREADS_NDITER(iter); if (skip_first_count > 0) { do { @@ -2797,9 +2785,7 @@ reduce_loop(NpyIter *iter, char **dataptrs, npy_intp *strides, } while (iternext(iter)); finish_loop: - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; return (needs_api && PyErr_Occurred()) ? -1 : 0; } @@ -2830,7 +2816,7 @@ PyUFunc_Reduce(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *out, PyArray_Descr *dtype; PyArrayObject *result; PyArray_AssignReduceIdentityFunc *assign_identity = NULL; - char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; + const char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; /* These parameters come from a TLS global */ int buffersize = 0, errormask = 0; @@ -2926,7 +2912,7 @@ PyUFunc_Accumulate(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *out, PyUFuncGenericFunction innerloop = NULL; void *innerloopdata = NULL; - char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; + const char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; /* These parameters come from extobj= or from a TLS global */ int buffersize = 0, errormask = 0; @@ -3126,9 +3112,7 @@ PyUFunc_Accumulate(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *out, needs_api = NpyIter_IterationNeedsAPI(iter); - if (!needs_api) { - NPY_BEGIN_THREADS; - } + NPY_BEGIN_THREADS_NDITER(iter); do { @@ -3158,9 +3142,7 @@ PyUFunc_Accumulate(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *out, } } while (iternext(iter)); - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; } else if (iter == NULL) { char *dataptr_copy[3]; @@ -3215,15 +3197,13 @@ PyUFunc_Accumulate(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *out, needs_api = PyDataType_REFCHK(op_dtypes[0]); if (!needs_api) { - NPY_BEGIN_THREADS; + NPY_BEGIN_THREADS_THRESHOLDED(count); } innerloop(dataptr_copy, &count, stride_copy, innerloopdata); - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; } } @@ -3274,7 +3254,7 @@ PyUFunc_Reduceat(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *ind, op_axes_arrays[2]}; npy_uint32 op_flags[3]; int i, idim, ndim, otype_final; - int needs_api, need_outer_iterator; + int need_outer_iterator; NpyIter *iter = NULL; @@ -3285,7 +3265,7 @@ PyUFunc_Reduceat(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *ind, PyUFuncGenericFunction innerloop = NULL; void *innerloopdata = NULL; - char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; + const char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; char *opname = "reduceat"; /* These parameters come from extobj= or from a TLS global */ @@ -3519,11 +3499,7 @@ PyUFunc_Reduceat(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *ind, stride_copy[1] = stride1; stride_copy[2] = stride0; - needs_api = NpyIter_IterationNeedsAPI(iter); - - if (!needs_api) { - NPY_BEGIN_THREADS; - } + NPY_BEGIN_THREADS_NDITER(iter); do { @@ -3560,9 +3536,7 @@ PyUFunc_Reduceat(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *ind, } } while (iternext(iter)); - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; } else if (iter == NULL) { char *dataptr_copy[3]; @@ -3575,7 +3549,7 @@ PyUFunc_Reduceat(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *ind, /* Execute the loop with no iterators */ npy_intp stride0 = 0, stride1 = PyArray_STRIDE(op[1], axis); - needs_api = PyDataType_REFCHK(op_dtypes[0]); + int needs_api = PyDataType_REFCHK(op_dtypes[0]); NPY_UF_DBG_PRINT("UFunc: Reduce loop with no iterators\n"); @@ -3619,9 +3593,7 @@ PyUFunc_Reduceat(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *ind, } } - if (!needs_api) { - NPY_END_THREADS; - } + NPY_END_THREADS; } finish: @@ -4093,7 +4065,7 @@ ufunc_generic_call(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) mps[i] = NULL; } - errval = PyUFunc_CheckOverride(ufunc, "__call__", args, kwds, &override, + errval = PyUFunc_CheckOverride(ufunc, "__call__", args, kwds, &override, ufunc->nin); if (errval) { return NULL; @@ -4333,7 +4305,7 @@ NPY_NO_EXPORT PyObject * PyUFunc_FromFuncAndData(PyUFuncGenericFunction *func, void **data, char *types, int ntypes, int nin, int nout, int identity, - char *name, char *doc, int check_return) + const char *name, const char *doc, int check_return) { return PyUFunc_FromFuncAndDataAndSignature(func, data, types, ntypes, nin, nout, identity, name, doc, check_return, NULL); @@ -4344,7 +4316,7 @@ NPY_NO_EXPORT PyObject * PyUFunc_FromFuncAndDataAndSignature(PyUFuncGenericFunction *func, void **data, char *types, int ntypes, int nin, int nout, int identity, - char *name, char *doc, + const char *name, const char *doc, int check_return, const char *signature) { PyUFuncObject *ufunc; @@ -4778,6 +4750,8 @@ static PyObject * ufunc_outer(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) { int i; + int errval; + PyObject *override = NULL; PyObject *ret; PyArrayObject *ap1 = NULL, *ap2 = NULL, *ap_new = NULL; PyObject *new_args, *tmp; @@ -4802,6 +4776,15 @@ ufunc_outer(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) return NULL; } + /* `nin`, the last arg, is unused. So we put 0. */ + errval = PyUFunc_CheckOverride(ufunc, "outer", args, kwds, &override, 0); + if (errval) { + return NULL; + } + else if (override) { + return override; + } + tmp = PySequence_GetItem(args, 0); if (tmp == NULL) { return NULL; @@ -4871,8 +4854,8 @@ ufunc_reduce(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) int errval; PyObject *override = NULL; - errval = PyUFunc_CheckOverride(ufunc, "reduce", args, kwds, &override, - ufunc->nin); + /* `nin`, the last arg, is unused. So we put 0. */ + errval = PyUFunc_CheckOverride(ufunc, "reduce", args, kwds, &override, 0); if (errval) { return NULL; } @@ -4888,8 +4871,8 @@ ufunc_accumulate(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) int errval; PyObject *override = NULL; - errval = PyUFunc_CheckOverride(ufunc, "accumulate", args, kwds, &override, - ufunc->nin); + /* `nin`, the last arg, is unused. So we put 0. */ + errval = PyUFunc_CheckOverride(ufunc, "accumulate", args, kwds, &override, 0); if (errval) { return NULL; } @@ -4905,8 +4888,8 @@ ufunc_reduceat(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) int errval; PyObject *override = NULL; - errval = PyUFunc_CheckOverride(ufunc, "reduceat", args, kwds, &override, - ufunc->nin); + /* `nin`, the last arg, is unused. So we put 0. */ + errval = PyUFunc_CheckOverride(ufunc, "reduceat", args, kwds, &override, 0); if (errval) { return NULL; } @@ -4958,13 +4941,27 @@ ufunc_at(PyUFuncObject *ufunc, PyObject *args) int i; int nop; + /* override vars */ + int errval; + PyObject *override = NULL; + NpyIter *iter_buffer; NpyIter_IterNextFunc *iternext; npy_uint32 op_flags[NPY_MAXARGS]; int buffersize; int errormask = 0; + char * err_msg = NULL; NPY_BEGIN_THREADS_DEF; + /* `nin`, the last arg, is unused. So we put 0. */ + errval = PyUFunc_CheckOverride(ufunc, "at", args, NULL, &override, 0); + if (errval) { + return NULL; + } + else if (override) { + return override; + } + if (ufunc->nin > 2) { PyErr_SetString(PyExc_ValueError, "Only unary and binary ufuncs supported at this time"); @@ -5162,7 +5159,11 @@ ufunc_at(PyUFuncObject *ufunc, PyObject *args) } /* Reset NpyIter data pointers which will trigger a buffer copy */ - NpyIter_ResetBasePointers(iter_buffer, dataptr, NULL); + NpyIter_ResetBasePointers(iter_buffer, dataptr, &err_msg); + if (err_msg) { + break; + } + buffer_dataptr = NpyIter_GetDataPtrArray(iter_buffer); innerloop(buffer_dataptr, count, stride, innerloopdata); @@ -5185,8 +5186,10 @@ ufunc_at(PyUFuncObject *ufunc, PyObject *args) i--; } - if (!needs_api) { - NPY_END_THREADS; + NPY_END_THREADS; + + if (err_msg) { + PyErr_SetString(PyExc_ValueError, err_msg); } NpyIter_Deallocate(iter_buffer); diff --git a/numpy/core/src/umath/ufunc_type_resolution.c b/numpy/core/src/umath/ufunc_type_resolution.c index 12d8e406b..3beb25cf1 100644 --- a/numpy/core/src/umath/ufunc_type_resolution.c +++ b/numpy/core/src/umath/ufunc_type_resolution.c @@ -58,7 +58,7 @@ PyUFunc_ValidateCasting(PyUFuncObject *ufunc, PyArray_Descr **dtypes) { int i, nin = ufunc->nin, nop = nin + ufunc->nout; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -186,7 +186,7 @@ PyUFunc_SimpleBinaryComparisonTypeResolver(PyUFuncObject *ufunc, PyArray_Descr **out_dtypes) { int i, type_num1, type_num2; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -292,7 +292,7 @@ PyUFunc_SimpleUnaryOperationTypeResolver(PyUFuncObject *ufunc, PyArray_Descr **out_dtypes) { int i, type_num1; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -367,6 +367,34 @@ PyUFunc_SimpleUnaryOperationTypeResolver(PyUFuncObject *ufunc, return 0; } + +NPY_NO_EXPORT int +PyUFunc_NegativeTypeResolver(PyUFuncObject *ufunc, + NPY_CASTING casting, + PyArrayObject **operands, + PyObject *type_tup, + PyArray_Descr **out_dtypes) +{ + int ret; + ret = PyUFunc_SimpleUnaryOperationTypeResolver(ufunc, casting, operands, + type_tup, out_dtypes); + if (ret < 0) { + return ret; + } + + /* The type resolver would have upcast already */ + if (out_dtypes[0]->type_num == NPY_BOOL) { + if (DEPRECATE("numpy boolean negative (the unary `-` operator) is " + "deprecated, use the bitwise_xor (the `^` operator) " + "or the logical_xor function instead.") < 0) { + return -1; + } + } + + return ret; +} + + /* * The ones_like function shouldn't really be a ufunc, but while it * still is, this provides type resolution that always forces UNSAFE @@ -405,7 +433,7 @@ PyUFunc_SimpleBinaryOperationTypeResolver(PyUFuncObject *ufunc, PyArray_Descr **out_dtypes) { int i, type_num1, type_num2; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -563,7 +591,7 @@ PyUFunc_AdditionTypeResolver(PyUFuncObject *ufunc, { int type_num1, type_num2; int i; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -753,7 +781,7 @@ PyUFunc_SubtractionTypeResolver(PyUFuncObject *ufunc, { int type_num1, type_num2; int i; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -762,8 +790,22 @@ PyUFunc_SubtractionTypeResolver(PyUFuncObject *ufunc, /* Use the default when datetime and timedelta are not involved */ if (!PyTypeNum_ISDATETIME(type_num1) && !PyTypeNum_ISDATETIME(type_num2)) { - return PyUFunc_SimpleBinaryOperationTypeResolver(ufunc, casting, - operands, type_tup, out_dtypes); + int ret; + ret = PyUFunc_SimpleBinaryOperationTypeResolver(ufunc, casting, + operands, type_tup, out_dtypes); + if (ret < 0) { + return ret; + } + + /* The type resolver would have upcast already */ + if (out_dtypes[0]->type_num == NPY_BOOL) { + if (DEPRECATE("numpy boolean subtract (the binary `-` operator) is " + "deprecated, use the bitwise_xor (the `^` operator) " + "or the logical_xor function instead.") < 0) { + return -1; + } + } + return ret; } if (type_num1 == NPY_TIMEDELTA) { @@ -921,7 +963,7 @@ PyUFunc_MultiplicationTypeResolver(PyUFuncObject *ufunc, { int type_num1, type_num2; int i; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -1064,7 +1106,7 @@ PyUFunc_DivisionTypeResolver(PyUFuncObject *ufunc, { int type_num1, type_num2; int i; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -1833,7 +1875,7 @@ linear_search_type_resolver(PyUFuncObject *self, { npy_intp i, j, nin = self->nin, nop = nin + self->nout; int types[NPY_MAXARGS]; - char *ufunc_name; + const char *ufunc_name; int no_castable_output, use_min_scalar; /* For making a better error message on coercion error */ @@ -1942,7 +1984,7 @@ type_tuple_type_resolver(PyUFuncObject *self, npy_intp i, j, n, nin = self->nin, nop = nin + self->nout; int n_specified = 0; int specified_types[NPY_MAXARGS], types[NPY_MAXARGS]; - char *ufunc_name; + const char *ufunc_name; int no_castable_output, use_min_scalar; /* For making a better error message on coercion error */ diff --git a/numpy/core/src/umath/ufunc_type_resolution.h b/numpy/core/src/umath/ufunc_type_resolution.h index a1241827e..a1e28d75b 100644 --- a/numpy/core/src/umath/ufunc_type_resolution.h +++ b/numpy/core/src/umath/ufunc_type_resolution.h @@ -16,6 +16,13 @@ PyUFunc_SimpleUnaryOperationTypeResolver(PyUFuncObject *ufunc, PyArray_Descr **out_dtypes); NPY_NO_EXPORT int +PyUFunc_NegativeTypeResolver(PyUFuncObject *ufunc, + NPY_CASTING casting, + PyArrayObject **operands, + PyObject *type_tup, + PyArray_Descr **out_dtypes); + +NPY_NO_EXPORT int PyUFunc_OnesLikeTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, diff --git a/numpy/core/src/umath/umathmodule.c b/numpy/core/src/umath/umathmodule.c index f395d5096..52aa2e48d 100644 --- a/numpy/core/src/umath/umathmodule.c +++ b/numpy/core/src/umath/umathmodule.c @@ -54,16 +54,15 @@ object_ufunc_type_resolver(PyUFuncObject *ufunc, PyArray_Descr **out_dtypes) { int i, nop = ufunc->nin + ufunc->nout; - PyArray_Descr *obj_dtype; - obj_dtype = PyArray_DescrFromType(NPY_OBJECT); - if (obj_dtype == NULL) { + out_dtypes[0] = PyArray_DescrFromType(NPY_OBJECT); + if (out_dtypes[0] == NULL) { return -1; } - for (i = 0; i < nop; ++i) { - Py_INCREF(obj_dtype); - out_dtypes[i] = obj_dtype; + for (i = 1; i < nop; ++i) { + Py_INCREF(out_dtypes[0]); + out_dtypes[i] = out_dtypes[0]; } return 0; @@ -215,9 +214,6 @@ static PyUFuncGenericFunction frexp_functions[] = { #endif }; -static void * blank3_data[] = { (void *)NULL, (void *)NULL, (void *)NULL}; -static void * blank6_data[] = { (void *)NULL, (void *)NULL, (void *)NULL, - (void *)NULL, (void *)NULL, (void *)NULL}; static char frexp_signatures[] = { #ifdef HAVE_FREXPF NPY_HALF, NPY_HALF, NPY_INT, @@ -228,6 +224,7 @@ static char frexp_signatures[] = { ,NPY_LONGDOUBLE, NPY_LONGDOUBLE, NPY_INT #endif }; +static void * blank_data[12]; #if NPY_SIZEOF_LONG == NPY_SIZEOF_INT #define LDEXP_LONG(typ) typ##_ldexp @@ -251,6 +248,50 @@ static PyUFuncGenericFunction ldexp_functions[] = { #endif }; +static const char frdoc[] = + " Decompose the elements of x into mantissa and twos exponent.\n" + "\n" + " Returns (`mantissa`, `exponent`), where `x = mantissa * 2**exponent``.\n" + " The mantissa is lies in the open interval(-1, 1), while the twos\n" + " exponent is a signed integer.\n" + "\n" + " Parameters\n" + " ----------\n" + " x : array_like\n" + " Array of numbers to be decomposed.\n" + " out1: ndarray, optional\n" + " Output array for the mantissa. Must have the same shape as `x`.\n" + " out2: ndarray, optional\n" + " Output array for the exponent. Must have the same shape as `x`.\n" + "\n" + " Returns\n" + " -------\n" + " (mantissa, exponent) : tuple of ndarrays, (float, int)\n" + " `mantissa` is a float array with values between -1 and 1.\n" + " `exponent` is an int array which represents the exponent of 2.\n" + "\n" + " See Also\n" + " --------\n" + " ldexp : Compute ``y = x1 * 2**x2``, the inverse of `frexp`.\n" + "\n" + " Notes\n" + " -----\n" + " Complex dtypes are not supported, they will raise a TypeError.\n" + "\n" + " Examples\n" + " --------\n" + " >>> x = np.arange(9)\n" + " >>> y1, y2 = np.frexp(x)\n" + " >>> y1\n" + " array([ 0. , 0.5 , 0.5 , 0.75 , 0.5 , 0.625, 0.75 , 0.875,\n" + " 0.5 ])\n" + " >>> y2\n" + " array([0, 1, 2, 2, 3, 3, 3, 3, 4])\n" + " >>> y1 * 2**y2\n" + " array([ 0., 1., 2., 3., 4., 5., 6., 7., 8.])\n" + "\n"; + + static char ldexp_signatures[] = { #ifdef HAVE_LDEXPF NPY_HALF, NPY_INT, NPY_HALF, @@ -266,24 +307,66 @@ static char ldexp_signatures[] = { #endif }; +static const char lddoc[] = + " Returns x1 * 2**x2, element-wise.\n" + "\n" + " The mantissas `x1` and twos exponents `x2` are used to construct\n" + " floating point numbers ``x1 * 2**x2``.\n" + "\n" + " Parameters\n" + " ----------\n" + " x1 : array_like\n" + " Array of multipliers.\n" + " x2 : array_like, int\n" + " Array of twos exponents.\n" + " out : ndarray, optional\n" + " Output array for the result.\n" + "\n" + " Returns\n" + " -------\n" + " y : ndarray or scalar\n" + " The result of ``x1 * 2**x2``.\n" + "\n" + " See Also\n" + " --------\n" + " frexp : Return (y1, y2) from ``x = y1 * 2**y2``, inverse to `ldexp`.\n" + "\n" + " Notes\n" + " -----\n" + " Complex dtypes are not supported, they will raise a TypeError.\n" + "\n" + " `ldexp` is useful as the inverse of `frexp`, if used by itself it is\n" + " more clear to simply use the expression ``x1 * 2**x2``.\n" + "\n" + " Examples\n" + " --------\n" + " >>> np.ldexp(5, np.arange(4))\n" + " array([ 5., 10., 20., 40.], dtype=float32)\n" + "\n" + " >>> x = np.arange(6)\n" + " >>> np.ldexp(*np.frexp(x))\n" + " array([ 0., 1., 2., 3., 4., 5.])\n" + "\n"; + + static void InitOtherOperators(PyObject *dictionary) { PyObject *f; int num; num = sizeof(frexp_functions) / sizeof(frexp_functions[0]); - f = PyUFunc_FromFuncAndData(frexp_functions, blank3_data, + assert(sizeof(blank_data) / sizeof(blank_data[0]) >= num); + f = PyUFunc_FromFuncAndData(frexp_functions, blank_data, frexp_signatures, num, - 1, 2, PyUFunc_None, "frexp", - "Split the number, x, into a normalized"\ - " fraction (y1) and exponent (y2)",0); + 1, 2, PyUFunc_None, "frexp", frdoc, 0); PyDict_SetItemString(dictionary, "frexp", f); Py_DECREF(f); num = sizeof(ldexp_functions) / sizeof(ldexp_functions[0]); - f = PyUFunc_FromFuncAndData(ldexp_functions, blank6_data, ldexp_signatures, num, - 2, 1, PyUFunc_None, "ldexp", - "Compute y = x1 * 2**x2.",0); + assert(sizeof(blank_data) / sizeof(blank_data[0]) >= num); + f = PyUFunc_FromFuncAndData(ldexp_functions, blank_data, + ldexp_signatures, num, + 2, 1, PyUFunc_None, "ldexp", lddoc, 0); PyDict_SetItemString(dictionary, "ldexp", f); Py_DECREF(f); @@ -306,13 +389,13 @@ NPY_VISIBILITY_HIDDEN PyObject * npy_um_str_pyvals_name = NULL; static int intern_strings(void) { - npy_um_str_out = PyUString_FromString("out"); - npy_um_str_subok = PyUString_FromString("subok"); - npy_um_str_array_prepare = PyUString_FromString("__array_prepare__"); - npy_um_str_array_wrap = PyUString_FromString("__array_wrap__"); - npy_um_str_array_finalize = PyUString_FromString("__array_finalize__"); - npy_um_str_ufunc = PyUString_FromString("__numpy_ufunc__"); - npy_um_str_pyvals_name = PyUString_FromString(UFUNC_PYVALS_NAME); + npy_um_str_out = PyUString_InternFromString("out"); + npy_um_str_subok = PyUString_InternFromString("subok"); + npy_um_str_array_prepare = PyUString_InternFromString("__array_prepare__"); + npy_um_str_array_wrap = PyUString_InternFromString("__array_wrap__"); + npy_um_str_array_finalize = PyUString_InternFromString("__array_finalize__"); + npy_um_str_ufunc = PyUString_InternFromString("__numpy_ufunc__"); + npy_um_str_pyvals_name = PyUString_InternFromString(UFUNC_PYVALS_NAME); return npy_um_str_out && npy_um_str_subok && npy_um_str_array_prepare && npy_um_str_array_wrap && npy_um_str_array_finalize && npy_um_str_ufunc; diff --git a/numpy/core/tests/test_abc.py b/numpy/core/tests/test_abc.py new file mode 100644 index 000000000..54edd7e90 --- /dev/null +++ b/numpy/core/tests/test_abc.py @@ -0,0 +1,45 @@ +from __future__ import division, absolute_import, print_function + +import numpy as np +from numpy.testing import TestCase, assert_ + +import numbers +from numpy.core.numerictypes import sctypes + +class ABC(TestCase): + def test_floats(self): + for t in sctypes['float']: + assert_(isinstance(t(), numbers.Real), + "{0} is not instance of Real".format(t.__name__)) + assert_(issubclass(t, numbers.Real), + "{0} is not subclass of Real".format(t.__name__)) + assert_(not isinstance(t(), numbers.Rational), + "{0} is instance of Rational".format(t.__name__)) + assert_(not issubclass(t, numbers.Rational), + "{0} is subclass of Rational".format(t.__name__)) + + def test_complex(self): + for t in sctypes['complex']: + assert_(isinstance(t(), numbers.Complex), + "{0} is not instance of Complex".format(t.__name__)) + assert_(issubclass(t, numbers.Complex), + "{0} is not subclass of Complex".format(t.__name__)) + assert_(not isinstance(t(), numbers.Real), + "{0} is instance of Real".format(t.__name__)) + assert_(not issubclass(t, numbers.Real), + "{0} is subclass of Real".format(t.__name__)) + + def test_int(self): + for t in sctypes['int']: + assert_(isinstance(t(), numbers.Integral), + "{0} is not instance of Integral".format(t.__name__)) + assert_(issubclass(t, numbers.Integral), + "{0} is not subclass of Integral".format(t.__name__)) + + def test_uint(self): + for t in sctypes['uint']: + assert_(isinstance(t(), numbers.Integral), + "{0} is not instance of Integral".format(t.__name__)) + assert_(issubclass(t, numbers.Integral), + "{0} is not subclass of Integral".format(t.__name__)) + diff --git a/numpy/core/tests/test_api.py b/numpy/core/tests/test_api.py index a1a3f896c..2fd6463c7 100644 --- a/numpy/core/tests/test_api.py +++ b/numpy/core/tests/test_api.py @@ -278,6 +278,12 @@ def test_array_astype(): b = np.ndarray(buffer=a, dtype='uint32', shape=2) assert_(b.size == 2) + a = np.array([1000], dtype='i4') + assert_raises(TypeError, a.astype, 'S1', casting='safe') + + a = np.array(1000, dtype='i4') + assert_raises(TypeError, a.astype, 'U1', casting='safe') + def test_copyto_fromscalar(): a = np.arange(6, dtype='f4').reshape(2, 3) diff --git a/numpy/core/tests/test_datetime.py b/numpy/core/tests/test_datetime.py index 74aa0d5b9..bf0ba6807 100644 --- a/numpy/core/tests/test_datetime.py +++ b/numpy/core/tests/test_datetime.py @@ -592,6 +592,15 @@ class TestDateTime(TestCase): assert_raises(OverflowError, np.promote_types, np.dtype('m8[s]'), np.dtype('m8[as]')) + def test_cast_overflow(self): + # gh-4486 + def cast(): + numpy.datetime64("1971-01-01 00:00:00.000000000000000").astype("<M8[D]") + assert_raises(OverflowError, cast) + def cast2(): + numpy.datetime64("2014").astype("<M8[fs]") + assert_raises(OverflowError, cast2) + def test_pyobject_roundtrip(self): # All datetime types should be able to roundtrip through object diff --git a/numpy/core/tests/test_defchararray.py b/numpy/core/tests/test_defchararray.py index 09fcff0d0..2b45ba4bc 100644 --- a/numpy/core/tests/test_defchararray.py +++ b/numpy/core/tests/test_defchararray.py @@ -128,9 +128,9 @@ class TestWhitespace(TestCase): assert_(all(self.A == self.B)) assert_(all(self.A >= self.B)) assert_(all(self.A <= self.B)) - assert_(all(negative(self.A > self.B))) - assert_(all(negative(self.A < self.B))) - assert_(all(negative(self.A != self.B))) + assert_(not any(self.A > self.B)) + assert_(not any(self.A < self.B)) + assert_(not any(self.A != self.B)) class TestChar(TestCase): def setUp(self): @@ -138,7 +138,7 @@ class TestChar(TestCase): def test_it(self): assert_equal(self.A.shape, (4,)) - assert_equal(self.A.upper()[:2].tostring(), asbytes('AB')) + assert_equal(self.A.upper()[:2].tobytes(), asbytes('AB')) class TestComparisons(TestCase): def setUp(self): diff --git a/numpy/core/tests/test_deprecations.py b/numpy/core/tests/test_deprecations.py index 55ca0f573..a1f4664a5 100644 --- a/numpy/core/tests/test_deprecations.py +++ b/numpy/core/tests/test_deprecations.py @@ -11,7 +11,8 @@ import warnings from nose.plugins.skip import SkipTest import numpy as np -from numpy.testing import dec, run_module_suite, assert_raises +from numpy.testing import (dec, run_module_suite, assert_raises, + assert_warns, assert_array_equal) class _DeprecationTestCase(object): @@ -85,7 +86,7 @@ class _DeprecationTestCase(object): elif not ignore_others: raise AssertionError("expected DeprecationWarning but %s given" % warning.category) - if num_found != num: + if num is not None and num_found != num: raise AssertionError("%i warnings found but %i expected" % (len(self.log), num)) @@ -151,7 +152,7 @@ class TestFloatNonIntegerArgumentDeprecation(_DeprecationTestCase): 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, 0.0]) assert_deprecated(lambda: a[0.0, 0, 0]) assert_deprecated(lambda: a[0, 0.0, 0]) @@ -161,11 +162,10 @@ class TestFloatNonIntegerArgumentDeprecation(_DeprecationTestCase): 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[0, 0, -1.4]) assert_deprecated(lambda: a[-1.4, 0, 0]) assert_deprecated(lambda: a[0, -1.4, 0]) - # [1] These are duplicate because of the _tuple_of_integers quick check # Test that the slice parameter deprecation warning doesn't mask # the scalar index warning. @@ -296,5 +296,189 @@ class TestArrayToIndexDeprecation(_DeprecationTestCase): self.assert_deprecated(lambda: a[a:a:a], exceptions=(), num=3) +class TestNonIntegerArrayLike(_DeprecationTestCase): + """Tests that array likes, i.e. lists give a deprecation warning + when they cannot be safely cast to an integer. + """ + message = "non integer \(and non boolean\) array-likes will not be " \ + "accepted as indices in the future" + + def test_basic(self): + a = np.arange(10) + self.assert_deprecated(a.__getitem__, args=([0.5, 1.5],), + exceptions=IndexError) + self.assert_deprecated(a.__getitem__, args=((['1', '2'],),), + exceptions=IndexError) + + self.assert_not_deprecated(a.__getitem__, ([],)) + + + def test_boolean_futurewarning(self): + a = np.arange(10) + with warnings.catch_warnings(): + warnings.filterwarnings('always') + assert_warns(FutureWarning, a.__getitem__, [True]) + # Unfortunatly, the deprecation warning takes precedence: + #assert_warns(FutureWarning, a.__getitem__, True) + + with warnings.catch_warnings(): + warnings.filterwarnings('error') + assert_raises(FutureWarning, a.__getitem__, [True]) + #assert_raises(FutureWarning, a.__getitem__, True) + + +class TestMultipleEllipsisDeprecation(_DeprecationTestCase): + message = "an index can only have a single Ellipsis \(`...`\); replace " \ + "all but one with slices \(`:`\)." + + def test_basic(self): + a = np.arange(10) + self.assert_deprecated(a.__getitem__, args=((Ellipsis, Ellipsis),)) + + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', '', DeprecationWarning) + # Just check that this works: + b = a[...,...] + assert_array_equal(a, b) + assert_raises(IndexError, a.__getitem__, ((Ellipsis, ) * 3,)) + + +class TestBooleanSubtractDeprecations(_DeprecationTestCase): + """Test deprecation of boolean `-`. While + and * are well + defined, - is not and even a corrected form seems to have + no real uses. + + The deprecation process was started in NumPy 1.9. + """ + message = r"numpy boolean .* \(the .* `-` operator\) is deprecated, " \ + "use the bitwise" + + def test_operator_deprecation(self): + array = np.array([True]) + generic = np.bool_(True) + + # Minus operator/subtract ufunc: + self.assert_deprecated(operator.sub, args=(array, array)) + self.assert_deprecated(operator.sub, args=(generic, generic)) + + # Unary minus/negative ufunc: + self.assert_deprecated(operator.neg, args=(array,)) + self.assert_deprecated(operator.neg, args=(generic,)) + + +class TestRankDeprecation(_DeprecationTestCase): + """Test that np.rank is deprecated. The function should simply be + removed. The VisibleDeprecationWarning may become unnecessary. + """ + def test(self): + a = np.arange(10) + assert_warns(np.VisibleDeprecationWarning, np.rank, a) + + +class TestComparisonDepreactions(_DeprecationTestCase): + """This tests the deprecation, for non-elementwise comparison logic. + This used to mean that when an error occured during element-wise comparison + (i.e. broadcasting) NotImplemented was returned, but also in the comparison + itself, False was given instead of the error. + + Also test FutureWarning for the None comparison. + """ + + message = "elementwise comparison failed; " \ + "this will raise the error in the future." + + def test_normal_types(self): + for op in (operator.eq, operator.ne): + # Broadcasting errors: + self.assert_deprecated(op, args=(np.zeros(3), [])) + a = np.zeros(3, dtype='i,i') + # (warning is issued a couple of times here) + self.assert_deprecated(op, args=(a, a[:-1]), num=None) + + # Element comparison error (numpy array can't be compared). + a = np.array([1, np.array([1,2,3])], dtype=object) + b = np.array([1, np.array([1,2,3])], dtype=object) + self.assert_deprecated(op, args=(a, b), num=None) + + + def test_string(self): + # For two string arrays, strings always raised the broadcasting error: + a = np.array(['a', 'b']) + b = np.array(['a', 'b', 'c']) + assert_raises(ValueError, lambda x, y: x == y, a, b) + + # The empty list is not cast to string, this is only to document + # that fact (it likely should be changed). This means that the + # following works (and returns False) due to dtype mismatch: + a == [] + + + def test_none_comparison(self): + # Test comparison of None, which should result in elementwise + # comparison in the future. [1, 2] == None should be [False, False]. + with warnings.catch_warnings(): + warnings.filterwarnings('always', '', FutureWarning) + assert_warns(FutureWarning, operator.eq, np.arange(3), None) + assert_warns(FutureWarning, operator.ne, np.arange(3), None) + + with warnings.catch_warnings(): + warnings.filterwarnings('error', '', FutureWarning) + assert_raises(FutureWarning, operator.eq, np.arange(3), None) + assert_raises(FutureWarning, operator.ne, np.arange(3), None) + + +class TestIdentityComparisonDepreactions(_DeprecationTestCase): + """This tests the equal and not_equal object ufuncs identity check + deprecation. This was due to the usage of PyObject_RichCompareBool. + + This tests that for example for `a = np.array([np.nan], dtype=object)` + `a == a` it is warned that False and not `np.nan is np.nan` is returned. + + Should be kept in sync with TestComparisonDepreactions and new tests + added when the deprecation is over. Requires only removing of @identity@ + (and blocks) from the ufunc loops.c.src of the OBJECT comparisons. + """ + + message = "numpy .* will not check object identity in the future." + + def test_identity_equality_mismatch(self): + a = np.array([np.nan], dtype=object) + + with warnings.catch_warnings(): + warnings.filterwarnings('always', '', FutureWarning) + assert_warns(FutureWarning, np.equal, a, a) + assert_warns(FutureWarning, np.not_equal, a, a) + + with warnings.catch_warnings(): + warnings.filterwarnings('error', '', FutureWarning) + assert_raises(FutureWarning, np.equal, a, a) + assert_raises(FutureWarning, np.not_equal, a, a) + # And the other do not warn: + with np.errstate(invalid='ignore'): + np.less(a, a) + np.greater(a, a) + np.less_equal(a, a) + np.greater_equal(a, a) + + + def test_comparison_error(self): + class FunkyType(object): + def __eq__(self, other): + raise TypeError("I won't compare") + def __ne__(self, other): + raise TypeError("I won't compare") + + a = np.array([FunkyType()]) + self.assert_deprecated(np.equal, args=(a, a)) + self.assert_deprecated(np.not_equal, args=(a, a)) + + + def test_bool_error(self): + # The comparison result cannot be interpreted as a bool + a = np.array([np.array([1, 2, 3]), None], dtype=object) + self.assert_deprecated(np.equal, args=(a, a)) + self.assert_deprecated(np.not_equal, args=(a, a)) + + if __name__ == "__main__": run_module_suite() diff --git a/numpy/core/tests/test_dtype.py b/numpy/core/tests/test_dtype.py index 83017ea6a..18660351c 100644 --- a/numpy/core/tests/test_dtype.py +++ b/numpy/core/tests/test_dtype.py @@ -291,6 +291,53 @@ class TestSubarray(TestCase): 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)))) + def test_shape_sequence(self): + # Any sequence of integers should work as shape, but the result + # should be a tuple (immutable) of base type integers. + a = np.array([1, 2, 3], dtype=np.int16) + l = [1, 2, 3] + # Array gets converted + dt = np.dtype([('a', 'f4', a)]) + assert_(isinstance(dt['a'].shape, tuple)) + assert_(isinstance(dt['a'].shape[0], int)) + # List gets converted + dt = np.dtype([('a', 'f4', l)]) + assert_(isinstance(dt['a'].shape, tuple)) + # + class IntLike(object): + def __index__(self): + return 3 + def __int__(self): + # (a PyNumber_Check fails without __int__) + return 3 + dt = np.dtype([('a', 'f4', IntLike())]) + assert_(isinstance(dt['a'].shape, tuple)) + assert_(isinstance(dt['a'].shape[0], int)) + dt = np.dtype([('a', 'f4', (IntLike(),))]) + assert_(isinstance(dt['a'].shape, tuple)) + assert_(isinstance(dt['a'].shape[0], int)) + + def test_shape_invalid(self): + # Check that the shape is valid. + max_int = np.iinfo(np.intc).max + max_intp = np.iinfo(np.intp).max + # Too large values (the datatype is part of this) + assert_raises(ValueError, np.dtype, [('a', 'f4', max_int // 4 + 1)]) + assert_raises(ValueError, np.dtype, [('a', 'f4', max_int + 1)]) + assert_raises(ValueError, np.dtype, [('a', 'f4', (max_int, 2))]) + # Takes a different code path (fails earlier: + assert_raises(ValueError, np.dtype, [('a', 'f4', max_intp + 1)]) + # Negative values + assert_raises(ValueError, np.dtype, [('a', 'f4', -1)]) + assert_raises(ValueError, np.dtype, [('a', 'f4', (-1, -1))]) + + def test_alignment(self): + #Check that subarrays are aligned + t1 = np.dtype('1i4', align=True) + t2 = np.dtype('2i4', align=True) + assert_equal(t1.alignment, t2.alignment) + + class TestMonsterType(TestCase): """Test deeply nested subtypes.""" def test1(self): @@ -449,6 +496,10 @@ class TestString(TestCase): # Issue gh-2798 a = np.array(['a'], dtype="O").astype(("O", [("name", "O")])) + def test_empty_string_to_object(self): + # Pull request #4722 + np.array(["", ""]).astype(object) + class TestDtypeAttributeDeletion(object): def test_dtype_non_writable_attributes_deletion(self): @@ -472,6 +523,20 @@ class TestDtypeAttributeDeletion(object): for s in attr: assert_raises(AttributeError, delattr, dt, s) +class TestDtypeAttributes(TestCase): + + def test_name_builtin(self): + for t in np.typeDict.values(): + name = t.__name__ + if name.endswith('_'): + name = name[:-1] + assert_equal(np.dtype(t).name, name) + + def test_name_dtype_subclass(self): + # Ticket #4357 + class user_def_subcls(np.void): pass + assert_equal(np.dtype(user_def_subcls).name, 'user_def_subcls') + if __name__ == "__main__": run_module_suite() diff --git a/numpy/core/tests/test_einsum.py b/numpy/core/tests/test_einsum.py index 31f94bf07..226bde0a3 100644 --- a/numpy/core/tests/test_einsum.py +++ b/numpy/core/tests/test_einsum.py @@ -31,6 +31,9 @@ class TestEinSum(TestCase): # other keyword arguments are rejected assert_raises(TypeError, np.einsum, "", 0, bad_arg=0) + # issue 4528 revealed a segfault with this call + assert_raises(TypeError, np.einsum, *(None,)*63) + # number of operands must match count in subscripts string assert_raises(ValueError, np.einsum, "", 0, 0) assert_raises(ValueError, np.einsum, ",", 0, [0], [0]) @@ -498,5 +501,73 @@ class TestEinSum(TestCase): [[[1, 3], [3, 9], [5, 15], [7, 21]], [[8, 16], [16, 32], [24, 48], [32, 64]]]) + def test_einsum_broadcast(self): + # Issue #2455 change in handling ellipsis + # remove the 'middle broadcast' error + # only use the 'RIGHT' iteration in prepare_op_axes + # adds auto broadcast on left where it belongs + # broadcast on right has to be explicit + + A = np.arange(2*3*4).reshape(2,3,4) + B = np.arange(3) + ref = np.einsum('ijk,j->ijk',A, B) + assert_equal(np.einsum('ij...,j...->ij...',A, B), ref) + assert_equal(np.einsum('ij...,...j->ij...',A, B), ref) + assert_equal(np.einsum('ij...,j->ij...',A, B), ref) # used to raise error + + A = np.arange(12).reshape((4,3)) + B = np.arange(6).reshape((3,2)) + ref = np.einsum('ik,kj->ij', A, B) + assert_equal(np.einsum('ik...,k...->i...', A, B), ref) + assert_equal(np.einsum('ik...,...kj->i...j', A, B), ref) + assert_equal(np.einsum('...k,kj', A, B), ref) # used to raise error + assert_equal(np.einsum('ik,k...->i...', A, B), ref) # used to raise error + + dims=[2,3,4,5]; + a = np.arange(np.prod(dims)).reshape(dims) + v = np.arange(dims[2]) + ref = np.einsum('ijkl,k->ijl', a, v) + assert_equal(np.einsum('ijkl,k', a, v), ref) + assert_equal(np.einsum('...kl,k', a, v), ref) # used to raise error + assert_equal(np.einsum('...kl,k...', a, v), ref) + # no real diff from 1st + + J,K,M=160,160,120; + A=np.arange(J*K*M).reshape(1,1,1,J,K,M) + B=np.arange(J*K*M*3).reshape(J,K,M,3) + ref = np.einsum('...lmn,...lmno->...o', A, B) + assert_equal(np.einsum('...lmn,lmno->...o', A, B), ref) # used to raise error + + def test_einsum_fixedstridebug(self): + # Issue #4485 obscure einsum bug + # This case revealed a bug in nditer where it reported a stride + # as 'fixed' (0) when it was in fact not fixed during processing + # (0 or 4). The reason for the bug was that the check for a fixed + # stride was using the information from the 2D inner loop reuse + # to restrict the iteration dimensions it had to validate to be + # the same, but that 2D inner loop reuse logic is only triggered + # during the buffer copying step, and hence it was invalid to + # rely on those values. The fix is to check all the dimensions + # of the stride in question, which in the test case reveals that + # the stride is not fixed. + # + # NOTE: This test is triggered by the fact that the default buffersize, + # used by einsum, is 8192, and 3*2731 = 8193, is larger than that + # and results in a mismatch between the buffering and the + # striding for operand A. + A = np.arange(2*3).reshape(2,3).astype(np.float32) + B = np.arange(2*3*2731).reshape(2,3,2731).astype(np.int16) + es = np.einsum('cl,cpx->lpx', A, B) + tp = np.tensordot(A, B, axes=(0, 0)) + assert_equal(es, tp) + # The following is the original test case from the bug report, + # made repeatable by changing random arrays to aranges. + A = np.arange(3*3).reshape(3,3).astype(np.float64) + B = np.arange(3*3*64*64).reshape(3,3,64,64).astype(np.float32) + es = np.einsum ('cl,cpxy->lpxy', A,B) + tp = np.tensordot(A,B, axes=(0,0)) + assert_equal(es, tp) + + if __name__ == "__main__": run_module_suite() diff --git a/numpy/core/tests/test_function_base.py b/numpy/core/tests/test_function_base.py index b43452e1c..f6ffd5a10 100644 --- a/numpy/core/tests/test_function_base.py +++ b/numpy/core/tests/test_function_base.py @@ -1,8 +1,7 @@ from __future__ import division, absolute_import, print_function from numpy.testing import * -from numpy import logspace, linspace, dtype - +from numpy import logspace, linspace, dtype, array class TestLogspace(TestCase): @@ -55,3 +54,58 @@ class TestLinspace(TestCase): assert_equal(y.dtype, dtype('float64')) y = linspace(0, 6, dtype='int32') assert_equal(y.dtype, dtype('int32')) + + def test_array_scalar(self): + lim1 = array([-120, 100], dtype="int8") + lim2 = array([120, -100], dtype="int8") + lim3 = array([1200, 1000], dtype="uint16") + t1 = linspace(lim1[0], lim1[1], 5) + t2 = linspace(lim2[0], lim2[1], 5) + t3 = linspace(lim3[0], lim3[1], 5) + t4 = linspace(-120.0, 100.0, 5) + t5 = linspace(120.0, -100.0, 5) + t6 = linspace(1200.0, 1000.0, 5) + assert_equal(t1, t4) + assert_equal(t2, t5) + assert_equal(t3, t6) + + def test_complex(self): + lim1 = linspace(1 + 2j, 3 + 4j, 5) + t1 = array([ 1.0+2.j , 1.5+2.5j, 2.0+3.j , 2.5+3.5j, 3.0+4.j]) + lim2 = linspace(1j, 10, 5) + t2 = array([ 0.0+1.j , 2.5+0.75j, 5.0+0.5j , 7.5+0.25j, 10.0+0.j]) + assert_equal(lim1, t1) + assert_equal(lim2, t2) + + def test_physical_quantities(self): + class PhysicalQuantity(float): + def __new__(cls, value): + return float.__new__(cls, value) + + def __add__(self, x): + assert_(isinstance(x, PhysicalQuantity)) + return PhysicalQuantity(float(x) + float(self)) + __radd__ = __add__ + + def __sub__(self, x): + assert_(isinstance(x, PhysicalQuantity)) + return PhysicalQuantity(float(self) - float(x)) + + def __rsub__(self, x): + assert_(isinstance(x, PhysicalQuantity)) + return PhysicalQuantity(float(x) - float(self)) + + def __mul__(self, x): + return PhysicalQuantity(float(x) * float(self)) + __rmul__ = __mul__ + + def __div__(self, x): + return PhysicalQuantity(float(self) / float(x)) + + def __rdiv__(self, x): + return PhysicalQuantity(float(x) / float(self)) + + + a = PhysicalQuantity(0.0) + b = PhysicalQuantity(1.0) + assert_equal(linspace(a, b), linspace(0.0, 1.0))
\ No newline at end of file diff --git a/numpy/core/tests/test_indexing.py b/numpy/core/tests/test_indexing.py index ad792eb08..bb1341455 100644 --- a/numpy/core/tests/test_indexing.py +++ b/numpy/core/tests/test_indexing.py @@ -1,10 +1,20 @@ from __future__ import division, absolute_import, print_function +import sys +import warnings +import functools + import numpy as np +from numpy.core.multiarray_tests import array_indexing from itertools import product -from numpy.compat import asbytes from numpy.testing import * -import sys, warnings, gc + + +try: + cdll = np.ctypeslib.load_library('multiarray', np.core.multiarray.__file__) + _HAS_CTYPE = True +except ImportError: + _HAS_CTYPE = False class TestIndexing(TestCase): @@ -22,6 +32,36 @@ class TestIndexing(TestCase): a = np.array(0) assert_(isinstance(a[()], np.int_)) + # Regression, it needs to fall through integer and fancy indexing + # cases, so need the with statement to ignore the non-integer error. + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', '', DeprecationWarning) + a = np.array([1.]) + assert_(isinstance(a[0.], np.float_)) + + a = np.array([np.array(1)], dtype=object) + assert_(isinstance(a[0.], np.ndarray)) + + def test_same_kind_index_casting(self): + # Indexes should be cast with same-kind and not safe, even if + # that is somewhat unsafe. So test various different code paths. + index = np.arange(5) + u_index = index.astype(np.uintp) + arr = np.arange(10) + + assert_array_equal(arr[index], arr[u_index]) + arr[u_index] = np.arange(5) + assert_array_equal(arr, np.arange(10)) + + arr = np.arange(10).reshape(5, 2) + assert_array_equal(arr[index], arr[u_index]) + + arr[u_index] = np.arange(5)[:,None] + assert_array_equal(arr, np.arange(5)[:,None].repeat(2, axis=1)) + + arr = np.arange(25).reshape(5, 5) + assert_array_equal(arr[u_index, u_index], arr[index, index]) + def test_empty_fancy_index(self): # Empty list index creates an empty array # with the same dtype (but with weird shape) @@ -42,7 +82,7 @@ class TestIndexing(TestCase): [4, 5, 6], [7, 8, 9]]) assert_equal(a[...], a) - assert_(a[...] is a) + assert_(a[...].base is a) # `a[...]` was `a` in numpy <1.9.) # Slicing with ellipsis can skip an # arbitrary number of dimensions @@ -85,8 +125,14 @@ class TestIndexing(TestCase): #assert_equal(a[False], a[0]) # Same with NumPy boolean scalar - assert_equal(a[np.array(True)], a[1]) - assert_equal(a[np.array(False)], a[0]) + # Before DEPRECATE, this is an error (as always, but telling about + # future change): + assert_raises(IndexError, a.__getitem__, np.array(True)) + assert_raises(IndexError, a.__getitem__, np.array(False)) + # After DEPRECATE, this behaviour can be enabled: + #assert_equal(a[np.array(True)], a[None]) + #assert_equal(a[np.array(False), a[None][0:0]]) + def test_boolean_indexing_onedim(self): # Indexing a 2-dimensional array with @@ -98,9 +144,10 @@ class TestIndexing(TestCase): a[b] = 1. assert_equal(a, [[1., 1., 1.]]) + def test_boolean_assignment_value_mismatch(self): # A boolean assignment should fail when the shape of the values - # cannot be broadcasted to the subscription. (see also gh-3458) + # cannot be broadcast to the subscription. (see also gh-3458) a = np.arange(4) def f(a, v): a[a > -1] = v @@ -109,6 +156,7 @@ class TestIndexing(TestCase): assert_raises(ValueError, f, a, [1, 2, 3]) assert_raises(ValueError, f, a[:1], [1, 2, 3]) + def test_boolean_indexing_twodim(self): # Indexing a 2-dimensional array with # 2-dimensional boolean array @@ -129,16 +177,371 @@ class TestIndexing(TestCase): [0, 8, 0]]) + def test_reverse_strides_and_subspace_bufferinit(self): + # This tests that the strides are not reversed for simple and + # subspace fancy indexing. + a = np.ones(5) + b = np.zeros(5, dtype=np.intp)[::-1] + c = np.arange(5)[::-1] + + a[b] = c + # If the strides are not reversed, the 0 in the arange comes last. + assert_equal(a[0], 0) + + # This also tests that the subspace buffer is initialized: + a = np.ones((5, 2)) + c = np.arange(10).reshape(5, 2)[::-1] + a[b, :] = c + assert_equal(a[0], [0, 1]) + + def test_reversed_strides_result_allocation(self): + # Test a bug when calculating the output strides for a result array + # when the subspace size was 1 (and test other cases as well) + a = np.arange(10)[:, None] + i = np.arange(10)[::-1] + assert_array_equal(a[i], a[i.copy('C')]) + + a = np.arange(20).reshape(-1, 2) + + + def test_uncontiguous_subspace_assignment(self): + # During development there was a bug activating a skip logic + # based on ndim instead of size. + a = np.full((3, 4, 2), -1) + b = np.full((3, 4, 2), -1) + + a[[0, 1]] = np.arange(2 * 4 * 2).reshape(2, 4, 2).T + b[[0, 1]] = np.arange(2 * 4 * 2).reshape(2, 4, 2).T.copy() + + assert_equal(a, b) + + + def test_too_many_fancy_indices_special_case(self): + # Just documents behaviour, this is a small limitation. + a = np.ones((1,) * 32) # 32 is NPY_MAXDIMS + assert_raises(IndexError, a.__getitem__, (np.array([0]),) * 32) + + + def test_scalar_array_bool(self): + # Numpy bools can be used as boolean index (python ones as of yet not) + a = np.array(1) + assert_equal(a[np.bool_(True)], a[np.array(True)]) + assert_equal(a[np.bool_(False)], a[np.array(False)]) + + # After deprecating bools as integers: + #a = np.array([0,1,2]) + #assert_equal(a[True, :], a[None, :]) + #assert_equal(a[:, True], a[:, None]) + # + #assert_(not np.may_share_memory(a, a[True, :])) + + + def test_everything_returns_views(self): + # Before `...` would return a itself. + a = np.arange(5) + + assert_(a is not a[()]) + assert_(a is not a[...]) + assert_(a is not a[:]) + + + def test_broaderrors_indexing(self): + a = np.zeros((5, 5)) + assert_raises(IndexError, a.__getitem__, ([0, 1], [0, 1, 2])) + assert_raises(IndexError, a.__setitem__, ([0, 1], [0, 1, 2]), 0) + + + def test_trivial_fancy_out_of_bounds(self): + a = np.zeros(5) + ind = np.ones(20, dtype=np.intp) + ind[-1] = 10 + assert_raises(IndexError, a.__getitem__, ind) + assert_raises(IndexError, a.__setitem__, ind, 0) + ind = np.ones(20, dtype=np.intp) + ind[0] = 11 + assert_raises(IndexError, a.__getitem__, ind) + assert_raises(IndexError, a.__setitem__, ind, 0) + + + def test_nonbaseclass_values(self): + class SubClass(np.ndarray): + def __array_finalize__(self, old): + # Have array finalize do funny things + self.fill(99) + + a = np.zeros((5, 5)) + s = a.copy().view(type=SubClass) + s.fill(1) + + a[[0, 1, 2, 3, 4], :] = s + assert_((a == 1).all()) + + # Subspace is last, so transposing might want to finalize + a[:, [0, 1, 2, 3, 4]] = s + assert_((a == 1).all()) + + a.fill(0) + a[...] = s + assert_((a == 1).all()) + + + def test_subclass_writeable(self): + d = np.rec.array([('NGC1001', 11), ('NGC1002', 1.), ('NGC1003', 1.)], + dtype=[('target', 'S20'), ('V_mag', '>f4')]) + ind = np.array([False, True, True], dtype=bool) + assert_(d[ind].flags.writeable) + ind = np.array([0, 1]) + assert_(d[ind].flags.writeable) + assert_(d[...].flags.writeable) + assert_(d[0].flags.writeable) + + + def test_memory_order(self): + # This is not necessary to preserve. Memory layouts for + # more complex indices are not as simple. + a = np.arange(10) + b = np.arange(10).reshape(5,2).T + assert_(a[b].flags.f_contiguous) + + # Takes a different implementation branch: + a = a.reshape(-1, 1) + assert_(a[b, 0].flags.f_contiguous) + + + def test_scalar_return_type(self): + # Full scalar indices should return scalars and object + # arrays should not call PyArray_Return on their items + class Zero(object): + # The most basic valid indexing + def __index__(self): + return 0 + z = Zero() + + class ArrayLike(object): + # Simple array, should behave like the array + def __array__(self): + return np.array(0) + + a = np.zeros(()) + assert_(isinstance(a[()], np.float_)) + a = np.zeros(1) + assert_(isinstance(a[z], np.float_)) + a = np.zeros((1, 1)) + assert_(isinstance(a[z, np.array(0)], np.float_)) + assert_(isinstance(a[z, ArrayLike()], np.float_)) + + # And object arrays do not call it too often: + b = np.array(0) + a = np.array(0, dtype=object) + a[()] = b + assert_(isinstance(a[()], np.ndarray)) + a = np.array([b, None]) + assert_(isinstance(a[z], np.ndarray)) + a = np.array([[b, None]]) + assert_(isinstance(a[z, np.array(0)], np.ndarray)) + assert_(isinstance(a[z, ArrayLike()], np.ndarray)) + + + def test_small_regressions(self): + # Reference count of intp for index checks + a = np.array([0]) + refcount = sys.getrefcount(np.dtype(np.intp)) + # item setting always checks indices in separate function: + a[np.array([0], dtype=np.intp)] = 1 + a[np.array([0], dtype=np.uint8)] = 1 + assert_raises(IndexError, a.__setitem__, + np.array([1], dtype=np.intp), 1) + assert_raises(IndexError, a.__setitem__, + np.array([1], dtype=np.uint8), 1) + + assert_equal(sys.getrefcount(np.dtype(np.intp)), refcount) + + def test_unaligned(self): + v = (np.zeros(64, dtype=np.int8) + ord('a'))[1:-7] + d = v.view(np.dtype("S8")) + # unaligned source + x = (np.zeros(16, dtype=np.int8) + ord('a'))[1:-7] + x = x.view(np.dtype("S8")) + x[...] = np.array("b" * 8, dtype="S") + b = np.arange(d.size) + #trivial + assert_equal(d[b], d) + d[b] = x + # nontrivial + # unaligned index array + b = np.zeros(d.size + 1).view(np.int8)[1:-(np.intp(0).itemsize - 1)] + b = b.view(np.intp)[:d.size] + b[...] = np.arange(d.size) + assert_equal(d[b.astype(np.int16)], d) + d[b.astype(np.int16)] = x + # boolean + d[b % 2 == 0] + d[b % 2 == 0] = x[::2] + + +class TestFieldIndexing(TestCase): + def test_scalar_return_type(self): + # Field access on an array should return an array, even if it + # is 0-d. + a = np.zeros((), [('a','f8')]) + assert_(isinstance(a['a'], np.ndarray)) + assert_(isinstance(a[['a']], np.ndarray)) + + +class TestBroadcastedAssignments(TestCase): + def assign(self, a, ind, val): + a[ind] = val + return a + + + def test_prepending_ones(self): + a = np.zeros((3, 2)) + + a[...] = np.ones((1, 3, 2)) + # Fancy with subspace with and without transpose + a[[0, 1, 2], :] = np.ones((1, 3, 2)) + a[:, [0, 1]] = np.ones((1, 3, 2)) + # Fancy without subspace (with broadcasting) + a[[[0], [1], [2]], [0, 1]] = np.ones((1, 3, 2)) + + + def test_prepend_not_one(self): + assign = self.assign + s_ = np.s_ + + a = np.zeros(5) + + # Too large and not only ones. + assert_raises(ValueError, assign, a, s_[...], np.ones((2, 1))) + + with warnings.catch_warnings(): + # Will be a ValueError as well. + warnings.simplefilter("error", DeprecationWarning) + assert_raises(DeprecationWarning, assign, a, s_[[1, 2, 3],], + np.ones((2, 1))) + assert_raises(DeprecationWarning, assign, a, s_[[[1], [2]],], + np.ones((2,2,1))) + + + def test_simple_broadcasting_errors(self): + assign = self.assign + s_ = np.s_ + + a = np.zeros((5, 1)) + assert_raises(ValueError, assign, a, s_[...], np.zeros((5, 2))) + assert_raises(ValueError, assign, a, s_[...], np.zeros((5, 0))) + + assert_raises(ValueError, assign, a, s_[:, [0]], np.zeros((5, 2))) + assert_raises(ValueError, assign, a, s_[:, [0]], np.zeros((5, 0))) + + assert_raises(ValueError, assign, a, s_[[0], :], np.zeros((2, 1))) + + + def test_index_is_larger(self): + # Simple case of fancy index broadcasting of the index. + a = np.zeros((5, 5)) + a[[[0], [1], [2]], [0, 1, 2]] = [2, 3, 4] + + assert_((a[:3, :3] == [2, 3, 4]).all()) + + + def test_broadcast_subspace(self): + a = np.zeros((100, 100)) + v = np.arange(100)[:,None] + b = np.arange(100)[::-1] + a[b] = v + assert_((a[::-1] == v).all()) + + +class TestSubclasses(TestCase): + def test_basic(self): + class SubClass(np.ndarray): + pass + + s = np.arange(5).view(SubClass) + assert_(isinstance(s[:3], SubClass)) + assert_(s[:3].base is s) + + assert_(isinstance(s[[0, 1, 2]], SubClass)) + assert_(isinstance(s[s > 0], SubClass)) + + + def test_matrix_fancy(self): + # The matrix class messes with the shape. While this is always + # weird (getitem is not used, it does not have setitem nor knows + # about fancy indexing), this tests gh-3110 + m = np.matrix([[1, 2], [3, 4]]) + + assert_(isinstance(m[[0,1,0], :], np.matrix)) + + # gh-3110. Note the transpose currently because matrices do *not* + # support dimension fixing for fancy indexing correctly. + x = np.asmatrix(np.arange(50).reshape(5,10)) + assert_equal(x[:2, np.array(-1)], x[:2, -1].T) + + + def test_finalize_gets_full_info(self): + # Array finalize should be called on the filled array. + class SubClass(np.ndarray): + def __array_finalize__(self, old): + self.finalize_status = np.array(self) + self.old = old + + s = np.arange(10).view(SubClass) + new_s = s[:3] + assert_array_equal(new_s.finalize_status, new_s) + assert_array_equal(new_s.old, s) + + new_s = s[[0,1,2,3]] + assert_array_equal(new_s.finalize_status, new_s) + assert_array_equal(new_s.old, s) + + new_s = s[s > 0] + assert_array_equal(new_s.finalize_status, new_s) + assert_array_equal(new_s.old, s) + + +class TestFancyIndexingEquivalence(TestCase): + def test_object_assign(self): + # Check that the field and object special case using copyto is active. + # The right hand side cannot be converted to an array here. + a = np.arange(5, dtype=object) + b = a.copy() + a[:3] = [1, (1,2), 3] + b[[0, 1, 2]] = [1, (1,2), 3] + assert_array_equal(a, b) + + # test same for subspace fancy indexing + b = np.arange(5, dtype=object)[None, :] + b[[0], :3] = [[1, (1,2), 3]] + assert_array_equal(a, b[0]) + + + def test_cast_equivalence(self): + # Yes, normal slicing uses unsafe casting. + a = np.arange(5) + b = a.copy() + + a[:3] = np.array(['2', '-3', '-1']) + b[[0, 2, 1]] = np.array(['2', '-1', '-3']) + assert_array_equal(a, b) + + # test the same for subspace fancy indexing + b = np.arange(5)[None, :] + b[[0], :3] = np.array([['2', '-3', '-1']]) + assert_array_equal(a, b[0]) + + class TestMultiIndexingAutomated(TestCase): """ These test use code to mimic the C-Code indexing for selection. NOTE: * This still lacks tests for complex item setting. - * If you change behavoir of indexing, you might want to modify + * If you change behavior of indexing, you might want to modify these tests to try more combinations. * Behavior was written to match numpy version 1.8. (though a first version matched 1.7.) - * Only tuple indicies are supported by the mimicing code. + * Only tuple indices are supported by the mimicking code. (and tested as of writing this) * Error types should match most of the time as long as there is only one error. For multiple errors, what gets raised @@ -161,11 +564,11 @@ class TestMultiIndexingAutomated(TestCase): slice(4, -1, -2), slice(None, None, -3), # Some Fancy indexes: - np.empty((0, 1, 1), dtype=np.intp), # empty broadcastable + np.empty((0, 1, 1), dtype=np.intp), # empty and can be broadcast np.array([0, 1, -2]), np.array([[2], [0], [1]]), - np.array([[0, -1], [0, 1]]), - np.array([2, -1]), + np.array([[0, -1], [0, 1]], dtype=np.dtype('intp').newbyteorder()), + np.array([2, -1], dtype=np.int8), 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 @@ -208,7 +611,7 @@ class TestMultiIndexingAutomated(TestCase): fancy_dim = 0 # NOTE: This is a funny twist (and probably OK to change). # The boolean array has illegal indexes, but this is - # allowed if the broadcasted fancy-indices are 0-sized. + # allowed if the broadcast fancy-indices are 0-sized. # This variable is to catch that case. error_unless_broadcast_to_empty = False @@ -231,9 +634,7 @@ class TestMultiIndexingAutomated(TestCase): if ellipsis_pos is None: ellipsis_pos = i continue # do not increment ndim counter - in_indices[i] = slice(None, None) - ndim += 1 - continue + raise IndexError if isinstance(indx, slice): ndim += 1 continue @@ -255,7 +656,7 @@ class TestMultiIndexingAutomated(TestCase): if arr.ndim - ndim < 0: # we can't take more dimensions then we have, not even for 0-d arrays. # since a[()] makes sense, but not a[(),]. We will raise an error - # lateron, unless a broadcasting error occurs first. + # later on, unless a broadcasting error occurs first. raise IndexError if ndim == 0 and not None in in_indices: @@ -267,7 +668,7 @@ class TestMultiIndexingAutomated(TestCase): for ax, indx in enumerate(in_indices): if isinstance(indx, slice): - # convert to an index array anways: + # convert to an index array indx = np.arange(*indx.indices(arr.shape[ax])) indices.append(['s', indx]) continue @@ -300,10 +701,23 @@ class TestMultiIndexingAutomated(TestCase): indx = flat_indx else: # This could be changed, a 0-d boolean index can - # make sense (even outide the 0-d indexed array case) + # make sense (even outside the 0-d indexed array case) # Note that originally this is could be interpreted as # integer in the full integer special case. raise IndexError + else: + # If the index is a singleton, the bounds check is done + # before the broadcasting. This used to be different in <1.9 + if indx.ndim == 0: + if indx >= arr.shape[ax] or indx < -arr.shape[ax]: + raise IndexError + if indx.ndim == 0: + # The index is a scalar. This used to be two fold, but if fancy + # indexing was active, the check was done later, possibly + # after broadcasting it away (1.7. or earlier). Now it is always + # done. + if indx >= arr.shape[ax] or indx < - arr.shape[ax]: + raise IndexError if len(indices) > 0 and indices[-1][0] == 'f' and ax != ellipsis_pos: # NOTE: There could still have been a 0-sized Ellipsis # between them. Checked that with ellipsis_pos. @@ -339,7 +753,7 @@ class TestMultiIndexingAutomated(TestCase): arr = arr.transpose(*(fancy_axes + axes)) # We only have one 'f' index now and arr is transposed accordingly. - # Now handle newaxes by reshaping... + # Now handle newaxis by reshaping... ax = 0 for indx in indices: if indx[0] == 'f': @@ -357,7 +771,7 @@ class TestMultiIndexingAutomated(TestCase): res = np.broadcast(*indx[1:]) # raises ValueError... else: res = indx[1] - # unfortunatly the indices might be out of bounds. So check + # unfortunately the indices might be out of bounds. So check # that first, and use mode='wrap' then. However only if # there are any indices... if res.size != 0: @@ -495,7 +909,7 @@ class TestMultiIndexingAutomated(TestCase): # spot and the simple ones in one other spot. with warnings.catch_warnings(): # This is so that np.array(True) is not accepted in a full integer - # index, when running the file seperatly. + # index, when running the file separately. warnings.filterwarnings('error', '', DeprecationWarning) for simple_pos in [0, 2, 3]: tocheck = [self.fill_indices, self.complex_indices, @@ -524,6 +938,44 @@ class TestMultiIndexingAutomated(TestCase): self._check_single_index(a, index) +class TestCApiAccess(TestCase): + def test_getitem(self): + subscript = functools.partial(array_indexing, 0) + + # 0-d arrays don't work: + assert_raises(IndexError, subscript, np.ones(()), 0) + # Out of bound values: + assert_raises(IndexError, subscript, np.ones(10), 11) + assert_raises(IndexError, subscript, np.ones(10), -11) + assert_raises(IndexError, subscript, np.ones((10, 10)), 11) + assert_raises(IndexError, subscript, np.ones((10, 10)), -11) + + a = np.arange(10) + assert_array_equal(a[4], subscript(a, 4)) + a = a.reshape(5, 2) + assert_array_equal(a[-4], subscript(a, -4)) + + def test_setitem(self): + assign = functools.partial(array_indexing, 1) + + # Deletion is impossible: + assert_raises(ValueError, assign, np.ones(10), 0) + # 0-d arrays don't work: + assert_raises(IndexError, assign, np.ones(()), 0, 0) + # Out of bound values: + assert_raises(IndexError, assign, np.ones(10), 11, 0) + assert_raises(IndexError, assign, np.ones(10), -11, 0) + assert_raises(IndexError, assign, np.ones((10, 10)), 11, 0) + assert_raises(IndexError, assign, np.ones((10, 10)), -11, 0) + + a = np.arange(10) + assign(a, 4, 10) + assert_(a[4] == 10) + + a = a.reshape(5, 2) + assign(a, 4, 10) + assert_array_equal(a[-1], [10, 10]) + if __name__ == "__main__": run_module_suite() diff --git a/numpy/core/tests/test_item_selection.py b/numpy/core/tests/test_item_selection.py index e501588c9..d8e9e6fd0 100644 --- a/numpy/core/tests/test_item_selection.py +++ b/numpy/core/tests/test_item_selection.py @@ -60,6 +60,11 @@ class TestTake(TestCase): del a assert_(all(sys.getrefcount(o) == 3 for o in objects)) + def test_unicode_mode(self): + d = np.arange(10) + k = b'\xc3\xa4'.decode("UTF8") + assert_raises(ValueError, d.take, 5, mode=k) + if __name__ == "__main__": run_module_suite() diff --git a/numpy/core/tests/test_memmap.py b/numpy/core/tests/test_memmap.py index 6de6319ef..b364f5eb9 100644 --- a/numpy/core/tests/test_memmap.py +++ b/numpy/core/tests/test_memmap.py @@ -1,8 +1,9 @@ from __future__ import division, absolute_import, print_function import sys -from tempfile import NamedTemporaryFile, TemporaryFile, mktemp +from tempfile import NamedTemporaryFile, TemporaryFile, mktemp, mkdtemp import os +import shutil from numpy import memmap from numpy import arange, allclose, asarray @@ -11,6 +12,7 @@ from numpy.testing import * class TestMemmap(TestCase): def setUp(self): self.tmpfp = NamedTemporaryFile(prefix='mmap') + self.tempdir = mkdtemp() self.shape = (3, 4) self.dtype = 'float32' self.data = arange(12, dtype=self.dtype) @@ -18,6 +20,7 @@ class TestMemmap(TestCase): def tearDown(self): self.tmpfp.close() + shutil.rmtree(self.tempdir) def test_roundtrip(self): # Write data to file @@ -33,12 +36,11 @@ class TestMemmap(TestCase): assert_array_equal(self.data, newfp) def test_open_with_filename(self): - tmpname = mktemp('', 'mmap') + tmpname = mktemp('', 'mmap', dir=self.tempdir) fp = memmap(tmpname, dtype=self.dtype, mode='w+', shape=self.shape) fp[:] = self.data[:] del fp - os.unlink(tmpname) def test_unnamed_file(self): with TemporaryFile() as f: @@ -55,7 +57,7 @@ class TestMemmap(TestCase): del fp def test_filename(self): - tmpname = mktemp('', 'mmap') + tmpname = mktemp('', 'mmap', dir=self.tempdir) fp = memmap(tmpname, dtype=self.dtype, mode='w+', shape=self.shape) abspath = os.path.abspath(tmpname) @@ -65,7 +67,6 @@ class TestMemmap(TestCase): self.assertEqual(abspath, b.filename) del b del fp - os.unlink(tmpname) def test_filename_fileobj(self): fp = memmap(self.tmpfp, dtype=self.dtype, mode="w+", diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py index 6336d41c7..cb5c0095c 100644 --- a/numpy/core/tests/test_multiarray.py +++ b/numpy/core/tests/test_multiarray.py @@ -3,6 +3,7 @@ from __future__ import division, absolute_import, print_function import tempfile import sys import os +import shutil import warnings import operator import io @@ -10,6 +11,8 @@ if sys.version_info[0] >= 3: import builtins else: import __builtin__ as builtins +from decimal import Decimal + import numpy as np from nose import SkipTest @@ -294,8 +297,8 @@ class TestZeroRank(TestCase): a, b = self.d self.assertEqual(a[...], 0) self.assertEqual(b[...], 'x') - self.assertTrue(a[...] is a) - self.assertTrue(b[...] is b) + self.assertTrue(a[...].base is a) # `a[...] is a` in numpy <1.9. + self.assertTrue(b[...].base is b) # `b[...] is b` in numpy <1.9. def test_empty_subscript(self): a, b = self.d @@ -508,6 +511,22 @@ class TestCreation(TestCase): assert_array_equal(d, [0] * 13) assert_equal(np.count_nonzero(d), 0) + def test_sequence_non_homogenous(self): + assert_equal(np.array([4, 2**80]).dtype, np.object) + assert_equal(np.array([4, 2**80, 4]).dtype, np.object) + assert_equal(np.array([2**80, 4]).dtype, np.object) + assert_equal(np.array([2**80] * 3).dtype, np.object) + assert_equal(np.array([[1, 1],[1j, 1j]]).dtype, np.complex) + assert_equal(np.array([[1j, 1j],[1, 1]]).dtype, np.complex) + assert_equal(np.array([[1, 1, 1],[1, 1j, 1.], [1, 1, 1]]).dtype, np.complex) + + @dec.skipif(sys.version_info[0] >= 3) + def test_sequence_long(self): + assert_equal(np.array([long(4), long(4)]).dtype, np.long) + assert_equal(np.array([long(4), 2**80]).dtype, np.object) + assert_equal(np.array([long(4), 2**80, long(4)]).dtype, np.object) + assert_equal(np.array([2**80, long(4)]).dtype, np.object) + def test_non_sequence_sequence(self): """Should not segfault. @@ -542,8 +561,9 @@ class TestStructured(TestCase): a = np.zeros((3, 5), dtype=[('a', ('i4', (2, 2)))]) a['a'] = np.arange(60).reshape(3, 5, 2, 2) - # Since the subarray is always in C-order, these aren't equal - assert_(np.any(a['a'].T != a.T['a'])) + # Since the subarray is always in C-order, a transpose + # does not swap the subarray: + assert_array_equal(a.T['a'], a['a'].transpose(1, 0, 2, 3)) # In Fortran order, the subarray gets appended # like in all other cases, not prepended as a special case @@ -604,6 +624,12 @@ class TestStructured(TestCase): y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')]) assert_equal(x == y, False) + # Check that structured arrays that are different only in + # byte-order work + a = np.array([(5, 42), (10, 1)], dtype=[('a', '>i8'), ('b', '<f8')]) + b = np.array([(5, 43), (10, 1)], dtype=[('a', '<i8'), ('b', '>f8')]) + assert_equal(a == b, [False, True]) + class TestBool(TestCase): def test_test_interning(self): @@ -653,6 +679,16 @@ class TestBool(TestCase): # covers all cases of the 16 byte unrolled code self.check_count_nonzero(17, 17) + def test_count_nonzero_unaligned(self): + # prevent mistakes as e.g. gh-4060 + for o in range(7): + a = np.zeros((18,), dtype=np.bool)[o+1:] + a[:o] = True + self.assertEqual(np.count_nonzero(a), builtins.sum(a.tolist())) + a = np.ones((18,), dtype=np.bool)[o+1:] + a[:o] = False + self.assertEqual(np.count_nonzero(a), builtins.sum(a.tolist())) + class TestMethods(TestCase): def test_test_round(self): assert_equal(array([1.2, 1.5]).round(), [1, 2]) @@ -994,6 +1030,12 @@ class TestMethods(TestCase): a = np.array(['aaaaaaaaa' for i in range(100)], dtype=np.unicode) assert_equal(a.argsort(kind='m'), r) + def test_sort_unicode_kind(self): + d = np.arange(10) + k = b'\xc3\xa4'.decode("UTF8") + assert_raises(ValueError, d.sort, kind=k) + assert_raises(ValueError, d.argsort, kind=k) + def test_searchsorted(self): # test for floats and complex containing nans. The logic is the # same for all float types so only test double types for now. @@ -1063,6 +1105,31 @@ class TestMethods(TestCase): b = a.searchsorted(unaligned, 'r') assert_equal(b, a + 1) + # Test smart resetting of binsearch indices + a = np.arange(5) + b = a.searchsorted([6, 5, 4], 'l') + assert_equal(b, [5, 5, 4]) + b = a.searchsorted([6, 5, 4], 'r') + assert_equal(b, [5, 5, 5]) + + # Test all type specific binary search functions + types = ''.join((np.typecodes['AllInteger'], np.typecodes['AllFloat'], + np.typecodes['Datetime'], '?O')) + for dt in types: + if dt == 'M': + dt = 'M8[D]' + if dt == '?': + a = np.arange(2, dtype=dt) + out = np.arange(2) + else: + a = np.arange(0, 5, dtype=dt) + out = np.arange(5) + b = a.searchsorted(a, 'l') + assert_equal(b, out) + b = a.searchsorted(a, 'r') + assert_equal(b, out + 1) + + def test_searchsorted_unicode(self): # Test searchsorted on unicode strings. @@ -1137,6 +1204,40 @@ class TestMethods(TestCase): b = a.searchsorted(unaligned, 'r', s) assert_equal(b, keys + 1) + # Test all type specific indirect binary search functions + types = ''.join((np.typecodes['AllInteger'], np.typecodes['AllFloat'], + np.typecodes['Datetime'], '?O')) + for dt in types: + if dt == 'M': + dt = 'M8[D]' + if dt == '?': + a = np.array([1, 0], dtype=dt) + # We want the sorter array to be of a type that is different + # from np.intp in all platforms, to check for #4698 + s = np.array([1, 0], dtype=np.int16) + out = np.array([1, 0]) + else: + a = np.array([3, 4, 1, 2, 0], dtype=dt) + # We want the sorter array to be of a type that is different + # from np.intp in all platforms, to check for #4698 + s = np.array([4, 2, 3, 0, 1], dtype=np.int16) + out = np.array([3, 4, 1, 2, 0], dtype=np.intp) + b = a.searchsorted(a, 'l', s) + assert_equal(b, out) + b = a.searchsorted(a, 'r', s) + assert_equal(b, out + 1) + + # Test non-contiguous sorter array + a = np.array([3, 4, 1, 2, 0]) + srt = np.empty((10,), dtype=np.intp) + srt[1::2] = -1 + srt[::2] = [4, 2, 3, 0, 1] + s = srt[::2] + out = np.array([3, 4, 1, 2, 0], dtype=np.intp) + b = a.searchsorted(a, 'l', s) + assert_equal(b, out) + b = a.searchsorted(a, 'r', s) + assert_equal(b, out + 1) def test_partition(self): d = np.arange(10) @@ -1231,6 +1332,16 @@ class TestMethods(TestCase): mid = x.size // 2 + 1 assert_equal(np.partition(x, mid)[mid], mid) + # max + d = np.ones(10); d[1] = 4; + assert_equal(np.partition(d, (2, -1))[-1], 4) + assert_equal(np.partition(d, (2, -1))[2], 1) + assert_equal(d[np.argpartition(d, (2, -1))][-1], 4) + assert_equal(d[np.argpartition(d, (2, -1))][2], 1) + d[1] = np.nan + assert_(np.isnan(d[np.argpartition(d, (2, -1))][-1])) + assert_(np.isnan(np.partition(d, (2, -1))[-1])) + # equal elements d = np.arange((47)) % 7 tgt = np.sort(np.arange((47)) % 7) @@ -1245,6 +1356,12 @@ class TestMethods(TestCase): d[i:].partition(0, kind=k) assert_array_equal(d, tgt) + d = np.array([0, 1, 2, 3, 4, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 9]) + kth = [0, 3, 19, 20] + assert_equal(np.partition(d, kth, kind=k)[kth], (0, 3, 7, 7)) + assert_equal(d[np.argpartition(d, kth, kind=k)][kth], (0, 3, 7, 7)) + d = np.array([2, 1]) d.partition(0, kind=k) assert_raises(ValueError, d.partition, 2) @@ -1434,6 +1551,24 @@ class TestMethods(TestCase): assert_equal(np.partition(d, k)[k], tgt[k]) assert_equal(d[np.argpartition(d, k)][k], tgt[k]) + def test_partition_unicode_kind(self): + d = np.arange(10) + k = b'\xc3\xa4'.decode("UTF8") + assert_raises(ValueError, d.partition, 2, kind=k) + assert_raises(ValueError, d.argpartition, 2, kind=k) + + def test_partition_fuzz(self): + # a few rounds of random data testing + for j in range(10, 30): + for i in range(1, j - 2): + d = np.arange(j) + np.random.shuffle(d) + d = d % np.random.randint(2, 30) + idx = np.random.randint(d.size) + kth = [0, idx, i, i + 1] + tgt = np.sort(d)[kth] + assert_array_equal(np.partition(d, kth)[kth], tgt, + err_msg="data: %r\n kth: %r" % (d, kth)) def test_flatten(self): x0 = np.array([[1, 2, 3], [4, 5, 6]], np.int32) @@ -1946,6 +2081,11 @@ class TestArgmax(TestCase): ([timedelta(days=10, seconds=24), timedelta(days=10, seconds=5), timedelta(days=10, seconds=43)], 2), + ([False, False, False, False, True], 4), + ([False, False, False, True, False], 3), + ([True, False, False, False, False], 0), + ([True, False, True, False, False], 0), + # Can't reduce a "flexible type" #(['a', 'z', 'aa', 'zz'], 3), #(['zz', 'a', 'aa', 'a'], 0), @@ -2032,6 +2172,11 @@ class TestArgmin(TestCase): ([timedelta(days=10, seconds=24), timedelta(days=10, seconds=5), timedelta(days=10, seconds=43)], 1), + ([True, True, True, True, False], 4), + ([True, True, True, False, True], 3), + ([False, True, True, True, True], 0), + ([False, True, False, True, True], 0), + # Can't reduce a "flexible type" #(['a', 'z', 'aa', 'zz'], 0), #(['zz', 'a', 'aa', 'a'], 1), @@ -2298,7 +2443,7 @@ class TestLexsort(TestCase): class TestIO(object): - """Test tofile, fromfile, tostring, and fromstring""" + """Test tofile, fromfile, tobytes, and fromstring""" def setUp(self): shape = (2, 4, 3) @@ -2306,18 +2451,29 @@ class TestIO(object): self.x = rand(shape) + rand(shape).astype(np.complex)*1j self.x[0,:, 1] = [nan, inf, -inf, nan] self.dtype = self.x.dtype - self.filename = tempfile.mktemp() + self.tempdir = tempfile.mkdtemp() + self.filename = tempfile.mktemp(dir=self.tempdir) def tearDown(self): - if os.path.isfile(self.filename): - os.unlink(self.filename) - #tmp_file.close() + shutil.rmtree(self.tempdir) def test_bool_fromstring(self): 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) + def test_uint64_fromstring(self): + d = np.fromstring("9923372036854775807 104783749223640", + dtype=np.uint64, sep=' '); + e = np.array([9923372036854775807, 104783749223640], dtype=np.uint64) + assert_array_equal(d, e) + + def test_int64_fromstring(self): + d = np.fromstring("-25041670086757 104783749223640", + dtype=np.int64, sep=' '); + e = np.array([-25041670086757, 104783749223640], dtype=np.int64) + assert_array_equal(d, e) + def test_empty_files_binary(self): f = open(self.filename, 'w') f.close() @@ -2339,7 +2495,6 @@ class TestIO(object): y = np.fromfile(f, dtype=self.dtype) f.close() assert_array_equal(y, self.x.flat) - os.unlink(self.filename) def test_roundtrip_filename(self): self.x.tofile(self.filename) @@ -2347,11 +2502,11 @@ class TestIO(object): assert_array_equal(y, self.x.flat) def test_roundtrip_binary_str(self): - s = self.x.tostring() + s = self.x.tobytes() y = np.fromstring(s, dtype=self.dtype) assert_array_equal(y, self.x.flat) - s = self.x.tostring('F') + s = self.x.tobytes('F') y = np.fromstring(s, dtype=self.dtype) assert_array_equal(y, self.x.flatten('F')) @@ -2392,8 +2547,6 @@ class TestIO(object): f.close() assert_equal(pos, 10, err_msg=err_msg) - os.unlink(self.filename) - def test_file_position_after_tofile(self): # gh-4118 sizes = [io.DEFAULT_BUFFER_SIZE//8, @@ -2415,13 +2568,12 @@ class TestIO(object): f = open(self.filename, 'r+b') f.read(2) + f.seek(0, 1) # seek between read&write required by ANSI C np.array([0], dtype=np.float64).tofile(f) pos = f.tell() f.close() assert_equal(pos, 10, err_msg=err_msg) - os.unlink(self.filename) - def _check_from(self, s, value, **kw): y = np.fromstring(asbytes(s), **kw) assert_array_equal(y, value) @@ -2524,7 +2676,6 @@ class TestIO(object): s = f.read() f.close() assert_equal(s, '1.51,2.0,3.51,4.0') - os.unlink(self.filename) def test_tofile_format(self): x = np.array([1.51, 2, 3.51, 4], dtype=float) @@ -2556,7 +2707,7 @@ class TestFromBuffer(object): for dtype in [float, int, np.complex]: dt = np.dtype(dtype).newbyteorder(byteorder) x = (np.random.random((4, 7))*5).astype(dt) - buf = x.tostring() + buf = x.tobytes() yield self.tst_basic, buf, x.flat, {'dtype':dt} def test_empty(self): @@ -2704,8 +2855,8 @@ class TestRecord(TestCase): # byte string indexing fails gracefully assert_raises(ValueError, a.__setitem__, asbytes('f1'), 1) assert_raises(ValueError, a.__getitem__, asbytes('f1')) - assert_raises(ValueError, a['f1'].__setitem__, asbytes('sf1'), 1) - assert_raises(ValueError, a['f1'].__getitem__, asbytes('sf1')) + assert_raises(IndexError, a['f1'].__setitem__, asbytes('sf1'), 1) + assert_raises(IndexError, a['f1'].__getitem__, asbytes('sf1')) else: funcs = (str, unicode) for func in funcs: @@ -2829,6 +2980,8 @@ class TestStats(TestCase): np.random.seed(range(3)) self.rmat = np.random.random((4, 5)) self.cmat = self.rmat + 1j * self.rmat + self.omat = np.array([Decimal(repr(r)) for r in self.rmat.flat]) + self.omat = self.omat.reshape(4, 5) def test_keepdims(self): mat = np.eye(3) @@ -2855,9 +3008,20 @@ class TestStats(TestCase): assert_raises(ValueError, f, mat, axis=1, out=out) def test_dtype_from_input(self): + icodes = np.typecodes['AllInteger'] fcodes = np.typecodes['AllFloat'] + # object type + for f in self.funcs: + mat = np.array([[Decimal(1)]*3]*3) + tgt = mat.dtype.type + res = f(mat, axis=1).dtype.type + assert_(res is tgt) + # scalar case + res = type(f(mat, axis=None)) + assert_(res is Decimal) + # integer types for f in self.funcs: for c in icodes: @@ -2868,6 +3032,7 @@ class TestStats(TestCase): # scalar case res = f(mat, axis=None).dtype.type assert_(res is tgt) + # mean for float types for f in [_mean]: for c in fcodes: @@ -2878,10 +3043,12 @@ class TestStats(TestCase): # scalar case res = f(mat, axis=None).dtype.type assert_(res is tgt) + # var, std for float types for f in [_var, _std]: for c in fcodes: mat = np.eye(3, dtype=c) + # deal with complex types tgt = mat.real.dtype.type res = f(mat, axis=1).dtype.type assert_(res is tgt) @@ -2957,7 +3124,7 @@ class TestStats(TestCase): assert_equal(f(A, axis=axis), np.zeros([])) def test_mean_values(self): - for mat in [self.rmat, self.cmat]: + for mat in [self.rmat, self.cmat, self.omat]: for axis in [0, 1]: tgt = mat.sum(axis=axis) res = _mean(mat, axis=axis) * mat.shape[axis] @@ -2968,16 +3135,16 @@ class TestStats(TestCase): assert_almost_equal(res, tgt) def test_var_values(self): - for mat in [self.rmat, self.cmat]: + for mat in [self.rmat, self.cmat, self.omat]: for axis in [0, 1, None]: msqr = _mean(mat * mat.conj(), axis=axis) mean = _mean(mat, axis=axis) - tgt = msqr - mean * mean.conj() + tgt = msqr - mean * mean.conjugate() res = _var(mat, axis=axis) assert_almost_equal(res, tgt) def test_std_values(self): - for mat in [self.rmat, self.cmat]: + for mat in [self.rmat, self.cmat, self.omat]: for axis in [0, 1, None]: tgt = np.sqrt(_var(mat, axis=axis)) res = _std(mat, axis=axis) @@ -3064,6 +3231,23 @@ class TestDot(TestCase): r = np.empty((1024, 32), dtype=int) assert_raises(ValueError, dot, f, v, r) + def test_dot_scalar_and_matrix_of_objects(self): + # Ticket #2469 + arr = np.matrix([1, 2], dtype=object) + desired = np.matrix([[3, 6]], dtype=object) + assert_equal(np.dot(arr, 3), desired) + assert_equal(np.dot(3, arr), desired) + + +class TestInner(TestCase): + + def test_inner_scalar_and_matrix_of_objects(self): + # Ticket #4482 + arr = np.matrix([1, 2], dtype=object) + desired = np.matrix([[3, 6]], dtype=object) + assert_equal(np.inner(arr, 3), desired) + assert_equal(np.inner(3, arr), desired) + class TestSummarization(TestCase): def test_1d(self): @@ -3105,12 +3289,6 @@ class TestChoose(TestCase): A = np.choose(self.ind, (self.x, self.y2)) assert_equal(A, [[2, 2, 3], [2, 2, 3]]) -def can_use_decimal(): - try: - from decimal import Decimal - return True - except ImportError: - return False # TODO: test for multidimensional NEIGH_MODE = {'zero': 0, 'one': 1, 'constant': 2, 'circular': 3, 'mirror': 4} @@ -3146,11 +3324,7 @@ class TestNeighborhoodIter(TestCase): def test_simple2d(self): self._test_simple2d(np.float) - @dec.skipif(not can_use_decimal(), - "Skip neighborhood iterator tests for decimal objects " \ - "(decimal module not available") def test_simple2d_object(self): - from decimal import Decimal self._test_simple2d(Decimal) def _test_mirror2d(self, dt): @@ -3166,11 +3340,7 @@ class TestNeighborhoodIter(TestCase): def test_mirror2d(self): self._test_mirror2d(np.float) - @dec.skipif(not can_use_decimal(), - "Skip neighborhood iterator tests for decimal objects " \ - "(decimal module not available") def test_mirror2d_object(self): - from decimal import Decimal self._test_mirror2d(Decimal) # Simple, 1d tests @@ -3192,11 +3362,7 @@ class TestNeighborhoodIter(TestCase): def test_simple_float(self): self._test_simple(np.float) - @dec.skipif(not can_use_decimal(), - "Skip neighborhood iterator tests for decimal objects " \ - "(decimal module not available") def test_simple_object(self): - from decimal import Decimal self._test_simple(Decimal) # Test mirror modes @@ -3211,11 +3377,7 @@ class TestNeighborhoodIter(TestCase): def test_mirror(self): self._test_mirror(np.float) - @dec.skipif(not can_use_decimal(), - "Skip neighborhood iterator tests for decimal objects " \ - "(decimal module not available") def test_mirror_object(self): - from decimal import Decimal self._test_mirror(Decimal) # Circular mode @@ -3229,11 +3391,7 @@ class TestNeighborhoodIter(TestCase): def test_circular(self): self._test_circular(np.float) - @dec.skipif(not can_use_decimal(), - "Skip neighborhood iterator tests for decimal objects " \ - "(decimal module not available") def test_circular_object(self): - from decimal import Decimal self._test_circular(Decimal) # Test stacking neighborhood iterators @@ -3866,7 +4024,8 @@ class TestMemEventHook(TestCase): # multiarray/multiarray_tests.c.src test_pydatamem_seteventhook_start() # force an allocation and free of a numpy array - a = np.zeros(10) + # needs to be larger then limit of small memory cacher in ctors.c + a = np.zeros(1000) del a test_pydatamem_seteventhook_end() @@ -4082,5 +4241,150 @@ class TestConversion(TestCase): "type %s and %s failed" % (dt1, dt2)) +class TestWhere(TestCase): + def test_basic(self): + dts = [np.bool, np.int16, np.int32, np.int64, np.double, np.complex128, + np.longdouble, np.clongdouble] + for dt in dts: + c = np.ones(53, dtype=np.bool) + assert_equal(np.where( c, dt(0), dt(1)), dt(0)) + assert_equal(np.where(~c, dt(0), dt(1)), dt(1)) + assert_equal(np.where(True, dt(0), dt(1)), dt(0)) + assert_equal(np.where(False, dt(0), dt(1)), dt(1)) + d = np.ones_like(c).astype(dt) + e = np.zeros_like(d) + r = d.astype(dt) + c[7] = False + r[7] = e[7] + assert_equal(np.where(c, e, e), e) + assert_equal(np.where(c, d, e), r) + assert_equal(np.where(c, d, e[0]), r) + assert_equal(np.where(c, d[0], e), r) + assert_equal(np.where(c[::2], d[::2], e[::2]), r[::2]) + assert_equal(np.where(c[1::2], d[1::2], e[1::2]), r[1::2]) + assert_equal(np.where(c[::3], d[::3], e[::3]), r[::3]) + assert_equal(np.where(c[1::3], d[1::3], e[1::3]), r[1::3]) + assert_equal(np.where(c[::-2], d[::-2], e[::-2]), r[::-2]) + assert_equal(np.where(c[::-3], d[::-3], e[::-3]), r[::-3]) + assert_equal(np.where(c[1::-3], d[1::-3], e[1::-3]), r[1::-3]) + + def test_exotic(self): + # object + assert_array_equal(np.where(True, None, None), np.array(None)) + # zero sized + m = np.array([], dtype=bool).reshape(0, 3) + b = np.array([], dtype=np.float64).reshape(0, 3) + assert_array_equal(np.where(m, 0, b), np.array([]).reshape(0, 3)) + + # object cast + d = np.array([-1.34, -0.16, -0.54, -0.31, -0.08, -0.95, 0.000, 0.313, + 0.547, -0.18, 0.876, 0.236, 1.969, 0.310, 0.699, 1.013, + 1.267, 0.229, -1.39, 0.487]) + nan = float('NaN') + e = np.array(['5z', '0l', nan, 'Wz', nan, nan, 'Xq', 'cs', nan, nan, + 'QN', nan, nan, 'Fd', nan, nan, 'kp', nan, '36', 'i1'], + dtype=object); + m = np.array([0,0,1,0,1,1,0,0,1,1,0,1,1,0,1,1,0,1,0,0], dtype=bool) + + r = e[:] + r[np.where(m)] = d[np.where(m)] + assert_array_equal(np.where(m, d, e), r) + + r = e[:] + r[np.where(~m)] = d[np.where(~m)] + assert_array_equal(np.where(m, e, d), r) + + assert_array_equal(np.where(m, e, e), e) + + # minimal dtype result with NaN scalar (e.g required by pandas) + d = np.array([1., 2.], dtype=np.float32) + e = float('NaN') + assert_equal(np.where(True, d, e).dtype, np.float32) + e = float('Infinity') + assert_equal(np.where(True, d, e).dtype, np.float32) + e = float('-Infinity') + assert_equal(np.where(True, d, e).dtype, np.float32) + # also check upcast + e = float(1e150) + assert_equal(np.where(True, d, e).dtype, np.float64) + + def test_ndim(self): + c = [True, False] + a = np.zeros((2, 25)) + b = np.ones((2, 25)) + r = np.where(np.array(c)[:,np.newaxis], a, b) + assert_array_equal(r[0], a[0]) + assert_array_equal(r[1], b[0]) + + a = a.T + b = b.T + r = np.where(c, a, b) + assert_array_equal(r[:,0], a[:,0]) + assert_array_equal(r[:,1], b[:,0]) + + def test_dtype_mix(self): + c = np.array([False, True, False, False, False, False, True, False, + False, False, True, False]) + a = np.uint32(1) + b = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.], + dtype=np.float64) + r = np.array([5., 1., 3., 2., -1., -4., 1., -10., 10., 1., 1., 3.], + dtype=np.float64) + assert_equal(np.where(c, a, b), r) + + a = a.astype(np.float32) + b = b.astype(np.int64) + assert_equal(np.where(c, a, b), r) + + # non bool mask + c = c.astype(np.int) + c[c != 0] = 34242324 + assert_equal(np.where(c, a, b), r) + # invert + tmpmask = c != 0 + c[c == 0] = 41247212 + c[tmpmask] = 0 + assert_equal(np.where(c, b, a), r) + + def test_foreign(self): + c = np.array([False, True, False, False, False, False, True, False, + False, False, True, False]) + r = np.array([5., 1., 3., 2., -1., -4., 1., -10., 10., 1., 1., 3.], + dtype=np.float64) + a = np.ones(1, dtype='>i4') + b = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.], + dtype=np.float64) + assert_equal(np.where(c, a, b), r) + + b = b.astype('>f8') + assert_equal(np.where(c, a, b), r) + + a = a.astype('<i4') + assert_equal(np.where(c, a, b), r) + + c = c.astype('>i4') + assert_equal(np.where(c, a, b), r) + + def test_error(self): + c = [True, True] + a = np.ones((4, 5)) + b = np.ones((5, 5)) + assert_raises(ValueError, np.where, c, a, a) + assert_raises(ValueError, np.where, c[0], a, b) + + def test_string(self): + # gh-4778 check strings are properly filled with nulls + a = np.array("abc") + b = np.array("x" * 753) + assert_equal(np.where(True, a, b), "abc") + assert_equal(np.where(False, b, a), "abc") + + # check native datatype sized strings + a = np.array("abcd") + b = np.array("x" * 8) + assert_equal(np.where(True, a, b), "abcd") + assert_equal(np.where(False, b, a), "abcd") + + if __name__ == "__main__": run_module_suite() diff --git a/numpy/core/tests/test_nditer.py b/numpy/core/tests/test_nditer.py index 95c127316..0055c038b 100644 --- a/numpy/core/tests/test_nditer.py +++ b/numpy/core/tests/test_nditer.py @@ -6,7 +6,7 @@ import numpy as np from numpy import array, arange, nditer, all from numpy.compat import asbytes, sixu from numpy.testing import * - +from numpy.core.multiarray_tests import test_nditer_too_large def iter_multi_index(i): @@ -657,9 +657,9 @@ def test_iter_broadcasting_errors(): # The message should contain "shape->remappedshape" for each operand assert_(msg.find('(2,3)->(2,3)') >= 0, 'Message "%s" doesn\'t contain operand shape (2,3)->(2,3)' % msg) - assert_(msg.find('(2)->(2,newaxis)') >= 0, + assert_(msg.find('(2,)->(2,newaxis)') >= 0, ('Message "%s" doesn\'t contain remapped operand shape' + - '(2)->(2,newaxis)') % msg) + '(2,)->(2,newaxis)') % msg) # The message should contain the itershape parameter assert_(msg.find('(4,3)') >= 0, 'Message "%s" doesn\'t contain itershape parameter (4,3)' % msg) @@ -2586,6 +2586,44 @@ def test_iter_too_large(): size = np.iinfo(np.intp).max // 1024 arr = np.lib.stride_tricks.as_strided(np.zeros(1), (size,), (0,)) assert_raises(ValueError, nditer, (arr, arr[:, None])) + # test the same for multiindex. That may get more interesting when + # removing 0 dimensional axis is allowed (since an iterator can grow then) + assert_raises(ValueError, nditer, + (arr, arr[:, None]), flags=['multi_index']) + + +def test_iter_too_large_with_multiindex(): + # When a multi index is being tracked, the error is delayed this + # checks the delayed error messages and getting below that by + # removing an axis. + base_size = 2**10 + num = 1 + while base_size**num < np.iinfo(np.intp).max: + num += 1 + + shape_template = [1, 1] * num + arrays = [] + for i in range(num): + shape = shape_template[:] + shape[i * 2] = 2**10 + arrays.append(np.empty(shape)) + arrays = tuple(arrays) + + # arrays are now too large to be broadcast. The different modes test + # different nditer functionality with or without GIL. + for mode in range(6): + assert_raises(ValueError, test_nditer_too_large, arrays, -1, mode) + # but if we do nothing with the nditer, it can be constructed: + test_nditer_too_large(arrays, -1, 7) + + # When an axis is removed, things should work again (half the time): + for i in range(num): + for mode in range(6): + # an axis with size 1024 is removed: + test_nditer_too_large(arrays, i*2, mode) + # an axis with size 1 is removed: + assert_raises(ValueError, test_nditer_too_large, + arrays, i*2 + 1, mode) if __name__ == "__main__": diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py index ac341468c..c85c5cf3e 100644 --- a/numpy/core/tests/test_numeric.py +++ b/numpy/core/tests/test_numeric.py @@ -5,6 +5,7 @@ import platform from decimal import Decimal import warnings import itertools +import platform import numpy as np from numpy.core import * @@ -346,33 +347,54 @@ class TestBoolCmp(TestCase): self.ed[s:s+4] = [(i & 2**x) != 0 for x in range(4)] s += 4 + self.nf = self.f.copy() + self.nd = self.d.copy() + self.nf[self.ef] = np.nan + self.nd[self.ed] = np.nan + def test_float(self): # offset for alignment test for i in range(4): - assert_array_equal(self.f[i:] != 0, self.ef[i:]) assert_array_equal(self.f[i:] > 0, self.ef[i:]) assert_array_equal(self.f[i:] - 1 >= 0, self.ef[i:]) assert_array_equal(self.f[i:] == 0, ~self.ef[i:]) assert_array_equal(-self.f[i:] < 0, self.ef[i:]) assert_array_equal(-self.f[i:] + 1 <= 0, self.ef[i:]) - - assert_array_equal(0 != self.f[i:], self.ef[i:]) - assert_array_equal(np.zeros_like(self.f)[i:] != self.f[i:], - self.ef[i:]) + r = self.f[i:] != 0 + assert_array_equal(r, self.ef[i:]) + r2 = self.f[i:] != np.zeros_like(self.f[i:]) + r3 = 0 != self.f[i:] + assert_array_equal(r, r2) + assert_array_equal(r, r3) + # check bool == 0x1 + assert_array_equal(r.view(np.int8), r.astype(np.int8)) + assert_array_equal(r2.view(np.int8), r2.astype(np.int8)) + assert_array_equal(r3.view(np.int8), r3.astype(np.int8)) + + # isnan on amd64 takes the same codepath + assert_array_equal(np.isnan(self.nf[i:]), self.ef[i:]) def test_double(self): # offset for alignment test for i in range(2): - assert_array_equal(self.d[i:] != 0, self.ed[i:]) assert_array_equal(self.d[i:] > 0, self.ed[i:]) assert_array_equal(self.d[i:] - 1 >= 0, self.ed[i:]) assert_array_equal(self.d[i:] == 0, ~self.ed[i:]) assert_array_equal(-self.d[i:] < 0, self.ed[i:]) assert_array_equal(-self.d[i:] + 1 <= 0, self.ed[i:]) + r = self.d[i:] != 0 + assert_array_equal(r, self.ed[i:]) + r2 = self.d[i:] != np.zeros_like(self.d[i:]) + r3 = 0 != self.d[i:] + assert_array_equal(r, r2) + assert_array_equal(r, r3) + # check bool == 0x1 + assert_array_equal(r.view(np.int8), r.astype(np.int8)) + assert_array_equal(r2.view(np.int8), r2.astype(np.int8)) + assert_array_equal(r3.view(np.int8), r3.astype(np.int8)) - assert_array_equal(0 != self.d[i:], self.ed[i:]) - assert_array_equal(np.zeros_like(self.d)[i:] != self.d[i:], - self.ed[i:]) + # isnan on amd64 takes the same codepath + assert_array_equal(np.isnan(self.nd[i:]), self.ed[i:]) class TestSeterr(TestCase): @@ -686,10 +708,10 @@ class TestTypes(TestCase): assert_equal(np.promote_types('<i8', '<i8'), np.dtype('i8')) assert_equal(np.promote_types('>i8', '>i8'), np.dtype('i8')) - assert_equal(np.promote_types('>i8', '>U16'), np.dtype('U16')) - assert_equal(np.promote_types('<i8', '<U16'), np.dtype('U16')) - assert_equal(np.promote_types('>U16', '>i8'), np.dtype('U16')) - assert_equal(np.promote_types('<U16', '<i8'), np.dtype('U16')) + assert_equal(np.promote_types('>i8', '>U16'), np.dtype('U21')) + assert_equal(np.promote_types('<i8', '<U16'), np.dtype('U21')) + assert_equal(np.promote_types('>U16', '>i8'), np.dtype('U21')) + assert_equal(np.promote_types('<U16', '<i8'), np.dtype('U21')) assert_equal(np.promote_types('<S5', '<U8'), np.dtype('U8')) assert_equal(np.promote_types('>S5', '>U8'), np.dtype('U8')) @@ -703,6 +725,39 @@ class TestTypes(TestCase): assert_equal(np.promote_types('<m8', '<m8'), np.dtype('m8')) assert_equal(np.promote_types('>m8', '>m8'), np.dtype('m8')) + def test_promote_types_strings(self): + assert_equal(np.promote_types('bool', 'S'), np.dtype('S5')) + assert_equal(np.promote_types('b', 'S'), np.dtype('S4')) + assert_equal(np.promote_types('u1', 'S'), np.dtype('S3')) + assert_equal(np.promote_types('u2', 'S'), np.dtype('S5')) + assert_equal(np.promote_types('u4', 'S'), np.dtype('S10')) + assert_equal(np.promote_types('u8', 'S'), np.dtype('S20')) + assert_equal(np.promote_types('i1', 'S'), np.dtype('S4')) + assert_equal(np.promote_types('i2', 'S'), np.dtype('S6')) + assert_equal(np.promote_types('i4', 'S'), np.dtype('S11')) + assert_equal(np.promote_types('i8', 'S'), np.dtype('S21')) + assert_equal(np.promote_types('bool', 'U'), np.dtype('U5')) + assert_equal(np.promote_types('b', 'U'), np.dtype('U4')) + assert_equal(np.promote_types('u1', 'U'), np.dtype('U3')) + assert_equal(np.promote_types('u2', 'U'), np.dtype('U5')) + assert_equal(np.promote_types('u4', 'U'), np.dtype('U10')) + assert_equal(np.promote_types('u8', 'U'), np.dtype('U20')) + assert_equal(np.promote_types('i1', 'U'), np.dtype('U4')) + assert_equal(np.promote_types('i2', 'U'), np.dtype('U6')) + assert_equal(np.promote_types('i4', 'U'), np.dtype('U11')) + assert_equal(np.promote_types('i8', 'U'), np.dtype('U21')) + assert_equal(np.promote_types('bool', 'S1'), np.dtype('S5')) + assert_equal(np.promote_types('bool', 'S30'), np.dtype('S30')) + assert_equal(np.promote_types('b', 'S1'), np.dtype('S4')) + assert_equal(np.promote_types('b', 'S30'), np.dtype('S30')) + assert_equal(np.promote_types('u1', 'S1'), np.dtype('S3')) + assert_equal(np.promote_types('u1', 'S30'), np.dtype('S30')) + assert_equal(np.promote_types('u2', 'S1'), np.dtype('S5')) + assert_equal(np.promote_types('u2', 'S30'), np.dtype('S30')) + assert_equal(np.promote_types('u4', 'S1'), np.dtype('S10')) + assert_equal(np.promote_types('u4', 'S30'), np.dtype('S30')) + assert_equal(np.promote_types('u8', 'S1'), np.dtype('S20')) + assert_equal(np.promote_types('u8', 'S30'), np.dtype('S30')) def test_can_cast(self): assert_(np.can_cast(np.int32, np.int64)) @@ -711,7 +766,7 @@ class TestTypes(TestCase): assert_(np.can_cast('i8', 'f8')) assert_(not np.can_cast('i8', 'f4')) - assert_(np.can_cast('i4', 'S4')) + assert_(np.can_cast('i4', 'S11')) assert_(np.can_cast('i8', 'i8', 'no')) assert_(not np.can_cast('<i8', '>i8', 'no')) @@ -727,6 +782,54 @@ class TestTypes(TestCase): assert_(np.can_cast('<i8', '>u4', 'unsafe')) + assert_(np.can_cast('bool', 'S5')) + assert_(not np.can_cast('bool', 'S4')) + + assert_(np.can_cast('b', 'S4')) + assert_(not np.can_cast('b', 'S3')) + + assert_(np.can_cast('u1', 'S3')) + assert_(not np.can_cast('u1', 'S2')) + assert_(np.can_cast('u2', 'S5')) + assert_(not np.can_cast('u2', 'S4')) + assert_(np.can_cast('u4', 'S10')) + assert_(not np.can_cast('u4', 'S9')) + assert_(np.can_cast('u8', 'S20')) + assert_(not np.can_cast('u8', 'S19')) + + assert_(np.can_cast('i1', 'S4')) + assert_(not np.can_cast('i1', 'S3')) + assert_(np.can_cast('i2', 'S6')) + assert_(not np.can_cast('i2', 'S5')) + assert_(np.can_cast('i4', 'S11')) + assert_(not np.can_cast('i4', 'S10')) + assert_(np.can_cast('i8', 'S21')) + assert_(not np.can_cast('i8', 'S20')) + + assert_(np.can_cast('bool', 'S5')) + assert_(not np.can_cast('bool', 'S4')) + + assert_(np.can_cast('b', 'U4')) + assert_(not np.can_cast('b', 'U3')) + + assert_(np.can_cast('u1', 'U3')) + assert_(not np.can_cast('u1', 'U2')) + assert_(np.can_cast('u2', 'U5')) + assert_(not np.can_cast('u2', 'U4')) + assert_(np.can_cast('u4', 'U10')) + assert_(not np.can_cast('u4', 'U9')) + assert_(np.can_cast('u8', 'U20')) + assert_(not np.can_cast('u8', 'U19')) + + assert_(np.can_cast('i1', 'U4')) + assert_(not np.can_cast('i1', 'U3')) + assert_(np.can_cast('i2', 'U6')) + assert_(not np.can_cast('i2', 'U5')) + assert_(np.can_cast('i4', 'U11')) + assert_(not np.can_cast('i4', 'U10')) + assert_(np.can_cast('i8', 'U21')) + assert_(not np.can_cast('i8', 'U20')) + assert_raises(TypeError, np.can_cast, 'i4', None) assert_raises(TypeError, np.can_cast, None, 'i4') @@ -829,11 +932,26 @@ class TestNonzero(TestCase): 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_(not x['a'].T.flags.aligned) 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])) + def test_sparse(self): + # test special sparse condition boolean code path + for i in range(20): + c = np.zeros(200, dtype=np.bool) + c[i::20] = True + assert_equal(np.nonzero(c)[0], np.arange(i, 200 + i, 20)) + + c = np.zeros(400, dtype=np.bool) + c[10 + i:20 + i] = True + c[20 + i*2] = True + assert_equal(np.nonzero(c)[0], + np.concatenate((np.arange(10 +i, 20 + i), [20 +i*2]))) + + class TestIndex(TestCase): def test_boolean(self): a = rand(3, 5, 8) @@ -932,7 +1050,15 @@ class TestArrayComparisons(TestCase): def assert_array_strict_equal(x, y): assert_array_equal(x, y) # Check flags - assert_(x.flags == y.flags) + if 'sparc' not in platform.platform().lower(): + assert_(x.flags == y.flags) + else: + # sparc arrays may not be aligned for long double types + assert_(x.flags.owndata == y.flags.owndata) + assert_(x.flags.writeable == y.flags.writeable) + assert_(x.flags.c_contiguous == y.flags.c_contiguous) + assert_(x.flags.f_contiguous == y.flags.f_contiguous) + assert_(x.flags.updateifcopy == y.flags.updateifcopy) # check endianness assert_(x.dtype.isnative == y.dtype.isnative) @@ -1420,6 +1546,13 @@ class TestAllclose(object): assert_array_equal(y, array([0, inf])) + def test_min_int(self): + # Could make problems because of abs(min_int) == min_int + min_int = np.iinfo(np.int_).min + a = np.array([min_int], dtype=np.int_) + assert_(allclose(a, a)) + + class TestIsclose(object): rtol = 1e-5 atol = 1e-8 @@ -1870,6 +2003,88 @@ class TestRoll(TestCase): x = np.array([]) assert_equal(np.roll(x, 1), np.array([])) +class TestCross(TestCase): + def test_2x2(self): + u = [1, 2] + v = [3, 4] + z = -2 + cp = np.cross(u, v) + assert_equal(cp, z) + cp = np.cross(v, u) + assert_equal(cp, -z) + + def test_2x3(self): + u = [1, 2] + v = [3, 4, 5] + z = np.array([10, -5, -2]) + cp = np.cross(u, v) + assert_equal(cp, z) + cp = np.cross(v, u) + assert_equal(cp, -z) + + def test_3x3(self): + u = [1, 2, 3] + v = [4, 5, 6] + z = np.array([-3, 6, -3]) + cp = cross(u, v) + assert_equal(cp, z) + cp = np.cross(v, u) + assert_equal(cp, -z) + + def test_broadcasting(self): + # Ticket #2624 (Trac #2032) + u = np.tile([1, 2], (11, 1)) + v = np.tile([3, 4], (11, 1)) + z = -2 + assert_equal(np.cross(u, v), z) + assert_equal(np.cross(v, u), -z) + assert_equal(np.cross(u, u), 0) + + u = np.tile([1, 2], (11, 1)).T + v = np.tile([3, 4, 5], (11, 1)) + z = np.tile([10, -5, -2], (11, 1)) + assert_equal(np.cross(u, v, axisa=0), z) + assert_equal(np.cross(v, u.T), -z) + assert_equal(np.cross(v, v), 0) + + u = np.tile([1, 2, 3], (11, 1)).T + v = np.tile([3, 4], (11, 1)).T + z = np.tile([-12, 9, -2], (11, 1)) + assert_equal(np.cross(u, v, axisa=0, axisb=0), z) + assert_equal(np.cross(v.T, u.T), -z) + assert_equal(np.cross(u.T, u.T), 0) + + u = np.tile([1, 2, 3], (5, 1)) + v = np.tile([4, 5, 6], (5, 1)).T + z = np.tile([-3, 6, -3], (5, 1)) + assert_equal(np.cross(u, v, axisb=0), z) + assert_equal(np.cross(v.T, u), -z) + assert_equal(np.cross(u, u), 0) + + def test_broadcasting_shapes(self): + u = np.ones((2, 1, 3)) + v = np.ones((5, 3)) + assert_equal(np.cross(u, v).shape, (2, 5, 3)) + u = np.ones((10, 3, 5)) + v = np.ones((2, 5)) + assert_equal(np.cross(u, v, axisa=1, axisb=0).shape, (10, 5, 3)) + assert_raises(ValueError, np.cross, u, v, axisa=1, axisb=2) + assert_raises(ValueError, np.cross, u, v, axisa=3, axisb=0) + u = np.ones((10, 3, 5, 7)) + v = np.ones((5, 7, 2)) + assert_equal(np.cross(u, v, axisa=1, axisc=2).shape, (10, 5, 3, 7)) + assert_raises(ValueError, np.cross, u, v, axisa=-5, axisb=2) + assert_raises(ValueError, np.cross, u, v, axisa=1, axisb=-4) + +def test_outer_out_param(): + arr1 = np.ones((5,)) + arr2 = np.ones((2,)) + arr3 = np.linspace(-2, 2, 5) + out1 = np.ndarray(shape=(5,5)) + out2 = np.ndarray(shape=(2, 5)) + res1 = np.outer(arr1, arr3, out1) + assert_equal(res1, out1) + assert_equal(np.outer(arr2, arr3, out2), out2) if __name__ == "__main__": run_module_suite() diff --git a/numpy/core/tests/test_numerictypes.py b/numpy/core/tests/test_numerictypes.py index 3cafcf65e..077e94475 100644 --- a/numpy/core/tests/test_numerictypes.py +++ b/numpy/core/tests/test_numerictypes.py @@ -365,7 +365,7 @@ class TestMultipleFields(TestCase): def _bad_call(self): return self.ary['f0', 'f1'] def test_no_tuple(self): - self.assertRaises(ValueError, self._bad_call) + self.assertRaises(IndexError, self._bad_call) def test_return(self): res = self.ary[['f0', 'f2']].tolist() assert_(res == [(1, 3), (5, 7)]) diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py index e35bbb320..726f0efb9 100644 --- a/numpy/core/tests/test_regression.py +++ b/numpy/core/tests/test_regression.py @@ -1,5 +1,6 @@ from __future__ import division, absolute_import, print_function +import copy import pickle import sys import platform @@ -153,7 +154,8 @@ class TestRegression(TestCase): {'names':['a'],'formats':['foo']}, align=1) @dec.knownfailureif((sys.version_info[0] >= 3) or - (sys.platform == "win32" and platform.architecture()[0] == "64bit"), + (sys.platform == "win32" and + platform.architecture()[0] == "64bit"), "numpy.intp('0xff', 16) not supported on Py3, " "as it does not inherit from Python int") def test_intp(self,level=rlevel): @@ -179,7 +181,7 @@ class TestRegression(TestCase): assert_(np.all(b[yb] > 0.5)) def test_endian_where(self,level=rlevel): - """GitHuB issue #369""" + """GitHub issue #369""" net = np.zeros(3, dtype='>f4') net[1] = 0.00458849 net[2] = 0.605202 @@ -286,11 +288,11 @@ class TestRegression(TestCase): b = np.array('world') a == b - def test_tostring_FORTRANORDER_discontiguous(self,level=rlevel): + def test_tobytes_FORTRANORDER_discontiguous(self,level=rlevel): """Fix in r2836""" - # Create discontiguous Fortran-ordered array + # Create non-contiguous Fortran ordered array x = np.array(np.random.rand(3, 3), order='F')[:, :2] - assert_array_almost_equal(x.ravel(), np.fromstring(x.tostring())) + assert_array_almost_equal(x.ravel(), np.fromstring(x.tobytes())) def test_flat_assignment(self,level=rlevel): """Correct behaviour of ticket #194""" @@ -309,7 +311,7 @@ class TestRegression(TestCase): self.assertRaises(ValueError, bfb) def test_nonarray_assignment(self): - # See also Issue gh-2870, test for nonarray assignment + # See also Issue gh-2870, test for non-array assignment # and equivalent unsafe casted array assignment a = np.arange(10) b = np.ones(10, dtype=bool) @@ -447,7 +449,10 @@ class TestRegression(TestCase): res1 = getattr(arr, func_meth)() res2 = getattr(np, func)(arr2) if res1 is None: - assert_(abs(arr-res2).max() < 1e-8, func) + res1 = arr + + if res1.dtype.kind in 'uib': + assert_((res1 == res2).all(), func) else: assert_(abs(res1-res2).max() < 1e-8, func) @@ -555,7 +560,7 @@ class TestRegression(TestCase): 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""" + """GitHub Issue #2700, setting shape failed for 0-sized arrays""" a = np.ones((0, 2)) a.shape = (-1, 2) @@ -563,7 +568,7 @@ class TestRegression(TestCase): # With NPY_RELAXED_STRIDES_CHECKING the test becomes superfluous. @dec.skipif(np.ones(1).strides[0] == np.iinfo(np.intp).max) def test_reshape_trailing_ones_strides(self): - # Github issue gh-2949, bad strides for trailing ones of new shape + # GitHub issue gh-2949, bad strides for trailing ones of new shape a = np.zeros(12, dtype=np.int32)[::2] # not contiguous strides_c = (16, 8, 8, 8) strides_f = (8, 24, 48, 48) @@ -751,8 +756,14 @@ class TestRegression(TestCase): 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)) + # After removing deprecation, the following are ValueErrors. + # This might seem odd as compared to the value error below. This + # is due to the fact that the new code always uses "nonzero" logic + # and the boolean special case is not taken. + self.assertRaises(IndexError, ia, x, s, np.zeros(9, dtype=float)) + self.assertRaises(IndexError, ia, x, s, np.zeros(11, dtype=float)) + # Old special case (different code path): + self.assertRaises(ValueError, ia, x.flat, s, np.zeros(9, dtype=float)) def test_mem_scalar_indexing(self, level=rlevel): """Ticket #603""" @@ -837,7 +848,7 @@ class TestRegression(TestCase): cnt0_b = cnt(b) cnt0_c = cnt(c) - # -- 0d -> 1d broadcasted slice assignment + # -- 0d -> 1-d broadcast slice assignment arr = np.zeros(5, dtype=np.object_) @@ -854,7 +865,7 @@ class TestRegression(TestCase): del arr - # -- 1d -> 2d broadcasted slice assignment + # -- 1-d -> 2-d broadcast slice assignment arr = np.zeros((5, 2), dtype=np.object_) arr0 = np.zeros(2, dtype=np.object_) @@ -873,7 +884,7 @@ class TestRegression(TestCase): del arr, arr0 - # -- 2d copying + flattening + # -- 2-d copying + flattening arr = np.zeros((5, 2), dtype=np.object_) @@ -1018,8 +1029,8 @@ class TestRegression(TestCase): b = np.zeros((2, 1), dtype = np.single) try: a.compress([True, False], axis = 1, out = b) - raise AssertionError("compress with an out which cannot be " \ - "safely casted should not return "\ + raise AssertionError("compress with an out which cannot be " + "safely casted should not return " "successfully") except TypeError: pass @@ -1200,7 +1211,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.tobytes()) assert_(test_string_void_scalar.view(test_string.dtype) == test_string) @@ -1208,7 +1219,7 @@ class TestRegression(TestCase): #reconstructed scalar is correct. test_record = np.ones((), "i,i") test_record_void_scalar = np.core.multiarray.scalar( - test_record.dtype, test_record.tostring()) + test_record.dtype, test_record.tobytes()) assert_(test_record_void_scalar == test_record) @@ -1378,10 +1389,10 @@ class TestRegression(TestCase): y = x.byteswap() if x.dtype.byteorder == z.dtype.byteorder: # little-endian machine - assert_equal(x, np.fromstring(y.tostring(), dtype=dtype.newbyteorder())) + assert_equal(x, np.fromstring(y.tobytes(), dtype=dtype.newbyteorder())) else: # big-endian machine - assert_equal(x, np.fromstring(y.tostring(), dtype=dtype)) + assert_equal(x, np.fromstring(y.tobytes(), dtype=dtype)) # double check real and imaginary parts: assert_equal(x.real, y.real.byteswap()) assert_equal(x.imag, y.imag.byteswap()) @@ -1527,7 +1538,7 @@ class TestRegression(TestCase): # file handle out of sync f0 = tempfile.NamedTemporaryFile() f = f0.file - f.write(np.arange(255, dtype='u1').tostring()) + f.write(np.arange(255, dtype='u1').tobytes()) f.seek(20) ret = np.fromfile(f, count=4, dtype='u1') @@ -1904,7 +1915,7 @@ class TestRegression(TestCase): # 2D array arr2 = np.reshape(arr, (2, 5)) # Fortran write followed by (C or F) read caused bus error - data_str = arr2.tostring('F') + data_str = arr2.tobytes('F') data_back = np.ndarray(arr2.shape, arr2.dtype, buffer=data_str, @@ -1940,5 +1951,62 @@ class TestRegression(TestCase): arr.__setitem__(slice(None), [9]) assert_equal(arr, [9, 9, 9]) + def test_format_on_flex_array_element(self): + # Ticket #4369. + dt = np.dtype([('date', '<M8[D]'), ('val', '<f8')]) + arr = np.array([('2000-01-01', 1)], dt) + formatted = '{0}'.format(arr[0]) + assert_equal(formatted, str(arr[0])) + + def test_deepcopy_on_0d_array(self): + # Ticket #3311. + arr = np.array(3) + arr_cp = copy.deepcopy(arr) + + assert_equal(arr, arr_cp) + assert_equal(arr.shape, arr_cp.shape) + assert_equal(int(arr), int(arr_cp)) + self.assertTrue(arr is not arr_cp) + self.assertTrue(isinstance(arr_cp, type(arr))) + + def test_bool_subscript_crash(self): + # gh-4494 + c = np.rec.array([(1, 2, 3), (4, 5, 6)]) + masked = c[np.array([True, False])] + base = masked.base + del masked, c + base.dtype + + def test_richcompare_crash(self): + # gh-4613 + import operator as op + + # dummy class where __array__ throws exception + class Foo(object): + __array_priority__ = 1002 + def __array__(self,*args,**kwargs): + raise Exception() + + rhs = Foo() + lhs = np.array(1) + for f in [op.lt, op.le, op.gt, op.ge]: + if sys.version_info[0] >= 3: + assert_raises(TypeError, f, lhs, rhs) + else: + f(lhs, rhs) + assert_(not op.eq(lhs, rhs)) + assert_(op.ne(lhs, rhs)) + + def test_richcompare_scalar_and_subclass(self): + # gh-4709 + class Foo(np.ndarray): + def __eq__(self, other): + return "OK" + x = np.array([1,2,3]).view(Foo) + assert_equal(10 == x, "OK") + assert_equal(np.int32(10) == x, "OK") + assert_equal(np.array([10]) == x, "OK") + + if __name__ == "__main__": run_module_suite() diff --git a/numpy/core/tests/test_scalarinherit.py b/numpy/core/tests/test_scalarinherit.py new file mode 100644 index 000000000..6f394196c --- /dev/null +++ b/numpy/core/tests/test_scalarinherit.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +""" Test printing of scalar types. + +""" + +import numpy as np +from numpy.testing import TestCase, run_module_suite + + +class A(object): pass +class B(A, np.float64): pass + +class C(B): pass +class D(C, B): pass + +class B0(np.float64, A): pass +class C0(B0): pass + +class TestInherit(TestCase): + def test_init(self): + x = B(1.0) + assert str(x) == '1.0' + y = C(2.0) + assert str(y) == '2.0' + z = D(3.0) + assert str(z) == '3.0' + def test_init2(self): + x = B0(1.0) + assert str(x) == '1.0' + y = C0(2.0) + assert str(y) == '2.0' + +if __name__ == "__main__": + run_module_suite() diff --git a/numpy/core/tests/test_scalarmath.py b/numpy/core/tests/test_scalarmath.py index 7bbb62be2..d823e963f 100644 --- a/numpy/core/tests/test_scalarmath.py +++ b/numpy/core/tests/test_scalarmath.py @@ -45,6 +45,12 @@ class TestTypes(TestCase): b = atype([1, 2, 3]) assert_equal(a, b) + def test_leak(self): + # test leak of scalar objects + # a leak would show up in valgrind as still-reachable of ~2.6MB + for i in range(200000): + np.add(1, 1) + class TestBaseMath(TestCase): def test_blocked(self): @@ -163,6 +169,12 @@ class TestConversion(TestCase): for code in 'lLqQ': assert_raises(OverflowError, Overflow_error_func, code) + def test_longdouble_int(self): + # gh-627 + x = np.longdouble(np.inf) + assert_raises(OverflowError, x.__int__) + x = np.clongdouble(np.inf) + assert_raises(OverflowError, x.__int__) def test_numpy_scalar_relational_operators(self): #All integer diff --git a/numpy/core/tests/test_shape_base.py b/numpy/core/tests/test_shape_base.py index e94e964b2..f1f5311c9 100644 --- a/numpy/core/tests/test_shape_base.py +++ b/numpy/core/tests/test_shape_base.py @@ -183,7 +183,7 @@ def test_concatenate_axis_None(): assert_equal(r.size, a.size + len(b)) assert_equal(r.dtype, a.dtype) r = np.concatenate((a, b, c), axis=None) - d = array(['0', '1', '2', '3', + d = array(['0.0', '1.0', '2.0', '3.0', '0', '1', '2', 'x']) assert_array_equal(r, d) diff --git a/numpy/core/tests/test_ufunc.py b/numpy/core/tests/test_ufunc.py index b217936f7..c9267671f 100644 --- a/numpy/core/tests/test_ufunc.py +++ b/numpy/core/tests/test_ufunc.py @@ -14,6 +14,10 @@ class TestUfunc(TestCase): import pickle assert pickle.loads(pickle.dumps(np.sin)) is np.sin + # Check that ufunc not defined in the top level numpy namespace such as + # numpy.core.test_rational.test_add can also be pickled + assert pickle.loads(pickle.dumps(test_add)) is test_add + def test_pickle_withstring(self): import pickle astring = asbytes("cnumpy.core\n_ufunc_reconstruct\np0\n" @@ -340,6 +344,10 @@ class TestUfunc(TestCase): assert_almost_equal(np.sum(d[-1::-2]), 250.) assert_almost_equal(np.sum(d[::-3]), 167.) assert_almost_equal(np.sum(d[-1::-3]), 167.) + # sum with first reduction entry != 0 + d = np.ones((1,), dtype=dt) + d += d + assert_almost_equal(d, 2.) def test_sum_complex(self): for dt in (np.complex64, np.complex128, np.clongdouble): @@ -361,6 +369,10 @@ class TestUfunc(TestCase): assert_almost_equal(np.sum(d[-1::-2]), 250. + 250j) assert_almost_equal(np.sum(d[::-3]), 167. + 167j) assert_almost_equal(np.sum(d[-1::-3]), 167. + 167j) + # sum with first reduction entry != 0 + d = np.ones((1,), dtype=dt) + 1j + d += d + assert_almost_equal(d, 2. + 2j) def test_inner1d(self): a = np.arange(6).reshape((2, 3)) @@ -580,6 +592,15 @@ class TestUfunc(TestCase): assert_equal(np.all(a), False) assert_equal(np.max(a), True) assert_equal(np.min(a), False) + assert_equal(np.array([[1]], dtype=object).sum(), 1) + assert_equal(np.array([[[1, 2]]], dtype=object).sum((0, 1)), [1, 2]) + + def test_object_scalar_multiply(self): + # Tickets #2469 and #4482 + arr = np.matrix([1, 2], dtype=object) + desired = np.matrix([[3, 6]], dtype=object) + assert_equal(np.multiply(arr, 3), desired) + assert_equal(np.multiply(3, arr), desired) def test_zerosize_reduction(self): # Test with default dtype and object dtype diff --git a/numpy/core/tests/test_umath.py b/numpy/core/tests/test_umath.py index 6db95e9a6..b3ddc2398 100644 --- a/numpy/core/tests/test_umath.py +++ b/numpy/core/tests/test_umath.py @@ -2,6 +2,7 @@ from __future__ import division, absolute_import, print_function import sys import platform +import warnings from numpy.testing import * from numpy.testing.utils import _gen_alignment_data @@ -175,6 +176,11 @@ class TestPower(TestCase): x = np.array([1, 2, 3], np.int16) assert_((x**2.00001).dtype is (x**2.0).dtype) + # Check that the fast path ignores 1-element not 0-d arrays + res = x ** np.array([[[2]]]) + assert_equal(res.shape, (1, 1, 3)) + + class TestLog2(TestCase): def test_log2_values(self) : x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] @@ -184,6 +190,27 @@ class TestLog2(TestCase): yf = np.array(y, dtype=dt) assert_almost_equal(np.log2(xf), yf) + def test_log2_ints(self): + # a good log2 implementation should provide this, + # might fail on OS with bad libm + for i in range(1, 65): + v = np.log2(2.**i) + assert_equal(v, float(i), err_msg='at exponent %d' % i) + + def test_log2_special(self): + assert_equal(np.log2(1.), 0.) + assert_equal(np.log2(np.inf), np.inf) + assert_(np.isnan(np.log2(np.nan))) + + with warnings.catch_warnings(record=True) as w: + warnings.filterwarnings('always', '', RuntimeWarning) + assert_(np.isnan(np.log2(-1.))) + assert_(np.isnan(np.log2(-np.inf))) + assert_equal(np.log2(0.), -np.inf) + assert_(w[0].category is RuntimeWarning) + assert_(w[1].category is RuntimeWarning) + assert_(w[2].category is RuntimeWarning) + class TestExp2(TestCase): def test_exp2_values(self) : @@ -305,12 +332,28 @@ class TestLog1p(TestCase): assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2)) assert_almost_equal(ncu.log1p(1e-6), ncu.log(1+1e-6)) + def test_special(self): + assert_equal(ncu.log1p(np.nan), np.nan) + assert_equal(ncu.log1p(np.inf), np.inf) + with np.errstate(divide="ignore"): + assert_equal(ncu.log1p(-1.), -np.inf) + with np.errstate(invalid="ignore"): + assert_equal(ncu.log1p(-2.), np.nan) + assert_equal(ncu.log1p(-np.inf), np.nan) + class TestExpm1(TestCase): def test_expm1(self): assert_almost_equal(ncu.expm1(0.2), ncu.exp(0.2)-1) assert_almost_equal(ncu.expm1(1e-6), ncu.exp(1e-6)-1) + def test_special(self): + assert_equal(ncu.expm1(np.inf), np.inf) + assert_equal(ncu.expm1(0.), 0.) + assert_equal(ncu.expm1(-0.), -0.) + assert_equal(ncu.expm1(np.inf), np.inf) + assert_equal(ncu.expm1(-np.inf), -1.) + class TestHypot(TestCase, object): def test_simple(self): @@ -642,6 +685,24 @@ class TestFmin(_FilterInvalids): assert_equal(np.fmin(arg1, arg2), out) +class TestBool(TestCase): + def test_truth_table(self): + arg1 = [False, False, True, True] + arg2 = [False, True, False, True] + # OR + out = [False, True, True, True] + for func in (np.logical_or, np.bitwise_or, np.maximum): + assert_equal(func(arg1, arg2), out) + # AND + out = [False, False, False, True] + for func in (np.logical_and, np.bitwise_and, np.minimum): + assert_equal(func(arg1, arg2), out) + # XOR + out = [False, True, True, False] + for func in (np.logical_xor, np.bitwise_xor, np.not_equal): + assert_equal(func(arg1, arg2), out) + + class TestFloatingPoint(TestCase): def test_floating_point(self): assert_equal(ncu.FLOATING_POINT_SUPPORT, 1) @@ -693,8 +754,8 @@ class TestMinMax(TestCase): assert_equal(inp.min(), -1e10, err_msg=msg) -class TestAbsolute(TestCase): - def test_abs_blocked(self): +class TestAbsoluteNegative(TestCase): + def test_abs_neg_blocked(self): # simd tests on abs, test all alignments for vz + 2 * (vs - 1) + 1 for dt, sz in [(np.float32, 11), (np.float64, 5)]: for out, inp, msg in _gen_alignment_data(dtype=dt, type='unary', @@ -704,6 +765,10 @@ class TestAbsolute(TestCase): assert_equal(out, tgt, err_msg=msg) self.assertTrue((out >= 0).all()) + tgt = [-1*(i) for i in inp] + np.negative(inp, out=out) + assert_equal(out, tgt, err_msg=msg) + # will throw invalid flag depending on compiler optimizations with np.errstate(invalid='ignore'): for v in [np.nan, -np.inf, np.inf]: @@ -716,6 +781,10 @@ class TestAbsolute(TestCase): np.abs(inp, out=out) assert_array_equal(out, d, err_msg=msg) + assert_array_equal(-inp, -1*inp, err_msg=msg) + np.negative(inp, out=out) + assert_array_equal(out, -1*inp, err_msg=msg) + class TestSpecialMethods(TestCase): def test_wrap(self): @@ -900,9 +969,9 @@ class TestSpecialMethods(TestCase): assert_equal(res1[4], (a, b)) assert_equal(res0[5], {}) assert_equal(res1[5], {}) - + def test_ufunc_override_mro(self): - + # Some multi arg functions for testing. def tres_mul(a, b, c): return a * b * c @@ -929,7 +998,7 @@ class TestSpecialMethods(TestCase): class C(object): def __numpy_ufunc__(self, func, method, pos, inputs, **kwargs): return NotImplemented - + class CSub(object): def __numpy_ufunc__(self, func, method, pos, inputs, **kwargs): return NotImplemented @@ -961,7 +1030,7 @@ class TestSpecialMethods(TestCase): assert_equal(three_mul_ufunc(a, 1, 2), "A") assert_equal(three_mul_ufunc(1, a, 2), "A") assert_equal(three_mul_ufunc(1, 2, a), "A") - + assert_equal(three_mul_ufunc(a, a, 6), "A") assert_equal(three_mul_ufunc(a, 2, a), "A") assert_equal(three_mul_ufunc(a, 2, b), "A") @@ -997,39 +1066,105 @@ class TestSpecialMethods(TestCase): def test_ufunc_override_methods(self): class A(object): def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs): - if method == "__call__": - return method - if method == "reduce": - return method - if method == "accumulate": - return method - if method == "reduceat": - return method + return self, ufunc, method, pos, inputs, kwargs + # __call__ a = A() - res = np.multiply(1, a) - assert_equal(res, "__call__") - - res = np.multiply.reduce(1, a) - assert_equal(res, "reduce") - - res = np.multiply.accumulate(1, a) - assert_equal(res, "accumulate") - - res = np.multiply.reduceat(1, a) - assert_equal(res, "reduceat") - - res = np.multiply(a, 1) - assert_equal(res, "__call__") - - res = np.multiply.reduce(a, 1) - assert_equal(res, "reduce") - - res = np.multiply.accumulate(a, 1) - assert_equal(res, "accumulate") - - res = np.multiply.reduceat(a, 1) - assert_equal(res, "reduceat") + res = np.multiply.__call__(1, a, foo='bar', answer=42) + assert_equal(res[0], a) + assert_equal(res[1], np.multiply) + assert_equal(res[2], '__call__') + assert_equal(res[3], 1) + assert_equal(res[4], (1, a)) + assert_equal(res[5], {'foo': 'bar', 'answer': 42}) + + # reduce, positional args + res = np.multiply.reduce(a, 'axis0', 'dtype0', 'out0', 'keep0') + assert_equal(res[0], a) + assert_equal(res[1], np.multiply) + assert_equal(res[2], 'reduce') + assert_equal(res[3], 0) + assert_equal(res[4], (a,)) + assert_equal(res[5], {'dtype':'dtype0', + 'out': 'out0', + 'keepdims': 'keep0', + 'axis': 'axis0'}) + + # reduce, kwargs + res = np.multiply.reduce(a, axis='axis0', dtype='dtype0', out='out0', + keepdims='keep0') + assert_equal(res[0], a) + assert_equal(res[1], np.multiply) + assert_equal(res[2], 'reduce') + assert_equal(res[3], 0) + assert_equal(res[4], (a,)) + assert_equal(res[5], {'dtype':'dtype0', + 'out': 'out0', + 'keepdims': 'keep0', + 'axis': 'axis0'}) + + # accumulate, pos args + res = np.multiply.accumulate(a, 'axis0', 'dtype0', 'out0') + assert_equal(res[0], a) + assert_equal(res[1], np.multiply) + assert_equal(res[2], 'accumulate') + assert_equal(res[3], 0) + assert_equal(res[4], (a,)) + assert_equal(res[5], {'dtype':'dtype0', + 'out': 'out0', + 'axis': 'axis0'}) + + # accumulate, kwargs + res = np.multiply.accumulate(a, axis='axis0', dtype='dtype0', + out='out0') + assert_equal(res[0], a) + assert_equal(res[1], np.multiply) + assert_equal(res[2], 'accumulate') + assert_equal(res[3], 0) + assert_equal(res[4], (a,)) + assert_equal(res[5], {'dtype':'dtype0', + 'out': 'out0', + 'axis': 'axis0'}) + + # reduceat, pos args + res = np.multiply.reduceat(a, [4, 2], 'axis0', 'dtype0', 'out0') + assert_equal(res[0], a) + assert_equal(res[1], np.multiply) + assert_equal(res[2], 'reduceat') + assert_equal(res[3], 0) + assert_equal(res[4], (a, [4, 2])) + assert_equal(res[5], {'dtype':'dtype0', + 'out': 'out0', + 'axis': 'axis0'}) + + # reduceat, kwargs + res = np.multiply.reduceat(a, [4, 2], axis='axis0', dtype='dtype0', + out='out0') + assert_equal(res[0], a) + assert_equal(res[1], np.multiply) + assert_equal(res[2], 'reduceat') + assert_equal(res[3], 0) + assert_equal(res[4], (a, [4, 2])) + assert_equal(res[5], {'dtype':'dtype0', + 'out': 'out0', + 'axis': 'axis0'}) + + # outer + res = np.multiply.outer(a, 42) + assert_equal(res[0], a) + assert_equal(res[1], np.multiply) + assert_equal(res[2], 'outer') + assert_equal(res[3], 0) + assert_equal(res[4], (a, 42)) + assert_equal(res[5], {}) + + # at + res = np.multiply.at(a, [4, 2], 'b0') + assert_equal(res[0], a) + assert_equal(res[1], np.multiply) + assert_equal(res[2], 'at') + assert_equal(res[3], 0) + assert_equal(res[4], (a, [4, 2], 'b0')) def test_ufunc_override_out(self): class A(object): @@ -1065,7 +1200,6 @@ class TestSpecialMethods(TestCase): assert_equal(res7['out'][0], 'out0') assert_equal(res7['out'][1], 'out1') - def test_ufunc_override_exception(self): class A(object): def __numpy_ufunc__(self, *a, **kwargs): diff --git a/numpy/distutils/command/config.py b/numpy/distutils/command/config.py index 5d363eb4e..0086e3632 100644 --- a/numpy/distutils/command/config.py +++ b/numpy/distutils/command/config.py @@ -307,7 +307,10 @@ int main () self._check_compiler() body = [] if decl: - body.append("int %s (void);" % func) + if type(decl) == str: + body.append(decl) + else: + body.append("int %s (void);" % func) # Handle MSVC intrinsics: force MS compiler to make a function call. # Useful to test for some functions when built with optimization on, to # avoid build error because the intrinsic and our 'fake' test @@ -401,7 +404,7 @@ int main () def get_output(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, - lang="c"): + lang="c", use_tee=None): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Returns the exit status code of the program and its output. @@ -426,7 +429,8 @@ int main () grabber.restore() raise exe = os.path.join('.', exe) - exitstatus, output = exec_command(exe, execute_in='.') + exitstatus, output = exec_command(exe, execute_in='.', + use_tee=use_tee) if hasattr(os, 'WEXITSTATUS'): exitcode = os.WEXITSTATUS(exitstatus) if os.WIFSIGNALED(exitstatus): diff --git a/numpy/distutils/command/install.py b/numpy/distutils/command/install.py index 2da21542f..a1dd47755 100644 --- a/numpy/distutils/command/install.py +++ b/numpy/distutils/command/install.py @@ -7,9 +7,10 @@ if 'setuptools' in sys.modules: else: import distutils.command.install as old_install_mod have_setuptools = False -old_install = old_install_mod.install from distutils.file_util import write_file +old_install = old_install_mod.install + class install(old_install): # Always run install_clib - the command is cheap, so no need to bypass it; @@ -28,9 +29,11 @@ class install(old_install): We must pull in the entire code so we can override the level used in the _getframe() call since we wrap this call by one more level. """ + from distutils.command.install import install as distutils_install + # Explicit request for old-style install? Just do it if self.old_and_unmanageable or self.single_version_externally_managed: - return old_install_mod._install.run(self) + return distutils_install.run(self) # Attempt to detect whether we were called from setup() or by another # command. If we were called by setup(), our caller will be the @@ -48,7 +51,7 @@ class install(old_install): # We weren't called from the command line or setup(), so we # should run in backward-compatibility mode to support bdist_* # commands. - old_install_mod._install.run(self) + distutils_install.run(self) else: self.do_egg_install() diff --git a/numpy/distutils/exec_command.py b/numpy/distutils/exec_command.py index 648a98efb..baf81f337 100644 --- a/numpy/distutils/exec_command.py +++ b/numpy/distutils/exec_command.py @@ -120,7 +120,7 @@ def find_executable(exe, path=None, _cache={}): if not os.path.islink(f_ext): f_ext = realpath(f_ext) if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK): - log.good('Found executable %s' % f_ext) + log.info('Found executable %s' % f_ext) _cache[key] = f_ext return f_ext diff --git a/numpy/distutils/fcompiler/gnu.py b/numpy/distutils/fcompiler/gnu.py index 5ee3df2dc..b786c0a46 100644 --- a/numpy/distutils/fcompiler/gnu.py +++ b/numpy/distutils/fcompiler/gnu.py @@ -35,13 +35,13 @@ class GnuFCompiler(FCompiler): def gnu_version_match(self, version_string): """Handle the different versions of GNU fortran compilers""" - m = re.match(r'GNU Fortran', version_string) + m = re.search(r'GNU Fortran', version_string) if not m: return None - m = re.match(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string) + m = re.search(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string) if m: return ('gfortran', m.group(1)) - m = re.match(r'GNU Fortran.*?\-?([0-9-.]+)', version_string) + m = re.search(r'GNU Fortran.*?\-?([0-9-.]+)', version_string) if m: v = m.group(1) if v.startswith('0') or v.startswith('2') or v.startswith('3'): diff --git a/numpy/distutils/fcompiler/intel.py b/numpy/distutils/fcompiler/intel.py index 21a3c5eaf..a80e525e3 100644 --- a/numpy/distutils/fcompiler/intel.py +++ b/numpy/distutils/fcompiler/intel.py @@ -68,7 +68,7 @@ class IntelFCompiler(BaseIntelFCompiler): opt.remove('-shared') except ValueError: idx = 0 - opt[idx:idx] = ['-dynamiclib', '-Wl,-undefined,dynamic_lookup', '-Wl,-framework,Python'] + opt[idx:idx] = ['-dynamiclib', '-Wl,-undefined,dynamic_lookup'] return opt class IntelItaniumFCompiler(IntelFCompiler): @@ -162,7 +162,7 @@ class IntelVisualFCompiler(BaseIntelFCompiler): return ['/4Yb', '/d2'] def get_flags_opt(self): - return ['/O2'] + return ['/O1'] # Scipy test failures with /O2 def get_flags_arch(self): return ["/arch:IA-32", "/QaxSSE3"] diff --git a/numpy/distutils/system_info.py b/numpy/distutils/system_info.py index 5ed12db6e..48c92c548 100644 --- a/numpy/distutils/system_info.py +++ b/numpy/distutils/system_info.py @@ -137,6 +137,9 @@ from numpy.distutils.misc_util import is_sequence, is_string, \ get_shared_lib_extension from numpy.distutils.command.config import config as cmd_config from numpy.distutils.compat import get_exception +import distutils.ccompiler +import tempfile +import shutil # Determine number of bits @@ -300,7 +303,10 @@ def get_info(name, notfound_action=0): 'lapack_atlas': lapack_atlas_info, # use lapack_opt instead 'lapack_atlas_threads': lapack_atlas_threads_info, # ditto 'mkl': mkl_info, + # openblas which may or may not have embedded lapack 'openblas': openblas_info, # use blas_opt instead + # openblas with embedded lapack + 'openblas_lapack': openblas_lapack_info, # use blas_opt instead 'lapack_mkl': lapack_mkl_info, # use lapack_opt instead 'blas_mkl': blas_mkl_info, # use blas_opt instead 'x11': x11_info, @@ -449,7 +455,6 @@ class system_info: self.__class__.info = {} self.local_prefixes = [] defaults = {} - defaults['libraries'] = '' defaults['library_dirs'] = os.pathsep.join(default_lib_dirs) defaults['include_dirs'] = os.pathsep.join(default_include_dirs) defaults['src_dirs'] = os.pathsep.join(default_src_dirs) @@ -703,7 +708,7 @@ class system_info: else: found_libs = self._lib_list(lib_dirs, libs, exts) found_dirs = [lib_dirs] - if len(found_libs) == len(libs): + if len(found_libs) > 0 and len(found_libs) == len(libs): info = {'libraries': found_libs, 'library_dirs': found_dirs} # Now, check for optional libraries if is_sequence(lib_dirs): @@ -756,9 +761,6 @@ class fftw_info(system_info): 'includes':['fftw.h', 'rfftw.h'], 'macros':[('SCIPY_FFTW_H', None)]}] - def __init__(self): - system_info.__init__(self) - def calc_ver_info(self, ver_param): """Returns True on successful version detection, else False""" lib_dirs = self.get_lib_dirs() @@ -1302,11 +1304,13 @@ def get_atlas_version(**config): info = {} try: s, o = c.get_output(atlas_version_c_text, - libraries=libraries, library_dirs=library_dirs) + libraries=libraries, library_dirs=library_dirs, + use_tee=(system_info.verbosity > 0)) if s and re.search(r'undefined reference to `_gfortran', o, re.M): s, o = c.get_output(atlas_version_c_text, libraries=libraries + ['gfortran'], - library_dirs=library_dirs) + library_dirs=library_dirs, + use_tee=(system_info.verbosity > 0)) if not s: warnings.warn(""" ***************************************************** @@ -1369,7 +1373,7 @@ class lapack_opt_info(system_info): def calc_info(self): - openblas_info = get_info('openblas') + openblas_info = get_info('openblas_lapack') if openblas_info: self.set_info(**openblas_info) return @@ -1480,7 +1484,7 @@ class blas_opt_info(system_info): if not atlas_info: atlas_info = get_info('atlas_blas') - if sys.platform == 'darwin'and not atlas_info: + if sys.platform == 'darwin' and not atlas_info: # Use the system BLAS from Accelerate or vecLib under OSX args = [] link_args = [] @@ -1562,17 +1566,59 @@ class openblas_info(blas_info): _lib_names = ['openblas'] notfounderror = BlasNotFoundError + def check_embedded_lapack(self, info): + return True + def calc_info(self): lib_dirs = self.get_lib_dirs() - openblas_libs = self.get_libs('openblas_libs', self._lib_names) + openblas_libs = self.get_libs('libraries', self._lib_names) + if openblas_libs == self._lib_names: # backward compat with 1.8.0 + openblas_libs = self.get_libs('openblas_libs', self._lib_names) info = self.check_libs(lib_dirs, openblas_libs, []) if info is None: return + + if not self.check_embedded_lapack(info): + return None + info['language'] = 'f77' # XXX: is it generally true? self.set_info(**info) +class openblas_lapack_info(openblas_info): + section = 'openblas' + dir_env_var = 'OPENBLAS' + _lib_names = ['openblas'] + notfounderror = BlasNotFoundError + + def check_embedded_lapack(self, info): + res = False + c = distutils.ccompiler.new_compiler() + tmpdir = tempfile.mkdtemp() + s = """void zungqr(); + int main(int argc, const char *argv[]) + { + zungqr_(); + return 0; + }""" + src = os.path.join(tmpdir, 'source.c') + out = os.path.join(tmpdir, 'a.out') + try: + with open(src, 'wt') as f: + f.write(s) + obj = c.compile([src], output_dir=tmpdir) + try: + c.link_executable(obj, out, libraries=info['libraries'], + library_dirs=info['library_dirs']) + res = True + except distutils.ccompiler.LinkError: + res = False + finally: + shutil.rmtree(tmpdir) + return res + + class blas_src_info(system_info): section = 'blas_src' dir_env_var = 'BLAS_SRC' diff --git a/numpy/doc/broadcasting.py b/numpy/doc/broadcasting.py index 43b725b83..717914cda 100644 --- a/numpy/doc/broadcasting.py +++ b/numpy/doc/broadcasting.py @@ -68,8 +68,8 @@ they are compatible:: Scale (1d array): 3 Result (3d array): 256 x 256 x 3 -When either of the dimensions compared is one, the larger of the two is -used. In other words, the smaller of two axes is stretched or "copied" +When either of the dimensions compared is one, the other is +used. In other words, dimensions with size 1 are stretched or "copied" to match the other. In the following example, both the ``A`` and ``B`` arrays have axes with @@ -171,7 +171,7 @@ Here the ``newaxis`` index operator inserts a new axis into ``a``, making it a two-dimensional ``4x1`` array. Combining the ``4x1`` array with ``b``, which has shape ``(3,)``, yields a ``4x3`` array. -See `this article <http://www.scipy.org/EricsBroadcastingDoc>`_ +See `this article <http://wiki.scipy.org/EricsBroadcastingDoc>`_ for illustrations of broadcasting concepts. """ diff --git a/numpy/doc/byteswapping.py b/numpy/doc/byteswapping.py index ffefe3168..430683d30 100644 --- a/numpy/doc/byteswapping.py +++ b/numpy/doc/byteswapping.py @@ -101,7 +101,7 @@ the correct endianness: Note the the array has not changed in memory: ->>> fixed_end_dtype_arr.tostring() == big_end_str +>>> fixed_end_dtype_arr.tobytes() == big_end_str True Data and type endianness don't match, change data to match dtype @@ -117,7 +117,7 @@ that needs a certain byte ordering. Now the array *has* changed in memory: ->>> fixed_end_mem_arr.tostring() == big_end_str +>>> fixed_end_mem_arr.tobytes() == big_end_str False Data and dtype endianness match, swap data and dtype @@ -131,7 +131,7 @@ the previous operations: >>> swapped_end_arr = big_end_arr.byteswap().newbyteorder() >>> swapped_end_arr[0] 1 ->>> swapped_end_arr.tostring() == big_end_str +>>> swapped_end_arr.tobytes() == big_end_str False An easier way of casting the data to a specific dtype and byte ordering @@ -140,7 +140,7 @@ can be achieved with the ndarray astype method: >>> swapped_end_arr = big_end_arr.astype('<i2') >>> swapped_end_arr[0] 1 ->>> swapped_end_arr.tostring() == big_end_str +>>> swapped_end_arr.tobytes() == big_end_str False """ diff --git a/numpy/doc/misc.py b/numpy/doc/misc.py index 311e6e0c8..1709ad66d 100644 --- a/numpy/doc/misc.py +++ b/numpy/doc/misc.py @@ -3,8 +3,8 @@ Miscellaneous ============= -IEEE 754 Floating Point Special Values: ------------------------------------------------ +IEEE 754 Floating Point Special Values +-------------------------------------- Special values defined in numpy: nan, inf, @@ -46,8 +46,8 @@ from the results: :: >>> np.nansum(x) 42.0 -How numpy handles numerical exceptions: ------------------------------------------- +How numpy handles numerical exceptions +-------------------------------------- The default is to ``'warn'`` for ``invalid``, ``divide``, and ``overflow`` and ``'ignore'`` for ``underflow``. But this can be changed, and it can be @@ -72,8 +72,8 @@ These behaviors can be set for all kinds of errors or specific ones: Note that integer divide-by-zero is handled by the same machinery. These behaviors are set on a per-thread basis. -Examples: ------------- +Examples +-------- :: @@ -96,8 +96,8 @@ Examples: >>> j = np.seterr(**oldsettings) # restore previous ... # error-handling settings -Interfacing to C: ------------------ +Interfacing to C +---------------- Only a survey of the choices. Little detail on how each works. 1) Bare metal, wrap your own C-code manually. @@ -121,29 +121,22 @@ Only a survey of the choices. Little detail on how each works. - API will change for Python 3.0! -2) pyrex +2) Cython - Plusses: - avoid learning C API's - no dealing with reference counting - - can code in psuedo python and generate C code + - can code in pseudo python and generate C code - can also interface to existing C code - should shield you from changes to Python C api - - become pretty popular within Python community + - has become the de-facto standard within the scientific Python community + - fast indexing support for arrays - Minuses: - Can write code in non-standard form which may become obsolete - Not as flexible as manual wrapping - - Maintainers not easily adaptable to new features - -Thus: - -3) cython - fork of pyrex to allow needed features for SAGE - - - being considered as the standard scipy/numpy wrapping tool - - fast indexing support for arrays 4) ctypes @@ -180,16 +173,15 @@ Thus: - generates lots of code between Python and the C code - can cause performance problems that are nearly impossible to optimize - out + out - interface files can be hard to write - doesn't necessarily avoid reference counting issues or needing to know API's -7) Weave +7) scipy.weave - Plusses: - - Phenomenal tool - can turn many numpy expressions into C code - dynamic compiling and loading of generated C code - can embed pure C code in Python module and have weave extract, generate @@ -197,7 +189,8 @@ Thus: - Minuses: - - Future uncertain--lacks a champion + - Future very uncertain: it's the only part of Scipy not ported to Python 3 + and is effectively deprecated in favor of Cython. 8) Psyco @@ -214,15 +207,19 @@ Thus: Interfacing to Fortran: ----------------------- -Fortran: Clear choice is f2py. (Pyfort is an older alternative, but not -supported any longer) +The clear choice to wrap Fortran code is +`f2py <http://docs.scipy.org/doc/numpy-dev/f2py/>`_. + +Pyfort is an older alternative, but not supported any longer. +Fwrap is a newer project that looked promising but isn't being developed any +longer. Interfacing to C++: ------------------- - 1) CXX - 2) Boost.python - 3) SWIG - 4) Sage has used cython to wrap C++ (not pretty, but it can be done) + 1) Cython + 2) CXX + 3) Boost.python + 4) SWIG 5) SIP (used mainly in PyQT) """ diff --git a/numpy/f2py/__init__.py b/numpy/f2py/__init__.py index ccdbd4e0b..fcfd1853e 100644 --- a/numpy/f2py/__init__.py +++ b/numpy/f2py/__init__.py @@ -28,20 +28,20 @@ def compile(source, from numpy.distutils.exec_command import exec_command import tempfile if source_fn is None: - fname = os.path.join(tempfile.mktemp()+'.f') + f = tempfile.NamedTemporaryFile(suffix='.f') else: - fname = source_fn - - f = open(fname, 'w') - f.write(source) - f.close() - - args = ' -c -m %s %s %s'%(modulename, fname, extra_args) - c = '%s -c "import numpy.f2py as f2py2e;f2py2e.main()" %s' %(sys.executable, args) - s, o = exec_command(c) - if source_fn is None: - try: os.remove(fname) - except OSError: pass + f = open(source_fn, 'w') + + try: + f.write(source) + f.flush() + + args = ' -c -m %s %s %s'%(modulename, f.name, extra_args) + c = '%s -c "import numpy.f2py as f2py2e;f2py2e.main()" %s' % \ + (sys.executable, args) + s, o = exec_command(c) + finally: + f.close() return s from numpy.testing import Tester diff --git a/numpy/f2py/cfuncs.py b/numpy/f2py/cfuncs.py index 5a5d2bf64..7fb630697 100644 --- a/numpy/f2py/cfuncs.py +++ b/numpy/f2py/cfuncs.py @@ -75,7 +75,7 @@ typedef long long long_long; typedef unsigned long long unsigned_long_long; #endif """ -typedefs['insinged_long_long']="""\ +typedefs['unsigned_long_long']="""\ #ifdef _WIN32 typedef __uint64 long_long; #else @@ -312,7 +312,7 @@ cppmacros['pyobj_from_complex_float1']='#define pyobj_from_complex_float1(v) (Py needs['pyobj_from_string1']=['string'] cppmacros['pyobj_from_string1']='#define pyobj_from_string1(v) (PyString_FromString((char *)v))' needs['pyobj_from_string1size']=['string'] -cppmacros['pyobj_from_string1size']='#define pyobj_from_string1size(v,len) (PyString_FromStringAndSize((char *)v, len))' +cppmacros['pyobj_from_string1size']='#define pyobj_from_string1size(v,len) (PyUString_FromStringAndSize((char *)v, len))' needs['TRYPYARRAYTEMPLATE']=['PRINTPYOBJERR'] cppmacros['TRYPYARRAYTEMPLATE']="""\ /* New SciPy */ diff --git a/numpy/f2py/f2py2e.py b/numpy/f2py/f2py2e.py index ff9d19e9d..25407d421 100755 --- a/numpy/f2py/f2py2e.py +++ b/numpy/f2py/f2py2e.py @@ -91,7 +91,7 @@ Options: --lower is assumed with -h key, and --no-lower without -h key. --build-dir <dirname> All f2py generated files are created in <dirname>. - Default is tempfile.mktemp(). + Default is tempfile.mkdtemp(). --overwrite-signature Overwrite existing signature file. @@ -424,7 +424,7 @@ def run_compile(): del sys.argv[i] else: remove_build_dir = 1 - build_dir = os.path.join(tempfile.mktemp()) + build_dir = tempfile.mkdtemp() _reg1 = re.compile(r'[-][-]link[-]') sysinfo_flags = [_m for _m in sys.argv[1:] if _reg1.match(_m)] diff --git a/numpy/f2py/src/fortranobject.c b/numpy/f2py/src/fortranobject.c index c07de99c0..9c96c1f46 100644 --- a/numpy/f2py/src/fortranobject.c +++ b/numpy/f2py/src/fortranobject.c @@ -335,7 +335,7 @@ fortran_call(PyFortranObject *fp, PyObject *arg, PyObject *kw) { name=%s,func=%p,data=%p,%p\n",fp->defs[i].name, fp->defs[i].func,fp->defs[i].data,&fp->defs[i].data); */ if (fp->defs[i].rank==-1) {/* is Fortran routine */ - if ((fp->defs[i].func==NULL)) { + if (fp->defs[i].func==NULL) { PyErr_Format(PyExc_RuntimeError, "no function to call"); return NULL; } @@ -741,14 +741,12 @@ PyArrayObject* array_from_pyobj(const int type_num, return arr; } - if ((intent & F2PY_INTENT_INOUT) - || (intent & F2PY_INTENT_INPLACE) - || (intent & F2PY_INTENT_CACHE)) { - sprintf(mess,"failed to initialize intent(inout|inplace|cache) array" - " -- input must be array but got %s", - PyString_AsString(PyObject_Str(PyObject_Type(obj))) - ); - PyErr_SetString(PyExc_TypeError,mess); + if ((intent & F2PY_INTENT_INOUT) || + (intent & F2PY_INTENT_INPLACE) || + (intent & F2PY_INTENT_CACHE)) { + PyErr_SetString(PyExc_TypeError, + "failed to initialize intent(inout|inplace|cache) " + "array, input not an array"); return NULL; } diff --git a/numpy/f2py/src/fortranobject.h b/numpy/f2py/src/fortranobject.h index 76a357b5e..689f78c92 100644 --- a/numpy/f2py/src/fortranobject.h +++ b/numpy/f2py/src/fortranobject.h @@ -20,6 +20,7 @@ extern "C" { #define PyString_GET_SIZE PyBytes_GET_SIZE #define PyString_AS_STRING PyBytes_AS_STRING #define PyString_FromString PyBytes_FromString +#define PyUString_FromStringAndSize PyUnicode_FromStringAndSize #define PyString_ConcatAndDel PyBytes_ConcatAndDel #define PyString_AsString PyBytes_AsString @@ -29,6 +30,10 @@ extern "C" { #define PyInt_AsLong PyLong_AsLong #define PyNumber_Int PyNumber_Long + +#else + +#define PyUString_FromStringAndSize PyString_FromStringAndSize #endif diff --git a/numpy/f2py/tests/test_array_from_pyobj.py b/numpy/f2py/tests/test_array_from_pyobj.py index 09d613293..de954c374 100644 --- a/numpy/f2py/tests/test_array_from_pyobj.py +++ b/numpy/f2py/tests/test_array_from_pyobj.py @@ -4,6 +4,7 @@ import unittest import os import sys import copy +import platform import nose @@ -81,37 +82,45 @@ class Intent(object): intent = Intent() -class Type(object): - _type_names = ['BOOL', 'BYTE', 'UBYTE', 'SHORT', 'USHORT', 'INT', 'UINT', - 'LONG', 'ULONG', 'LONGLONG', 'ULONGLONG', - 'FLOAT', 'DOUBLE', 'LONGDOUBLE', 'CFLOAT', 'CDOUBLE', - 'CLONGDOUBLE'] - _type_cache = {} - - _cast_dict = {'BOOL':['BOOL']} - _cast_dict['BYTE'] = _cast_dict['BOOL'] + ['BYTE'] - _cast_dict['UBYTE'] = _cast_dict['BOOL'] + ['UBYTE'] - _cast_dict['BYTE'] = ['BYTE'] - _cast_dict['UBYTE'] = ['UBYTE'] - _cast_dict['SHORT'] = _cast_dict['BYTE'] + ['UBYTE', 'SHORT'] - _cast_dict['USHORT'] = _cast_dict['UBYTE'] + ['BYTE', 'USHORT'] - _cast_dict['INT'] = _cast_dict['SHORT'] + ['USHORT', 'INT'] - _cast_dict['UINT'] = _cast_dict['USHORT'] + ['SHORT', 'UINT'] - - _cast_dict['LONG'] = _cast_dict['INT'] + ['LONG'] - _cast_dict['ULONG'] = _cast_dict['UINT'] + ['ULONG'] - - _cast_dict['LONGLONG'] = _cast_dict['LONG'] + ['LONGLONG'] - _cast_dict['ULONGLONG'] = _cast_dict['ULONG'] + ['ULONGLONG'] - - _cast_dict['FLOAT'] = _cast_dict['SHORT'] + ['USHORT', 'FLOAT'] - _cast_dict['DOUBLE'] = _cast_dict['INT'] + ['UINT', 'FLOAT', 'DOUBLE'] - _cast_dict['LONGDOUBLE'] = _cast_dict['LONG'] + ['ULONG', 'FLOAT', 'DOUBLE', 'LONGDOUBLE'] - - _cast_dict['CFLOAT'] = _cast_dict['FLOAT'] + ['CFLOAT'] +_type_names = ['BOOL', 'BYTE', 'UBYTE', 'SHORT', 'USHORT', 'INT', 'UINT', + 'LONG', 'ULONG', 'LONGLONG', 'ULONGLONG', + 'FLOAT', 'DOUBLE', 'CFLOAT'] + +_cast_dict = {'BOOL':['BOOL']} +_cast_dict['BYTE'] = _cast_dict['BOOL'] + ['BYTE'] +_cast_dict['UBYTE'] = _cast_dict['BOOL'] + ['UBYTE'] +_cast_dict['BYTE'] = ['BYTE'] +_cast_dict['UBYTE'] = ['UBYTE'] +_cast_dict['SHORT'] = _cast_dict['BYTE'] + ['UBYTE', 'SHORT'] +_cast_dict['USHORT'] = _cast_dict['UBYTE'] + ['BYTE', 'USHORT'] +_cast_dict['INT'] = _cast_dict['SHORT'] + ['USHORT', 'INT'] +_cast_dict['UINT'] = _cast_dict['USHORT'] + ['SHORT', 'UINT'] + +_cast_dict['LONG'] = _cast_dict['INT'] + ['LONG'] +_cast_dict['ULONG'] = _cast_dict['UINT'] + ['ULONG'] + +_cast_dict['LONGLONG'] = _cast_dict['LONG'] + ['LONGLONG'] +_cast_dict['ULONGLONG'] = _cast_dict['ULONG'] + ['ULONGLONG'] + +_cast_dict['FLOAT'] = _cast_dict['SHORT'] + ['USHORT', 'FLOAT'] +_cast_dict['DOUBLE'] = _cast_dict['INT'] + ['UINT', 'FLOAT', 'DOUBLE'] + +_cast_dict['CFLOAT'] = _cast_dict['FLOAT'] + ['CFLOAT'] + +# (debian) sparc system malloc does not provide the alignment required by +# 16 byte long double types this means the inout intent cannot be satisfied and +# several tests fail as the alignment flag can be randomly true or fals +# when numpy gains an aligned allocator the tests could be enabled again +if 'sparc' not in platform.platform().lower(): + _type_names.extend(['LONGDOUBLE', 'CDOUBLE', 'CLONGDOUBLE']) + _cast_dict['LONGDOUBLE'] = _cast_dict['LONG'] + \ + ['ULONG', 'FLOAT', 'DOUBLE', 'LONGDOUBLE'] + _cast_dict['CLONGDOUBLE'] = _cast_dict['LONGDOUBLE'] + \ + ['CFLOAT', 'CDOUBLE', 'CLONGDOUBLE'] _cast_dict['CDOUBLE'] = _cast_dict['DOUBLE'] + ['CFLOAT', 'CDOUBLE'] - _cast_dict['CLONGDOUBLE'] = _cast_dict['LONGDOUBLE'] + ['CFLOAT', 'CDOUBLE', 'CLONGDOUBLE'] +class Type(object): + _type_cache = {} def __new__(cls, name): if isinstance(name, dtype): @@ -138,15 +147,15 @@ class Type(object): self.dtypechar = typeinfo[self.NAME][0] def cast_types(self): - return [self.__class__(_m) for _m in self._cast_dict[self.NAME]] + return [self.__class__(_m) for _m in _cast_dict[self.NAME]] def all_types(self): - return [self.__class__(_m) for _m in self._type_names] + return [self.__class__(_m) for _m in _type_names] def smaller_types(self): bits = typeinfo[self.NAME][3] types = [] - for name in self._type_names: + for name in _type_names: if typeinfo[name][3]<bits: types.append(Type(name)) return types @@ -154,7 +163,7 @@ class Type(object): def equal_types(self): bits = typeinfo[self.NAME][3] types = [] - for name in self._type_names: + for name in _type_names: if name==self.NAME: continue if typeinfo[name][3]==bits: types.append(Type(name)) @@ -163,7 +172,7 @@ class Type(object): def larger_types(self): bits = typeinfo[self.NAME][3] types = [] - for name in self._type_names: + for name in _type_names: if typeinfo[name][3]>bits: types.append(Type(name)) return types @@ -227,7 +236,8 @@ class Array(object): assert_(self.arr_attr[2]==self.pyarr_attr[2]) # dimensions if self.arr_attr[1]<=1: assert_(self.arr_attr[3]==self.pyarr_attr[3],\ - repr((self.arr_attr[3], self.pyarr_attr[3], self.arr.tostring(), self.pyarr.tostring()))) # strides + repr((self.arr_attr[3], self.pyarr_attr[3], + self.arr.tobytes(), self.pyarr.tobytes()))) # strides assert_(self.arr_attr[5][-2:]==self.pyarr_attr[5][-2:],\ repr((self.arr_attr[5], self.pyarr_attr[5]))) # descr assert_(self.arr_attr[6]==self.pyarr_attr[6],\ @@ -531,7 +541,7 @@ class _test_shared_memory: assert_(obj.dtype.type is self.type.dtype) # obj type is changed inplace! -for t in Type._type_names: +for t in _type_names: exec('''\ class test_%s_gen(unittest.TestCase, _test_shared_memory diff --git a/numpy/f2py/tests/test_callback.py b/numpy/f2py/tests/test_callback.py index 98a90a28c..16464140f 100644 --- a/numpy/f2py/tests/test_callback.py +++ b/numpy/f2py/tests/test_callback.py @@ -34,6 +34,17 @@ cf2py intent(out) a external fun call fun(a) end + + subroutine string_callback(callback, a) + external callback + double precision callback + double precision a + character*1 r +cf2py intent(out) a + r = 'r' + a = callback(r) + end + """ @dec.slow @@ -103,6 +114,19 @@ cf2py intent(out) a r = t(a.mth) assert_( r==9, repr(r)) + def test_string_callback(self): + + def callback(code): + if code == 'r': + return 0 + else: + return 1 + + f = getattr(self.module, 'string_callback') + r = f(callback) + assert_(r == 0, repr(r)) + + if __name__ == "__main__": import nose nose.runmodule() diff --git a/numpy/fft/fftpack.py b/numpy/fft/fftpack.py index 9a169b04c..706fcdd2f 100644 --- a/numpy/fft/fftpack.py +++ b/numpy/fft/fftpack.py @@ -53,10 +53,12 @@ def _raw_fft(a, n=None, axis=-1, init_function=fftpack.cffti, raise ValueError("Invalid number of FFT data points (%d) specified." % n) try: - wsave = fft_cache[n] - except(KeyError): + # Thread-safety note: We rely on list.pop() here to atomically + # retrieve-and-remove a wsave from the cache. This ensures that no + # other thread can get the same wsave while we're using it. + wsave = fft_cache.setdefault(n, []).pop() + except (IndexError): wsave = init_function(n) - fft_cache[n] = wsave if a.shape[axis] != n: s = list(a.shape) @@ -77,6 +79,12 @@ def _raw_fft(a, n=None, axis=-1, init_function=fftpack.cffti, r = work_function(a, wsave) if axis != -1: r = swapaxes(r, axis, -1) + + # As soon as we put wsave back into the cache, another thread could pick it + # up and start using it, so we must not do this until after we're + # completely done using it ourselves. + fft_cache[n].append(wsave) + return r @@ -296,7 +304,7 @@ def rfft(a, n=None, axis=-1): conjugates of the corresponding positive-frequency terms, and the negative-frequency terms are therefore redundant. This function does not compute the negative frequency terms, and the length of the transformed - axis of the output is therefore ``n//2+1``. + axis of the output is therefore ``n//2 + 1``. When ``A = rfft(a)`` and fs is the sampling frequency, ``A[0]`` contains the zero-frequency term 0*fs, which is real due to Hermitian symmetry. @@ -821,11 +829,16 @@ def fft2(a, s=None, axes=(-2, -1)): -------- >>> a = np.mgrid[:5, :5][0] >>> np.fft.fft2(a) - array([[ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], - [ 5.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], - [ 10.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], - [ 15.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], - [ 20.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j]]) + array([[ 50.0 +0.j , 0.0 +0.j , 0.0 +0.j , + 0.0 +0.j , 0.0 +0.j ], + [-12.5+17.20477401j, 0.0 +0.j , 0.0 +0.j , + 0.0 +0.j , 0.0 +0.j ], + [-12.5 +4.0614962j , 0.0 +0.j , 0.0 +0.j , + 0.0 +0.j , 0.0 +0.j ], + [-12.5 -4.0614962j , 0.0 +0.j , 0.0 +0.j , + 0.0 +0.j , 0.0 +0.j ], + [-12.5-17.20477401j, 0.0 +0.j , 0.0 +0.j , + 0.0 +0.j , 0.0 +0.j ]]) """ diff --git a/numpy/fft/fftpack_litemodule.c b/numpy/fft/fftpack_litemodule.c index 6f6a6c9f3..95da3194f 100644 --- a/numpy/fft/fftpack_litemodule.c +++ b/numpy/fft/fftpack_litemodule.c @@ -44,14 +44,14 @@ fftpack_cfftf(PyObject *NPY_UNUSED(self), PyObject *args) nrepeats = PyArray_SIZE(data)/npts; dptr = (double *)PyArray_DATA(data); - NPY_SIGINT_ON; Py_BEGIN_ALLOW_THREADS; + NPY_SIGINT_ON; for (i = 0; i < nrepeats; i++) { cfftf(npts, dptr, wsave); dptr += npts*2; } - Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; + Py_END_ALLOW_THREADS; PyArray_Free(op2, (char *)wsave); return (PyObject *)data; @@ -97,14 +97,14 @@ fftpack_cfftb(PyObject *NPY_UNUSED(self), PyObject *args) nrepeats = PyArray_SIZE(data)/npts; dptr = (double *)PyArray_DATA(data); - NPY_SIGINT_ON; Py_BEGIN_ALLOW_THREADS; + NPY_SIGINT_ON; for (i = 0; i < nrepeats; i++) { cfftb(npts, dptr, wsave); dptr += npts*2; } - Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; + Py_END_ALLOW_THREADS; PyArray_Free(op2, (char *)wsave); return (PyObject *)data; @@ -134,11 +134,11 @@ fftpack_cffti(PyObject *NPY_UNUSED(self), PyObject *args) return NULL; } - NPY_SIGINT_ON; Py_BEGIN_ALLOW_THREADS; + NPY_SIGINT_ON; cffti(n, (double *)PyArray_DATA((PyArrayObject*)op)); - Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; + Py_END_ALLOW_THREADS; return (PyObject *)op; } @@ -188,8 +188,8 @@ fftpack_rfftf(PyObject *NPY_UNUSED(self), PyObject *args) dptr = (double *)PyArray_DATA(data); - NPY_SIGINT_ON; Py_BEGIN_ALLOW_THREADS; + NPY_SIGINT_ON; for (i = 0; i < nrepeats; i++) { memcpy((char *)(rptr+1), dptr, npts*sizeof(double)); rfftf(npts, rptr+1, wsave); @@ -198,8 +198,8 @@ fftpack_rfftf(PyObject *NPY_UNUSED(self), PyObject *args) rptr += rstep; dptr += npts; } - Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; + Py_END_ALLOW_THREADS; PyArray_Free(op2, (char *)wsave); Py_DECREF(data); return (PyObject *)ret; @@ -252,8 +252,8 @@ fftpack_rfftb(PyObject *NPY_UNUSED(self), PyObject *args) rptr = (double *)PyArray_DATA(ret); dptr = (double *)PyArray_DATA(data); - NPY_SIGINT_ON; Py_BEGIN_ALLOW_THREADS; + NPY_SIGINT_ON; for (i = 0; i < nrepeats; i++) { memcpy((char *)(rptr + 1), (dptr + 2), (npts - 1)*sizeof(double)); rptr[0] = dptr[0]; @@ -261,8 +261,8 @@ fftpack_rfftb(PyObject *NPY_UNUSED(self), PyObject *args) rptr += npts; dptr += npts*2; } - Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; + Py_END_ALLOW_THREADS; PyArray_Free(op2, (char *)wsave); Py_DECREF(data); return (PyObject *)ret; @@ -294,11 +294,11 @@ fftpack_rffti(PyObject *NPY_UNUSED(self), PyObject *args) if (op == NULL) { return NULL; } - NPY_SIGINT_ON; Py_BEGIN_ALLOW_THREADS; + NPY_SIGINT_ON; rffti(n, (double *)PyArray_DATA((PyArrayObject*)op)); - Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; + Py_END_ALLOW_THREADS; return (PyObject *)op; } diff --git a/numpy/fft/tests/test_fftpack.py b/numpy/fft/tests/test_fftpack.py index 50702ab3c..ac892c83b 100644 --- a/numpy/fft/tests/test_fftpack.py +++ b/numpy/fft/tests/test_fftpack.py @@ -2,6 +2,14 @@ from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import TestCase, run_module_suite, assert_array_almost_equal +from numpy.testing import assert_array_equal +import threading +import sys +if sys.version_info[0] >= 3: + import queue +else: + import Queue as queue + def fft1(x): L = len(x) @@ -9,6 +17,7 @@ def fft1(x): phase = np.arange(L).reshape(-1, 1) * phase return np.sum(x*np.exp(phase), axis=1) + class TestFFTShift(TestCase): def test_fft_n(self): @@ -23,5 +32,44 @@ class TestFFT1D(TestCase): assert_array_almost_equal(fft1(x), np.fft.fft(x)) +class TestFFTThreadSafe(TestCase): + threads = 16 + input_shape = (800, 200) + + def _test_mtsame(self, func, *args): + def worker(args, q): + q.put(func(*args)) + + q = queue.Queue() + expected = func(*args) + + # Spin off a bunch of threads to call the same function simultaneously + t = [threading.Thread(target=worker, args=(args, q)) + for i in range(self.threads)] + [x.start() for x in t] + + # Make sure all threads returned the correct value + for i in range(self.threads): + assert_array_equal(q.get(timeout=5), expected, + 'Function returned wrong value in multithreaded context') + [x.join() for x in t] + + def test_fft(self): + a = np.ones(self.input_shape) * 1+0j + self._test_mtsame(np.fft.fft, a) + + def test_ifft(self): + a = np.ones(self.input_shape) * 1+0j + self._test_mtsame(np.fft.ifft, a) + + def test_rfft(self): + a = np.ones(self.input_shape) + self._test_mtsame(np.fft.rfft, a) + + def test_irfft(self): + a = np.ones(self.input_shape) * 1+0j + self._test_mtsame(np.fft.irfft, a) + + if __name__ == "__main__": run_module_suite() diff --git a/numpy/lib/__init__.py b/numpy/lib/__init__.py index 73e4b2306..8c420b0c3 100644 --- a/numpy/lib/__init__.py +++ b/numpy/lib/__init__.py @@ -23,6 +23,7 @@ from .npyio import * from .financial import * from .arrayterator import * from .arraypad import * +from ._version import * __all__ = ['emath', 'math'] __all__ += type_check.__all__ diff --git a/numpy/lib/_version.py b/numpy/lib/_version.py new file mode 100644 index 000000000..4eaabd0ff --- /dev/null +++ b/numpy/lib/_version.py @@ -0,0 +1,155 @@ +"""Utility to compare (Numpy) version strings. + +The NumpyVersion class allows properly comparing numpy version strings. +The LooseVersion and StrictVersion classes that distutils provides don't +work; they don't recognize anything like alpha/beta/rc/dev versions. + +""" +from __future__ import division, absolute_import, print_function + +import re + +from numpy.compat import basestring + + +__all__ = ['NumpyVersion'] + + +class NumpyVersion(): + """Parse and compare numpy version strings. + + Numpy has the following versioning scheme (numbers given are examples; they + can be > 9) in principle): + + - Released version: '1.8.0', '1.8.1', etc. + - Alpha: '1.8.0a1', '1.8.0a2', etc. + - Beta: '1.8.0b1', '1.8.0b2', etc. + - Release candidates: '1.8.0rc1', '1.8.0rc2', etc. + - Development versions: '1.8.0.dev-f1234afa' (git commit hash appended) + - Development versions after a1: '1.8.0a1.dev-f1234afa', + '1.8.0b2.dev-f1234afa', + '1.8.1rc1.dev-f1234afa', etc. + - Development versions (no git hash available): '1.8.0.dev-Unknown' + + Comparing needs to be done against a valid version string or other + `NumpyVersion` instance. Note that all development versions of the same + (pre-)release compare equal. + + .. versionadded:: 1.9.0 + + Parameters + ---------- + vstring : str + Numpy version string (``np.__version__``). + + Examples + -------- + >>> from numpy.lib import NumpyVersion + >>> if NumpyVersion(np.__version__) < '1.7.0'): + ... print('skip') + skip + + >>> NumpyVersion('1.7') # raises ValueError, add ".0" + + """ + def __init__(self, vstring): + self.vstring = vstring + ver_main = re.match(r'\d[.]\d+[.]\d+', vstring) + if not ver_main: + raise ValueError("Not a valid numpy version string") + + self.version = ver_main.group() + self.major, self.minor, self.bugfix = [int(x) for x in + self.version.split('.')] + if len(vstring) == ver_main.end(): + self.pre_release = 'final' + else: + alpha = re.match(r'a\d', vstring[ver_main.end():]) + beta = re.match(r'b\d', vstring[ver_main.end():]) + rc = re.match(r'rc\d', vstring[ver_main.end():]) + pre_rel = [m for m in [alpha, beta, rc] if m is not None] + if pre_rel: + self.pre_release = pre_rel[0].group() + else: + self.pre_release = '' + + self.is_devversion = bool(re.search(r'.dev', vstring)) + + def _compare_version(self, other): + """Compare major.minor.bugfix""" + if self.major == other.major: + if self.minor == other.minor: + if self.bugfix == other.bugfix: + vercmp = 0 + elif self.bugfix > other.bugfix: + vercmp = 1 + else: + vercmp = -1 + elif self.minor > other.minor: + vercmp = 1 + else: + vercmp = -1 + elif self.major > other.major: + vercmp = 1 + else: + vercmp = -1 + + return vercmp + + def _compare_pre_release(self, other): + """Compare alpha/beta/rc/final.""" + if self.pre_release == other.pre_release: + vercmp = 0 + elif self.pre_release == 'final': + vercmp = 1 + elif other.pre_release == 'final': + vercmp = -1 + elif self.pre_release > other.pre_release: + vercmp = 1 + else: + vercmp = -1 + + return vercmp + + def _compare(self, other): + if not isinstance(other, (basestring, NumpyVersion)): + raise ValueError("Invalid object to compare with NumpyVersion.") + + if isinstance(other, basestring): + other = NumpyVersion(other) + + vercmp = self._compare_version(other) + if vercmp == 0: + # Same x.y.z version, check for alpha/beta/rc + vercmp = self._compare_pre_release(other) + if vercmp == 0: + # Same version and same pre-release, check if dev version + if self.is_devversion is other.is_devversion: + vercmp = 0 + elif self.is_devversion: + vercmp = -1 + else: + vercmp = 1 + + return vercmp + + def __lt__(self, other): + return self._compare(other) < 0 + + def __le__(self, other): + return self._compare(other) <= 0 + + def __eq__(self, other): + return self._compare(other) == 0 + + def __ne__(self, other): + return self._compare(other) != 0 + + def __gt__(self, other): + return self._compare(other) > 0 + + def __ge__(self, other): + return self._compare(other) >= 0 + + def __repr(self): + return "NumpyVersion(%s)" % self.vstring diff --git a/numpy/lib/arraysetops.py b/numpy/lib/arraysetops.py index 5cd535703..005703d16 100644 --- a/numpy/lib/arraysetops.py +++ b/numpy/lib/arraysetops.py @@ -90,7 +90,7 @@ def ediff1d(ary, to_end=None, to_begin=None): return ed -def unique(ar, return_index=False, return_inverse=False): +def unique(ar, return_index=False, return_inverse=False, return_counts=False): """ Find the unique elements of an array. @@ -109,6 +109,10 @@ def unique(ar, return_index=False, return_inverse=False): return_inverse : bool, optional If True, also return the indices of the unique array that can be used to reconstruct `ar`. + return_counts : bool, optional + .. versionadded:: 1.9.0 + If True, also return the number of times each unique value comes up + in `ar`. Returns ------- @@ -120,6 +124,10 @@ def unique(ar, return_index=False, return_inverse=False): unique_inverse : ndarray, optional The indices to reconstruct the (flattened) original array from the unique array. Only provided if `return_inverse` is True. + unique_counts : ndarray, optional + .. versionadded:: 1.9.0 + The number of times each of the unique values comes up in the + original array. Only provided if `return_counts` is True. See Also -------- @@ -159,45 +167,46 @@ def unique(ar, return_index=False, return_inverse=False): array([1, 2, 6, 4, 2, 3, 2]) """ - try: - ar = ar.flatten() - except AttributeError: - if not return_inverse and not return_index: - items = sorted(set(ar)) - return np.asarray(items) - else: - ar = np.asanyarray(ar).flatten() + ar = np.asanyarray(ar).flatten() + + optional_indices = return_index or return_inverse + optional_returns = optional_indices or return_counts if ar.size == 0: - if return_inverse and return_index: - return ar, np.empty(0, np.bool), np.empty(0, np.bool) - elif return_inverse or return_index: - return ar, np.empty(0, np.bool) + if not optional_returns: + ret = ar else: - return ar + ret = (ar,) + if return_index: + ret += (np.empty(0, np.bool),) + if return_inverse: + ret += (np.empty(0, np.bool),) + if return_counts: + ret += (np.empty(0, np.intp),) + return ret + + if optional_indices: + perm = ar.argsort(kind='mergesort' if return_index else 'quicksort') + aux = ar[perm] + else: + ar.sort() + aux = ar + flag = np.concatenate(([True], aux[1:] != aux[:-1])) - if return_inverse or return_index: + if not optional_returns: + ret = aux[flag] + else: + ret = (aux[flag],) if return_index: - perm = ar.argsort(kind='mergesort') - else: - perm = ar.argsort() - aux = ar[perm] - flag = np.concatenate(([True], aux[1:] != aux[:-1])) + ret += (perm[flag],) if return_inverse: iflag = np.cumsum(flag) - 1 iperm = perm.argsort() - if return_index: - return aux[flag], perm[flag], iflag[iperm] - else: - return aux[flag], iflag[iperm] - else: - return aux[flag], perm[flag] - - else: - ar.sort() - flag = np.concatenate(([True], ar[1:] != ar[:-1])) - return ar[flag] - + ret += (np.take(iflag, iperm),) + if return_counts: + idx = np.concatenate(np.nonzero(flag) + ([ar.size],)) + ret += (np.diff(idx),) + return ret def intersect1d(ar1, ar2, assume_unique=False): """ diff --git a/numpy/lib/bscript b/numpy/lib/bscript index a9200d043..61debfe41 100644 --- a/numpy/lib/bscript +++ b/numpy/lib/bscript @@ -4,4 +4,8 @@ from bento.commands import hooks def build(context): context.tweak_extension("_compiled_base", includes=["../core/include", "../core/include/numpy", "../core", - "../core/src/private"]) + "../core/src/private"], + defines=['_FILE_OFFSET_BITS=64', + '_LARGEFILE_SOURCE=1', + '_LARGEFILE64_SOURCE=1'] + ) diff --git a/numpy/lib/financial.py b/numpy/lib/financial.py index ec642afd3..c085a5d53 100644 --- a/numpy/lib/financial.py +++ b/numpy/lib/financial.py @@ -628,21 +628,29 @@ def irr(values): Examples -------- - >>> print round(np.irr([-100, 39, 59, 55, 20]), 5) + >>> round(irr([-100, 39, 59, 55, 20]), 5) 0.28095 + >>> round(irr([-100, 0, 0, 74]), 5) + -0.0955 + >>> round(irr([-100, 100, 0, -7]), 5) + -0.0833 + >>> round(irr([-100, 100, 0, 7]), 5) + 0.06206 + >>> round(irr([-5, 10.5, 1, -8, 1]), 5) + 0.0886 (Compare with the Example given for numpy.lib.financial.npv) """ res = np.roots(values[::-1]) - # Find the root(s) between 0 and 1 - mask = (res.imag == 0) & (res.real > 0) & (res.real <= 1) - res = res[mask].real + mask = (res.imag == 0) & (res.real > 0) if res.size == 0: return np.nan + res = res[mask].real + # NPV(rate) = 0 can have more than one solution so we return + # only the solution closest to zero. rate = 1.0/res - 1 - if rate.size == 1: - rate = rate.item() + rate = rate.item(np.argmin(np.abs(rate))) return rate def npv(rate, values): diff --git a/numpy/lib/format.py b/numpy/lib/format.py index 4cfbbe05d..6083312de 100644 --- a/numpy/lib/format.py +++ b/numpy/lib/format.py @@ -139,6 +139,7 @@ from __future__ import division, absolute_import, print_function import numpy import sys import io +import warnings from numpy.lib.utils import safe_eval from numpy.compat import asbytes, isfileobj, long, basestring @@ -151,6 +152,14 @@ MAGIC_PREFIX = asbytes('\x93NUMPY') MAGIC_LEN = len(MAGIC_PREFIX) + 2 BUFFER_SIZE = 2 ** 18 #size of buffer for reading npz files in bytes +# difference between version 1.0 and 2.0 is a 4 byte (I) header length +# instead of 2 bytes (H) allowing storage of large structured arrays + +def _check_version(version): + if version not in [(1, 0), (2, 0), None]: + msg = "we only support format version (1,0) and (2, 0), not %s" + raise ValueError(msg % (version,)) + def magic(major, minor): """ Return the magic string for the given file format version. @@ -258,8 +267,8 @@ def header_data_from_array_1_0(array): d['descr'] = dtype_to_descr(array.dtype) return d -def write_array_header_1_0(fp, d): - """ Write the header for an array using the 1.0 format. +def _write_array_header(fp, d, version=None): + """ Write the header for an array and returns the version used Parameters ---------- @@ -267,6 +276,14 @@ def write_array_header_1_0(fp, d): d : dict This has the appropriate entries for writing its string representation to the header of the file. + version: tuple or None + None means use oldest that works + explicit version will raise a ValueError if the format does not + allow saving this data. Default: None + Returns + ------- + version : tuple of int + the file version which needs to be used to store the data """ import struct header = ["{"] @@ -282,11 +299,52 @@ def write_array_header_1_0(fp, d): current_header_len = MAGIC_LEN + 2 + len(header) + 1 # 1 for the newline topad = 16 - (current_header_len % 16) header = asbytes(header + ' '*topad + '\n') - if len(header) >= (256*256): - raise ValueError("header does not fit inside %s bytes" % (256*256)) - header_len_str = struct.pack('<H', len(header)) + + if len(header) >= (256*256) and version == (1, 0): + raise ValueError("header does not fit inside %s bytes required by the" + " 1.0 format" % (256*256)) + if len(header) < (256*256): + header_len_str = struct.pack('<H', len(header)) + version = (1, 0) + elif len(header) < (2**32): + header_len_str = struct.pack('<I', len(header)) + version = (2, 0) + else: + raise ValueError("header does not fit inside 4 GiB required by " + "the 2.0 format") + + fp.write(magic(*version)) fp.write(header_len_str) fp.write(header) + return version + +def write_array_header_1_0(fp, d): + """ Write the header for an array using the 1.0 format. + + Parameters + ---------- + fp : filelike object + d : dict + This has the appropriate entries for writing its string representation + to the header of the file. + """ + _write_array_header(fp, d, (1, 0)) + + +def write_array_header_2_0(fp, d): + """ Write the header for an array using the 2.0 format. + The 2.0 format allows storing very large structured arrays. + + .. versionadded:: 1.9.0 + + Parameters + ---------- + fp : filelike object + d : dict + This has the appropriate entries for writing its string representation + to the header of the file. + """ + _write_array_header(fp, d, (2, 0)) def read_array_header_1_0(fp): """ @@ -317,12 +375,58 @@ def read_array_header_1_0(fp): If the data is invalid. """ + _read_array_header(fp, version=(1, 0)) + +def read_array_header_2_0(fp): + """ + Read an array header from a filelike object using the 2.0 file format + version. + + This will leave the file object located just after the header. + + .. versionadded:: 1.9.0 + + Parameters + ---------- + fp : filelike object + A file object or something with a `.read()` method like a file. + + Returns + ------- + shape : tuple of int + The shape of the array. + fortran_order : bool + The array data will be written out directly if it is either C-contiguous + or Fortran-contiguous. Otherwise, it will be made contiguous before + writing it out. + dtype : dtype + The dtype of the file's data. + + Raises + ------ + ValueError + If the data is invalid. + + """ + _read_array_header(fp, version=(2, 0)) + +def _read_array_header(fp, version): + """ + see read_array_header_1_0 + """ # Read an unsigned, little-endian short int which has the length of the # header. import struct - hlength_str = _read_bytes(fp, 2, "array header length") - header_length = struct.unpack('<H', hlength_str)[0] - header = _read_bytes(fp, header_length, "array header") + if version == (1, 0): + hlength_str = _read_bytes(fp, 2, "array header length") + header_length = struct.unpack('<H', hlength_str)[0] + header = _read_bytes(fp, header_length, "array header") + elif version == (2, 0): + hlength_str = _read_bytes(fp, 4, "array header length") + header_length = struct.unpack('<I', hlength_str)[0] + header = _read_bytes(fp, header_length, "array header") + else: + raise ValueError("Invalid version %r" % version) # The header is a pretty-printed string representation of a literal Python # dictionary with trailing newlines padded to a 16-byte boundary. The keys @@ -359,7 +463,7 @@ def read_array_header_1_0(fp): return d['shape'], d['fortran_order'], dtype -def write_array(fp, array, version=(1, 0)): +def write_array(fp, array, version=None): """ Write an array to an NPY file, including a header. @@ -374,8 +478,9 @@ def write_array(fp, array, version=(1, 0)): method. array : ndarray The array to write to disk. - version : (int, int), optional - The version number of the format. Default: (1, 0) + version : (int, int) or None, optional + The version number of the format. None means use the oldest supported + version that is able to store the data. Default: None Raises ------ @@ -387,11 +492,13 @@ def write_array(fp, array, version=(1, 0)): are not picklable. """ - if version != (1, 0): - msg = "we only support format version (1,0), not %s" - raise ValueError(msg % (version,)) - fp.write(magic(*version)) - write_array_header_1_0(fp, header_data_from_array_1_0(array)) + _check_version(version) + used_ver = _write_array_header(fp, header_data_from_array_1_0(array), + version) + # this warning can be removed when 1.9 has aged enough + if version != (2, 0) and used_ver == (2, 0): + warnings.warn("Stored array in format 2.0. It can only be" + "read by NumPy >= 1.9", UserWarning) # Set buffer size to 16 MiB to hide the Python loop overhead. buffersize = max(16 * 1024 ** 2 // array.itemsize, 1) @@ -407,7 +514,7 @@ def write_array(fp, array, version=(1, 0)): for chunk in numpy.nditer( array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='F'): - fp.write(chunk.tostring('C')) + fp.write(chunk.tobytes('C')) else: if isfileobj(fp): array.tofile(fp) @@ -415,7 +522,7 @@ def write_array(fp, array, version=(1, 0)): for chunk in numpy.nditer( array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='C'): - fp.write(chunk.tostring('C')) + fp.write(chunk.tobytes('C')) def read_array(fp): @@ -440,10 +547,8 @@ def read_array(fp): """ version = read_magic(fp) - if version != (1, 0): - msg = "only support version (1,0) of file format, not %r" - raise ValueError(msg % (version,)) - shape, fortran_order, dtype = read_array_header_1_0(fp) + _check_version(version) + shape, fortran_order, dtype = _read_array_header(fp, version) if len(shape) == 0: count = 1 else: @@ -486,7 +591,7 @@ def read_array(fp): def open_memmap(filename, mode='r+', dtype=None, shape=None, - fortran_order=False, version=(1, 0)): + fortran_order=False, version=None): """ Open a .npy file as a memory-mapped array. @@ -513,9 +618,11 @@ def open_memmap(filename, mode='r+', dtype=None, shape=None, Whether the array should be Fortran-contiguous (True) or C-contiguous (False, the default) if we are creating a new file in "write" mode. - version : tuple of int (major, minor) + version : tuple of int (major, minor) or None If the mode is a "write" mode, then this is the version of the file - format used to create the file. Default: (1,0) + format used to create the file. + None means use the oldest supported version that is able to store the + data. Default: None Returns ------- @@ -541,9 +648,7 @@ def open_memmap(filename, mode='r+', dtype=None, shape=None, if 'w' in mode: # We are creating the file, not reading it. # Check if we ought to create the file. - if version != (1, 0): - msg = "only support version (1,0) of file format, not %r" - raise ValueError(msg % (version,)) + _check_version(version) # Ensure that the given dtype is an authentic dtype object rather than # just something that can be interpreted as a dtype object. dtype = numpy.dtype(dtype) @@ -558,8 +663,11 @@ def open_memmap(filename, mode='r+', dtype=None, shape=None, # If we got here, then it should be safe to create the file. fp = open(filename, mode+'b') try: - fp.write(magic(*version)) - write_array_header_1_0(fp, d) + used_ver = _write_array_header(fp, d, version) + # this warning can be removed when 1.9 has aged enough + if version != (2, 0) and used_ver == (2, 0): + warnings.warn("Stored array in format 2.0. It can only be" + "read by NumPy >= 1.9", UserWarning) offset = fp.tell() finally: fp.close() @@ -568,10 +676,9 @@ def open_memmap(filename, mode='r+', dtype=None, shape=None, fp = open(filename, 'rb') try: version = read_magic(fp) - if version != (1, 0): - msg = "only support version (1,0) of file format, not %r" - raise ValueError(msg % (version,)) - shape, fortran_order, dtype = read_array_header_1_0(fp) + _check_version(version) + + shape, fortran_order, dtype = _read_array_header(fp, version) if dtype.hasobject: msg = "Array can't be memory-mapped: Python objects in dtype." raise ValueError(msg) diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 63b191b07..f625bcb90 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -13,6 +13,7 @@ __all__ = [ import warnings import sys import collections +import operator import numpy as np import numpy.core.numeric as _nx @@ -20,7 +21,7 @@ from numpy.core import linspace, atleast_1d, atleast_2d from numpy.core.numeric import ( ones, zeros, arange, concatenate, array, asarray, asanyarray, empty, empty_like, ndarray, around, floor, ceil, take, ScalarType, dot, where, - newaxis, intp, integer, isscalar + intp, integer, isscalar ) from numpy.core.umath import ( pi, multiply, add, arctan2, frompyfunc, cos, less_equal, sqrt, sin, @@ -256,22 +257,22 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None): range : sequence, optional A sequence of lower and upper bin edges to be used if the edges are - not given explicitely in `bins`. Defaults to the minimum and maximum + not given explicitly in `bins`. Defaults to the minimum and maximum values along each dimension. normed : bool, optional - If False, returns the number of samples in each bin. If True, returns - the bin density, ie, the bin count divided by the bin hypervolume. + If False, returns the number of samples in each bin. If True, + returns the bin density ``bin_count / sample_count / bin_volume``. weights : array_like (N,), optional An array of values `w_i` weighing each sample `(x_i, y_i, z_i, ...)`. - Weights are normalized to 1 if normed is True. If normed is False, the - values of the returned histogram are equal to the sum of the weights - belonging to the samples falling into each bin. + Weights are normalized to 1 if normed is True. If normed is False, + the values of the returned histogram are equal to the sum of the + weights belonging to the samples falling into each bin. Returns ------- H : ndarray - The multidimensional histogram of sample x. See normed and weights for - the different possible semantics. + The multidimensional histogram of sample x. See normed and weights + for the different possible semantics. edges : list A list of D arrays describing the bin edges for each dimension. @@ -335,6 +336,11 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None): smin[i] = smin[i] - .5 smax[i] = smax[i] + .5 + # avoid rounding issues for comparisons when dealing with inexact types + if np.issubdtype(sample.dtype, np.inexact): + edge_dt = sample.dtype + else: + edge_dt = float # Create edge arrays for i in arange(D): if isscalar(bins[i]): @@ -343,9 +349,9 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None): "Element at index %s in `bins` should be a positive " "integer." % i) nbin[i] = bins[i] + 2 # +2 for outlier bins - edges[i] = linspace(smin[i], smax[i], nbin[i]-1) + edges[i] = linspace(smin[i], smax[i], nbin[i]-1, dtype=edge_dt) else: - edges[i] = asarray(bins[i], float) + edges[i] = asarray(bins[i], edge_dt) nbin[i] = len(edges[i]) + 1 # +1 for outlier bins dedges[i] = diff(edges[i]) if np.any(np.asarray(dedges[i]) <= 0): @@ -373,10 +379,10 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None): if not np.isinf(mindiff): decimal = int(-log10(mindiff)) + 6 # Find which points are on the rightmost edge. - on_edge = where(around(sample[:, i], decimal) == - around(edges[i][-1], decimal))[0] + not_smaller_than_edge = (sample[:, i] >= edges[i][-1]) + on_edge = (around(sample[:, i], decimal) == around(edges[i][-1], decimal)) # Shift these points one bin to the left. - Ncount[i][on_edge] -= 1 + Ncount[i][where(on_edge & not_smaller_than_edge)[0]] -= 1 # Flattened histogram matrix (1D) # Reshape is used so that overlarge arrays @@ -650,7 +656,7 @@ def piecewise(x, condlist, funclist, *args, **kw): The output is the same shape and type as x and is found by calling the functions in `funclist` on the appropriate portions of `x`, as defined by the boolean arrays in `condlist`. Portions not covered - by any condition have undefined values. + by any condition have a default value of 0. See Also @@ -692,32 +698,24 @@ def piecewise(x, condlist, funclist, *args, **kw): if (isscalar(condlist) or not (isinstance(condlist[0], list) or isinstance(condlist[0], ndarray))): condlist = [condlist] - condlist = [asarray(c, dtype=bool) for c in condlist] + condlist = array(condlist, dtype=bool) n = len(condlist) - if n == n2 - 1: # compute the "otherwise" condition. - totlist = condlist[0] - for k in range(1, n): - totlist |= condlist[k] - condlist.append(~totlist) - n += 1 - if (n != n2): - raise ValueError( - "function list and condition list must be the same") - zerod = False # This is a hack to work around problems with NumPy's # handling of 0-d arrays and boolean indexing with # numpy.bool_ scalars + zerod = False if x.ndim == 0: x = x[None] zerod = True - newcondlist = [] - for k in range(n): - if condlist[k].ndim == 0: - condition = condlist[k][None] - else: - condition = condlist[k] - newcondlist.append(condition) - condlist = newcondlist + if condlist.shape[-1] != 1: + condlist = condlist.T + if n == n2 - 1: # compute the "otherwise" condition. + totlist = np.logical_or.reduce(condlist, axis=0) + condlist = np.vstack([condlist, ~totlist]) + n += 1 + if (n != n2): + raise ValueError( + "function list and condition list must be the same") y = zeros(x.shape, x.dtype) for k in range(n): @@ -770,29 +768,68 @@ def select(condlist, choicelist, default=0): array([ 0, 1, 2, 0, 0, 0, 36, 49, 64, 81]) """ - n = len(condlist) - n2 = len(choicelist) - if n2 != n: + # Check the size of condlist and choicelist are the same, or abort. + if len(condlist) != len(choicelist): raise ValueError( - "list of cases must be same length as list of conditions") - choicelist = [default] + choicelist - S = 0 - pfac = 1 - for k in range(1, n+1): - S += k * pfac * asarray(condlist[k-1]) - if k < n: - pfac *= (1-asarray(condlist[k-1])) - # handle special case of a 1-element condition but - # a multi-element choice - if type(S) in ScalarType or max(asarray(S).shape) == 1: - pfac = asarray(1) - for k in range(n2+1): - pfac = pfac + asarray(choicelist[k]) - if type(S) in ScalarType: - S = S*ones(asarray(pfac).shape, type(S)) - else: - S = S*ones(asarray(pfac).shape, S.dtype) - return choose(S, tuple(choicelist)) + 'list of cases must be same length as list of conditions') + + # Now that the dtype is known, handle the deprecated select([], []) case + if len(condlist) == 0: + warnings.warn("select with an empty condition list is not possible" + "and will be deprecated", + DeprecationWarning) + return np.asarray(default)[()] + + choicelist = [np.asarray(choice) for choice in choicelist] + choicelist.append(np.asarray(default)) + + # need to get the result type before broadcasting for correct scalar + # behaviour + dtype = np.result_type(*choicelist) + + # Convert conditions to arrays and broadcast conditions and choices + # as the shape is needed for the result. Doing it seperatly optimizes + # for example when all choices are scalars. + condlist = np.broadcast_arrays(*condlist) + choicelist = np.broadcast_arrays(*choicelist) + + # If cond array is not an ndarray in boolean format or scalar bool, abort. + deprecated_ints = False + for i in range(len(condlist)): + cond = condlist[i] + if cond.dtype.type is not np.bool_: + if np.issubdtype(cond.dtype, np.integer): + # A previous implementation accepted int ndarrays accidentally. + # Supported here deliberately, but deprecated. + condlist[i] = condlist[i].astype(bool) + deprecated_ints = True + else: + raise ValueError( + 'invalid entry in choicelist: should be boolean ndarray') + + if deprecated_ints: + msg = "select condlists containing integer ndarrays is deprecated " \ + "and will be removed in the future. Use `.astype(bool)` to " \ + "convert to bools." + warnings.warn(msg, DeprecationWarning) + + if choicelist[0].ndim == 0: + # This may be common, so avoid the call. + result_shape = condlist[0].shape + else: + result_shape = np.broadcast_arrays(condlist[0], choicelist[0])[0].shape + + result = np.full(result_shape, choicelist[-1], dtype) + + # Use np.copyto to burn each choicelist array onto result, using the + # corresponding condlist as a boolean mask. This is done in reverse + # order since the first choice should take precedence. + choicelist = choicelist[-2::-1] + condlist = condlist[::-1] + for choice, cond in zip(choicelist, condlist): + np.copyto(result, choice, where=cond) + + return result def copy(a, order='K'): @@ -1101,7 +1138,7 @@ def interp(x, xp, fp, left=None, right=None): ----- Does not check that the x-coordinate sequence `xp` is increasing. If `xp` is not increasing, the results are nonsense. - A simple check for increasingness is:: + A simple check for increasing is:: np.all(np.diff(xp) > 0) @@ -1578,20 +1615,22 @@ class vectorize(object): The `vectorize` function is provided primarily for convenience, not for performance. The implementation is essentially a for loop. - If `otypes` is not specified, then a call to the function with the first - argument will be used to determine the number of outputs. The results of - this call will be cached if `cache` is `True` to prevent calling the - function twice. However, to implement the cache, the original function - must be wrapped which will slow down subsequent calls, so only do this if - your function is expensive. + If `otypes` is not specified, then a call to the function with the + first argument will be used to determine the number of outputs. The + results of this call will be cached if `cache` is `True` to prevent + calling the function twice. However, to implement the cache, the + original function must be wrapped which will slow down subsequent + calls, so only do this if your function is expensive. + + The new keyword argument interface and `excluded` argument support + further degrades performance. - The new keyword argument interface and `excluded` argument support further - degrades performance. """ def __init__(self, pyfunc, otypes='', doc=None, excluded=None, cache=False): self.pyfunc = pyfunc self.cache = cache + self._ufunc = None # Caching to improve default performance if doc is None: self.__doc__ = pyfunc.__doc__ @@ -1615,9 +1654,6 @@ class vectorize(object): excluded = set() self.excluded = set(excluded) - if self.otypes and not self.excluded: - self._ufunc = None # Caching to improve default performance - def __call__(self, *args, **kwargs): """ Return arrays with the results of `pyfunc` broadcast (vectorized) over @@ -1651,7 +1687,8 @@ class vectorize(object): def _get_ufunc_and_otypes(self, func, args): """Return (ufunc, otypes).""" # frompyfunc will fail if args is empty - assert args + if not args: + raise ValueError('args can not be empty') if self.otypes: otypes = self.otypes @@ -1810,9 +1847,11 @@ def cov(m, y=None, rowvar=1, bias=0, ddof=None): "ddof must be integer") # Handles complex arrays too + m = np.asarray(m) if y is None: dtype = np.result_type(m, np.float64) else: + y = np.asarray(y) dtype = np.result_type(m, y, np.float64) X = array(m, ndmin=2, dtype=dtype) @@ -1821,11 +1860,9 @@ def cov(m, y=None, rowvar=1, bias=0, ddof=None): if rowvar: N = X.shape[1] axis = 0 - tup = (slice(None), newaxis) else: N = X.shape[0] axis = 1 - tup = (newaxis, slice(None)) # check ddof if ddof is None: @@ -1842,7 +1879,7 @@ def cov(m, y=None, rowvar=1, bias=0, ddof=None): y = array(y, copy=False, ndmin=2, dtype=dtype) X = concatenate((X, y), axis) - X -= X.mean(axis=1-axis)[tup] + X -= X.mean(axis=1-axis, keepdims=True) if not rowvar: return (dot(X.T, X.conj()) / fact).squeeze() else: @@ -1909,7 +1946,7 @@ def blackman(M): """ Return the Blackman window. - The Blackman window is a taper formed by using the the first three + The Blackman window is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window. @@ -2139,9 +2176,10 @@ def hanning(M): .. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right) \\qquad 0 \\leq n \\leq M-1 - The Hanning was named for Julius van Hann, an Austrian meterologist. It is - also known as the Cosine Bell. Some authors prefer that it be called a - Hann window, to help avoid confusion with the very similar Hamming window. + The Hanning was named for Julius van Hann, an Austrian meteorologist. + It is also known as the Cosine Bell. Some authors prefer that it be + called a Hann window, to help avoid confusion with the very similar + Hamming window. Most references to the Hanning window come from the signal processing literature, where it is used as one of many windowing functions for @@ -2238,9 +2276,9 @@ def hamming(M): .. math:: w(n) = 0.54 - 0.46cos\\left(\\frac{2\\pi{n}}{M-1}\\right) \\qquad 0 \\leq n \\leq M-1 - The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and - is described in Blackman and Tukey. It was recommended for smoothing the - truncated autocovariance function in the time domain. + The Hamming was named for R. W. Hamming, an associate of J. W. Tukey + and is described in Blackman and Tukey. It was recommended for + smoothing the truncated autocovariance function in the time domain. Most references to the Hamming window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means @@ -2420,11 +2458,11 @@ def i0(x): Notes ----- We use the algorithm published by Clenshaw [1]_ and referenced by - Abramowitz and Stegun [2]_, for which the function domain is partitioned - into the two intervals [0,8] and (8,inf), and Chebyshev polynomial - expansions are employed in each interval. Relative error on the domain - [0,30] using IEEE arithmetic is documented [3]_ as having a peak of 5.8e-16 - with an rms of 1.4e-16 (n = 30000). + Abramowitz and Stegun [2]_, for which the function domain is + partitioned into the two intervals [0,8] and (8,inf), and Chebyshev + polynomial expansions are employed in each interval. Relative error on + the domain [0,30] using IEEE arithmetic is documented [3]_ as having a + peak of 5.8e-16 with an rms of 1.4e-16 (n = 30000). References ---------- @@ -2494,12 +2532,11 @@ def kaiser(M, beta): where :math:`I_0` is the modified zeroth-order Bessel function. - The Kaiser was named for Jim Kaiser, who discovered a simple approximation - to the DPSS window based on Bessel functions. - The Kaiser window is a very good approximation to the Digital Prolate - Spheroidal Sequence, or Slepian window, which is the transform which - maximizes the energy in the main lobe of the window relative to total - energy. + The Kaiser was named for Jim Kaiser, who discovered a simple + approximation to the DPSS window based on Bessel functions. The Kaiser + window is a very good approximation to the Digital Prolate Spheroidal + Sequence, or Slepian window, which is the transform which maximizes the + energy in the main lobe of the window relative to total energy. The Kaiser can approximate many other windows by varying the beta parameter. @@ -2609,8 +2646,8 @@ def sinc(x): The name sinc is short for "sine cardinal" or "sinus cardinalis". The sinc function is used in various signal processing applications, - including in anti-aliasing, in the construction of a - Lanczos resampling filter, and in interpolation. + including in anti-aliasing, in the construction of a Lanczos resampling + filter, and in interpolation. For bandlimited interpolation of discrete-time signals, the ideal interpolation kernel is proportional to the sinc function. @@ -2692,7 +2729,67 @@ def msort(a): return b -def median(a, axis=None, out=None, overwrite_input=False): +def _ureduce(a, func, **kwargs): + """ + Internal Function. + Call `func` with `a` as first argument swapping the axes to use extended + axis on functions that don't support it natively. + + Returns result and a.shape with axis dims set to 1. + + Parameters + ---------- + a : array_like + Input array or object that can be converted to an array. + func : callable + Reduction function Kapable of receiving an axis argument. + It is is called with `a` as first argument followed by `kwargs`. + kwargs : keyword arguments + additional keyword arguments to pass to `func`. + + Returns + ------- + result : tuple + Result of func(a, **kwargs) and a.shape with axis dims set to 1 + which can be used to reshape the result to the same shape a ufunc with + keepdims=True would produce. + + """ + a = np.asanyarray(a) + axis = kwargs.get('axis', None) + if axis is not None: + keepdim = list(a.shape) + nd = a.ndim + try: + axis = operator.index(axis) + if axis >= nd or axis < -nd: + raise IndexError("axis %d out of bounds (%d)" % (axis, a.ndim)) + keepdim[axis] = 1 + except TypeError: + sax = set() + for x in axis: + if x >= nd or x < -nd: + raise IndexError("axis %d out of bounds (%d)" % (x, nd)) + if x in sax: + raise ValueError("duplicate value in axis") + sax.add(x % nd) + keepdim[x] = 1 + keep = sax.symmetric_difference(frozenset(range(nd))) + nkeep = len(keep) + # swap axis that should not be reduced to front + for i, s in enumerate(sorted(keep)): + a = a.swapaxes(i, s) + # merge reduced axis + a = a.reshape(a.shape[:nkeep] + (-1,)) + kwargs['axis'] = -1 + else: + keepdim = [1] * a.ndim + + r = func(a, **kwargs) + return r, keepdim + + +def median(a, axis=None, out=None, overwrite_input=False, keepdims=False): """ Compute the median along the specified axis. @@ -2702,27 +2799,35 @@ def median(a, axis=None, out=None, overwrite_input=False): ---------- a : array_like Input array or object that can be converted to an array. - axis : int, optional + axis : int or sequence of int, optional Axis along which the medians are computed. The default (axis=None) is to compute the median along a flattened version of the array. + A sequence of axes is supported since version 1.9.0. out : ndarray, optional - Alternative output array in which to place the result. It must - have the same shape and buffer length as the expected output, - but the type (of the output) will be cast if necessary. + Alternative output array in which to place the result. It must have + the same shape and buffer length as the expected output, but the + type (of the output) will be cast if necessary. overwrite_input : bool, optional If True, then allow use of memory of input array (a) for calculations. The input array will be modified by the call to - median. This will save memory when you do not need to preserve - the contents of the input array. Treat the input as undefined, - but it will probably be fully or partially sorted. Default is - False. Note that, if `overwrite_input` is True and the input - is not already an ndarray, an error will be raised. + median. This will save memory when you do not need to preserve the + contents of the input array. Treat the input as undefined, but it + will probably be fully or partially sorted. Default is False. Note + that, if `overwrite_input` is True and the input is not already an + ndarray, an error will be raised. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the original `arr`. + + .. versionadded:: 1.9.0 + Returns ------- median : ndarray - A new array holding the result (unless `out` is specified, in - which case that array is returned instead). If the input contains + A new array holding the result (unless `out` is specified, in which + case that array is returned instead). If the input contains integers, or floats of smaller precision than 64, then the output data-type is float64. Otherwise, the output data-type is the same as that of the input. @@ -2766,6 +2871,16 @@ def median(a, axis=None, out=None, overwrite_input=False): >>> assert not np.all(a==b) """ + r, k = _ureduce(a, func=_median, axis=axis, out=out, + overwrite_input=overwrite_input) + if keepdims: + return r.reshape(k) + else: + return r + +def _median(a, axis=None, out=None, overwrite_input=False): + # can't be reasonably be implemented in terms of percentile as we have to + # call mean to not break astropy a = np.asanyarray(a) if axis is not None and axis >= a.ndim: raise IndexError( @@ -2815,7 +2930,7 @@ def median(a, axis=None, out=None, overwrite_input=False): def percentile(a, q, axis=None, out=None, - overwrite_input=False, interpolation='linear'): + overwrite_input=False, interpolation='linear', keepdims=False): """ Compute the qth percentile of the data along the specified axis. @@ -2827,9 +2942,10 @@ def percentile(a, q, axis=None, out=None, Input array or object that can be converted to an array. q : float in range of [0,100] (or sequence of floats) Percentile to compute which must be between 0 and 100 inclusive. - axis : int, optional + axis : int or sequence of int, optional Axis along which the percentiles are computed. The default (None) is to compute the percentiles along a flattened version of the array. + A sequence of axes is supported since version 1.9.0. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, @@ -2855,17 +2971,23 @@ def percentile(a, q, axis=None, out=None, * midpoint: (`i` + `j`) / 2. .. versionadded:: 1.9.0 + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the original `arr`. + + .. versionadded:: 1.9.0 Returns ------- percentile : scalar or ndarray - If a single percentile `q` is given and axis=None a scalar is returned. - If multiple percentiles `q` are given an array holding the result is - returned. The results are listed in the first axis. - (If `out` is specified, in which case that array is returned instead). - If the input contains integers, or floats of smaller precision than 64, - then the output data-type is float64. Otherwise, the output data-type - is the same as that of the input. + If a single percentile `q` is given and axis=None a scalar is + returned. If multiple percentiles `q` are given an array holding + the result is returned. The results are listed in the first axis. + (If `out` is specified, in which case that array is returned + instead). If the input contains integers, or floats of smaller + precision than 64, then the output data-type is float64. Otherwise, + the output data-type is the same as that of the input. See Also -------- @@ -2873,12 +2995,12 @@ def percentile(a, q, axis=None, out=None, Notes ----- - Given a vector V of length N, the qth percentile of V is the qth ranked - value in a sorted copy of V. The values and distances of the two nearest - neighbors as well as the `interpolation` parameter will determine the - percentile if the normalized ranking does not match q exactly. This - function is the same as the median if ``q=50``, the same as the minimum - if ``q=0``and the same as the maximum if ``q=100``. + Given a vector V of length N, the q-th percentile of V is the q-th ranked + value in a sorted copy of V. The values and distances of the two + nearest neighbors as well as the `interpolation` parameter will + determine the percentile if the normalized ranking does not match q + exactly. This function is the same as the median if ``q=50``, the same + as the minimum if ``q=0``and the same as the maximum if ``q=100``. Examples -------- @@ -2911,8 +3033,22 @@ def percentile(a, q, axis=None, out=None, array([ 3.5]) """ + q = asarray(q, dtype=np.float64) + r, k = _ureduce(a, func=_percentile, q=q, axis=axis, out=out, + overwrite_input=overwrite_input, + interpolation=interpolation) + if keepdims: + if q.ndim == 0: + return r.reshape(k) + else: + return r.reshape([len(q)] + k) + else: + return r + + +def _percentile(a, q, axis=None, out=None, + overwrite_input=False, interpolation='linear', keepdims=False): a = asarray(a) - q = asarray(q) if q.ndim == 0: # Do not allow 0-d arrays because following code fails for scalar zerod = True @@ -2920,10 +3056,17 @@ def percentile(a, q, axis=None, out=None, else: zerod = False - q = q / 100.0 - if (q < 0).any() or (q > 1).any(): - raise ValueError( - "Percentiles must be in the range [0,100]") + # avoid expensive reductions, relevant for arrays with < O(1000) elements + if q.size < 10: + for i in range(q.size): + if q[i] < 0. or q[i] > 100.: + raise ValueError("Percentiles must be in the range [0,100]") + q[i] /= 100. + else: + # faster than any() + if np.count_nonzero(q < 0.) or np.count_nonzero(q > 100.): + raise ValueError("Percentiles must be in the range [0,100]") + q /= 100. # prepare a for partioning if overwrite_input: @@ -3029,10 +3172,11 @@ def trapz(y, x=None, dx=1.0, axis=-1): Notes ----- - Image [2]_ illustrates trapezoidal rule -- y-axis locations of points will - be taken from `y` array, by default x-axis distances between points will be - 1.0, alternatively they can be provided with `x` array or with `dx` scalar. - Return value will be equal to combined area under the red lines. + Image [2]_ illustrates trapezoidal rule -- y-axis locations of points + will be taken from `y` array, by default x-axis distances between + points will be 1.0, alternatively they can be provided with `x` array + or with `dx` scalar. Return value will be equal to combined area under + the red lines. References @@ -3130,7 +3274,7 @@ def meshgrid(*xi, **kwargs): Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,..., xn. - + .. versionchanged:: 1.9 1-D and 0-D cases are allowed. @@ -3141,16 +3285,22 @@ def meshgrid(*xi, **kwargs): indexing : {'xy', 'ij'}, optional Cartesian ('xy', default) or matrix ('ij') indexing of output. See Notes for more details. + + .. versionadded:: 1.7.0 sparse : bool, optional - If True a sparse grid is returned in order to conserve memory. - Default is False. + If True a sparse grid is returned in order to conserve memory. + Default is False. + + .. versionadded:: 1.7.0 copy : bool, optional - If False, a view into the original arrays are returned in - order to conserve memory. Default is True. Please note that - ``sparse=False, copy=False`` will likely return non-contiguous arrays. - Furthermore, more than one element of a broadcast array may refer to - a single memory location. If you need to write to the arrays, make - copies first. + If False, a view into the original arrays are returned in order to + conserve memory. Default is True. Please note that + ``sparse=False, copy=False`` will likely return non-contiguous + arrays. Furthermore, more than one element of a broadcast array + may refer to a single memory location. If you need to write to the + arrays, make copies first. + + .. versionadded:: 1.7.0 Returns ------- @@ -3164,13 +3314,13 @@ def meshgrid(*xi, **kwargs): Notes ----- This function supports both indexing conventions through the indexing - keyword argument. Giving the string 'ij' returns a meshgrid with matrix - indexing, while 'xy' returns a meshgrid with Cartesian indexing. In the - 2-D case with inputs of length M and N, the outputs are of shape (N, M) for - 'xy' indexing and (M, N) for 'ij' indexing. In the 3-D case with inputs of - length M, N and P, outputs are of shape (N, M, P) for 'xy' indexing and - (M, N, P) for 'ij' indexing. The difference is illustrated by the - following code snippet:: + keyword argument. Giving the string 'ij' returns a meshgrid with + matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing. + In the 2-D case with inputs of length M and N, the outputs are of shape + (N, M) for 'xy' indexing and (M, N) for 'ij' indexing. In the 3-D case + with inputs of length M, N and P, outputs are of shape (N, M, P) for + 'xy' indexing and (M, N, P) for 'ij' indexing. The difference is + illustrated by the following code snippet:: xv, yv = meshgrid(x, y, sparse=False, indexing='ij') for i in range(nx): @@ -3181,7 +3331,7 @@ def meshgrid(*xi, **kwargs): for i in range(nx): for j in range(ny): # treat xv[j,i], yv[j,i] - + In the 1-D and 0-D case, the indexing and sparse keywords have no effect. See Also @@ -3221,9 +3371,13 @@ def meshgrid(*xi, **kwargs): """ ndim = len(xi) - copy_ = kwargs.get('copy', True) - sparse = kwargs.get('sparse', False) - indexing = kwargs.get('indexing', 'xy') + copy_ = kwargs.pop('copy', True) + sparse = kwargs.pop('sparse', False) + indexing = kwargs.pop('indexing', 'xy') + + if kwargs: + raise TypeError("meshgrid() got an unexpected keyword argument '%s'" + % (list(kwargs)[0],)) if not indexing in ['xy', 'ij']: raise ValueError( @@ -3258,7 +3412,8 @@ def meshgrid(*xi, **kwargs): def delete(arr, obj, axis=None): """ Return a new array with sub-arrays along an axis deleted. For a one - dimensional array, this returns those entries not returned by `arr[obj]`. + dimensional array, this returns those entries not returned by + `arr[obj]`. Parameters ---------- @@ -3285,9 +3440,11 @@ def delete(arr, obj, axis=None): Notes ----- Often it is preferable to use a boolean mask. For example: + >>> mask = np.ones(len(arr), dtype=bool) >>> mask[[0,2,4]] = False >>> result = arr[mask,...] + Is equivalent to `np.delete(arr, [0,2,4], axis=0)`, but allows further use of `mask`. @@ -3465,7 +3622,8 @@ def insert(arr, obj, values, axis=None): .. versionadded:: 1.8.0 Support for multiple insertions when `obj` is a single scalar or a - sequence with one element (similar to calling insert multiple times). + sequence with one element (similar to calling insert multiple + times). values : array_like Values to insert into `arr`. If the type of `values` is different from that of `arr`, `values` is converted to the type of `arr`. @@ -3664,19 +3822,19 @@ def append(arr, values, axis=None): Values are appended to a copy of this array. values : array_like These values are appended to a copy of `arr`. It must be of the - correct shape (the same shape as `arr`, excluding `axis`). If `axis` - is not specified, `values` can be any shape and will be flattened - before use. + correct shape (the same shape as `arr`, excluding `axis`). If + `axis` is not specified, `values` can be any shape and will be + flattened before use. axis : int, optional - The axis along which `values` are appended. If `axis` is not given, - both `arr` and `values` are flattened before use. + The axis along which `values` are appended. If `axis` is not + given, both `arr` and `values` are flattened before use. Returns ------- append : ndarray - A copy of `arr` with `values` appended to `axis`. Note that `append` - does not occur in-place: a new array is allocated and filled. If - `axis` is None, `out` is a flattened array. + A copy of `arr` with `values` appended to `axis`. Note that + `append` does not occur in-place: a new array is allocated and + filled. If `axis` is None, `out` is a flattened array. See Also -------- diff --git a/numpy/lib/nanfunctions.py b/numpy/lib/nanfunctions.py index 5766084ab..7120760b5 100644 --- a/numpy/lib/nanfunctions.py +++ b/numpy/lib/nanfunctions.py @@ -17,12 +17,14 @@ Functions from __future__ import division, absolute_import, print_function import warnings +import operator import numpy as np - +from numpy.core.fromnumeric import partition +from numpy.lib.function_base import _ureduce as _ureduce __all__ = [ 'nansum', 'nanmax', 'nanmin', 'nanargmax', 'nanargmin', 'nanmean', - 'nanvar', 'nanstd' + 'nanmedian', 'nanpercentile', 'nanvar', 'nanstd' ] @@ -228,7 +230,7 @@ def nanmin(a, axis=None, out=None, keepdims=False): # Check for all-NaN axis mask = np.all(mask, axis=axis, keepdims=keepdims) if np.any(mask): - res = _copyto(res, mask, np.nan) + res = _copyto(res, np.nan, mask) warnings.warn("All-NaN axis encountered", RuntimeWarning) return res @@ -327,7 +329,7 @@ def nanmax(a, axis=None, out=None, keepdims=False): # Check for all-NaN axis mask = np.all(mask, axis=axis, keepdims=keepdims) if np.any(mask): - res = _copyto(res, mask, np.nan) + res = _copyto(res, np.nan, mask) warnings.warn("All-NaN axis encountered", RuntimeWarning) return res @@ -601,6 +603,335 @@ def nanmean(a, axis=None, dtype=None, out=None, keepdims=False): return avg +def _nanmedian1d(arr1d, overwrite_input=False): + """ + Private function for rank 1 arrays. Compute the median ignoring NaNs. + See nanmedian for parameter usage + """ + c = np.isnan(arr1d) + s = np.where(c)[0] + if s.size == arr1d.size: + warnings.warn("All-NaN slice encountered", RuntimeWarning) + return np.nan + elif s.size == 0: + return np.median(arr1d, overwrite_input=overwrite_input) + else: + if overwrite_input: + x = arr1d + else: + x = arr1d.copy() + # select non-nans at end of array + enonan = arr1d[-s.size:][~c[-s.size:]] + # fill nans in beginning of array with non-nans of end + x[s[:enonan.size]] = enonan + # slice nans away + return np.median(x[:-s.size], overwrite_input=True) + + +def _nanmedian(a, axis=None, out=None, overwrite_input=False): + """ + Private function that doesn't support extended axis or keepdims. + These methods are extended to this function using _ureduce + See nanmedian for parameter usage + + """ + if axis is None or a.ndim == 1: + part = a.ravel() + if out is None: + return _nanmedian1d(part, overwrite_input) + else: + out[...] = _nanmedian1d(part, overwrite_input) + return out + else: + # for small medians use sort + indexing which is still faster than + # apply_along_axis + if a.shape[axis] < 400: + return _nanmedian_small(a, axis, out, overwrite_input) + result = np.apply_along_axis(_nanmedian1d, axis, a, overwrite_input) + if out is not None: + out[...] = result + return result + +def _nanmedian_small(a, axis=None, out=None, overwrite_input=False): + """ + sort + indexing median, faster for small medians along multiple dimensions + due to the high overhead of apply_along_axis + see nanmedian for parameter usage + """ + a = np.ma.masked_array(a, np.isnan(a)) + m = np.ma.median(a, axis=axis, overwrite_input=overwrite_input) + for i in range(np.count_nonzero(m.mask.ravel())): + warnings.warn("All-NaN slice encountered", RuntimeWarning) + if out is not None: + out[...] = m.filled(np.nan) + return out + return m.filled(np.nan) + +def nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=False): + """ + Compute the median along the specified axis, while ignoring NaNs. + + Returns the median of the array elements. + + .. versionadded:: 1.9.0 + + Parameters + ---------- + a : array_like + Input array or object that can be converted to an array. + axis : int, optional + Axis along which the medians are computed. The default (axis=None) + is to compute the median along a flattened version of the array. + A sequence of axes is supported since version 1.9.0. + out : ndarray, optional + Alternative output array in which to place the result. It must have + the same shape and buffer length as the expected output, but the + type (of the output) will be cast if necessary. + overwrite_input : bool, optional + If True, then allow use of memory of input array (a) for + calculations. The input array will be modified by the call to + median. This will save memory when you do not need to preserve + the contents of the input array. Treat the input as undefined, + but it will probably be fully or partially sorted. Default is + False. Note that, if `overwrite_input` is True and the input + is not already an ndarray, an error will be raised. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the original `arr`. + + + + Returns + ------- + median : ndarray + A new array holding the result. If the input contains integers, or + floats of smaller precision than 64, then the output data-type is + float64. Otherwise, the output data-type is the same as that of the + input. + + See Also + -------- + mean, median, percentile + + Notes + ----- + Given a vector V of length N, the median of V is the middle value of + a sorted copy of V, ``V_sorted`` - i.e., ``V_sorted[(N-1)/2]``, when N is + odd. When N is even, it is the average of the two middle values of + ``V_sorted``. + + Examples + -------- + >>> a = np.array([[10.0, 7, 4], [3, 2, 1]]) + >>> a[0, 1] = np.nan + >>> a + array([[ 10., nan, 4.], + [ 3., 2., 1.]]) + >>> np.median(a) + nan + >>> np.nanmedian(a) + 3.0 + >>> np.nanmedian(a, axis=0) + array([ 6.5, 2., 2.5]) + >>> np.median(a, axis=1) + array([ 7., 2.]) + >>> b = a.copy() + >>> np.nanmedian(b, axis=1, overwrite_input=True) + array([ 7., 2.]) + >>> assert not np.all(a==b) + >>> b = a.copy() + >>> np.nanmedian(b, axis=None, overwrite_input=True) + 3.0 + >>> assert not np.all(a==b) + + """ + a = np.asanyarray(a) + # apply_along_axis in _nanmedian doesn't handle empty arrays well, + # so deal them upfront + if a.size == 0: + return np.nanmean(a, axis, out=out, keepdims=keepdims) + + r, k = _ureduce(a, func=_nanmedian, axis=axis, out=out, + overwrite_input=overwrite_input) + if keepdims: + return r.reshape(k) + else: + return r + + +def nanpercentile(a, q, axis=None, out=None, overwrite_input=False, + interpolation='linear', keepdims=False): + """ + Compute the qth percentile of the data along the specified axis, while + ignoring nan values. + + Returns the qth percentile of the array elements. + + Parameters + ---------- + a : array_like + Input array or object that can be converted to an array. + q : float in range of [0,100] (or sequence of floats) + Percentile to compute which must be between 0 and 100 inclusive. + axis : int or sequence of int, optional + Axis along which the percentiles are computed. The default (None) + is to compute the percentiles along a flattened version of the array. + A sequence of axes is supported since version 1.9.0. + out : ndarray, optional + Alternative output array in which to place the result. It must + have the same shape and buffer length as the expected output, + but the type (of the output) will be cast if necessary. + overwrite_input : bool, optional + If True, then allow use of memory of input array `a` for + calculations. The input array will be modified by the call to + percentile. This will save memory when you do not need to preserve + the contents of the input array. In this case you should not make + any assumptions about the content of the passed in array `a` after + this function completes -- treat it as undefined. Default is False. + Note that, if the `a` input is not already an array this parameter + will have no effect, `a` will be converted to an array internally + regardless of the value of this parameter. + interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} + This optional parameter specifies the interpolation method to use, + when the desired quantile lies between two data points `i` and `j`: + * linear: `i + (j - i) * fraction`, where `fraction` is the + fractional part of the index surrounded by `i` and `j`. + * lower: `i`. + * higher: `j`. + * nearest: `i` or `j` whichever is nearest. + * midpoint: (`i` + `j`) / 2. + + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the original `arr`. + + + Returns + ------- + nanpercentile : scalar or ndarray + If a single percentile `q` is given and axis=None a scalar is + returned. If multiple percentiles `q` are given an array holding + the result is returned. The results are listed in the first axis. + (If `out` is specified, in which case that array is returned + instead). If the input contains integers, or floats of smaller + precision than 64, then the output data-type is float64. Otherwise, + the output data-type is the same as that of the input. + + See Also + -------- + nanmean, nanmedian, percentile, median, mean + + Notes + ----- + Given a vector V of length N, the q-th percentile of V is the q-th ranked + value in a sorted copy of V. The values and distances of the two + nearest neighbors as well as the `interpolation` parameter will + determine the percentile if the normalized ranking does not match q + exactly. This function is the same as the median if ``q=50``, the same + as the minimum if ``q=0``and the same as the maximum if ``q=100``. + + Examples + -------- + >>> a = np.array([[10., 7., 4.], [3., 2., 1.]]) + >>> a[0][1] = np.nan + >>> a + array([[ 10., nan, 4.], + [ 3., 2., 1.]]) + >>> np.percentile(a, 50) + nan + >>> np.nanpercentile(a, 50) + 3.5 + >>> np.nanpercentile(a, 50, axis=0) + array([[ 6.5, 4.5, 2.5]]) + >>> np.nanpercentile(a, 50, axis=1) + array([[ 7.], + [ 2.]]) + >>> m = np.nanpercentile(a, 50, axis=0) + >>> out = np.zeros_like(m) + >>> np.nanpercentile(a, 50, axis=0, out=m) + array([[ 6.5, 4.5, 2.5]]) + >>> m + array([[ 6.5, 4.5, 2.5]]) + >>> b = a.copy() + >>> np.nanpercentile(b, 50, axis=1, overwrite_input=True) + array([[ 7.], + [ 2.]]) + >>> assert not np.all(a==b) + >>> b = a.copy() + >>> np.nanpercentile(b, 50, axis=None, overwrite_input=True) + array([ 3.5]) + + """ + + a = np.asanyarray(a) + q = np.asanyarray(q) + # apply_along_axis in _nanpercentile doesn't handle empty arrays well, + # so deal them upfront + if a.size == 0: + return np.nanmean(a, axis, out=out, keepdims=keepdims) + + r, k = _ureduce(a, func=_nanpercentile, q=q, axis=axis, out=out, + overwrite_input=overwrite_input, + interpolation=interpolation) + if keepdims: + if q.ndim == 0: + return r.reshape(k) + else: + return r.reshape([len(q)] + k) + else: + return r + + +def _nanpercentile(a, q, axis=None, out=None, overwrite_input=False, + interpolation='linear', keepdims=False): + """ + Private function that doesn't support extended axis or keepdims. + These methods are extended to this function using _ureduce + See nanpercentile for parameter usage + + """ + if axis is None: + part = a.ravel() + result = _nanpercentile1d(part, q, overwrite_input, interpolation) + else: + result = np.apply_along_axis(_nanpercentile1d, axis, a, q, + overwrite_input, interpolation) + + if out is not None: + out[...] = result + return result + + +def _nanpercentile1d(arr1d, q, overwrite_input=False, interpolation='linear'): + """ + Private function for rank 1 arrays. Compute percentile ignoring NaNs. + See nanpercentile for parameter usage + + """ + c = np.isnan(arr1d) + s = np.where(c)[0] + if s.size == arr1d.size: + warnings.warn("All-NaN slice encountered", RuntimeWarning) + return np.nan + elif s.size == 0: + return np.percentile(arr1d, q, overwrite_input=overwrite_input, + interpolation=interpolation) + else: + if overwrite_input: + x = arr1d + else: + x = arr1d.copy() + # select non-nans at end of array + enonan = arr1d[-s.size:][~c[-s.size:]] + # fill nans in beginning of array with non-nans of end + x[s[:enonan.size]] = enonan + # slice nans away + return np.percentile(x[:-s.size], q, overwrite_input=True, + interpolation=interpolation) + + def nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): """ Compute the variance along the specified axis, while ignoring NaNs. diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index af259cfef..42a539f78 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -285,21 +285,22 @@ def load(file, mmap_mode=None): Parameters ---------- file : file-like object or string - The file to read. It must support ``seek()`` and ``read()`` methods. - If the filename extension is ``.gz``, the file is first decompressed. + The file to read. File-like objects must support the + ``seek()`` and ``read()`` methods. Pickled files require that the + file-like object support the ``readline()`` method as well. mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional - If not None, then memory-map the file, using the given mode - (see `numpy.memmap` for a detailed description of the modes). - A memory-mapped array is kept on disk. However, it can be accessed - and sliced like any ndarray. Memory mapping is especially useful for - accessing small fragments of large files without reading the entire - file into memory. + If not None, then memory-map the file, using the given mode (see + `numpy.memmap` for a detailed description of the modes). A + memory-mapped array is kept on disk. However, it can be accessed + and sliced like any ndarray. Memory mapping is especially useful + for accessing small fragments of large files without reading the + entire file into memory. Returns ------- result : array, tuple, dict, etc. - Data stored in the file. For ``.npz`` files, the returned instance of - NpzFile class must be closed to avoid leaking file descriptors. + Data stored in the file. For ``.npz`` files, the returned instance + of NpzFile class must be closed to avoid leaking file descriptors. Raises ------ @@ -308,7 +309,7 @@ def load(file, mmap_mode=None): See Also -------- - save, savez, loadtxt + save, savez, savez_compressed, loadtxt memmap : Create a memory-map to an array stored in a file on disk. Notes @@ -319,13 +320,14 @@ def load(file, mmap_mode=None): - If the file is a ``.npz`` file, then a dictionary-like object is returned, containing ``{filename: array}`` key-value pairs, one for each file in the archive. - - If the file is a ``.npz`` file, the returned value supports the context - manager protocol in a similar fashion to the open function:: + - If the file is a ``.npz`` file, the returned value supports the + context manager protocol in a similar fashion to the open function:: with load('foo.npz') as data: a = data['a'] - The underlying file descriptor is closed when exiting the 'with' block. + The underlying file descriptor is closed when exiting the 'with' + block. Examples -------- @@ -549,6 +551,7 @@ def savez_compressed(file, *args, **kwds): See Also -------- numpy.savez : Save several arrays into an uncompressed ``.npz`` file format + numpy.load : Load the files created by savez_compressed. """ _savez(file, args, kwds, True) @@ -668,6 +671,7 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, The returned array will have at least `ndmin` dimensions. Otherwise mono-dimensional axes will be squeezed. Legal values: 0 (default), 1 or 2. + .. versionadded:: 1.6.0 Returns @@ -840,6 +844,11 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, continue if usecols: vals = [vals[i] for i in usecols] + if len(vals) != N: + line_num = i + skiprows + 1 + raise ValueError("Wrong number of columns at line %d" + % line_num) + # Convert each value according to its column and store items = [conv(val) for (conv, val) in zip(converters, vals)] # Then pack it according to the dtype's nesting @@ -906,22 +915,26 @@ def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', and imaginary part must have separate specifiers, e.g. `['%.3e + %.3ej', '(%.15e%+.15ej)']` for 2 columns delimiter : str, optional - Character separating columns. + String or character separating columns. newline : str, optional + String or character separating lines. + .. versionadded:: 1.5.0 header : str, optional String that will be written at the beginning of the file. + .. versionadded:: 1.7.0 footer : str, optional String that will be written at the end of the file. + .. versionadded:: 1.7.0 comments : str, optional String that will be prepended to the ``header`` and ``footer`` strings, to mark them as comments. Default: '# ', as expected by e.g. ``numpy.loadtxt``. + .. versionadded:: 1.7.0 - Character separating lines. See Also -------- @@ -1191,14 +1204,20 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, The string used to separate values. By default, any consecutive whitespaces act as delimiter. An integer or sequence of integers can also be provided as width(s) of each field. + skip_rows : int, optional + `skip_rows` was deprecated in numpy 1.5, and will be removed in + numpy 2.0. Please use `skip_header` instead. skip_header : int, optional - The numbers of lines to skip at the beginning of the file. + The number of lines to skip at the beginning of the file. skip_footer : int, optional - The numbers of lines to skip at the end of the file + The number of lines to skip at the end of the file. converters : variable, optional The set of functions that convert the data of a column to a value. The converters can also be used to provide a default value for missing data: ``converters = {3: lambda s: float(s or 0)}``. + missing : variable, optional + `missing` was deprecated in numpy 1.5, and will be removed in + numpy 2.0. Please use `missing_values` instead. missing_values : variable, optional The set of strings corresponding to missing data. filling_values : variable, optional @@ -1236,6 +1255,8 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, usemask : bool, optional If True, return a masked array. If False, return a regular array. + loose : bool, optional + If True, do not raise errors for invalid values. invalid_raise : bool, optional If True, an exception is raised if an inconsistency is detected in the number of columns. @@ -1840,7 +1861,7 @@ def recfromtxt(fname, **kwargs): array will be determined from the data. """ - kwargs.update(dtype=kwargs.get('dtype', None)) + kwargs.setdefault("dtype", None) usemask = kwargs.get('usemask', False) output = genfromtxt(fname, **kwargs) if usemask: @@ -1867,17 +1888,20 @@ def recfromcsv(fname, **kwargs): -------- numpy.genfromtxt : generic function to load ASCII data. + Notes + ----- + By default, `dtype` is None, which means that the data-type of the output + array will be determined from the data. + """ - case_sensitive = kwargs.get('case_sensitive', "lower") or "lower" - names = kwargs.get('names', True) - if names is None: - names = True - kwargs.update(dtype=kwargs.get('update', None), - delimiter=kwargs.get('delimiter', ",") or ",", - names=names, - case_sensitive=case_sensitive) - usemask = kwargs.get("usemask", False) + # Set default kwargs for genfromtxt as relevant to csv import. + kwargs.setdefault("case_sensitive", "lower") + kwargs.setdefault("names", True) + kwargs.setdefault("delimiter", ",") + kwargs.setdefault("dtype", None) output = genfromtxt(fname, **kwargs) + + usemask = kwargs.get("usemask", False) if usemask: from numpy.ma.mrecords import MaskedRecords output = output.view(MaskedRecords) diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py index 8545375cd..10ae32a60 100644 --- a/numpy/lib/polynomial.py +++ b/numpy/lib/polynomial.py @@ -127,7 +127,7 @@ def poly(seq_of_zeros): elif len(sh) == 1: pass else: - raise ValueError("input must be 1d or square 2d array.") + raise ValueError("input must be 1d or non-empty square 2d array.") if len(seq_of_zeros) == 0: return 1.0 @@ -806,6 +806,8 @@ def polymul(a1, a2): poly1d : A one-dimensional polynomial class. poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval + convolve : Array convolution. Same output as polymul, but has parameter + for overlap mode. Examples -------- @@ -1191,10 +1193,12 @@ class poly1d(object): __rtruediv__ = __rdiv__ def __eq__(self, other): - return NX.alltrue(self.coeffs == other.coeffs) + if self.coeffs.shape != other.coeffs.shape: + return False + return (self.coeffs == other.coeffs).all() def __ne__(self, other): - return NX.any(self.coeffs != other.coeffs) + return not self.__eq__(other) def __setattr__(self, key, val): raise ValueError("Attributes cannot be changed this way.") diff --git a/numpy/lib/shape_base.py b/numpy/lib/shape_base.py index 4fdaba349..a6d391728 100644 --- a/numpy/lib/shape_base.py +++ b/numpy/lib/shape_base.py @@ -12,7 +12,7 @@ from numpy.core.numeric import asarray, zeros, newaxis, outer, \ from numpy.core.fromnumeric import product, reshape from numpy.core import hstack, vstack, atleast_3d -def apply_along_axis(func1d,axis,arr,*args): +def apply_along_axis(func1d, axis, arr, *args, **kwargs): """ Apply a function to 1-D slices along the given axis. @@ -30,6 +30,11 @@ def apply_along_axis(func1d,axis,arr,*args): Input array. args : any Additional arguments to `func1d`. + kwargs: any + Additional named arguments to `func1d`. + + .. versionadded:: 1.9.0 + Returns ------- @@ -78,7 +83,7 @@ def apply_along_axis(func1d,axis,arr,*args): i[axis] = slice(None, None) outshape = asarray(arr.shape).take(indlist) i.put(indlist, ind) - res = func1d(arr[tuple(i.tolist())],*args) + res = func1d(arr[tuple(i.tolist())], *args, **kwargs) # if res is a number, then we have a smaller output array if isscalar(res): outarr = zeros(outshape, asarray(res).dtype) @@ -94,7 +99,7 @@ def apply_along_axis(func1d,axis,arr,*args): ind[n] = 0 n -= 1 i.put(indlist, ind) - res = func1d(arr[tuple(i.tolist())],*args) + res = func1d(arr[tuple(i.tolist())], *args, **kwargs) outarr[tuple(ind)] = res k += 1 return outarr @@ -115,7 +120,7 @@ def apply_along_axis(func1d,axis,arr,*args): ind[n] = 0 n -= 1 i.put(indlist, ind) - res = func1d(arr[tuple(i.tolist())],*args) + res = func1d(arr[tuple(i.tolist())], *args, **kwargs) outarr[tuple(i.tolist())] = res k += 1 return outarr @@ -153,6 +158,12 @@ def apply_over_axes(func, a, axes): apply_along_axis : Apply a function to 1-D slices of an array along the given axis. + Notes + ------ + This function is equivalent to tuple axis arguments to reorderable ufuncs + with keepdims=True. Tuple axis arguments to ufuncs have been availabe since + version 1.7.0. + Examples -------- >>> a = np.arange(24).reshape(2,3,4) @@ -172,6 +183,13 @@ def apply_over_axes(func, a, axes): [ 92], [124]]]) + Tuple axis arguments to ufuncs are equivalent: + + >>> np.sum(a, axis=(0,2), keepdims=True) + array([[[ 60], + [ 92], + [124]]]) + """ val = asarray(a) N = a.ndim @@ -274,10 +292,6 @@ def column_stack(tup): -------- hstack, vstack, concatenate - Notes - ----- - This function is equivalent to ``np.vstack(tup).T``. - Examples -------- >>> a = np.array((1,2,3)) @@ -638,7 +652,7 @@ def dsplit(ary, indices_or_sections): """ if len(_nx.shape(ary)) < 3: - raise ValueError('vsplit only works on arrays of 3 or more dimensions') + raise ValueError('dsplit only works on arrays of 3 or more dimensions') return split(ary, indices_or_sections, 2) def get_array_prepare(*args): diff --git a/numpy/lib/src/_compiled_base.c b/numpy/lib/src/_compiled_base.c index 328fc2d14..a461613e3 100644 --- a/numpy/lib/src/_compiled_base.c +++ b/numpy/lib/src/_compiled_base.c @@ -60,29 +60,44 @@ decr_slot_right_(double x, double * bins, npy_intp lbins) return 0; } -/** +/* * Returns -1 if the array is monotonic decreasing, * +1 if the array is monotonic increasing, * and 0 if the array is not monotonic. */ static int -check_array_monotonic(double * a, int lena) +check_array_monotonic(const double *a, npy_int lena) { - int i; + npy_intp i; + double next; + double last = a[0]; + + /* Skip repeated values at the beginning of the array */ + for (i = 1; (i < lena) && (a[i] == last); i++); + + if (i == lena) { + /* all bin edges hold the same value */ + return 1; + } - if (a [0] <= a [1]) { - /* possibly monotonic increasing */ - for (i = 1; i < lena - 1; i ++) { - if (a [i] > a [i + 1]) { + next = a[i]; + if (last < next) { + /* Possibly monotonic increasing */ + for (i += 1; i < lena; i++) { + last = next; + next = a[i]; + if (last > next) { return 0; } } return 1; } else { - /* possibly monotonic decreasing */ - for (i = 1; i < lena - 1; i ++) { - if (a [i] < a [i + 1]) { + /* last > next, possibly monotonic decreasing */ + for (i += 1; i < lena; i++) { + last = next; + next = a[i]; + if (last < next) { return 0; } } @@ -90,39 +105,26 @@ check_array_monotonic(double * a, int lena) } } - - -/* find the index of the maximum element of an integer array */ -static npy_intp -mxx (npy_intp *i , npy_intp len) +/* Find the minimum and maximum of an integer array */ +static void +minmax(const npy_intp *data, npy_intp data_len, npy_intp *mn, npy_intp *mx) { - npy_intp mx = 0, max = i[0]; - npy_intp j; + npy_intp min = *data; + npy_intp max = *data; - for ( j = 1; j < len; j ++ ) { - if ( i [j] > max ) { - max = i [j]; - mx = j; + while (--data_len) { + const npy_intp val = *(++data); + if (val < min) { + min = val; + } + else if (val > max) { + max = val; } } - return mx; -} -/* find the index of the minimum element of an integer array */ -static npy_intp -mnx (npy_intp *i , npy_intp len) -{ - npy_intp mn = 0, min = i [0]; - npy_intp j; - - for ( j = 1; j < len; j ++ ) - if ( i [j] < min ) - {min = i [j]; - mn = j;} - return mn; + *mn = min; + *mx = max; } - - /* * arr_bincount is registered as bincount. * @@ -142,7 +144,7 @@ arr_bincount(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) PyArray_Descr *type; PyObject *list = NULL, *weight=Py_None, *mlength=Py_None; PyArrayObject *lst=NULL, *ans=NULL, *wts=NULL; - npy_intp *numbers, *ians, len , mxi, mni, ans_size, minlength; + npy_intp *numbers, *ians, len , mx, mn, ans_size, minlength; int i; double *weights , *dans; static char *kwlist[] = {"list", "weights", "minlength", NULL}; @@ -159,14 +161,22 @@ arr_bincount(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) len = PyArray_SIZE(lst); type = PyArray_DescrFromType(NPY_INTP); - /* handle empty list */ - if (len < 1) { - if (mlength == Py_None) { - minlength = 0; - } - else if (!(minlength = PyArray_PyIntAsIntp(mlength))) { + if (mlength == Py_None) { + minlength = 0; + } + else { + minlength = PyArray_PyIntAsIntp(mlength); + if (minlength <= 0) { + if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "minlength must be positive"); + } goto fail; } + } + + /* handle empty list */ + if (len == 0) { if (!(ans = (PyArrayObject *)PyArray_Zeros(1, &minlength, type, 0))){ goto fail; } @@ -175,24 +185,14 @@ arr_bincount(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) } numbers = (npy_intp *) PyArray_DATA(lst); - mxi = mxx(numbers, len); - mni = mnx(numbers, len); - if (numbers[mni] < 0) { + minmax(numbers, len, &mn, &mx); + if (mn < 0) { PyErr_SetString(PyExc_ValueError, "The first argument of bincount must be non-negative"); goto fail; } - ans_size = numbers [mxi] + 1; + ans_size = mx + 1; if (mlength != Py_None) { - if (!(minlength = PyArray_PyIntAsIntp(mlength))) { - goto fail; - } - if (minlength <= 0) { - /* superfluous, but may catch incorrect usage */ - PyErr_SetString(PyExc_ValueError, - "minlength must be positive"); - goto fail; - } if (ans_size < minlength) { ans_size = minlength; } @@ -680,8 +680,15 @@ arr_interp(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict) slopes[i] = (dy[i + 1] - dy[i])/(dx[i + 1] - dx[i]); } for (i = 0; i < lenx; i++) { - npy_intp j = binary_search(dz[i], dx, lenxp); + const double x = dz[i]; + npy_intp j; + if (npy_isnan(x)) { + dres[i] = x; + continue; + } + + j = binary_search(x, dx, lenxp); if (j == -1) { dres[i] = lval; } @@ -692,7 +699,7 @@ arr_interp(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict) dres[i] = rval; } else { - dres[i] = slopes[j]*(dz[i] - dx[j]) + dy[j]; + dres[i] = slopes[j]*(x - dx[j]) + dy[j]; } } NPY_END_ALLOW_THREADS; @@ -701,8 +708,15 @@ arr_interp(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict) else { NPY_BEGIN_ALLOW_THREADS; for (i = 0; i < lenx; i++) { - npy_intp j = binary_search(dz[i], dx, lenxp); + const double x = dz[i]; + npy_intp j; + + if (npy_isnan(x)) { + dres[i] = x; + continue; + } + j = binary_search(x, dx, lenxp); if (j == -1) { dres[i] = lval; } @@ -713,8 +727,8 @@ arr_interp(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict) dres[i] = rval; } else { - double slope = (dy[j + 1] - dy[j])/(dx[j + 1] - dx[j]); - dres[i] = slope*(dz[i] - dx[j]) + dy[j]; + const double slope = (dy[j + 1] - dy[j])/(dx[j + 1] - dx[j]); + dres[i] = slope*(x - dx[j]) + dy[j]; } } NPY_END_ALLOW_THREADS; @@ -1402,6 +1416,9 @@ _packbits( void *In, npy_intp out_Nm1; int maxi, remain, nonzero, j; char *outptr,*inptr; + NPY_BEGIN_THREADS_DEF; + + NPY_BEGIN_THREADS_THRESHOLDED(out_N); outptr = Out; /* pointer to output buffer */ inptr = In; /* pointer to input buffer */ @@ -1436,6 +1453,8 @@ _packbits( void *In, *outptr = build; outptr += out_stride; } + + NPY_END_THREADS; return; } @@ -1453,6 +1472,9 @@ _unpackbits(void *In, unsigned char mask; int i, index; char *inptr, *outptr; + NPY_BEGIN_THREADS_DEF; + + NPY_BEGIN_THREADS_THRESHOLDED(in_N); outptr = Out; inptr = In; @@ -1465,6 +1487,8 @@ _unpackbits(void *In, } inptr += in_stride; } + + NPY_END_THREADS; return; } diff --git a/numpy/lib/stride_tricks.py b/numpy/lib/stride_tricks.py index d092f92a8..1ffaaee36 100644 --- a/numpy/lib/stride_tricks.py +++ b/numpy/lib/stride_tricks.py @@ -29,7 +29,8 @@ def as_strided(x, shape=None, strides=None): interface['strides'] = tuple(strides) array = np.asarray(DummyArray(interface, base=x)) # Make sure dtype is correct in case of custom dtype - array.dtype = x.dtype + if array.dtype.kind == 'V': + array.dtype = x.dtype return array def broadcast_arrays(*args): diff --git a/numpy/lib/tests/test__version.py b/numpy/lib/tests/test__version.py new file mode 100644 index 000000000..bbafe68eb --- /dev/null +++ b/numpy/lib/tests/test__version.py @@ -0,0 +1,57 @@ +"""Tests for the NumpyVersion class. + +""" +from __future__ import division, absolute_import, print_function + +from numpy.testing import assert_, run_module_suite, assert_raises +from numpy.lib import NumpyVersion + + +def test_main_versions(): + assert_(NumpyVersion('1.8.0') == '1.8.0') + for ver in ['1.9.0', '2.0.0', '1.8.1']: + assert_(NumpyVersion('1.8.0') < ver) + + for ver in ['1.7.0', '1.7.1', '0.9.9']: + assert_(NumpyVersion('1.8.0') > ver) + + +def test_version_1_point_10(): + # regression test for gh-2998. + assert_(NumpyVersion('1.9.0') < '1.10.0') + assert_(NumpyVersion('1.11.0') < '1.11.1') + assert_(NumpyVersion('1.11.0') == '1.11.0') + assert_(NumpyVersion('1.99.11') < '1.99.12') + + +def test_alpha_beta_rc(): + assert_(NumpyVersion('1.8.0rc1') == '1.8.0rc1') + for ver in ['1.8.0', '1.8.0rc2']: + assert_(NumpyVersion('1.8.0rc1') < ver) + + for ver in ['1.8.0a2', '1.8.0b3', '1.7.2rc4']: + assert_(NumpyVersion('1.8.0rc1') > ver) + + assert_(NumpyVersion('1.8.0b1') > '1.8.0a2') + + +def test_dev_version(): + assert_(NumpyVersion('1.9.0.dev-Unknown') < '1.9.0') + for ver in ['1.9.0', '1.9.0a1', '1.9.0b2', '1.9.0b2.dev-ffffffff']: + assert_(NumpyVersion('1.9.0.dev-f16acvda') < ver) + + assert_(NumpyVersion('1.9.0.dev-f16acvda') == '1.9.0.dev-11111111') + + +def test_dev_a_b_rc_mixed(): + assert_(NumpyVersion('1.9.0a2.dev-f16acvda') == '1.9.0a2.dev-11111111') + assert_(NumpyVersion('1.9.0a2.dev-6acvda54') < '1.9.0a2') + + +def test_raises(): + for ver in ['1.9', '1,9.0', '1.7.x']: + assert_raises(ValueError, NumpyVersion, ver) + + +if __name__ == "__main__": + run_module_suite() diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py index 5934ca05a..271943abc 100644 --- a/numpy/lib/tests/test_arraysetops.py +++ b/numpy/lib/tests/test_arraysetops.py @@ -14,31 +14,59 @@ class TestSetOps(TestCase): def test_unique(self): - def check_all(a, b, i1, i2, dt): - msg = "check values failed for type '%s'" % dt + def check_all(a, b, i1, i2, c, dt): + base_msg = 'check {0} failed for type {1}' + + msg = base_msg.format('values', dt) v = unique(a) assert_array_equal(v, b, msg) - msg = "check indexes failed for type '%s'" % dt - v, j = unique(a, 1, 0) + msg = base_msg.format('return_index', dt) + v, j = unique(a, 1, 0, 0) assert_array_equal(v, b, msg) assert_array_equal(j, i1, msg) - msg = "check reverse indexes failed for type '%s'" % dt - v, j = unique(a, 0, 1) + msg = base_msg.format('return_inverse', dt) + v, j = unique(a, 0, 1, 0) assert_array_equal(v, b, msg) assert_array_equal(j, i2, msg) - msg = "check with all indexes failed for type '%s'" % dt - v, j1, j2 = unique(a, 1, 1) + msg = base_msg.format('return_counts', dt) + v, j = unique(a, 0, 0, 1) + assert_array_equal(v, b, msg) + assert_array_equal(j, c, msg) + + msg = base_msg.format('return_index and return_inverse', dt) + v, j1, j2 = unique(a, 1, 1, 0) + assert_array_equal(v, b, msg) + assert_array_equal(j1, i1, msg) + assert_array_equal(j2, i2, msg) + + msg = base_msg.format('return_index and return_counts', dt) + v, j1, j2 = unique(a, 1, 0, 1) + assert_array_equal(v, b, msg) + assert_array_equal(j1, i1, msg) + assert_array_equal(j2, c, msg) + + msg = base_msg.format('return_inverse and return_counts', dt) + v, j1, j2 = unique(a, 0, 1, 1) + assert_array_equal(v, b, msg) + assert_array_equal(j1, i2, msg) + assert_array_equal(j2, c, msg) + + msg = base_msg.format(('return_index, return_inverse ' + 'and return_counts'), dt) + v, j1, j2, j3 = unique(a, 1, 1, 1) assert_array_equal(v, b, msg) assert_array_equal(j1, i1, msg) assert_array_equal(j2, i2, msg) + assert_array_equal(j3, c, msg) a = [5, 7, 1, 2, 1, 5, 7]*10 b = [1, 2, 5, 7] i1 = [2, 3, 0, 1] i2 = [2, 3, 0, 1, 0, 2, 3]*10 + c = np.multiply([2, 1, 2, 2], 10) # test for numeric arrays types = [] @@ -49,7 +77,7 @@ class TestSetOps(TestCase): for dt in types: aa = np.array(a, dt) bb = np.array(b, dt) - check_all(aa, bb, i1, i2, dt) + check_all(aa, bb, i1, i2, c, dt) # test for object arrays dt = 'O' @@ -57,13 +85,27 @@ class TestSetOps(TestCase): aa[:] = a bb = np.empty(len(b), dt) bb[:] = b - check_all(aa, bb, i1, i2, dt) + check_all(aa, bb, i1, i2, c, dt) # test for structured arrays dt = [('', 'i'), ('', 'i')] aa = np.array(list(zip(a, a)), dt) bb = np.array(list(zip(b, b)), dt) - check_all(aa, bb, i1, i2, dt) + check_all(aa, bb, i1, i2, c, dt) + + # test for ticket #2799 + aa = [1.+0.j, 1- 1.j, 1] + assert_array_equal(np.unique(aa), [ 1.-1.j, 1.+0.j]) + + # test for ticket #4785 + a = [(1, 2), (1, 2), (2, 3)] + unq = [1, 2, 3] + inv = [0, 1, 0, 1, 1, 2] + a1 = unique(a) + assert_array_equal(a1, unq) + a2, a2_inv = unique(a, return_inverse=True) + assert_array_equal(a2, unq) + assert_array_equal(a2_inv, inv) def test_intersect1d(self): # unique inputs diff --git a/numpy/lib/tests/test_financial.py b/numpy/lib/tests/test_financial.py index 6b7c6ef53..41a060a3f 100644 --- a/numpy/lib/tests/test_financial.py +++ b/numpy/lib/tests/test_financial.py @@ -13,6 +13,21 @@ class TestFinancial(TestCase): v = [-150000, 15000, 25000, 35000, 45000, 60000] assert_almost_equal(np.irr(v), 0.0524, 2) + v = [-100, 0, 0, 74] + assert_almost_equal(np.irr(v), + -0.0955, 2) + v = [-100, 39, 59, 55, 20] + assert_almost_equal(np.irr(v), + 0.28095, 2) + v = [-100, 100, 0, -7] + assert_almost_equal(np.irr(v), + -0.0833, 2) + v = [-100, 100, 0, 7] + assert_almost_equal(np.irr(v), + 0.06206, 2) + v = [-5, 10.5, 1, -8, 1] + assert_almost_equal(np.irr(v), + 0.0886, 2) def test_pv(self): assert_almost_equal(np.pv(0.07, 20, 12000, 0), diff --git a/numpy/lib/tests/test_format.py b/numpy/lib/tests/test_format.py index b9be643c8..1034b5125 100644 --- a/numpy/lib/tests/test_format.py +++ b/numpy/lib/tests/test_format.py @@ -280,6 +280,7 @@ import sys import os import shutil import tempfile +import warnings from io import BytesIO import numpy as np @@ -521,19 +522,71 @@ def test_compressed_roundtrip(): assert_array_equal(arr, arr1) -def test_write_version_1_0(): +def test_version_2_0(): + f = BytesIO() + # requires more than 2 byte for header + dt = [(("%d" % i) * 100, float) for i in range(500)] + d = np.ones(1000, dtype=dt) + + format.write_array(f, d, version=(2, 0)) + with warnings.catch_warnings(record=True) as w: + warnings.filterwarnings('always', '', UserWarning) + format.write_array(f, d) + assert_(w[0].category is UserWarning) + + f.seek(0) + n = format.read_array(f) + assert_array_equal(d, n) + + # 1.0 requested but data cannot be saved this way + assert_raises(ValueError, format.write_array, f, d, (1, 0)) + + +def test_version_2_0_memmap(): + # requires more than 2 byte for header + dt = [(("%d" % i) * 100, float) for i in range(500)] + d = np.ones(1000, dtype=dt) + tf = tempfile.mktemp('', 'mmap', dir=tempdir) + + # 1.0 requested but data cannot be saved this way + assert_raises(ValueError, format.open_memmap, tf, mode='w+', dtype=d.dtype, + shape=d.shape, version=(1, 0)) + + ma = format.open_memmap(tf, mode='w+', dtype=d.dtype, + shape=d.shape, version=(2, 0)) + ma[...] = d + del ma + + with warnings.catch_warnings(record=True) as w: + warnings.filterwarnings('always', '', UserWarning) + ma = format.open_memmap(tf, mode='w+', dtype=d.dtype, + shape=d.shape, version=None) + assert_(w[0].category is UserWarning) + ma[...] = d + del ma + + ma = format.open_memmap(tf, mode='r') + assert_array_equal(ma, d) + + +def test_write_version(): f = BytesIO() arr = np.arange(1) # These should pass. format.write_array(f, arr, version=(1, 0)) format.write_array(f, arr) + format.write_array(f, arr, version=None) + format.write_array(f, arr) + + format.write_array(f, arr, version=(2, 0)) + format.write_array(f, arr) + # These should all fail. bad_versions = [ (1, 1), (0, 0), (0, 1), - (2, 0), (2, 2), (255, 255), ] @@ -620,5 +673,32 @@ def test_bad_header(): format.write_array_header_1_0(s, d) assert_raises(ValueError, format.read_array_header_1_0, s) + +def test_large_file_support(): + from nose import SkipTest + # try creating a large sparse file + with tempfile.NamedTemporaryFile() as tf: + try: + # seek past end would work too, but linux truncate somewhat + # increases the chances that we have a sparse filesystem and can + # avoid actually writing 5GB + import subprocess as sp + sp.check_call(["truncate", "-s", "5368709120", tf.name]) + except: + raise SkipTest("Could not create 5GB large file") + # write a small array to the end + f = open(tf.name, "wb") + f.seek(5368709120) + d = np.arange(5) + np.save(f, d) + f.close() + # read it back + f = open(tf.name, "rb") + f.seek(5368709120) + r = np.load(f) + f.close() + assert_array_equal(r, d) + + if __name__ == "__main__": run_module_suite() diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index 494b512f7..ac677a308 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -6,7 +6,7 @@ import numpy as np from numpy.testing import ( run_module_suite, TestCase, assert_, assert_equal, assert_array_equal, assert_almost_equal, assert_array_almost_equal, assert_raises, - assert_allclose, assert_array_max_ulp, assert_warns + assert_allclose, assert_array_max_ulp, assert_warns, assert_raises_regex ) from numpy.random import rand from numpy.lib import * @@ -150,6 +150,13 @@ class TestAverage(TestCase): class TestSelect(TestCase): + choices = [np.array([1, 2, 3]), + np.array([4, 5, 6]), + np.array([7, 8, 9])] + conditions = [np.array([False, False, False]), + np.array([False, True, False]), + np.array([False, False, True])] + def _select(self, cond, values, default=0): output = [] for m in range(len(cond)): @@ -157,18 +164,62 @@ class TestSelect(TestCase): return output def test_basic(self): - choices = [np.array([1, 2, 3]), - np.array([4, 5, 6]), - np.array([7, 8, 9])] - conditions = [np.array([0, 0, 0]), - np.array([0, 1, 0]), - np.array([0, 0, 1])] + choices = self.choices + conditions = self.conditions assert_array_equal(select(conditions, choices, default=15), self._select(conditions, choices, default=15)) assert_equal(len(choices), 3) assert_equal(len(conditions), 3) + def test_broadcasting(self): + conditions = [np.array(True), np.array([False, True, False])] + choices = [1, np.arange(12).reshape(4, 3)] + assert_array_equal(select(conditions, choices), np.ones((4, 3))) + # default can broadcast too: + assert_equal(select([True], [0], default=[0]).shape, (1,)) + + def test_return_dtype(self): + assert_equal(select(self.conditions, self.choices, 1j).dtype, + np.complex_) + # But the conditions need to be stronger then the scalar default + # if it is scalar. + choices = [choice.astype(np.int8) for choice in self.choices] + assert_equal(select(self.conditions, choices).dtype, np.int8) + + d = np.array([1, 2, 3, np.nan, 5, 7]) + m = np.isnan(d) + assert_equal(select([m], [d]), [0, 0, 0, np.nan, 0, 0]) + + def test_deprecated_empty(self): + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + assert_equal(select([], [], 3j), 3j) + + with warnings.catch_warnings(): + warnings.simplefilter("always") + assert_warns(DeprecationWarning, select, [], []) + warnings.simplefilter("error") + assert_raises(DeprecationWarning, select, [], []) + + def test_non_bool_deprecation(self): + choices = self.choices + conditions = self.conditions[:] + with warnings.catch_warnings(): + warnings.filterwarnings("always") + conditions[0] = conditions[0].astype(np.int_) + assert_warns(DeprecationWarning, select, conditions, choices) + conditions[0] = conditions[0].astype(np.uint8) + assert_warns(DeprecationWarning, select, conditions, choices) + warnings.filterwarnings("error") + assert_raises(DeprecationWarning, select, conditions, choices) + + def test_many_arguments(self): + # This used to be limited by NPY_MAXARGS == 32 + conditions = [np.array([False])] * 100 + choices = [np.array([1])] * 100 + select(conditions, choices) + class TestInsert(TestCase): def test_basic(self): @@ -249,7 +300,7 @@ class TestInsert(TestCase): assert_(isinstance(np.insert(a, [], []), SubClass)) assert_(isinstance(np.insert(a, [0, 1], [1, 2]), SubClass)) assert_(isinstance(np.insert(a, slice(1, 2), [1, 2]), SubClass)) - assert_(isinstance(np.insert(a, slice(1, -2), []), SubClass)) + assert_(isinstance(np.insert(a, slice(1, -2, -1), []), SubClass)) # This is an error in the future: a = np.array(1).view(SubClass) assert_(isinstance(np.insert(a, 0, [0]), SubClass)) @@ -721,6 +772,12 @@ class TestVectorize(TestCase): assert_array_equal(f(x), x*x) assert_equal(_calls[0], len(x)) + def test_otypes(self): + f = np.vectorize(lambda x: x) + f.otypes = 'i' + x = np.arange(5) + assert_array_equal(f(x), x) + class TestDigitize(TestCase): def test_forward(self): @@ -761,6 +818,22 @@ class TestDigitize(TestCase): bins = np.linspace(x.min(), x.max(), 10) assert_(np.all(digitize(x, bins, True) != 10)) + def test_monotonic(self): + x = [-1, 0, 1, 2] + bins = [0, 0, 1] + assert_array_equal(digitize(x, bins, False), [0, 2, 3, 3]) + assert_array_equal(digitize(x, bins, True), [0, 0, 2, 3]) + bins = [1, 1, 0] + assert_array_equal(digitize(x, bins, False), [3, 2, 0, 0]) + assert_array_equal(digitize(x, bins, True), [3, 3, 2, 0]) + bins = [1, 1, 1, 1] + assert_array_equal(digitize(x, bins, False), [0, 0, 4, 4]) + assert_array_equal(digitize(x, bins, True), [0, 0, 0, 4]) + bins = [0, 0, 1, 0] + assert_raises(ValueError, digitize, x, bins) + bins = [1, 1, 0, 1] + assert_raises(ValueError, digitize, x, bins) + class TestUnwrap(TestCase): def test_simple(self): @@ -997,6 +1070,13 @@ class TestHistogram(TestCase): h, b = histogram(a, weights=np.ones(10, float)) assert_(issubdtype(h.dtype, float)) + def test_f32_rounding(self): + # gh-4799, check that the rounding of the edges works with float32 + x = np.array([276.318359 , -69.593948 , 21.329449], dtype=np.float32) + y = np.array([5005.689453, 4481.327637, 6010.369629], dtype=np.float32) + counts_hist, xedges, yedges = np.histogram2d(x, y, bins=100) + assert_equal(counts_hist.sum(), 3.) + def test_weights(self): v = rand(100) w = np.ones(100) * 5 @@ -1139,6 +1219,30 @@ class TestHistogramdd(TestCase): h, e = np.histogramdd(x, bins=[3, [-np.inf, 3, np.inf]]) assert_allclose(h, expected) + def test_rightmost_binedge(self): + """Test event very close to rightmost binedge. + See Github issue #4266""" + x = [0.9999999995] + bins = [[0.,0.5,1.0]] + hist, _ = histogramdd(x, bins=bins) + assert_(hist[0] == 0.0) + assert_(hist[1] == 1.) + x = [1.0] + bins = [[0.,0.5,1.0]] + hist, _ = histogramdd(x, bins=bins) + assert_(hist[0] == 0.0) + assert_(hist[1] == 1.) + x = [1.0000000001] + bins = [[0.,0.5,1.0]] + hist, _ = histogramdd(x, bins=bins) + assert_(hist[0] == 0.0) + assert_(hist[1] == 1.) + x = [1.0001] + bins = [[0.,0.5,1.0]] + hist, _ = histogramdd(x, bins=bins) + assert_(hist[0] == 0.0) + assert_(hist[1] == 0.0) + class TestUnique(TestCase): def test_simple(self): @@ -1188,6 +1292,10 @@ class TestCorrCoef(TestCase): [0.66318558, 0.88157256, 0.71483595, -0.51366032, 1., 0.98317823], [0.51532523, 0.78052386, 0.83053601, -0.66173113, 0.98317823, 1.]]) + def test_non_array(self): + assert_almost_equal(np.corrcoef([0, 1, 0], [1, 0, 1]), + [[1., -1.], [-1., 1.]]) + def test_simple(self): assert_almost_equal(corrcoef(self.A), self.res1) assert_almost_equal(corrcoef(self.A, self.B), self.res2) @@ -1206,8 +1314,8 @@ class TestCorrCoef(TestCase): assert_allclose(np.corrcoef(x, y), np.array([[1., -1.j], [1.j, 1.]])) def test_empty(self): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', RuntimeWarning) + with warnings.catch_warnings(record=True): + warnings.simplefilter('always', RuntimeWarning) assert_array_equal(corrcoef(np.array([])), np.nan) assert_array_equal(corrcoef(np.array([]).reshape(0, 2)), np.array([]).reshape(0, 0)) @@ -1216,8 +1324,8 @@ class TestCorrCoef(TestCase): def test_wrong_ddof(self): x = np.array([[0, 2], [1, 1], [2, 0]]).T - with warnings.catch_warnings(): - warnings.simplefilter('ignore', RuntimeWarning) + with warnings.catch_warnings(record=True): + warnings.simplefilter('always', RuntimeWarning) assert_array_equal(corrcoef(x, ddof=5), np.array([[np.nan, np.nan], [np.nan, np.nan]])) @@ -1237,8 +1345,8 @@ class TestCov(TestCase): assert_allclose(cov(x, y), np.array([[1., -1.j], [1.j, 1.]])) def test_empty(self): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', RuntimeWarning) + with warnings.catch_warnings(record=True): + warnings.simplefilter('always', RuntimeWarning) assert_array_equal(cov(np.array([])), np.nan) assert_array_equal(cov(np.array([]).reshape(0, 2)), np.array([]).reshape(0, 0)) @@ -1247,8 +1355,8 @@ class TestCov(TestCase): def test_wrong_ddof(self): x = np.array([[0, 2], [1, 1], [2, 0]]).T - with warnings.catch_warnings(): - warnings.simplefilter('ignore', RuntimeWarning) + with warnings.catch_warnings(record=True): + warnings.simplefilter('always', RuntimeWarning) assert_array_equal(cov(x, ddof=5), np.array([[np.inf, -np.inf], [-np.inf, np.inf]])) @@ -1353,6 +1461,13 @@ class TestMeshgrid(TestCase): assert_array_equal(X, np.array([[1, 2, 3]])) assert_array_equal(Y, np.array([[4], [5], [6], [7]])) + def test_invalid_arguments(self): + # Test that meshgrid complains about invalid arguments + # Regression test for issue #4755: + # https://github.com/numpy/numpy/issues/4755 + assert_raises(TypeError, meshgrid, + [1, 2, 3], [4, 5, 6, 7], indices='ij') + class TestPiecewise(TestCase): def test_simple(self): @@ -1379,6 +1494,7 @@ class TestPiecewise(TestCase): x = piecewise([0, 0], [[False, True]], [lambda x:-1]) assert_array_equal(x, [0, -1]) + def test_two_conditions(self): x = piecewise([1, 2], [[True, False], [False, True]], [3, 4]) assert_array_equal(x, [3, 4]) @@ -1397,6 +1513,15 @@ class TestPiecewise(TestCase): assert_(y.ndim == 0) assert_(y == 0) + x = 5 + y = piecewise(x, [[True], [False]], [1, 0]) + assert_(y.ndim == 0) + assert_(y == 1) + + def test_0d_comparison(self): + x = 3 + y = piecewise(x, [x <= 3, x > 3], [4, 0]) + class TestBincount(TestCase): def test_simple(self): @@ -1445,6 +1570,23 @@ class TestBincount(TestCase): y = np.bincount(x, minlength=5) assert_array_equal(y, np.zeros(5, dtype=int)) + def test_with_incorrect_minlength(self): + x = np.array([], dtype=int) + assert_raises_regex(TypeError, "an integer is required", + lambda: np.bincount(x, minlength="foobar")) + assert_raises_regex(ValueError, "must be positive", + lambda: np.bincount(x, minlength=-1)) + assert_raises_regex(ValueError, "must be positive", + lambda: np.bincount(x, minlength=0)) + + x = np.arange(5) + assert_raises_regex(TypeError, "an integer is required", + lambda: np.bincount(x, minlength="foobar")) + assert_raises_regex(ValueError, "minlength must be positive", + lambda: np.bincount(x, minlength=-1)) + assert_raises_regex(ValueError, "minlength must be positive", + lambda: np.bincount(x, minlength=0)) + class TestInterp(TestCase): def test_exceptions(self): @@ -1474,6 +1616,8 @@ class TestInterp(TestCase): assert_almost_equal(np.interp(x0, x, y), x0) x0 = np.float64(.3) assert_almost_equal(np.interp(x0, x, y), x0) + x0 = np.nan + assert_almost_equal(np.interp(x0, x, y), x0) def test_zero_dimensional_interpolation_point(self): x = np.linspace(0, 1, 5) @@ -1636,6 +1780,8 @@ class TestScoreatpercentile(TestCase): interpolation='foobar') assert_raises(ValueError, np.percentile, [1], 101) assert_raises(ValueError, np.percentile, [1], -1) + assert_raises(ValueError, np.percentile, [1], list(range(50)) + [101]) + assert_raises(ValueError, np.percentile, [1], list(range(50)) + [-0.1]) def test_percentile_list(self): assert_equal(np.percentile([1, 2, 3], 0), 1) @@ -1727,6 +1873,65 @@ class TestScoreatpercentile(TestCase): b = np.percentile([2, 3, 4, 1], [50], overwrite_input=True) assert_equal(b, np.array([2.5])) + def test_extended_axis(self): + o = np.random.normal(size=(71, 23)) + x = np.dstack([o] * 10) + assert_equal(np.percentile(x, 30, axis=(0, 1)), np.percentile(o, 30)) + x = np.rollaxis(x, -1, 0) + assert_equal(np.percentile(x, 30, axis=(-2, -1)), np.percentile(o, 30)) + x = x.swapaxes(0, 1).copy() + assert_equal(np.percentile(x, 30, axis=(0, -1)), np.percentile(o, 30)) + x = x.swapaxes(0, 1).copy() + + assert_equal(np.percentile(x, [25, 60], axis=(0, 1, 2)), + np.percentile(x, [25, 60], axis=None)) + assert_equal(np.percentile(x, [25, 60], axis=(0,)), + np.percentile(x, [25, 60], axis=0)) + + d = np.arange(3 * 5 * 7 * 11).reshape(3, 5, 7, 11) + np.random.shuffle(d) + assert_equal(np.percentile(d, 25, axis=(0, 1, 2))[0], + np.percentile(d[:, :, :, 0].flatten(), 25)) + assert_equal(np.percentile(d, [10, 90], axis=(0, 1, 3))[:, 1], + np.percentile(d[:, :, 1, :].flatten(), [10, 90])) + assert_equal(np.percentile(d, 25, axis=(3, 1, -4))[2], + np.percentile(d[:, :, 2, :].flatten(), 25)) + assert_equal(np.percentile(d, 25, axis=(3, 1, 2))[2], + np.percentile(d[2, :, :, :].flatten(), 25)) + assert_equal(np.percentile(d, 25, axis=(3, 2))[2, 1], + np.percentile(d[2, 1, :, :].flatten(), 25)) + assert_equal(np.percentile(d, 25, axis=(1, -2))[2, 1], + np.percentile(d[2, :, :, 1].flatten(), 25)) + assert_equal(np.percentile(d, 25, axis=(1, 3))[2, 2], + np.percentile(d[2, :, 2, :].flatten(), 25)) + + def test_extended_axis_invalid(self): + d = np.ones((3, 5, 7, 11)) + assert_raises(IndexError, np.percentile, d, axis=-5, q=25) + assert_raises(IndexError, np.percentile, d, axis=(0, -5), q=25) + assert_raises(IndexError, np.percentile, d, axis=4, q=25) + assert_raises(IndexError, np.percentile, d, axis=(0, 4), q=25) + assert_raises(ValueError, np.percentile, d, axis=(1, 1), q=25) + + def test_keepdims(self): + d = np.ones((3, 5, 7, 11)) + assert_equal(np.percentile(d, 7, axis=None, keepdims=True).shape, + (1, 1, 1, 1)) + assert_equal(np.percentile(d, 7, axis=(0, 1), keepdims=True).shape, + (1, 1, 7, 11)) + assert_equal(np.percentile(d, 7, axis=(0, 3), keepdims=True).shape, + (1, 5, 7, 1)) + assert_equal(np.percentile(d, 7, axis=(1,), keepdims=True).shape, + (3, 1, 7, 11)) + assert_equal(np.percentile(d, 7, (0, 1, 2, 3), keepdims=True).shape, + (1, 1, 1, 1)) + assert_equal(np.percentile(d, 7, axis=(0, 1, 3), keepdims=True).shape, + (1, 1, 7, 1)) + + assert_equal(np.percentile(d, [1, 7], axis=(0, 1, 3), + keepdims=True).shape, (2, 1, 1, 7, 1)) + assert_equal(np.percentile(d, [1, 7], axis=(0, 3), + keepdims=True).shape, (2, 1, 5, 7, 1)) class TestMedian(TestCase): @@ -1734,19 +1939,23 @@ class TestMedian(TestCase): a0 = np.array(1) a1 = np.arange(2) a2 = np.arange(6).reshape(2, 3) - assert_allclose(np.median(a0), 1) + assert_equal(np.median(a0), 1) assert_allclose(np.median(a1), 0.5) assert_allclose(np.median(a2), 2.5) assert_allclose(np.median(a2, axis=0), [1.5, 2.5, 3.5]) - assert_allclose(np.median(a2, axis=1), [1, 4]) + assert_equal(np.median(a2, axis=1), [1, 4]) assert_allclose(np.median(a2, axis=None), 2.5) a = np.array([0.0444502, 0.0463301, 0.141249, 0.0606775]) assert_almost_equal((a[1] + a[3]) / 2., np.median(a)) a = np.array([0.0463301, 0.0444502, 0.141249]) - assert_almost_equal(a[0], np.median(a)) + assert_equal(a[0], np.median(a)) a = np.array([0.0444502, 0.141249, 0.0463301]) - assert_almost_equal(a[-1], np.median(a)) + assert_equal(a[-1], np.median(a)) + # check array scalar result + assert_equal(np.median(a).ndim, 0) + a[1] = np.nan + assert_equal(np.median(a).ndim, 0) def test_axis_keyword(self): a3 = np.array([[2, 3], @@ -1820,6 +2029,66 @@ class TestMedian(TestCase): a = MySubClass([1,2,3]) assert_equal(np.median(a), -7) + def test_object(self): + o = np.arange(7.); + assert_(type(np.median(o.astype(object))), float) + o[2] = np.nan + assert_(type(np.median(o.astype(object))), float) + + def test_extended_axis(self): + o = np.random.normal(size=(71, 23)) + x = np.dstack([o] * 10) + assert_equal(np.median(x, axis=(0, 1)), np.median(o)) + x = np.rollaxis(x, -1, 0) + assert_equal(np.median(x, axis=(-2, -1)), np.median(o)) + x = x.swapaxes(0, 1).copy() + assert_equal(np.median(x, axis=(0, -1)), np.median(o)) + + assert_equal(np.median(x, axis=(0, 1, 2)), np.median(x, axis=None)) + assert_equal(np.median(x, axis=(0, )), np.median(x, axis=0)) + assert_equal(np.median(x, axis=(-1, )), np.median(x, axis=-1)) + + d = np.arange(3 * 5 * 7 * 11).reshape(3, 5, 7, 11) + np.random.shuffle(d) + assert_equal(np.median(d, axis=(0, 1, 2))[0], + np.median(d[:, :, :, 0].flatten())) + assert_equal(np.median(d, axis=(0, 1, 3))[1], + np.median(d[:, :, 1, :].flatten())) + assert_equal(np.median(d, axis=(3, 1, -4))[2], + np.median(d[:, :, 2, :].flatten())) + assert_equal(np.median(d, axis=(3, 1, 2))[2], + np.median(d[2, :, :, :].flatten())) + assert_equal(np.median(d, axis=(3, 2))[2, 1], + np.median(d[2, 1, :, :].flatten())) + assert_equal(np.median(d, axis=(1, -2))[2, 1], + np.median(d[2, :, :, 1].flatten())) + assert_equal(np.median(d, axis=(1, 3))[2, 2], + np.median(d[2, :, 2, :].flatten())) + + def test_extended_axis_invalid(self): + d = np.ones((3, 5, 7, 11)) + assert_raises(IndexError, np.median, d, axis=-5) + assert_raises(IndexError, np.median, d, axis=(0, -5)) + assert_raises(IndexError, np.median, d, axis=4) + assert_raises(IndexError, np.median, d, axis=(0, 4)) + assert_raises(ValueError, np.median, d, axis=(1, 1)) + + def test_keepdims(self): + d = np.ones((3, 5, 7, 11)) + assert_equal(np.median(d, axis=None, keepdims=True).shape, + (1, 1, 1, 1)) + assert_equal(np.median(d, axis=(0, 1), keepdims=True).shape, + (1, 1, 7, 11)) + assert_equal(np.median(d, axis=(0, 3), keepdims=True).shape, + (1, 5, 7, 1)) + assert_equal(np.median(d, axis=(1,), keepdims=True).shape, + (3, 1, 7, 11)) + assert_equal(np.median(d, axis=(0, 1, 2, 3), keepdims=True).shape, + (1, 1, 1, 1)) + assert_equal(np.median(d, axis=(0, 1, 3), keepdims=True).shape, + (1, 1, 7, 1)) + + class TestAdd_newdoc_ufunc(TestCase): diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index e3ccb391c..03e238261 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -4,7 +4,7 @@ import sys import gzip import os import threading -from tempfile import mkstemp, mktemp, NamedTemporaryFile +from tempfile import mkstemp, NamedTemporaryFile import time import warnings import gc @@ -17,9 +17,12 @@ from numpy.lib._iotools import (ConverterError, ConverterLockError, ConversionWarning) from numpy.compat import asbytes, asbytes_nested, bytes, asstr from nose import SkipTest -from numpy.ma.testutils import (TestCase, assert_equal, assert_array_equal, - assert_raises, run_module_suite) +from numpy.ma.testutils import ( + TestCase, assert_equal, assert_array_equal, + assert_raises, assert_raises_regex, run_module_suite +) from numpy.testing import assert_warns, assert_, build_err_msg +from numpy.testing.utils import tempdir class TextIO(BytesIO): @@ -77,32 +80,32 @@ class RoundtripTest(object): file_on_disk = kwargs.get('file_on_disk', False) if file_on_disk: - # Do not delete the file on windows, because we can't - # reopen an already opened file on that platform, so we - # need to close the file and reopen it, implying no - # automatic deletion. - if sys.platform == 'win32' and MAJVER >= 2 and MINVER >= 6: - target_file = NamedTemporaryFile(delete=False) - else: - target_file = NamedTemporaryFile() + target_file = NamedTemporaryFile(delete=False) load_file = target_file.name else: target_file = BytesIO() load_file = target_file - arr = args + try: + arr = args - save_func(target_file, *arr, **save_kwds) - target_file.flush() - target_file.seek(0) + save_func(target_file, *arr, **save_kwds) + target_file.flush() + target_file.seek(0) - if sys.platform == 'win32' and not isinstance(target_file, BytesIO): - target_file.close() + if sys.platform == 'win32' and not isinstance(target_file, BytesIO): + target_file.close() - arr_reloaded = np.load(load_file, **load_kwds) + arr_reloaded = np.load(load_file, **load_kwds) - self.arr = arr - self.arr_reloaded = arr_reloaded + self.arr = arr + self.arr_reloaded = arr_reloaded + finally: + if not isinstance(target_file, BytesIO): + target_file.close() + # holds an open file descriptor so it can't be deleted on win + if not isinstance(arr_reloaded, np.lib.npyio.NpzFile): + os.remove(target_file.name) def check_roundtrips(self, a): self.roundtrip(a) @@ -155,6 +158,13 @@ class RoundtripTest(object): a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')]) self.check_roundtrips(a) + def test_format_2_0(self): + dt = [(("%d" % i) * 100, float) for i in range(500)] + a = np.ones(1000, dtype=dt) + with warnings.catch_warnings(record=True): + warnings.filterwarnings('always', '', UserWarning) + self.check_roundtrips(a) + class TestSaveLoad(RoundtripTest, TestCase): def roundtrip(self, *args, **kwargs): @@ -167,24 +177,30 @@ class TestSaveLoad(RoundtripTest, TestCase): class TestSavezLoad(RoundtripTest, TestCase): def roundtrip(self, *args, **kwargs): RoundtripTest.roundtrip(self, np.savez, *args, **kwargs) - for n, arr in enumerate(self.arr): - reloaded = self.arr_reloaded['arr_%d' % n] - assert_equal(arr, reloaded) - assert_equal(arr.dtype, reloaded.dtype) - assert_equal(arr.flags.fnc, reloaded.flags.fnc) + try: + for n, arr in enumerate(self.arr): + reloaded = self.arr_reloaded['arr_%d' % n] + assert_equal(arr, reloaded) + assert_equal(arr.dtype, reloaded.dtype) + assert_equal(arr.flags.fnc, reloaded.flags.fnc) + finally: + # delete tempfile, must be done here on windows + if self.arr_reloaded.fid: + self.arr_reloaded.fid.close() + os.remove(self.arr_reloaded.fid.name) @np.testing.dec.skipif(not IS_64BIT, "Works only with 64bit systems") @np.testing.dec.slow def test_big_arrays(self): L = (1 << 31) + 100000 - tmp = mktemp(suffix='.npz') a = np.empty(L, dtype=np.uint8) - np.savez(tmp, a=a) - del a - npfile = np.load(tmp) - a = npfile['a'] - npfile.close() - os.remove(tmp) + with tempdir(prefix="numpy_test_big_arrays_") as tmpdir: + tmp = os.path.join(tmpdir, "file.npz") + np.savez(tmp, a=a) + del a + npfile = np.load(tmp) + a = npfile['a'] + npfile.close() def test_multiple_arrays(self): a = np.array([[1, 2], [3, 4]], float) @@ -287,13 +303,14 @@ class TestSavezLoad(RoundtripTest, TestCase): # Check that zipfile owns file and can close it. # This needs to pass a file name to load for the # test. - fd, tmp = mkstemp(suffix='.npz') - os.close(fd) - np.savez(tmp, lab='place holder') - data = np.load(tmp) - fp = data.zip.fp - data.close() - assert_(fp.closed) + with tempdir(prefix="numpy_test_closing_zipfile_after_load_") as tmpdir: + fd, tmp = mkstemp(suffix='.npz', dir=tmpdir) + os.close(fd) + np.savez(tmp, lab='place holder') + data = np.load(tmp) + fp = data.zip.fp + data.close() + assert_(fp.closed) class TestSaveTxt(TestCase): @@ -750,6 +767,14 @@ class TestLoadTxt(TestCase): res = np.loadtxt(count()) assert_array_equal(res, np.arange(10)) + def test_bad_line(self): + c = TextIO() + c.write('1 2 3\n4 5 6\n2 3') + c.seek(0) + + # Check for exception and that exception contains line number + assert_raises_regex(ValueError, "3", np.loadtxt, c) + class Testfromregex(TestCase): # np.fromregex expects files opened in binary mode. @@ -1563,6 +1588,14 @@ M 33 21.99 dtype=[('a', np.int), ('b', np.int)]) self.assertTrue(isinstance(test, np.recarray)) assert_equal(test, control) + # + data = TextIO('A,B\n0,1\n2,3') + dtype = [('a', np.int), ('b', np.float)] + test = np.recfromcsv(data, missing_values='N/A', dtype=dtype) + control = np.array([(0, 1), (2, 3)], + dtype=dtype) + self.assertTrue(isinstance(test, np.recarray)) + assert_equal(test, control) def test_gft_using_filename(self): # Test that we can load data from a filename as well as a file object diff --git a/numpy/lib/tests/test_nanfunctions.py b/numpy/lib/tests/test_nanfunctions.py index af01a7167..c5af61434 100644 --- a/numpy/lib/tests/test_nanfunctions.py +++ b/numpy/lib/tests/test_nanfunctions.py @@ -5,21 +5,21 @@ import warnings import numpy as np from numpy.testing import ( run_module_suite, TestCase, assert_, assert_equal, assert_almost_equal, - assert_raises + assert_raises, assert_array_equal ) # Test data _ndat = np.array([[0.6244, np.nan, 0.2692, 0.0116, np.nan, 0.1170], - [0.5351, 0.9403, np.nan, 0.2100, 0.4759, 0.2833], - [np.nan, np.nan, np.nan, 0.1042, np.nan, 0.5954], + [0.5351, -0.9403, np.nan, 0.2100, 0.4759, 0.2833], + [np.nan, np.nan, np.nan, 0.1042, np.nan, -0.5954], [0.1610, np.nan, np.nan, 0.1859, 0.3146, np.nan]]) # Rows of _ndat with nans removed _rdat = [np.array([ 0.6244, 0.2692, 0.0116, 0.1170]), - np.array([ 0.5351, 0.9403, 0.2100, 0.4759, 0.2833]), - np.array([ 0.1042, 0.5954]), + np.array([ 0.5351, -0.9403, 0.2100, 0.4759, 0.2833]), + np.array([ 0.1042, -0.5954]), np.array([ 0.1610, 0.1859, 0.3146])] @@ -114,6 +114,31 @@ class TestNanFunctions_MinMax(TestCase): assert_(res.shape == (3, 1)) res = f(mat) assert_(np.isscalar(res)) + # check that rows of nan are dealt with for subclasses (#4628) + mat[1] = np.nan + for f in self.nanfuncs: + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + res = f(mat, axis=0) + assert_(isinstance(res, np.matrix)) + assert_(not np.any(np.isnan(res))) + assert_(len(w) == 0) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + res = f(mat, axis=1) + assert_(isinstance(res, np.matrix)) + assert_(np.isnan(res[1, 0]) and not np.isnan(res[0, 0]) + and not np.isnan(res[2, 0])) + assert_(len(w) == 1, 'no warning raised') + assert_(issubclass(w[0].category, RuntimeWarning)) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + res = f(mat) + assert_(np.isscalar(res)) + assert_(res != np.nan) + assert_(len(w) == 0) class TestNanFunctions_ArgminArgmax(TestCase): @@ -130,8 +155,8 @@ class TestNanFunctions_ArgminArgmax(TestCase): def test_result_values(self): for f, fcmp in zip(self.nanfuncs, [np.greater, np.less]): for row in _ndat: - with warnings.catch_warnings(): - warnings.simplefilter('ignore') + with warnings.catch_warnings(record=True): + warnings.simplefilter('always') ind = f(row) val = row[ind] # comparing with NaN is tricky as the result @@ -502,5 +527,232 @@ class TestNanFunctions_MeanVarStd(TestCase): assert_(np.isscalar(res)) +class TestNanFunctions_Median(TestCase): + + def test_mutation(self): + # Check that passed array is not modified. + ndat = _ndat.copy() + np.nanmedian(ndat) + assert_equal(ndat, _ndat) + + def test_keepdims(self): + mat = np.eye(3) + for axis in [None, 0, 1]: + tgt = np.median(mat, axis=axis, out=None, overwrite_input=False) + res = np.nanmedian(mat, axis=axis, out=None, overwrite_input=False) + assert_(res.ndim == tgt.ndim) + + d = np.ones((3, 5, 7, 11)) + # Randomly set some elements to NaN: + w = np.random.random((4, 200)) * np.array(d.shape)[:, None] + w = w.astype(np.intp) + d[tuple(w)] = np.nan + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always', RuntimeWarning) + res = np.nanmedian(d, axis=None, keepdims=True) + assert_equal(res.shape, (1, 1, 1, 1)) + res = np.nanmedian(d, axis=(0, 1), keepdims=True) + assert_equal(res.shape, (1, 1, 7, 11)) + res = np.nanmedian(d, axis=(0, 3), keepdims=True) + assert_equal(res.shape, (1, 5, 7, 1)) + res = np.nanmedian(d, axis=(1,), keepdims=True) + assert_equal(res.shape, (3, 1, 7, 11)) + res = np.nanmedian(d, axis=(0, 1, 2, 3), keepdims=True) + assert_equal(res.shape, (1, 1, 1, 1)) + res = np.nanmedian(d, axis=(0, 1, 3), keepdims=True) + assert_equal(res.shape, (1, 1, 7, 1)) + + def test_out(self): + mat = np.random.rand(3, 3) + nan_mat = np.insert(mat, [0, 2], np.nan, axis=1) + resout = np.zeros(3) + tgt = np.median(mat, axis=1) + res = np.nanmedian(nan_mat, axis=1, out=resout) + assert_almost_equal(res, resout) + assert_almost_equal(res, tgt) + # 0-d output: + resout = np.zeros(()) + tgt = np.median(mat, axis=None) + res = np.nanmedian(nan_mat, axis=None, out=resout) + assert_almost_equal(res, resout) + assert_almost_equal(res, tgt) + res = np.nanmedian(nan_mat, axis=(0, 1), out=resout) + assert_almost_equal(res, resout) + assert_almost_equal(res, tgt) + + def test_small_large(self): + # test the small and large code paths, current cutoff 400 elements + for s in [5, 20, 51, 200, 1000]: + d = np.random.randn(4, s) + # Randomly set some elements to NaN: + w = np.random.randint(0, d.size, size=d.size // 5) + d.ravel()[w] = np.nan + d[:,0] = 1. # ensure at least one good value + # use normal median without nans to compare + tgt = [] + for x in d: + nonan = np.compress(~np.isnan(x), x) + tgt.append(np.median(nonan, overwrite_input=True)) + + assert_array_equal(np.nanmedian(d, axis=-1), tgt) + + def test_result_values(self): + tgt = [np.median(d) for d in _rdat] + res = np.nanmedian(_ndat, axis=1) + assert_almost_equal(res, tgt) + + def test_allnans(self): + mat = np.array([np.nan]*9).reshape(3, 3) + for axis in [None, 0, 1]: + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + assert_(np.isnan(np.nanmedian(mat, axis=axis)).all()) + if axis is None: + assert_(len(w) == 1) + else: + assert_(len(w) == 3) + assert_(issubclass(w[0].category, RuntimeWarning)) + # Check scalar + assert_(np.isnan(np.nanmedian(np.nan))) + if axis is None: + assert_(len(w) == 2) + else: + assert_(len(w) == 4) + assert_(issubclass(w[0].category, RuntimeWarning)) + + def test_empty(self): + mat = np.zeros((0, 3)) + for axis in [0, None]: + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + assert_(np.isnan(np.nanmedian(mat, axis=axis)).all()) + assert_(len(w) == 1) + assert_(issubclass(w[0].category, RuntimeWarning)) + for axis in [1]: + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + assert_equal(np.nanmedian(mat, axis=axis), np.zeros([])) + assert_(len(w) == 0) + + def test_scalar(self): + assert_(np.nanmedian(0.) == 0.) + + def test_extended_axis_invalid(self): + d = np.ones((3, 5, 7, 11)) + assert_raises(IndexError, np.nanmedian, d, axis=-5) + assert_raises(IndexError, np.nanmedian, d, axis=(0, -5)) + assert_raises(IndexError, np.nanmedian, d, axis=4) + assert_raises(IndexError, np.nanmedian, d, axis=(0, 4)) + assert_raises(ValueError, np.nanmedian, d, axis=(1, 1)) + + +class TestNanFunctions_Percentile(TestCase): + + def test_mutation(self): + # Check that passed array is not modified. + ndat = _ndat.copy() + np.nanpercentile(ndat, 30) + assert_equal(ndat, _ndat) + + def test_keepdims(self): + mat = np.eye(3) + for axis in [None, 0, 1]: + tgt = np.percentile(mat, 70, axis=axis, out=None, + overwrite_input=False) + res = np.nanpercentile(mat, 70, axis=axis, out=None, + overwrite_input=False) + assert_(res.ndim == tgt.ndim) + + d = np.ones((3, 5, 7, 11)) + # Randomly set some elements to NaN: + w = np.random.random((4, 200)) * np.array(d.shape)[:, None] + w = w.astype(np.intp) + d[tuple(w)] = np.nan + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always', RuntimeWarning) + res = np.nanpercentile(d, 90, axis=None, keepdims=True) + assert_equal(res.shape, (1, 1, 1, 1)) + res = np.nanpercentile(d, 90, axis=(0, 1), keepdims=True) + assert_equal(res.shape, (1, 1, 7, 11)) + res = np.nanpercentile(d, 90, axis=(0, 3), keepdims=True) + assert_equal(res.shape, (1, 5, 7, 1)) + res = np.nanpercentile(d, 90, axis=(1,), keepdims=True) + assert_equal(res.shape, (3, 1, 7, 11)) + res = np.nanpercentile(d, 90, axis=(0, 1, 2, 3), keepdims=True) + assert_equal(res.shape, (1, 1, 1, 1)) + res = np.nanpercentile(d, 90, axis=(0, 1, 3), keepdims=True) + assert_equal(res.shape, (1, 1, 7, 1)) + + def test_out(self): + mat = np.random.rand(3, 3) + nan_mat = np.insert(mat, [0, 2], np.nan, axis=1) + resout = np.zeros(3) + tgt = np.percentile(mat, 42, axis=1) + res = np.nanpercentile(nan_mat, 42, axis=1, out=resout) + assert_almost_equal(res, resout) + assert_almost_equal(res, tgt) + # 0-d output: + resout = np.zeros(()) + tgt = np.percentile(mat, 42, axis=None) + res = np.nanpercentile(nan_mat, 42, axis=None, out=resout) + assert_almost_equal(res, resout) + assert_almost_equal(res, tgt) + res = np.nanpercentile(nan_mat, 42, axis=(0, 1), out=resout) + assert_almost_equal(res, resout) + assert_almost_equal(res, tgt) + + def test_result_values(self): + tgt = [np.percentile(d, 28) for d in _rdat] + res = np.nanpercentile(_ndat, 28, axis=1) + assert_almost_equal(res, tgt) + tgt = [np.percentile(d, (28, 98)) for d in _rdat] + res = np.nanpercentile(_ndat, (28, 98), axis=1) + assert_almost_equal(res, tgt) + + def test_allnans(self): + mat = np.array([np.nan]*9).reshape(3, 3) + for axis in [None, 0, 1]: + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + assert_(np.isnan(np.nanpercentile(mat, 60, axis=axis)).all()) + if axis is None: + assert_(len(w) == 1) + else: + assert_(len(w) == 3) + assert_(issubclass(w[0].category, RuntimeWarning)) + # Check scalar + assert_(np.isnan(np.nanpercentile(np.nan, 60))) + if axis is None: + assert_(len(w) == 2) + else: + assert_(len(w) == 4) + assert_(issubclass(w[0].category, RuntimeWarning)) + + def test_empty(self): + mat = np.zeros((0, 3)) + for axis in [0, None]: + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + assert_(np.isnan(np.nanpercentile(mat, 40, axis=axis)).all()) + assert_(len(w) == 1) + assert_(issubclass(w[0].category, RuntimeWarning)) + for axis in [1]: + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + assert_equal(np.nanpercentile(mat, 40, axis=axis), np.zeros([])) + assert_(len(w) == 0) + + def test_scalar(self): + assert_(np.nanpercentile(0., 100) == 0.) + + def test_extended_axis_invalid(self): + d = np.ones((3, 5, 7, 11)) + assert_raises(IndexError, np.nanpercentile, d, q=5, axis=-5) + assert_raises(IndexError, np.nanpercentile, d, q=5, axis=(0, -5)) + assert_raises(IndexError, np.nanpercentile, d, q=5, axis=4) + assert_raises(IndexError, np.nanpercentile, d, q=5, axis=(0, 4)) + assert_raises(ValueError, np.nanpercentile, d, q=5, axis=(1, 1)) + + if __name__ == "__main__": run_module_suite() diff --git a/numpy/lib/tests/test_stride_tricks.py b/numpy/lib/tests/test_stride_tricks.py index 4d57d2ca7..3adcf0b41 100644 --- a/numpy/lib/tests/test_stride_tricks.py +++ b/numpy/lib/tests/test_stride_tricks.py @@ -3,6 +3,7 @@ from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import * from numpy.lib.stride_tricks import broadcast_arrays +from numpy.lib.stride_tricks import as_strided def assert_shapes_correct(input_shapes, expected_shape): @@ -214,6 +215,22 @@ def test_same_as_ufunc(): assert_same_as_ufunc(input_shapes[0], input_shapes[1], False, True) assert_same_as_ufunc(input_shapes[0], input_shapes[1], True, True) +def test_as_strided(): + a = np.array([None]) + a_view = as_strided(a) + expected = np.array([None]) + assert_array_equal(a_view, np.array([None])) + + a = np.array([1, 2, 3, 4]) + a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,)) + expected = np.array([1, 3]) + assert_array_equal(a_view, expected) + + a = np.array([1, 2, 3, 4]) + a_view = as_strided(a, shape=(3, 4), strides=(0, 1 * a.itemsize)) + expected = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) + assert_array_equal(a_view, expected) + if __name__ == "__main__": run_module_suite() diff --git a/numpy/lib/tests/test_twodim_base.py b/numpy/lib/tests/test_twodim_base.py index 8d0275a25..f5b8fab4a 100644 --- a/numpy/lib/tests/test_twodim_base.py +++ b/numpy/lib/tests/test_twodim_base.py @@ -254,7 +254,7 @@ class TestHistogram2d(TestCase): assert_array_almost_equal(H, answer, 3) def test_all_outliers(self): - r = rand(100)+1. + r = rand(100) + 1. + 1e6 # histogramdd rounds by decimal=6 H, xed, yed = histogram2d(r, r, (4, 5), range=([0, 1], [0, 1])) assert_array_equal(H, 0) @@ -275,16 +275,41 @@ class TestTri(TestCase): assert_array_equal(tri(3, dtype=bool), out.astype(bool)) -def test_tril_triu(): +def test_tril_triu_ndim2(): for dtype in np.typecodes['AllFloat'] + np.typecodes['AllInteger']: a = np.ones((2, 2), dtype=dtype) b = np.tril(a) c = np.triu(a) - assert_array_equal(b, [[1, 0], [1, 1]]) - assert_array_equal(c, b.T) + yield assert_array_equal, b, [[1, 0], [1, 1]] + yield assert_array_equal, c, b.T # should return the same dtype as the original array - assert_equal(b.dtype, a.dtype) - assert_equal(c.dtype, a.dtype) + yield assert_equal, b.dtype, a.dtype + yield assert_equal, c.dtype, a.dtype + + +def test_tril_triu_ndim3(): + for dtype in np.typecodes['AllFloat'] + np.typecodes['AllInteger']: + a = np.array([ + [[1, 1], [1, 1]], + [[1, 1], [1, 0]], + [[1, 1], [0, 0]], + ], dtype=dtype) + a_tril_desired = np.array([ + [[1, 0], [1, 1]], + [[1, 0], [1, 0]], + [[1, 0], [0, 0]], + ], dtype=dtype) + a_triu_desired = np.array([ + [[1, 1], [0, 1]], + [[1, 1], [0, 0]], + [[1, 1], [0, 0]], + ], dtype=dtype) + a_triu_observed = np.triu(a) + a_tril_observed = np.tril(a) + yield assert_array_equal, a_triu_observed, a_triu_desired + yield assert_array_equal, a_tril_observed, a_tril_desired + yield assert_equal, a_triu_observed.dtype, a.dtype + yield assert_equal, a_tril_observed.dtype, a.dtype def test_mask_indices(): @@ -300,16 +325,21 @@ def test_mask_indices(): def test_tril_indices(): # indices without and with offset il1 = tril_indices(4) - il2 = tril_indices(4, 2) + il2 = tril_indices(4, k=2) + il3 = tril_indices(4, m=5) + il4 = tril_indices(4, k=2, m=5) a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) + b = np.arange(1, 21).reshape(4, 5) # indexing: yield (assert_array_equal, a[il1], array([1, 5, 6, 9, 10, 11, 13, 14, 15, 16])) + yield (assert_array_equal, b[il3], + array([1, 6, 7, 11, 12, 13, 16, 17, 18, 19])) # And for assigning values: a[il1] = -1 @@ -318,7 +348,12 @@ def test_tril_indices(): [-1, -1, 7, 8], [-1, -1, -1, 12], [-1, -1, -1, -1]])) - + b[il3] = -1 + yield (assert_array_equal, b, + array([[-1, 2, 3, 4, 5], + [-1, -1, 8, 9, 10], + [-1, -1, -1, 14, 15], + [-1, -1, -1, -1, 20]])) # These cover almost the whole array (two diagonals right of the main one): a[il2] = -10 yield (assert_array_equal, a, @@ -326,21 +361,32 @@ def test_tril_indices(): [-10, -10, -10, -10], [-10, -10, -10, -10], [-10, -10, -10, -10]])) + b[il4] = -10 + yield (assert_array_equal, b, + array([[-10, -10, -10, 4, 5], + [-10, -10, -10, -10, 10], + [-10, -10, -10, -10, -10], + [-10, -10, -10, -10, -10]])) class TestTriuIndices(object): def test_triu_indices(self): iu1 = triu_indices(4) - iu2 = triu_indices(4, 2) + iu2 = triu_indices(4, k=2) + iu3 = triu_indices(4, m=5) + iu4 = triu_indices(4, k=2, m=5) a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) + b = np.arange(1, 21).reshape(4, 5) # Both for indexing: yield (assert_array_equal, a[iu1], array([1, 2, 3, 4, 6, 7, 8, 11, 12, 16])) + yield (assert_array_equal, b[iu3], + array([1, 2, 3, 4, 5, 7, 8, 9, 10, 13, 14, 15, 19, 20])) # And for assigning values: a[iu1] = -1 @@ -349,6 +395,12 @@ class TestTriuIndices(object): [5, -1, -1, -1], [9, 10, -1, -1], [13, 14, 15, -1]])) + b[iu3] = -1 + yield (assert_array_equal, b, + array([[-1, -1, -1, -1, -1], + [ 6, -1, -1, -1, -1], + [11, 12, -1, -1, -1], + [16, 17, 18, -1, -1]])) # These cover almost the whole array (two diagonals right of the # main one): @@ -358,20 +410,26 @@ class TestTriuIndices(object): [5, -1, -1, -10], [9, 10, -1, -1], [13, 14, 15, -1]])) + b[iu4] = -10 + yield (assert_array_equal, b, + array([[-1, -1, -10, -10, -10], + [6, -1, -1, -10, -10], + [11, 12, -1, -1, -10], + [16, 17, 18, -1, -1]])) class TestTrilIndicesFrom(object): def test_exceptions(self): assert_raises(ValueError, tril_indices_from, np.ones((2,))) assert_raises(ValueError, tril_indices_from, np.ones((2, 2, 2))) - assert_raises(ValueError, tril_indices_from, np.ones((2, 3))) + # assert_raises(ValueError, tril_indices_from, np.ones((2, 3))) class TestTriuIndicesFrom(object): def test_exceptions(self): assert_raises(ValueError, triu_indices_from, np.ones((2,))) assert_raises(ValueError, triu_indices_from, np.ones((2, 2, 2))) - assert_raises(ValueError, triu_indices_from, np.ones((2, 3))) + # assert_raises(ValueError, triu_indices_from, np.ones((2, 3))) class TestVander(object): diff --git a/numpy/lib/tests/test_utils.py b/numpy/lib/tests/test_utils.py index 93c674766..36d5d6428 100644 --- a/numpy/lib/tests/test_utils.py +++ b/numpy/lib/tests/test_utils.py @@ -1,6 +1,7 @@ from __future__ import division, absolute_import, print_function import sys +from numpy.core import arange from numpy.testing import * import numpy.lib.utils as utils from numpy.lib import deprecate @@ -46,9 +47,17 @@ def test_deprecate_fn(): assert_('old_func3' in new_func3.__doc__) assert_('new_func3' in new_func3.__doc__) + def test_safe_eval_nameconstant(): # Test if safe_eval supports Python 3.4 _ast.NameConstant utils.safe_eval('None') + +def test_byte_bounds(): + a = arange(12).reshape(3, 4) + low, high = utils.byte_bounds(a) + assert_equal(high - low, a.size * a.itemsize) + + if __name__ == "__main__": run_module_suite() diff --git a/numpy/lib/twodim_base.py b/numpy/lib/twodim_base.py index 12c0f9bb3..a8925592a 100644 --- a/numpy/lib/twodim_base.py +++ b/numpy/lib/twodim_base.py @@ -11,8 +11,23 @@ __all__ = ['diag', 'diagflat', 'eye', 'fliplr', 'flipud', 'rot90', 'tri', from numpy.core.numeric import ( asanyarray, subtract, arange, zeros, greater_equal, multiply, ones, - asarray, where, + asarray, where, less, int8, int16, int32, int64, empty, promote_types ) +from numpy.core import iinfo + + +i1 = iinfo(int8) +i2 = iinfo(int16) +i4 = iinfo(int32) +def _min_int(low, high): + """ get small int that fits the range """ + if high <= i1.max and low >= i1.min: + return int8 + if high <= i2.max and low >= i2.min: + return int16 + if high <= i4.max and low >= i4.min: + return int32 + return int64 def fliplr(m): @@ -25,7 +40,7 @@ def fliplr(m): Parameters ---------- m : array_like - Input array. + Input array, must be at least 2-D. Returns ------- @@ -40,8 +55,7 @@ def fliplr(m): Notes ----- - Equivalent to A[:,::-1]. Does not require the array to be - two-dimensional. + Equivalent to A[:,::-1]. Requires the array to be at least 2-D. Examples -------- @@ -373,6 +387,7 @@ def tri(N, M=None, k=0, dtype=float): dtype : dtype, optional Data type of the returned array. The default is float. + Returns ------- tri : ndarray of shape (N, M) @@ -394,8 +409,14 @@ def tri(N, M=None, k=0, dtype=float): """ if M is None: M = N - m = greater_equal(subtract.outer(arange(N), arange(M)), -k) - return m.astype(dtype) + + m = greater_equal.outer(arange(N, dtype=_min_int(0, N)), + arange(-k, M-k, dtype=_min_int(-k, M - k))) + + # Avoid making a copy if the requested type is already bool + m = m.astype(dtype, copy=False) + + return m def tril(m, k=0): @@ -431,8 +452,7 @@ def tril(m, k=0): """ m = asanyarray(m) - out = multiply(tri(m.shape[0], m.shape[1], k=k, dtype=m.dtype), m) - return out + return multiply(tri(*m.shape[-2:], k=k, dtype=bool), m, dtype=m.dtype) def triu(m, k=0): @@ -458,22 +478,20 @@ def triu(m, k=0): """ m = asanyarray(m) - out = multiply((1 - tri(m.shape[0], m.shape[1], k - 1, dtype=m.dtype)), m) - return out + return multiply(~tri(*m.shape[-2:], k=k-1, dtype=bool), m, dtype=m.dtype) # Originally borrowed from John Hunter and matplotlib -def vander(x, N=None, order='decreasing'): +def vander(x, N=None, increasing=False): """ Generate a Vandermonde matrix. - The columns of the output matrix are powers of the input vector. The - order of the powers is determined by the `order` argument, either - "decreasing" (the default) or "increasing". Specifically, when - `order` is "decreasing", the `i`-th output column is the input vector - raised element-wise to the power of ``N - i - 1``. Such a matrix with - a geometric progression in each row is named for Alexandre-Theophile - Vandermonde. + The columns of the output matrix are powers of the input vector. The + order of the powers is determined by the `increasing` boolean argument. + Specifically, when `increasing` is False, the `i`-th output column is + the input vector raised element-wise to the power of ``N - i - 1``. Such + a matrix with a geometric progression in each row is named for Alexandre- + Theophile Vandermonde. Parameters ---------- @@ -482,16 +500,18 @@ def vander(x, N=None, order='decreasing'): N : int, optional Number of columns in the output. If `N` is not specified, a square array is returned (``N = len(x)``). - order : str, optional - Order of the powers of the columns. Must be either 'decreasing' - (the default) or 'increasing'. + increasing : bool, optional + Order of the powers of the columns. If True, the powers increase + from left to right, if False (the default) they are reversed. + + .. versionadded:: 1.9.0 Returns ------- out : ndarray - Vandermonde matrix. If `order` is "decreasing", the first column is - ``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `order` is - "increasing", the columns are ``x^0, x^1, ..., x^(N-1)``. + Vandermonde matrix. If `increasing` is False, the first column is + ``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `increasing` is + True, the columns are ``x^0, x^1, ..., x^(N-1)``. See Also -------- @@ -519,7 +539,7 @@ def vander(x, N=None, order='decreasing'): [ 8, 4, 2, 1], [ 27, 9, 3, 1], [125, 25, 5, 1]]) - >>> np.vander(x, order='increasing') + >>> np.vander(x, increasing=True) array([[ 1, 1, 1, 1], [ 1, 2, 4, 8], [ 1, 3, 9, 27], @@ -534,22 +554,22 @@ def vander(x, N=None, order='decreasing'): 48 """ - if order not in ['decreasing', 'increasing']: - raise ValueError("Invalid order %r; order must be either " - "'decreasing' or 'increasing'." % (order,)) x = asarray(x) if x.ndim != 1: raise ValueError("x must be a one-dimensional array or sequence.") if N is None: N = len(x) - if order == "decreasing": - powers = arange(N - 1, -1, -1) - else: - powers = arange(N) - V = x.reshape(-1, 1) ** powers + v = empty((len(x), N), dtype=promote_types(x.dtype, int)) + tmp = v[:, ::-1] if not increasing else v + + if N > 0: + tmp[:, 0] = 1 + if N > 1: + tmp[:, 1:] = x[:, None] + multiply.accumulate(tmp[:, 1:], out=tmp[:, 1:], axis=1) - return V + return v def histogram2d(x, y, bins=10, range=None, normed=False, weights=None): @@ -559,9 +579,11 @@ def histogram2d(x, y, bins=10, range=None, normed=False, weights=None): Parameters ---------- x : array_like, shape (N,) - An array containing the x coordinates of the points to be histogrammed. + An array containing the x coordinates of the points to be + histogrammed. y : array_like, shape (N,) - An array containing the y coordinates of the points to be histogrammed. + An array containing the y coordinates of the points to be + histogrammed. bins : int or [int, int] or array_like or [array, array], optional The bin specification: @@ -579,13 +601,13 @@ def histogram2d(x, y, bins=10, range=None, normed=False, weights=None): ``[[xmin, xmax], [ymin, ymax]]``. All values outside of this range will be considered outliers and not tallied in the histogram. normed : bool, optional - If False, returns the number of samples in each bin. If True, returns - the bin density, i.e. the bin count divided by the bin area. + If False, returns the number of samples in each bin. If True, + returns the bin density ``bin_count / sample_count / bin_area``. weights : array_like, shape(N,), optional - An array of values ``w_i`` weighing each sample ``(x_i, y_i)``. Weights - are normalized to 1 if `normed` is True. If `normed` is False, the - values of the returned histogram are equal to the sum of the weights - belonging to the samples falling into each bin. + An array of values ``w_i`` weighing each sample ``(x_i, y_i)``. + Weights are normalized to 1 if `normed` is True. If `normed` is + False, the values of the returned histogram are equal to the sum of + the weights belonging to the samples falling into each bin. Returns ------- @@ -605,20 +627,15 @@ def histogram2d(x, y, bins=10, range=None, normed=False, weights=None): Notes ----- - When `normed` is True, then the returned histogram is the sample density, - defined such that: - - .. math:: - \\sum_{i=0}^{nx-1} \\sum_{j=0}^{ny-1} H_{i,j} \\Delta x_i \\Delta y_j = 1 - - where `H` is the histogram array and :math:`\\Delta x_i \\Delta y_i` - the area of bin ``{i,j}``. + When `normed` is True, then the returned histogram is the sample + density, defined such that the sum over bins of the product + ``bin_value * bin_area`` is 1. Please note that the histogram does not follow the Cartesian convention - where `x` values are on the abcissa and `y` values on the ordinate axis. - Rather, `x` is histogrammed along the first dimension of the array - (vertical), and `y` along the second dimension of the array (horizontal). - This ensures compatibility with `histogramdd`. + where `x` values are on the abscissa and `y` values on the ordinate + axis. Rather, `x` is histogrammed along the first dimension of the + array (vertical), and `y` along the second dimension of the array + (horizontal). This ensures compatibility with `histogramdd`. Examples -------- @@ -650,14 +667,14 @@ def histogram2d(x, y, bins=10, range=None, normed=False, weights=None): >>> fig = plt.figure(figsize=(7, 3)) >>> ax = fig.add_subplot(131) - >>> ax.set_title('imshow:\nequidistant') + >>> ax.set_title('imshow: equidistant') >>> im = plt.imshow(H, interpolation='nearest', origin='low', - extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]]) + extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]]) pcolormesh can display exact bin edges: >>> ax = fig.add_subplot(132) - >>> ax.set_title('pcolormesh:\nexact bin edges') + >>> ax.set_title('pcolormesh: exact bin edges') >>> X, Y = np.meshgrid(xedges, yedges) >>> ax.pcolormesh(X, Y, H) >>> ax.set_aspect('equal') @@ -665,7 +682,7 @@ def histogram2d(x, y, bins=10, range=None, normed=False, weights=None): NonUniformImage displays exact bin edges with interpolation: >>> ax = fig.add_subplot(133) - >>> ax.set_title('NonUniformImage:\ninterpolated') + >>> ax.set_title('NonUniformImage: interpolated') >>> im = mpl.image.NonUniformImage(ax, interpolation='bilinear') >>> xcenters = xedges[:-1] + 0.5 * (xedges[1:] - xedges[:-1]) >>> ycenters = yedges[:-1] + 0.5 * (yedges[1:] - yedges[:-1]) @@ -761,17 +778,24 @@ def mask_indices(n, mask_func, k=0): return where(a != 0) -def tril_indices(n, k=0): +def tril_indices(n, k=0, m=None): """ - Return the indices for the lower-triangle of an (n, n) array. + Return the indices for the lower-triangle of an (n, m) array. Parameters ---------- n : int - The row dimension of the square arrays for which the returned + The row dimension of the arrays for which the returned indices will be valid. k : int, optional Diagonal offset (see `tril` for details). + m : int, optional + .. versionadded:: 1.9.0 + + The column dimension of the arrays for which the returned + arrays will be valid. + By default `m` is taken equal to `n`. + Returns ------- @@ -831,7 +855,7 @@ def tril_indices(n, k=0): [-10, -10, -10, -10]]) """ - return mask_indices(n, tril, k) + return where(tri(n, m, k=k, dtype=bool)) def tril_indices_from(arr, k=0): @@ -857,14 +881,14 @@ def tril_indices_from(arr, k=0): .. versionadded:: 1.4.0 """ - if not (arr.ndim == 2 and arr.shape[0] == arr.shape[1]): - raise ValueError("input array must be 2-d and square") - return tril_indices(arr.shape[0], k) + if arr.ndim != 2: + raise ValueError("input array must be 2-d") + return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1]) -def triu_indices(n, k=0): +def triu_indices(n, k=0, m=None): """ - Return the indices for the upper-triangle of an (n, n) array. + Return the indices for the upper-triangle of an (n, m) array. Parameters ---------- @@ -873,6 +897,13 @@ def triu_indices(n, k=0): be valid. k : int, optional Diagonal offset (see `triu` for details). + m : int, optional + .. versionadded:: 1.9.0 + + The column dimension of the arrays for which the returned + arrays will be valid. + By default `m` is taken equal to `n`. + Returns ------- @@ -934,12 +965,12 @@ def triu_indices(n, k=0): [ 12, 13, 14, -1]]) """ - return mask_indices(n, triu, k) + return where(~tri(n, m, k=k-1, dtype=bool)) def triu_indices_from(arr, k=0): """ - Return the indices for the upper-triangle of a (N, N) array. + Return the indices for the upper-triangle of arr. See `triu_indices` for full details. @@ -964,6 +995,6 @@ def triu_indices_from(arr, k=0): .. versionadded:: 1.4.0 """ - if not (arr.ndim == 2 and arr.shape[0] == arr.shape[1]): - raise ValueError("input array must be 2-d and square") - return triu_indices(arr.shape[0], k) + if arr.ndim != 2: + raise ValueError("input array must be 2-d") + return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1]) diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index 1f1cdfc8a..6d41e8eb4 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -6,7 +6,7 @@ import types import re from numpy.core.numerictypes import issubclass_, issubsctype, issubdtype -from numpy.core import product, ndarray, ufunc +from numpy.core import product, ndarray, ufunc, asarray __all__ = [ 'issubclass_', 'issubsctype', 'issubdtype', 'deprecate', @@ -210,8 +210,9 @@ def byte_bounds(a): a_data = ai['data'][0] astrides = ai['strides'] ashape = ai['shape'] - bytes_a = int(ai['typestr'][2:]) - + + bytes_a = asarray(a).dtype.itemsize + a_low = a_high = a_data if astrides is None: # contiguous case a_high += a.size * bytes_a diff --git a/numpy/linalg/lapack_lite/python_xerbla.c b/numpy/linalg/lapack_lite/python_xerbla.c index bc5d41f58..2296cc53f 100644 --- a/numpy/linalg/lapack_lite/python_xerbla.c +++ b/numpy/linalg/lapack_lite/python_xerbla.c @@ -26,16 +26,22 @@ int xerbla_(char *srname, integer *info) 6 for name, 4 for param. num. */ int len = 0; /* length of subroutine name*/ +#ifdef WITH_THREAD PyGILState_STATE save; +#endif while( len<6 && srname[len]!='\0' ) len++; while( len && srname[len-1]==' ' ) len--; - - PyOS_snprintf(buf, sizeof(buf), format, len, srname, *info); +#ifdef WITH_THREAD save = PyGILState_Ensure(); +#endif + PyOS_snprintf(buf, sizeof(buf), format, len, srname, *info); PyErr_SetString(PyExc_ValueError, buf); +#ifdef WITH_THREAD PyGILState_Release(save); +#endif + return 0; } diff --git a/numpy/linalg/lapack_litemodule.c b/numpy/linalg/lapack_litemodule.c index 5a5c6f010..f9f515bb7 100644 --- a/numpy/linalg/lapack_litemodule.c +++ b/numpy/linalg/lapack_litemodule.c @@ -17,31 +17,11 @@ typedef struct { float r, i; } f2c_complex; typedef struct { double r, i; } f2c_doublecomplex; /* typedef long int (*L_fp)(); */ -extern int FNAME(dgeev)(char *jobvl, char *jobvr, int *n, - double a[], int *lda, double wr[], double wi[], - double vl[], int *ldvl, double vr[], int *ldvr, - double work[], int lwork[], int *info); -extern int FNAME(zgeev)(char *jobvl, char *jobvr, int *n, - f2c_doublecomplex a[], int *lda, - f2c_doublecomplex w[], - f2c_doublecomplex vl[], int *ldvl, - f2c_doublecomplex vr[], int *ldvr, - f2c_doublecomplex work[], int *lwork, - double rwork[], int *info); - -extern int FNAME(dsyevd)(char *jobz, char *uplo, int *n, - double a[], int *lda, double w[], double work[], - int *lwork, int iwork[], int *liwork, int *info); -extern int FNAME(zheevd)(char *jobz, char *uplo, int *n, - f2c_doublecomplex a[], int *lda, - double w[], f2c_doublecomplex work[], - int *lwork, double rwork[], int *lrwork, int iwork[], - int *liwork, int *info); - extern int FNAME(dgelsd)(int *m, int *n, int *nrhs, double a[], int *lda, double b[], int *ldb, double s[], double *rcond, int *rank, double work[], int *lwork, int iwork[], int *info); + extern int FNAME(zgelsd)(int *m, int *n, int *nrhs, f2c_doublecomplex a[], int *lda, f2c_doublecomplex b[], int *ldb, @@ -49,34 +29,6 @@ extern int FNAME(zgelsd)(int *m, int *n, int *nrhs, f2c_doublecomplex work[], int *lwork, double rwork[], int iwork[], int *info); -extern int FNAME(dgesv)(int *n, int *nrhs, - double a[], int *lda, int ipiv[], - double b[], int *ldb, int *info); -extern int FNAME(zgesv)(int *n, int *nrhs, - f2c_doublecomplex a[], int *lda, int ipiv[], - f2c_doublecomplex b[], int *ldb, int *info); - -extern int FNAME(dgetrf)(int *m, int *n, - double a[], int *lda, int ipiv[], int *info); -extern int FNAME(zgetrf)(int *m, int *n, - f2c_doublecomplex a[], int *lda, int ipiv[], - int *info); - -extern int FNAME(dpotrf)(char *uplo, int *n, double a[], int *lda, int *info); -extern int FNAME(zpotrf)(char *uplo, int *n, - f2c_doublecomplex a[], int *lda, int *info); - -extern int FNAME(dgesdd)(char *jobz, int *m, int *n, - double a[], int *lda, double s[], double u[], - int *ldu, double vt[], int *ldvt, double work[], - int *lwork, int iwork[], int *info); -extern int FNAME(zgesdd)(char *jobz, int *m, int *n, - f2c_doublecomplex a[], int *lda, - double s[], f2c_doublecomplex u[], int *ldu, - f2c_doublecomplex vt[], int *ldvt, - f2c_doublecomplex work[], int *lwork, - double rwork[], int iwork[], int *info); - extern int FNAME(dgeqrf)(int *m, int *n, double a[], int *lda, double tau[], double work[], int *lwork, int *info); @@ -141,225 +93,6 @@ check_object(PyObject *ob, int t, char *obname, #define IDATA(p) ((int *) PyArray_DATA((PyArrayObject *)p)) static PyObject * -lapack_lite_dgeev(PyObject *NPY_UNUSED(self), PyObject *args) -{ - int lapack_lite_status; - char jobvl; - char jobvr; - int n; - PyObject *a; - int lda; - PyObject *wr; - PyObject *wi; - PyObject *vl; - int ldvl; - PyObject *vr; - int ldvr; - PyObject *work; - int lwork; - int info; - TRY(PyArg_ParseTuple(args,"cciOiOOOiOiOii", - &jobvl,&jobvr,&n,&a,&lda,&wr,&wi,&vl,&ldvl, - &vr,&ldvr,&work,&lwork,&info)); - - TRY(check_object(a,NPY_DOUBLE,"a","NPY_DOUBLE","dgeev")); - TRY(check_object(wr,NPY_DOUBLE,"wr","NPY_DOUBLE","dgeev")); - TRY(check_object(wi,NPY_DOUBLE,"wi","NPY_DOUBLE","dgeev")); - TRY(check_object(vl,NPY_DOUBLE,"vl","NPY_DOUBLE","dgeev")); - TRY(check_object(vr,NPY_DOUBLE,"vr","NPY_DOUBLE","dgeev")); - TRY(check_object(work,NPY_DOUBLE,"work","NPY_DOUBLE","dgeev")); - - lapack_lite_status = - FNAME(dgeev)(&jobvl,&jobvr,&n,DDATA(a),&lda,DDATA(wr),DDATA(wi), - DDATA(vl),&ldvl,DDATA(vr),&ldvr,DDATA(work),&lwork, - &info); - if (PyErr_Occurred()) { - return NULL; - } - - return Py_BuildValue("{s:i,s:c,s:c,s:i,s:i,s:i,s:i,s:i,s:i}","dgeev_", - lapack_lite_status,"jobvl",jobvl,"jobvr",jobvr, - "n",n,"lda",lda,"ldvl",ldvl,"ldvr",ldvr, - "lwork",lwork,"info",info); -} - -static PyObject * -lapack_lite_dsyevd(PyObject *NPY_UNUSED(self), PyObject *args) -{ - /* Arguments */ - /* ========= */ - - char jobz; - /* JOBZ (input) CHARACTER*1 */ - /* = 'N': Compute eigenvalues only; */ - /* = 'V': Compute eigenvalues and eigenvectors. */ - - char uplo; - /* UPLO (input) CHARACTER*1 */ - /* = 'U': Upper triangle of A is stored; */ - /* = 'L': Lower triangle of A is stored. */ - - int n; - /* N (input) INTEGER */ - /* The order of the matrix A. N >= 0. */ - - PyObject *a; - /* A (input/output) DOUBLE PRECISION array, dimension (LDA, N) */ - /* On entry, the symmetric matrix A. If UPLO = 'U', the */ - /* leading N-by-N upper triangular part of A contains the */ - /* upper triangular part of the matrix A. If UPLO = 'L', */ - /* the leading N-by-N lower triangular part of A contains */ - /* the lower triangular part of the matrix A. */ - /* On exit, if JOBZ = 'V', then if INFO = 0, A contains the */ - /* orthonormal eigenvectors of the matrix A. */ - /* If JOBZ = 'N', then on exit the lower triangle (if UPLO='L') */ - /* or the upper triangle (if UPLO='U') of A, including the */ - /* diagonal, is destroyed. */ - - int lda; - /* LDA (input) INTEGER */ - /* The leading dimension of the array A. LDA >= max(1,N). */ - - PyObject *w; - /* W (output) DOUBLE PRECISION array, dimension (N) */ - /* If INFO = 0, the eigenvalues in ascending order. */ - - PyObject *work; - /* WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) */ - /* On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */ - - int lwork; - /* LWORK (input) INTEGER */ - /* The length of the array WORK. LWORK >= max(1,3*N-1). */ - /* For optimal efficiency, LWORK >= (NB+2)*N, */ - /* where NB is the blocksize for DSYTRD returned by ILAENV. */ - - PyObject *iwork; - int liwork; - - int info; - /* INFO (output) INTEGER */ - /* = 0: successful exit */ - /* < 0: if INFO = -i, the i-th argument had an illegal value */ - /* > 0: if INFO = i, the algorithm failed to converge; i */ - /* off-diagonal elements of an intermediate tridiagonal */ - /* form did not converge to zero. */ - - int lapack_lite_status; - - TRY(PyArg_ParseTuple(args,"cciOiOOiOii", - &jobz,&uplo,&n,&a,&lda,&w,&work,&lwork, - &iwork,&liwork,&info)); - - TRY(check_object(a,NPY_DOUBLE,"a","NPY_DOUBLE","dsyevd")); - TRY(check_object(w,NPY_DOUBLE,"w","NPY_DOUBLE","dsyevd")); - TRY(check_object(work,NPY_DOUBLE,"work","NPY_DOUBLE","dsyevd")); - TRY(check_object(iwork,NPY_INT,"iwork","NPY_INT","dsyevd")); - - lapack_lite_status = - FNAME(dsyevd)(&jobz,&uplo,&n,DDATA(a),&lda,DDATA(w),DDATA(work), - &lwork,IDATA(iwork),&liwork,&info); - if (PyErr_Occurred()) { - return NULL; - } - - return Py_BuildValue("{s:i,s:c,s:c,s:i,s:i,s:i,s:i,s:i}","dsyevd_", - lapack_lite_status,"jobz",jobz,"uplo",uplo, - "n",n,"lda",lda,"lwork",lwork,"liwork",liwork,"info",info); -} - -static PyObject * -lapack_lite_zheevd(PyObject *NPY_UNUSED(self), PyObject *args) -{ - /* Arguments */ - /* ========= */ - - char jobz; - /* JOBZ (input) CHARACTER*1 */ - /* = 'N': Compute eigenvalues only; */ - /* = 'V': Compute eigenvalues and eigenvectors. */ - - char uplo; - /* UPLO (input) CHARACTER*1 */ - /* = 'U': Upper triangle of A is stored; */ - /* = 'L': Lower triangle of A is stored. */ - - int n; - /* N (input) INTEGER */ - /* The order of the matrix A. N >= 0. */ - - PyObject *a; - /* A (input/output) COMPLEX*16 array, dimension (LDA, N) */ - /* On entry, the Hermitian matrix A. If UPLO = 'U', the */ - /* leading N-by-N upper triangular part of A contains the */ - /* upper triangular part of the matrix A. If UPLO = 'L', */ - /* the leading N-by-N lower triangular part of A contains */ - /* the lower triangular part of the matrix A. */ - /* On exit, if JOBZ = 'V', then if INFO = 0, A contains the */ - /* orthonormal eigenvectors of the matrix A. */ - /* If JOBZ = 'N', then on exit the lower triangle (if UPLO='L') */ - /* or the upper triangle (if UPLO='U') of A, including the */ - /* diagonal, is destroyed. */ - - int lda; - /* LDA (input) INTEGER */ - /* The leading dimension of the array A. LDA >= max(1,N). */ - - PyObject *w; - /* W (output) DOUBLE PRECISION array, dimension (N) */ - /* If INFO = 0, the eigenvalues in ascending order. */ - - PyObject *work; - /* WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) */ - /* On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */ - - int lwork; - /* LWORK (input) INTEGER */ - /* The length of the array WORK. LWORK >= max(1,3*N-1). */ - /* For optimal efficiency, LWORK >= (NB+2)*N, */ - /* where NB is the blocksize for DSYTRD returned by ILAENV. */ - - PyObject *rwork; - /* RWORK (workspace) DOUBLE PRECISION array, dimension (max(1, 3*N-2)) */ - int lrwork; - - PyObject *iwork; - int liwork; - - int info; - /* INFO (output) INTEGER */ - /* = 0: successful exit */ - /* < 0: if INFO = -i, the i-th argument had an illegal value */ - /* > 0: if INFO = i, the algorithm failed to converge; i */ - /* off-diagonal elements of an intermediate tridiagonal */ - /* form did not converge to zero. */ - - int lapack_lite_status; - - TRY(PyArg_ParseTuple(args,"cciOiOOiOiOii", - &jobz,&uplo,&n,&a,&lda,&w,&work,&lwork,&rwork, - &lrwork,&iwork,&liwork,&info)); - - TRY(check_object(a,NPY_CDOUBLE,"a","NPY_CDOUBLE","zheevd")); - TRY(check_object(w,NPY_DOUBLE,"w","NPY_DOUBLE","zheevd")); - TRY(check_object(work,NPY_CDOUBLE,"work","NPY_CDOUBLE","zheevd")); - TRY(check_object(w,NPY_DOUBLE,"rwork","NPY_DOUBLE","zheevd")); - TRY(check_object(iwork,NPY_INT,"iwork","NPY_INT","zheevd")); - - lapack_lite_status = - FNAME(zheevd)(&jobz,&uplo,&n,ZDATA(a),&lda,DDATA(w),ZDATA(work), - &lwork,DDATA(rwork),&lrwork,IDATA(iwork),&liwork,&info); - if (PyErr_Occurred()) { - return NULL; - } - - return Py_BuildValue("{s:i,s:c,s:c,s:i,s:i,s:i,s:i,s:i,s:i}","zheevd_", - lapack_lite_status,"jobz",jobz,"uplo",uplo,"n",n, - "lda",lda,"lwork",lwork,"lrwork",lrwork, - "liwork",liwork,"info",info); -} - -static PyObject * lapack_lite_dgelsd(PyObject *NPY_UNUSED(self), PyObject *args) { int lapack_lite_status; @@ -402,152 +135,6 @@ lapack_lite_dgelsd(PyObject *NPY_UNUSED(self), PyObject *args) } static PyObject * -lapack_lite_dgesv(PyObject *NPY_UNUSED(self), PyObject *args) -{ - int lapack_lite_status; - int n; - int nrhs; - PyObject *a; - int lda; - PyObject *ipiv; - PyObject *b; - int ldb; - int info; - TRY(PyArg_ParseTuple(args,"iiOiOOii",&n,&nrhs,&a,&lda,&ipiv,&b,&ldb,&info)); - - TRY(check_object(a,NPY_DOUBLE,"a","NPY_DOUBLE","dgesv")); - TRY(check_object(ipiv,NPY_INT,"ipiv","NPY_INT","dgesv")); - TRY(check_object(b,NPY_DOUBLE,"b","NPY_DOUBLE","dgesv")); - - lapack_lite_status = - FNAME(dgesv)(&n,&nrhs,DDATA(a),&lda,IDATA(ipiv),DDATA(b),&ldb,&info); - if (PyErr_Occurred()) { - return NULL; - } - - return Py_BuildValue("{s:i,s:i,s:i,s:i,s:i,s:i}","dgesv_", - lapack_lite_status,"n",n,"nrhs",nrhs,"lda",lda, - "ldb",ldb,"info",info); -} - -static PyObject * -lapack_lite_dgesdd(PyObject *NPY_UNUSED(self), PyObject *args) -{ - int lapack_lite_status; - char jobz; - int m; - int n; - PyObject *a; - int lda; - PyObject *s; - PyObject *u; - int ldu; - PyObject *vt; - int ldvt; - PyObject *work; - int lwork; - PyObject *iwork; - int info; - TRY(PyArg_ParseTuple(args,"ciiOiOOiOiOiOi", - &jobz,&m,&n,&a,&lda,&s,&u,&ldu,&vt,&ldvt, - &work,&lwork,&iwork,&info)); - - TRY(check_object(a,NPY_DOUBLE,"a","NPY_DOUBLE","dgesdd")); - TRY(check_object(s,NPY_DOUBLE,"s","NPY_DOUBLE","dgesdd")); - TRY(check_object(u,NPY_DOUBLE,"u","NPY_DOUBLE","dgesdd")); - TRY(check_object(vt,NPY_DOUBLE,"vt","NPY_DOUBLE","dgesdd")); - TRY(check_object(work,NPY_DOUBLE,"work","NPY_DOUBLE","dgesdd")); - TRY(check_object(iwork,NPY_INT,"iwork","NPY_INT","dgesdd")); - - lapack_lite_status = - FNAME(dgesdd)(&jobz,&m,&n,DDATA(a),&lda,DDATA(s),DDATA(u),&ldu, - DDATA(vt),&ldvt,DDATA(work),&lwork,IDATA(iwork), - &info); - if (PyErr_Occurred()) { - return NULL; - } - - if (info == 0 && lwork == -1) { - /* We need to check the result because - sometimes the "optimal" value is actually - too small. - Change it to the maximum of the minimum and the optimal. - */ - long work0 = (long) *DDATA(work); - int mn = PyArray_MIN(m,n); - int mx = PyArray_MAX(m,n); - - switch(jobz){ - case 'N': - work0 = PyArray_MAX(work0,3*mn + PyArray_MAX(mx,6*mn)+500); - break; - case 'O': - work0 = PyArray_MAX(work0,3*mn*mn + - PyArray_MAX(mx,5*mn*mn+4*mn+500)); - break; - case 'S': - case 'A': - work0 = PyArray_MAX(work0,3*mn*mn + - PyArray_MAX(mx,4*mn*(mn+1))+500); - break; - } - *DDATA(work) = (double) work0; - } - return Py_BuildValue("{s:i,s:c,s:i,s:i,s:i,s:i,s:i,s:i,s:i}","dgesdd_", - lapack_lite_status,"jobz",jobz,"m",m,"n",n, - "lda",lda,"ldu",ldu,"ldvt",ldvt,"lwork",lwork, - "info",info); -} - -static PyObject * -lapack_lite_dgetrf(PyObject *NPY_UNUSED(self), PyObject *args) -{ - int lapack_lite_status; - int m; - int n; - PyObject *a; - int lda; - PyObject *ipiv; - int info; - TRY(PyArg_ParseTuple(args,"iiOiOi",&m,&n,&a,&lda,&ipiv,&info)); - - TRY(check_object(a,NPY_DOUBLE,"a","NPY_DOUBLE","dgetrf")); - TRY(check_object(ipiv,NPY_INT,"ipiv","NPY_INT","dgetrf")); - - lapack_lite_status = - FNAME(dgetrf)(&m,&n,DDATA(a),&lda,IDATA(ipiv),&info); - if (PyErr_Occurred()) { - return NULL; - } - - return Py_BuildValue("{s:i,s:i,s:i,s:i,s:i}","dgetrf_", lapack_lite_status, - "m",m,"n",n,"lda",lda,"info",info); -} - -static PyObject * -lapack_lite_dpotrf(PyObject *NPY_UNUSED(self), PyObject *args) -{ - int lapack_lite_status; - int n; - PyObject *a; - int lda; - char uplo; - int info; - - TRY(PyArg_ParseTuple(args,"ciOii",&uplo,&n,&a,&lda,&info)); - TRY(check_object(a,NPY_DOUBLE,"a","NPY_DOUBLE","dpotrf")); - - lapack_lite_status = - FNAME(dpotrf)(&uplo,&n,DDATA(a),&lda,&info); - if (PyErr_Occurred()) { - return NULL; - } - - return Py_BuildValue("{s:i,s:i,s:i,s:i}","dpotrf_", lapack_lite_status, - "n",n,"lda",lda,"info",info); -} - -static PyObject * lapack_lite_dgeqrf(PyObject *NPY_UNUSED(self), PyObject *args) { int lapack_lite_status; @@ -602,49 +189,6 @@ lapack_lite_dorgqr(PyObject *NPY_UNUSED(self), PyObject *args) static PyObject * -lapack_lite_zgeev(PyObject *NPY_UNUSED(self), PyObject *args) -{ - int lapack_lite_status; - char jobvl; - char jobvr; - int n; - PyObject *a; - int lda; - PyObject *w; - PyObject *vl; - int ldvl; - PyObject *vr; - int ldvr; - PyObject *work; - int lwork; - PyObject *rwork; - int info; - TRY(PyArg_ParseTuple(args,"cciOiOOiOiOiOi", - &jobvl,&jobvr,&n,&a,&lda,&w,&vl,&ldvl, - &vr,&ldvr,&work,&lwork,&rwork,&info)); - - TRY(check_object(a,NPY_CDOUBLE,"a","NPY_CDOUBLE","zgeev")); - TRY(check_object(w,NPY_CDOUBLE,"w","NPY_CDOUBLE","zgeev")); - TRY(check_object(vl,NPY_CDOUBLE,"vl","NPY_CDOUBLE","zgeev")); - TRY(check_object(vr,NPY_CDOUBLE,"vr","NPY_CDOUBLE","zgeev")); - TRY(check_object(work,NPY_CDOUBLE,"work","NPY_CDOUBLE","zgeev")); - TRY(check_object(rwork,NPY_DOUBLE,"rwork","NPY_DOUBLE","zgeev")); - - lapack_lite_status = - FNAME(zgeev)(&jobvl,&jobvr,&n,ZDATA(a),&lda,ZDATA(w),ZDATA(vl), - &ldvl,ZDATA(vr),&ldvr,ZDATA(work),&lwork, - DDATA(rwork),&info); - if (PyErr_Occurred()) { - return NULL; - } - - return Py_BuildValue("{s:i,s:c,s:c,s:i,s:i,s:i,s:i,s:i,s:i}","zgeev_", - lapack_lite_status,"jobvl",jobvl,"jobvr",jobvr, - "n",n,"lda",lda,"ldvl",ldvl,"ldvr",ldvr, - "lwork",lwork,"info",info); -} - -static PyObject * lapack_lite_zgelsd(PyObject *NPY_UNUSED(self), PyObject *args) { int lapack_lite_status; @@ -687,127 +231,6 @@ lapack_lite_zgelsd(PyObject *NPY_UNUSED(self), PyObject *args) } static PyObject * -lapack_lite_zgesv(PyObject *NPY_UNUSED(self), PyObject *args) -{ - int lapack_lite_status; - int n; - int nrhs; - PyObject *a; - int lda; - PyObject *ipiv; - PyObject *b; - int ldb; - int info; - TRY(PyArg_ParseTuple(args,"iiOiOOii",&n,&nrhs,&a,&lda,&ipiv,&b,&ldb,&info)); - - TRY(check_object(a,NPY_CDOUBLE,"a","NPY_CDOUBLE","zgesv")); - TRY(check_object(ipiv,NPY_INT,"ipiv","NPY_INT","zgesv")); - TRY(check_object(b,NPY_CDOUBLE,"b","NPY_CDOUBLE","zgesv")); - - lapack_lite_status = - FNAME(zgesv)(&n,&nrhs,ZDATA(a),&lda,IDATA(ipiv),ZDATA(b),&ldb,&info); - if (PyErr_Occurred()) { - return NULL; - } - - return Py_BuildValue("{s:i,s:i,s:i,s:i,s:i,s:i}","zgesv_", - lapack_lite_status,"n",n,"nrhs",nrhs,"lda",lda, - "ldb",ldb,"info",info); -} - -static PyObject * -lapack_lite_zgesdd(PyObject *NPY_UNUSED(self), PyObject *args) -{ - int lapack_lite_status; - char jobz; - int m; - int n; - PyObject *a; - int lda; - PyObject *s; - PyObject *u; - int ldu; - PyObject *vt; - int ldvt; - PyObject *work; - int lwork; - PyObject *rwork; - PyObject *iwork; - int info; - TRY(PyArg_ParseTuple(args,"ciiOiOOiOiOiOOi", - &jobz,&m,&n,&a,&lda,&s,&u,&ldu, - &vt,&ldvt,&work,&lwork,&rwork,&iwork,&info)); - - TRY(check_object(a,NPY_CDOUBLE,"a","NPY_CDOUBLE","zgesdd")); - TRY(check_object(s,NPY_DOUBLE,"s","NPY_DOUBLE","zgesdd")); - TRY(check_object(u,NPY_CDOUBLE,"u","NPY_CDOUBLE","zgesdd")); - TRY(check_object(vt,NPY_CDOUBLE,"vt","NPY_CDOUBLE","zgesdd")); - TRY(check_object(work,NPY_CDOUBLE,"work","NPY_CDOUBLE","zgesdd")); - TRY(check_object(rwork,NPY_DOUBLE,"rwork","NPY_DOUBLE","zgesdd")); - TRY(check_object(iwork,NPY_INT,"iwork","NPY_INT","zgesdd")); - - lapack_lite_status = - FNAME(zgesdd)(&jobz,&m,&n,ZDATA(a),&lda,DDATA(s),ZDATA(u),&ldu, - ZDATA(vt),&ldvt,ZDATA(work),&lwork,DDATA(rwork), - IDATA(iwork),&info); - if (PyErr_Occurred()) { - return NULL; - } - - return Py_BuildValue("{s:i,s:c,s:i,s:i,s:i,s:i,s:i,s:i,s:i}","zgesdd_", - lapack_lite_status,"jobz",jobz,"m",m,"n",n, - "lda",lda,"ldu",ldu,"ldvt",ldvt,"lwork",lwork, - "info",info); -} - -static PyObject * -lapack_lite_zgetrf(PyObject *NPY_UNUSED(self), PyObject *args) -{ - int lapack_lite_status; - int m; - int n; - PyObject *a; - int lda; - PyObject *ipiv; - int info; - TRY(PyArg_ParseTuple(args,"iiOiOi",&m,&n,&a,&lda,&ipiv,&info)); - - TRY(check_object(a,NPY_CDOUBLE,"a","NPY_CDOUBLE","zgetrf")); - TRY(check_object(ipiv,NPY_INT,"ipiv","NPY_INT","zgetrf")); - - lapack_lite_status = - FNAME(zgetrf)(&m,&n,ZDATA(a),&lda,IDATA(ipiv),&info); - if (PyErr_Occurred()) { - return NULL; - } - - return Py_BuildValue("{s:i,s:i,s:i,s:i,s:i}","zgetrf_", - lapack_lite_status,"m",m,"n",n,"lda",lda,"info",info); -} - -static PyObject * -lapack_lite_zpotrf(PyObject *NPY_UNUSED(self), PyObject *args) -{ - int lapack_lite_status; - int n; - PyObject *a; - int lda; - char uplo; - int info; - - TRY(PyArg_ParseTuple(args,"ciOii",&uplo,&n,&a,&lda,&info)); - TRY(check_object(a,NPY_CDOUBLE,"a","NPY_CDOUBLE","zpotrf")); - lapack_lite_status = - FNAME(zpotrf)(&uplo,&n,ZDATA(a),&lda,&info); - if (PyErr_Occurred()) { - return NULL; - } - - return Py_BuildValue("{s:i,s:i,s:i,s:i}","zpotrf_", - lapack_lite_status,"n",n,"lda",lda,"info",info); -} - -static PyObject * lapack_lite_zgeqrf(PyObject *NPY_UNUSED(self), PyObject *args) { int lapack_lite_status; @@ -882,22 +305,10 @@ lapack_lite_xerbla(PyObject *NPY_UNUSED(self), PyObject *args) #define STR(x) #x #define lameth(name) {STR(name), lapack_lite_##name, METH_VARARGS, NULL} static struct PyMethodDef lapack_lite_module_methods[] = { - lameth(zheevd), - lameth(dsyevd), - lameth(dgeev), lameth(dgelsd), - lameth(dgesv), - lameth(dgesdd), - lameth(dgetrf), - lameth(dpotrf), lameth(dgeqrf), lameth(dorgqr), - lameth(zgeev), lameth(zgelsd), - lameth(zgesv), - lameth(zgesdd), - lameth(zgetrf), - lameth(zpotrf), lameth(zgeqrf), lameth(zungqr), lameth(xerbla), diff --git a/numpy/linalg/linalg.py b/numpy/linalg/linalg.py index a7e12aa08..e5d13efc8 100644 --- a/numpy/linalg/linalg.py +++ b/numpy/linalg/linalg.py @@ -1763,7 +1763,7 @@ def lstsq(a, b, rcond=-1): residuals : {(), (1,), (K,)} ndarray Sums of residuals; squared Euclidean 2-norm for each column in ``b - a*x``. - If the rank of `a` is < N or > M, this is an empty array. + If the rank of `a` is < N or M <= N, this is an empty array. If `b` is 1-dimensional, this is a (1,) shape array. Otherwise the shape is (K,). rank : int @@ -2053,7 +2053,12 @@ def norm(x, ord=None, axis=None): # Check the default case first and handle it immediately. if ord is None and axis is None: - return sqrt(add.reduce((x.conj() * x).real, axis=None)) + x = x.ravel(order='K') + if isComplexType(x.dtype.type): + sqnorm = dot(x.real, x.real) + dot(x.imag, x.imag) + else: + sqnorm = dot(x, x) + return sqrt(sqnorm) # Normalize the `axis` argument to a tuple. nd = x.ndim diff --git a/numpy/linalg/tests/test_build.py b/numpy/linalg/tests/test_build.py index 27fbd6429..0d237c81c 100644 --- a/numpy/linalg/tests/test_build.py +++ b/numpy/linalg/tests/test_build.py @@ -20,16 +20,16 @@ class FindDependenciesLdd(object): except OSError: raise RuntimeError("command %s cannot be run" % self.cmd) - def get_dependencies(self, file): - p = Popen(self.cmd + [file], stdout=PIPE, stderr=PIPE) + def get_dependencies(self, lfile): + p = Popen(self.cmd + [lfile], stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() if not (p.returncode == 0): - raise RuntimeError("Failed to check dependencies for %s" % libfile) + raise RuntimeError("failed dependencies check for %s" % lfile) return stdout - def grep_dependencies(self, file, deps): - stdout = self.get_dependencies(file) + def grep_dependencies(self, lfile, deps): + stdout = self.get_dependencies(lfile) rdeps = dict([(dep, re.compile(dep)) for dep in deps]) founds = [] diff --git a/numpy/linalg/tests/test_linalg.py b/numpy/linalg/tests/test_linalg.py index 0c21a4229..8edf36aa6 100644 --- a/numpy/linalg/tests/test_linalg.py +++ b/numpy/linalg/tests/test_linalg.py @@ -1130,13 +1130,13 @@ def test_xerbla_override(): os._exit(os.EX_CONFIG) try: - a = np.array([[1]]) - np.linalg.lapack_lite.dgetrf( - 1, 1, a.astype(np.double), + a = np.array([[1.]]) + np.linalg.lapack_lite.dorgqr( + 1, 1, 1, a, 0, # <- invalid value - a.astype(np.intc), 0) + a, a, 0, 0) except ValueError as e: - if "DGETRF parameter number 4" in str(e): + if "DORGQR parameter number 5" in str(e): # success os._exit(os.EX_OK) diff --git a/numpy/linalg/tests/test_regression.py b/numpy/linalg/tests/test_regression.py index 4ff14a6a5..18d212cdc 100644 --- a/numpy/linalg/tests/test_regression.py +++ b/numpy/linalg/tests/test_regression.py @@ -69,5 +69,22 @@ class TestRegression(TestCase): bp = linalg.cholesky(b) assert_array_equal(ap, bp) + def test_large_svd_32bit(self): + # See gh-4442, 64bit would require very large/slow matrices. + x = np.eye(1000, 66) + np.linalg.svd(x) + + def test_svd_no_uv(self): + # gh-4733 + for shape in (3, 4), (4, 4), (4, 3): + for t in float, complex: + a = np.ones(shape, dtype=t) + w = linalg.svd(a, compute_uv=False) + c = np.count_nonzero(np.absolute(w) > 0.5) + assert_equal(c, 1) + assert_equal(np.linalg.matrix_rank(a), 1) + assert_array_less(1, np.linalg.norm(a, ord=2)) + + if __name__ == '__main__': run_module_suite() diff --git a/numpy/linalg/umath_linalg.c.src b/numpy/linalg/umath_linalg.c.src index 4b50bf1f6..a09d2c10a 100644 --- a/numpy/linalg/umath_linalg.c.src +++ b/numpy/linalg/umath_linalg.c.src @@ -2208,10 +2208,10 @@ process_@lapack_func@_results(GEEV_PARAMS_t *NPY_UNUSED(params)) /**begin repeat - #TYPE=FLOAT,DOUBLE,CFLOAT,CDOUBLE# - #COMPLEXTYPE=CFLOAT,CDOUBLE,CFLOAT,CDOUBLE# - #ftype=fortran_real,fortran_doublereal,fortran_complex,fortran_doublecomplex# - #lapack_func=sgeev,dgeev,cgeev,zgeev# + #TYPE=FLOAT,DOUBLE,CDOUBLE# + #COMPLEXTYPE=CFLOAT,CDOUBLE,CDOUBLE# + #ftype=fortran_real,fortran_doublereal,fortran_doublecomplex# + #lapack_func=sgeev,dgeev,zgeev# */ static inline void @@ -2875,27 +2875,6 @@ static char equal_3_types[] = { NPY_CDOUBLE, NPY_CDOUBLE, NPY_CDOUBLE }; -static char equal_4_types[] = { - NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, - NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, - NPY_CFLOAT, NPY_CFLOAT, NPY_CFLOAT, NPY_CFLOAT, - NPY_CDOUBLE, NPY_CDOUBLE, NPY_CDOUBLE, NPY_CDOUBLE -}; - -static char equal_5_types[] = { - NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, - NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, - NPY_CFLOAT, NPY_CFLOAT, NPY_CFLOAT, NPY_CFLOAT, NPY_CFLOAT, - NPY_CDOUBLE, NPY_CDOUBLE, NPY_CDOUBLE, NPY_CDOUBLE, NPY_CDOUBLE -}; - -static char equal_6_types[] = { - NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, - NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, - NPY_CFLOAT, NPY_CFLOAT, NPY_CFLOAT, NPY_CFLOAT, NPY_CFLOAT, NPY_CFLOAT, - NPY_CDOUBLE, NPY_CDOUBLE, NPY_CDOUBLE, NPY_CDOUBLE, NPY_CDOUBLE, NPY_CDOUBLE -}; - /* second result is logdet, that will always be a REAL */ static char slogdet_types[] = { NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, @@ -3073,7 +3052,7 @@ GUFUNC_DESCRIPTOR_t gufunc_descriptors [] = { "svd when n>=m. ", 4, 1, 1, FUNC_ARRAY_NAME(svd_N), - equal_2_types + svd_1_1_types }, { "svd_n", diff --git a/numpy/ma/core.py b/numpy/ma/core.py index 8dc2ca86e..6c0a8f345 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -46,7 +46,7 @@ __docformat__ = "restructuredtext en" __all__ = ['MAError', 'MaskError', 'MaskType', 'MaskedArray', 'bool_', 'abs', 'absolute', 'add', 'all', 'allclose', 'allequal', 'alltrue', - 'amax', 'amin', 'angle', 'anom', 'anomalies', 'any', 'arange', + 'amax', 'amin', 'angle', 'anom', 'anomalies', 'any', 'append', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argsort', 'around', 'array', 'asarray', 'asanyarray', @@ -416,14 +416,19 @@ def _check_fill_value(fill_value, ndtype): fill_value = np.array(_recursive_set_fill_value(fill_value, descr), dtype=ndtype) else: - if isinstance(fill_value, basestring) and (ndtype.char not in 'SVU'): - fill_value = default_fill_value(ndtype) + if isinstance(fill_value, basestring) and (ndtype.char not in 'OSVU'): + err_msg = "Cannot set fill value of string with array of dtype %s" + raise TypeError(err_msg % ndtype) else: - # In case we want to convert 1e+20 to int... + # In case we want to convert 1e20 to int... try: - fill_value = np.array(fill_value, copy=False, dtype=ndtype)#.item() + fill_value = np.array(fill_value, copy=False, dtype=ndtype) except OverflowError: - fill_value = default_fill_value(ndtype) + # Raise TypeError instead of OverflowError. OverflowError + # is seldom used, and the real problem here is that the + # passed fill_value is not compatible with the ndtype. + err_msg = "Fill value %s overflows dtype %s" + raise TypeError(err_msg % (fill_value, ndtype)) return np.array(fill_value) @@ -838,8 +843,7 @@ class _MaskedUnaryOperation: d = getdata(a) # Case 1.1. : Domained function if self.domain is not None: - with np.errstate(): - np.seterr(divide='ignore', invalid='ignore') + with np.errstate(divide='ignore', invalid='ignore'): result = self.f(d, *args, **kwargs) # Make a mask m = ~umath.isfinite(result) @@ -927,8 +931,7 @@ class _MaskedBinaryOperation: else: m = umath.logical_or(ma, mb) # Get the result - with np.errstate(): - np.seterr(divide='ignore', invalid='ignore') + with np.errstate(divide='ignore', invalid='ignore'): result = self.f(da, db, *args, **kwargs) # check it worked if result is NotImplemented: @@ -940,11 +943,8 @@ class _MaskedBinaryOperation: return result # Case 2. : array # Revert result to da where masked - if m.any(): - np.copyto(result, 0, casting='unsafe', where=m) - # This only makes sense if the operation preserved the dtype - if result.dtype == da.dtype: - result += m * da + if m is not nomask: + np.copyto(result, da, casting='unsafe', where=m) # Transforms to a (subclass of) MaskedArray result = result.view(get_masked_subclass(a, b)) result._mask = m @@ -1068,8 +1068,7 @@ class _DomainedBinaryOperation: (da, db) = (getdata(a, subok=False), getdata(b, subok=False)) (ma, mb) = (getmask(a), getmask(b)) # Get the result - with np.errstate(): - np.seterr(divide='ignore', invalid='ignore') + with np.errstate(divide='ignore', invalid='ignore'): result = self.f(da, db, *args, **kwargs) # check it worked if result is NotImplemented: @@ -1089,8 +1088,7 @@ class _DomainedBinaryOperation: else: return result # When the mask is True, put back da - np.copyto(result, 0, casting='unsafe', where=m) - result += m * da + np.copyto(result, da, casting='unsafe', where=m) result = result.view(get_masked_subclass(a, b)) result._mask = m if isinstance(b, MaskedArray): @@ -2465,7 +2463,6 @@ class _arraymethod(object): return result - class MaskedIterator(object): """ Flat iterator object to iterate over masked arrays. @@ -2529,8 +2526,14 @@ class MaskedIterator(object): result = self.dataiter.__getitem__(indx).view(type(self.ma)) if self.maskiter is not None: _mask = self.maskiter.__getitem__(indx) - _mask.shape = result.shape - result._mask = _mask + if isinstance(_mask, ndarray): + # set shape to match that of data; this is needed for matrices + _mask.shape = result.shape + result._mask = _mask + elif isinstance(_mask, np.void): + return mvoid(result, mask=_mask, hardmask=self.ma._hardmask) + elif _mask: # Just a scalar, masked + return masked return result ### This won't work is ravel makes a copy @@ -2562,8 +2565,12 @@ class MaskedIterator(object): """ d = next(self.dataiter) - if self.maskiter is not None and next(self.maskiter): - d = masked + if self.maskiter is not None: + m = next(self.maskiter) + if isinstance(m, np.void): + return mvoid(d, mask=m, hardmask=self.ma._hardmask) + elif m: # Just a scalar, masked + return masked return d next = __next__ @@ -3580,9 +3587,8 @@ class MaskedArray(ndarray): if m.dtype.names: m = m.view((bool, len(m.dtype))) if m.any(): - r = np.array(self._data.tolist(), dtype=object) - np.copyto(r, f, where=m) - return str(tuple(r)) + return str(tuple((f if _m else _d) for _d, _m in + zip(self._data.tolist(), m))) else: return str(self._data) elif m: @@ -3593,7 +3599,7 @@ class MaskedArray(ndarray): names = self.dtype.names if names is None: res = self._data.astype("O") - res[m] = f + res.view(ndarray)[m] = f else: rdtype = _recursive_make_descr(self.dtype, "O") res = self._data.astype(rdtype) @@ -3607,19 +3613,22 @@ class MaskedArray(ndarray): """ n = len(self.shape) - name = repr(self._data).split('(')[0] + if self._baseclass is np.ndarray: + name = 'array' + else: + name = self._baseclass.__name__ + parameters = dict(name=name, nlen=" " * len(name), - data=str(self), mask=str(self._mask), - fill=str(self.fill_value), dtype=str(self.dtype)) + data=str(self), mask=str(self._mask), + fill=str(self.fill_value), dtype=str(self.dtype)) if self.dtype.names: if n <= 1: return _print_templates['short_flx'] % parameters - return _print_templates['long_flx'] % parameters + return _print_templates['long_flx'] % parameters elif n <= 1: return _print_templates['short_std'] % parameters return _print_templates['long_std'] % parameters - def __eq__(self, other): "Check whether other equals self elementwise" if self is masked: @@ -3824,8 +3833,7 @@ class MaskedArray(ndarray): "Raise self to the power other, in place." other_data = getdata(other) other_mask = getmask(other) - with np.errstate(): - np.seterr(divide='ignore', invalid='ignore') + with np.errstate(divide='ignore', invalid='ignore'): ndarray.__ipow__(self._data, np.where(self._mask, 1, other_data)) invalid = np.logical_not(np.isfinite(self._data)) if invalid.any(): @@ -3976,21 +3984,16 @@ class MaskedArray(ndarray): """ m = self._mask s = self.shape - ls = len(s) if m is nomask: - if ls == 0: - return 1 - if ls == 1: - return s[0] if axis is None: return self.size else: n = s[axis] t = list(s) del t[axis] - return np.ones(t) * n + return np.full(t, n, dtype=np.intp) n1 = np.size(m, axis) - n2 = m.astype(int).sum(axis) + n2 = np.sum(m, axis=axis, dtype=np.intp) if axis is None: return (n1 - n2) else: @@ -5071,12 +5074,12 @@ class MaskedArray(ndarray): filler = maximum_fill_value(self) else: filler = fill_value - idx = np.indices(self.shape) + idx = np.meshgrid(*[np.arange(x) for x in self.shape], sparse=True, + indexing='ij') idx[axis] = self.filled(filler).argsort(axis=axis, kind=kind, order=order) - idx_l = idx.tolist() - tmp_mask = self._mask[idx_l].flat - tmp_data = self._data[idx_l].flat + tmp_mask = self._mask[idx].flat + tmp_data = self._data[idx].flat self._data.flat = tmp_data self._mask.flat = tmp_mask return @@ -5387,10 +5390,20 @@ class MaskedArray(ndarray): #........................ def tostring(self, fill_value=None, order='C'): """ + This function is a compatibility alias for tobytes. Despite its name it + returns bytes not strings. + """ + + return self.tobytes(fill_value, order='C') + #........................ + def tobytes(self, fill_value=None, order='C'): + """ Return the array data as a string containing the raw bytes in the array. The array is filled with a fill value before the string conversion. + .. versionadded:: 1.9.0 + Parameters ---------- fill_value : scalar, optional @@ -5406,22 +5419,22 @@ class MaskedArray(ndarray): See Also -------- - ndarray.tostring + ndarray.tobytes tolist, tofile Notes ----- - As for `ndarray.tostring`, information about the shape, dtype, etc., + As for `ndarray.tobytes`, information about the shape, dtype, etc., but also about `fill_value`, will be lost. Examples -------- >>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]]) - >>> x.tostring() + >>> x.tobytes() '\\x01\\x00\\x00\\x00?B\\x0f\\x00?B\\x0f\\x00\\x04\\x00\\x00\\x00' """ - return self.filled(fill_value).tostring(order=order) + return self.filled(fill_value).tobytes(order=order) #........................ def tofile(self, fid, sep="", format="%s"): """ @@ -5503,9 +5516,9 @@ class MaskedArray(ndarray): self.shape, self.dtype, self.flags.fnc, - self._data.tostring(cf), + self._data.tobytes(cf), #self._data.tolist(), - getmaskarray(self).tostring(cf), + getmaskarray(self).tobytes(cf), #getmaskarray(self).tolist(), self._fill_value, ) @@ -6089,8 +6102,7 @@ def power(a, b, third=None): else: basetype = MaskedArray # Get the result and view it as a (subclass of) MaskedArray - with np.errstate(): - np.seterr(divide='ignore', invalid='ignore') + with np.errstate(divide='ignore', invalid='ignore'): result = np.where(m, fa, umath.power(fa, fb)).view(basetype) result._update_from(a) # Find where we're in trouble w/ NaNs and Infs @@ -6151,7 +6163,7 @@ def argmax(a, axis=None, fill_value=None): pass d = filled(a, fill_value) return d.argmax(axis=axis) -argmin.__doc__ = MaskedArray.argmax.__doc__ +argmax.__doc__ = MaskedArray.argmax.__doc__ def sort(a, axis= -1, kind='quicksort', order=None, endwith=True, fill_value=None): "Function version of the eponymous method." @@ -6167,7 +6179,8 @@ def sort(a, axis= -1, kind='quicksort', order=None, endwith=True, fill_value=Non else: filler = fill_value # return - indx = np.indices(a.shape).tolist() + indx = np.meshgrid(*[np.arange(x) for x in a.shape], sparse=True, + indexing='ij') indx[axis] = filled(a, filler).argsort(axis=axis, kind=kind, order=order) return a[indx] sort.__doc__ = MaskedArray.sort.__doc__ @@ -6921,6 +6934,13 @@ def allclose (a, b, masked_equal=True, rtol=1e-5, atol=1e-8): """ x = masked_array(a, copy=False) y = masked_array(b, copy=False) + + # make sure y is an inexact type to avoid abs(MIN_INT); will cause + # casting of x later. + dtype = np.result_type(y, 1.) + if y.dtype != dtype: + y = masked_array(y, dtype=dtype, copy=False) + m = mask_or(getmask(x), getmask(y)) xinf = np.isinf(masked_array(x, copy=False, mask=m)).filled(False) # If we have some infs, they should fall at the same place. @@ -6932,13 +6952,16 @@ def allclose (a, b, masked_equal=True, rtol=1e-5, atol=1e-8): atol + rtol * umath.absolute(y)), masked_equal) return np.all(d) + if not np.all(filled(x[xinf] == y[xinf], masked_equal)): return False x = x[~xinf] y = y[~xinf] + d = filled(umath.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y)), masked_equal) + return np.all(d) #.............................................................................. @@ -7243,3 +7266,41 @@ zeros = _convert2ma('zeros', params=dict(fill_value=None, hardmask=False)) zeros_like = np.zeros_like ############################################################################### +def append(a, b, axis=None): + """Append values to the end of an array. + + .. versionadded:: 1.9.0 + + Parameters + ---------- + arr : array_like + Values are appended to a copy of this array. + values : array_like + These values are appended to a copy of `arr`. It must be of the + correct shape (the same shape as `arr`, excluding `axis`). If `axis` + is not specified, `values` can be any shape and will be flattened + before use. + axis : int, optional + The axis along which `values` are appended. If `axis` is not given, + both `arr` and `values` are flattened before use. + + Returns + ------- + append : MaskedArray + A copy of `arr` with `values` appended to `axis`. Note that `append` + does not occur in-place: a new array is allocated and filled. If + `axis` is None, the result is a flattened array. + + See Also + -------- + numpy.append : Equivalent function in the top-level NumPy module. + + Examples + -------- + >>> import numpy.ma as ma + >>> a = ma.masked_values([1, 2, 3], 2) + >>> b = ma.masked_values([[4, 5, 6], [7, 8, 9]], 7) + >>> print(ma.append(a, b)) + [1 -- 3 4 5 6 -- 8 9] + """ + return concatenate([a, b], axis) diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py index d14812093..82a61a67c 100644 --- a/numpy/ma/extras.py +++ b/numpy/ma/extras.py @@ -416,26 +416,53 @@ def apply_over_axes(func, a, axes): """ (This docstring will be overwritten) """ - val = np.asarray(a) - msk = getmaskarray(a) + val = asarray(a) N = a.ndim if array(axes).ndim == 0: axes = (axes,) for axis in axes: if axis < 0: axis = N + axis args = (val, axis) - res = ma.array(func(*(val, axis)), mask=func(*(msk, axis))) + res = func(*args) if res.ndim == val.ndim: - (val, msk) = (res._data, res._mask) + val = res else: res = ma.expand_dims(res, axis) if res.ndim == val.ndim: - (val, msk) = (res._data, res._mask) + val = res else: - raise ValueError("Function is not returning"\ - " an array of correct shape") + raise ValueError("function is not returning " + "an array of the correct shape") return val -apply_over_axes.__doc__ = np.apply_over_axes.__doc__ +apply_over_axes.__doc__ = np.apply_over_axes.__doc__[ + :np.apply_over_axes.__doc__.find('Notes')].rstrip() + \ + """ + + Examples + -------- + >>> a = ma.arange(24).reshape(2,3,4) + >>> a[:,0,1] = ma.masked + >>> a[:,1,:] = ma.masked + >>> print a + [[[0 -- 2 3] + [-- -- -- --] + [8 9 10 11]] + + [[12 -- 14 15] + [-- -- -- --] + [20 21 22 23]]] + >>> print ma.apply_over_axes(ma.sum, a, [0,2]) + [[[46] + [--] + [124]]] + + Tuple axis arguments to ufuncs are equivalent: + + >>> print ma.sum(a, axis=(0,2)).reshape((1,-1,1)) + [[[46] + [--] + [124]]] +""" def average(a, axis=None, weights=None, returned=False): @@ -448,8 +475,8 @@ def average(a, axis=None, weights=None, returned=False): Data to be averaged. Masked entries are not taken into account in the computation. axis : int, optional - Axis along which the variance is computed. The default is to compute - the variance of the flattened array. + Axis along which the average is computed. The default is to compute + the average of the flattened array. weights : array_like, optional The importance that each element has in the computation of the average. The weights array can either be 1-D (in which case its length must be @@ -540,7 +567,7 @@ def average(a, axis=None, weights=None, returned=False): else: if weights is None: n = add.reduce(a, axis) - d = umath.add.reduce((-mask), axis=axis, dtype=float) + d = umath.add.reduce((~mask), axis=axis, dtype=float) else: w = filled(weights, 0.0) wsh = w.shape @@ -641,15 +668,9 @@ def median(a, axis=None, out=None, overwrite_input=False): fill_value = 1e+20) """ - def _median1D(data): - counts = filled(count(data), 0) - (idx, rmd) = divmod(counts, 2) - if rmd: - choice = slice(idx, idx + 1) - else: - choice = slice(idx - 1, idx + 1) - return data[choice].mean(0) - # + if not hasattr(a, 'mask') or np.count_nonzero(a.mask) == 0: + return masked_array(np.median(a, axis=axis, out=out, + overwrite_input=overwrite_input), copy=False) if overwrite_input: if axis is None: asorted = a.ravel() @@ -660,14 +681,29 @@ def median(a, axis=None, out=None, overwrite_input=False): else: asorted = sort(a, axis=axis) if axis is None: - result = _median1D(asorted) + axis = 0 + elif axis < 0: + axis += a.ndim + + counts = asorted.shape[axis] - (asorted.mask).sum(axis=axis) + h = counts // 2 + # create indexing mesh grid for all but reduced axis + axes_grid = [np.arange(x) for i, x in enumerate(asorted.shape) + if i != axis] + ind = np.meshgrid(*axes_grid, sparse=True, indexing='ij') + # insert indices of low and high median + ind.insert(axis, h - 1) + low = asorted[ind] + ind[axis] = h + high = asorted[ind] + # duplicate high if odd number of elements so mean does nothing + odd = counts % 2 == 1 + if asorted.ndim == 1: + if odd: + low = high else: - result = apply_along_axis(_median1D, axis, asorted) - if out is not None: - out = result - return result - - + low[odd] = high[odd] + return np.ma.mean([low, high], axis=0, out=out) #.............................................................................. @@ -842,9 +878,9 @@ def mask_rowcols(a, axis=None): fill_value=999999) """ - a = asarray(a) + a = array(a, subok=False) if a.ndim != 2: - raise NotImplementedError("compress2d works for 2D arrays only.") + raise NotImplementedError("mask_rowcols works for 2D arrays only.") m = getmask(a) # Nothing is masked: return a if m is nomask or not m.any(): @@ -1735,7 +1771,7 @@ def _ezclump(mask): #def clump_masked(a): if mask.ndim > 1: mask = mask.ravel() - idx = (mask[1:] - mask[:-1]).nonzero() + idx = (mask[1:] ^ mask[:-1]).nonzero() idx = idx[0] + 1 slices = [slice(left, right) for (left, right) in zip(itertools.chain([0], idx), diff --git a/numpy/ma/mrecords.py b/numpy/ma/mrecords.py index a2380d813..e66596509 100644 --- a/numpy/ma/mrecords.py +++ b/numpy/ma/mrecords.py @@ -426,8 +426,8 @@ The fieldname base is either `_data` or `_mask`.""" self.shape, self.dtype, self.flags.fnc, - self._data.tostring(), - self._mask.tostring(), + self._data.tobytes(), + self._mask.tobytes(), self._fill_value, ) return state diff --git a/numpy/ma/tests/test_core.py b/numpy/ma/tests/test_core.py index 764915236..8172335a8 100644 --- a/numpy/ma/tests/test_core.py +++ b/numpy/ma/tests/test_core.py @@ -13,6 +13,8 @@ import sys import pickle from functools import reduce +from nose.tools import assert_raises + import numpy as np import numpy.ma.core import numpy.core.fromnumeric as fromnumeric @@ -192,8 +194,7 @@ class TestMaskedArray(TestCase): def test_fix_invalid(self): # Checks fix_invalid. - with np.errstate(): - np.seterr(invalid='ignore') + with np.errstate(invalid='ignore'): data = masked_array([np.nan, 0., 1.], mask=[0, 0, 1]) data_fixed = fix_invalid(data) assert_equal(data_fixed._data, [data.fill_value, 0., 1.]) @@ -354,6 +355,13 @@ class TestMaskedArray(TestCase): assert_equal(copied.mask, [0, 0, 0]) assert_equal(a.mask, [0, 1, 0]) + def test_str_repr(self): + a = array([0, 1, 2], mask=[False, True, False]) + assert_equal(str(a), '[0 -- 2]') + assert_equal(repr(a), 'masked_array(data = [0 -- 2],\n' + ' mask = [False True False],\n' + ' fill_value = 999999)\n') + def test_pickling(self): # Tests pickling a = arange(10) @@ -474,6 +482,10 @@ class TestMaskedArray(TestCase): atest[idx] = btest[idx] assert_equal(atest, [20]) + def test_filled_w_object_dtype(self): + a = np.ma.masked_all(1, dtype='O') + assert_equal(a.filled('x')[0], 'x') + def test_filled_w_flexible_dtype(self): # Test filled w/ flexible dtype flexi = array([(1, 1, 1)], @@ -795,23 +807,29 @@ class TestMaskedArrayArithmetic(TestCase): def test_count_func(self): # Tests count - ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) - if sys.version_info[0] >= 3: - self.assertTrue(isinstance(count(ott), np.integer)) - else: - self.assertTrue(isinstance(count(ott), int)) - assert_equal(3, count(ott)) assert_equal(1, count(1)) assert_equal(0, array(1, mask=[1])) + + ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) + res = count(ott) + self.assertTrue(res.dtype.type is np.intp) + assert_equal(3, res) + ott = ott.reshape((2, 2)) - assert_(isinstance(count(ott, 0), ndarray)) - if sys.version_info[0] >= 3: - assert_(isinstance(count(ott), np.integer)) - else: - assert_(isinstance(count(ott), int)) - assert_equal(3, count(ott)) - assert_(getmask(count(ott, 0)) is nomask) - assert_equal([1, 2], count(ott, 0)) + res = count(ott) + assert_(res.dtype.type is np.intp) + assert_equal(3, res) + res = count(ott, 0) + assert_(isinstance(res, ndarray)) + assert_equal([1, 2], res) + assert_(getmask(res) is nomask) + + ott= array([0., 1., 2., 3.]) + res = count(ott, 0) + assert_(isinstance(res, ndarray)) + assert_(res.dtype.type is np.intp) + + assert_raises(IndexError, ott.count, 1) def test_minmax_func(self): # Tests minimum and maximum. @@ -1275,23 +1293,64 @@ class TestMaskedArrayAttributes(TestCase): assert_equal(a.mask, nomask) def test_flat(self): + # Test that flat can return all types of items [#4585, #4615] + # test simple access + test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1]) + assert_equal(test.flat[1], 2) + assert_equal(test.flat[2], masked) + self.assertTrue(np.all(test.flat[0:2] == test[0, 0:2])) # Test flat on masked_matrices test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1]) test.flat = masked_array([3, 2, 1], mask=[1, 0, 0]) control = masked_array(np.matrix([[3, 2, 1]]), mask=[1, 0, 0]) assert_equal(test, control) - # + # Test setting test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1]) testflat = test.flat testflat[:] = testflat[[2, 1, 0]] assert_equal(test, control) + testflat[0] = 9 + assert_equal(test[0, 0], 9) + # test 2-D record array + # ... on structured array w/ masked records + x = array([[(1, 1.1, 'one'), (2, 2.2, 'two'), (3, 3.3, 'thr')], + [(4, 4.4, 'fou'), (5, 5.5, 'fiv'), (6, 6.6, 'six')]], + dtype=[('a', int), ('b', float), ('c', '|S8')]) + x['a'][0, 1] = masked + x['b'][1, 0] = masked + x['c'][0, 2] = masked + x[-1, -1] = masked + xflat = x.flat + assert_equal(xflat[0], x[0, 0]) + assert_equal(xflat[1], x[0, 1]) + assert_equal(xflat[2], x[0, 2]) + assert_equal(xflat[:3], x[0]) + assert_equal(xflat[3], x[1, 0]) + assert_equal(xflat[4], x[1, 1]) + assert_equal(xflat[5], x[1, 2]) + assert_equal(xflat[3:], x[1]) + assert_equal(xflat[-1], x[-1, -1]) + i = 0 + j = 0 + for xf in xflat: + assert_equal(xf, x[j, i]) + i += 1 + if i >= x.shape[-1]: + i = 0 + j += 1 + # test that matrices keep the correct shape (#4615) + a = masked_array(np.matrix(np.eye(2)), mask=0) + b = a.flat + b01 = b[:2] + assert_equal(b01.data, array([[1., 0.]])) + assert_equal(b01.mask, array([[False, False]])) #------------------------------------------------------------------------------ class TestFillingValues(TestCase): - # + def test_check_on_scalar(self): - # Test _check_fill_value + # Test _check_fill_value set to valid and invalid values _check_fill_value = np.ma.core._check_fill_value # fval = _check_fill_value(0, int) @@ -1303,9 +1362,8 @@ class TestFillingValues(TestCase): assert_equal(fval, asbytes("0")) fval = _check_fill_value(None, "|S3") assert_equal(fval, default_fill_value("|S3")) - # - fval = _check_fill_value(1e+20, int) - assert_equal(fval, default_fill_value(0)) + self.assertRaises(TypeError, _check_fill_value, 1e+20, int) + self.assertRaises(TypeError, _check_fill_value, 'stuff', int) def test_check_on_fields(self): # Tests _check_fill_value with records @@ -1991,6 +2049,10 @@ class TestMaskedArrayMethods(TestCase): a[0] = 0 self.assertTrue(allclose(a, 0, masked_equal=True)) + # Test that the function works for MIN_INT integer typed arrays + a = masked_array([np.iinfo(np.int_).min], dtype=np.int_) + self.assertTrue(allclose(a, a)) + def test_allany(self): # Checks the any/all methods/functions. x = np.array([[0.13, 0.26, 0.90], @@ -3571,6 +3633,45 @@ def test_masked_array(): a = np.ma.array([0, 1, 2, 3], mask=[0, 0, 1, 0]) assert_equal(np.argwhere(a), [[1], [3]]) +def test_append_masked_array(): + a = np.ma.masked_equal([1,2,3], value=2) + b = np.ma.masked_equal([4,3,2], value=2) + + result = np.ma.append(a, b) + expected_data = [1, 2, 3, 4, 3, 2] + expected_mask = [False, True, False, False, False, True] + assert_array_equal(result.data, expected_data) + assert_array_equal(result.mask, expected_mask) + + a = np.ma.masked_all((2,2)) + b = np.ma.ones((3,1)) + + result = np.ma.append(a, b) + expected_data = [1] * 3 + expected_mask = [True] * 4 + [False] * 3 + assert_array_equal(result.data[-3], expected_data) + assert_array_equal(result.mask, expected_mask) + + result = np.ma.append(a, b, axis=None) + assert_array_equal(result.data[-3], expected_data) + assert_array_equal(result.mask, expected_mask) + + +def test_append_masked_array_along_axis(): + a = np.ma.masked_equal([1,2,3], value=2) + b = np.ma.masked_values([[4, 5, 6], [7, 8, 9]], 7) + + # When `axis` is specified, `values` must have the correct shape. + assert_raises(ValueError, np.ma.append, a, b, axis=0) + + result = np.ma.append(a[np.newaxis,:], b, axis=0) + expected = np.ma.arange(1, 10) + expected[[1, 6]] = np.ma.masked + expected = expected.reshape((3,3)) + assert_array_equal(result.data, expected.data) + assert_array_equal(result.mask, expected.mask) + + ############################################################################### if __name__ == "__main__": run_module_suite() diff --git a/numpy/ma/tests/test_extras.py b/numpy/ma/tests/test_extras.py index dc0f87b92..6ce1dc346 100644 --- a/numpy/ma/tests/test_extras.py +++ b/numpy/ma/tests/test_extras.py @@ -479,6 +479,16 @@ class TestApplyAlongAxis(TestCase): xa = apply_along_axis(myfunc, 2, a) assert_equal(xa, [[1, 4], [7, 10]]) + # Tests kwargs functions + def test_3d_kwargs(self): + a = arange(12).reshape(2, 2, 3) + + def myfunc(b, offset=0): + return b[1+offset] + + xa = apply_along_axis(myfunc, 2, a, offset=1) + assert_equal(xa, [[2, 5], [8, 11]]) + class TestApplyOverAxes(TestCase): # Tests apply_over_axes @@ -489,7 +499,8 @@ class TestApplyOverAxes(TestCase): assert_equal(test, ctrl) a[(a % 2).astype(np.bool)] = masked test = apply_over_axes(np.sum, a, [0, 2]) - ctrl = np.array([[[30], [44], [60]]]) + ctrl = np.array([[[28], [44], [60]]]) + assert_equal(test, ctrl) class TestMedian(TestCase): @@ -530,6 +541,19 @@ class TestMedian(TestCase): x[x % 5 == 0] = masked assert_equal(median(x, 0), [[12, 10], [8, 9], [16, 17]]) + def test_neg_axis(self): + x = masked_array(np.arange(30).reshape(10, 3)) + x[:3] = x[-3:] = masked + assert_equal(median(x, axis=-1), median(x, axis=1)) + + def test_out(self): + x = masked_array(np.arange(30).reshape(10, 3)) + x[:3] = x[-3:] = masked + out = masked_array(np.ones(10)) + r = median(x, axis=1, out=out) + assert_equal(r, out) + assert_(type(r) == MaskedArray) + class TestCov(TestCase): diff --git a/numpy/ma/tests/test_old_ma.py b/numpy/ma/tests/test_old_ma.py index 27d699385..047f91c77 100644 --- a/numpy/ma/tests/test_old_ma.py +++ b/numpy/ma/tests/test_old_ma.py @@ -153,19 +153,14 @@ class TestMa(TestCase): def test_xtestCount(self): # Test count ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) - if sys.version_info[0] >= 3: - self.assertTrue(isinstance(count(ott), np.integer)) - else: - self.assertTrue(isinstance(count(ott), int)) + self.assertTrue(count(ott).dtype.type is np.intp) self.assertEqual(3, count(ott)) self.assertEqual(1, count(1)) self.assertTrue(eq(0, array(1, mask=[1]))) ott = ott.reshape((2, 2)) + self.assertTrue(count(ott).dtype.type is np.intp) assert_(isinstance(count(ott, 0), np.ndarray)) - if sys.version_info[0] >= 3: - assert_(isinstance(count(ott), np.integer)) - else: - assert_(isinstance(count(ott), int)) + self.assertTrue(count(ott).dtype.type is np.intp) self.assertTrue(eq(3, count(ott))) assert_(getmask(count(ott, 0)) is nomask) self.assertTrue(eq([1, 2], count(ott, 0))) @@ -612,8 +607,7 @@ class TestMa(TestCase): def test_testScalarArithmetic(self): xm = array(0, mask=1) #TODO FIXME: Find out what the following raises a warning in r8247 - with np.errstate(): - np.seterr(divide='ignore') + with np.errstate(divide='ignore'): self.assertTrue((1 / array(0)).mask) self.assertTrue((1 + xm).mask) self.assertTrue((-xm).mask) diff --git a/numpy/ma/tests/test_subclassing.py b/numpy/ma/tests/test_subclassing.py index c2c9b8ec9..ade5c59da 100644 --- a/numpy/ma/tests/test_subclassing.py +++ b/numpy/ma/tests/test_subclassing.py @@ -82,6 +82,24 @@ class MMatrix(MaskedArray, np.matrix,): mmatrix = MMatrix +# also a subclass that overrides __str__, __repr__ and __setitem__, disallowing +# setting to non-class values (and thus np.ma.core.masked_print_option) +class ComplicatedSubArray(SubArray): + def __str__(self): + return 'myprefix {0} mypostfix'.format( + super(ComplicatedSubArray, self).__str__()) + + def __repr__(self): + # Return a repr that does not start with 'name(' + return '<{0} {1}>'.format(self.__class__.__name__, self) + + def __setitem__(self, item, value): + # this ensures direct assignment to masked_print_option will fail + if not isinstance(value, ComplicatedSubArray): + raise ValueError("Can only set to MySubArray values") + super(ComplicatedSubArray, self).__setitem__(item, value) + + class TestSubclassing(TestCase): # Test suite for masked subclasses of ndarray. @@ -187,6 +205,31 @@ class TestSubclassing(TestCase): assert_equal(mxsub.info, xsub.info) assert_equal(mxsub._mask, m) + def test_subclass_repr(self): + """test that repr uses the name of the subclass + and 'array' for np.ndarray""" + x = np.arange(5) + mx = masked_array(x, mask=[True, False, True, False, False]) + self.assertTrue(repr(mx).startswith('masked_array')) + xsub = SubArray(x) + mxsub = masked_array(xsub, mask=[True, False, True, False, False]) + self.assertTrue(repr(mxsub).startswith( + 'masked_{0}(data = [-- 1 -- 3 4]'.format(SubArray.__name__))) + + def test_subclass_str(self): + """test str with subclass that has overridden str, setitem""" + # first without override + x = np.arange(5) + xsub = SubArray(x) + mxsub = masked_array(xsub, mask=[True, False, True, False, False]) + self.assertTrue(str(mxsub) == '[-- 1 -- 3 4]') + + xcsub = ComplicatedSubArray(x) + assert_raises(ValueError, xcsub.__setitem__, 0, + np.ma.core.masked_print_option) + mxcsub = masked_array(xcsub, mask=[True, False, True, False, False]) + self.assertTrue(str(mxcsub) == 'myprefix [-- 1 -- 3 4] mypostfix') + ############################################################################### if __name__ == '__main__': diff --git a/numpy/matrixlib/tests/test_defmatrix.py b/numpy/matrixlib/tests/test_defmatrix.py index d1a4e4ab5..a06a564aa 100644 --- a/numpy/matrixlib/tests/test_defmatrix.py +++ b/numpy/matrixlib/tests/test_defmatrix.py @@ -285,8 +285,8 @@ class TestMatrixReturn(TestCase): 'getA', 'getA1', 'item', 'nonzero', 'put', 'putmask', 'resize', 'searchsorted', 'setflags', 'setfield', 'sort', 'partition', 'argpartition', - 'take', 'tofile', 'tolist', 'tostring', 'all', 'any', 'sum', - 'argmax', 'argmin', 'min', 'max', 'mean', 'var', 'ptp', + 'take', 'tofile', 'tolist', 'tostring', 'tobytes', 'all', 'any', + 'sum', 'argmax', 'argmin', 'min', 'max', 'mean', 'var', 'ptp', 'prod', 'std', 'ctypes', 'itemset', 'setasflat' ] for attrib in dir(a): diff --git a/numpy/polynomial/_polybase.py b/numpy/polynomial/_polybase.py new file mode 100644 index 000000000..23608c74a --- /dev/null +++ b/numpy/polynomial/_polybase.py @@ -0,0 +1,964 @@ +""" +Abstract base class for the various polynomial Classes. + +The ABCPolyBase class provides the methods needed to implement the common API +for the various polynomial classes. It operates as a mixin, but uses the +abc module from the stdlib, hence it is only available for Python >= 2.6. + +""" +from __future__ import division, absolute_import, print_function + +from abc import ABCMeta, abstractmethod, abstractproperty +from numbers import Number + +import numpy as np +from . import polyutils as pu + +__all__ = ['ABCPolyBase'] + +class ABCPolyBase(object): + """An abstract base class for series classes. + + ABCPolyBase provides the standard Python numerical methods + '+', '-', '*', '//', '%', 'divmod', '**', and '()' along with the + methods listed below. + + .. versionadded:: 1.9.0 + + Parameters + ---------- + coef : array_like + Series coefficients in order of increasing degree, i.e., + ``(1, 2, 3)`` gives ``1*P_0(x) + 2*P_1(x) + 3*P_2(x)``, where + ``P_i`` is the basis polynomials of degree ``i``. + domain : (2,) array_like, optional + Domain to use. The interval ``[domain[0], domain[1]]`` is mapped + to the interval ``[window[0], window[1]]`` by shifting and scaling. + The default value is the derived class domain. + window : (2,) array_like, optional + Window, see domain for its use. The default value is the + derived class window. + + Attributes + ---------- + coef : (N,) ndarray + Series coefficients in order of increasing degree. + domain : (2,) ndarray + Domain that is mapped to window. + window : (2,) ndarray + Window that domain is mapped to. + + Class Attributes + ---------------- + maxpower : int + Maximum power allowed, i.e., the largest number ``n`` such that + ``p(x)**n`` is allowed. This is to limit runaway polynomial size. + domain : (2,) ndarray + Default domain of the class. + window : (2,) ndarray + Default window of the class. + + """ + __metaclass__ = ABCMeta + + # Not hashable + __hash__ = None + + # Don't let participate in array operations. Value doesn't matter. + __array_priority__ = 1000 + + # Limit runaway size. T_n^m has degree n*m + maxpower = 100 + + @abstractproperty + def domain(self): + pass + + @abstractproperty + def window(self): + pass + + @abstractproperty + def nickname(self): + pass + + @abstractmethod + def _add(self): + pass + + @abstractmethod + def _sub(self): + pass + + @abstractmethod + def _mul(self): + pass + + @abstractmethod + def _div(self): + pass + + @abstractmethod + def _pow(self): + pass + + @abstractmethod + def _val(self): + pass + + @abstractmethod + def _int(self): + pass + + @abstractmethod + def _der(self): + pass + + @abstractmethod + def _fit(self): + pass + + @abstractmethod + def _line(self): + pass + + @abstractmethod + def _roots(self): + pass + + @abstractmethod + def _fromroots(self): + pass + + def has_samecoef(self, other): + """Check if coefficients match. + + .. versionadded:: 1.6.0 + + Parameters + ---------- + other : class instance + The other class must have the ``coef`` attribute. + + Returns + ------- + bool : boolean + True if the coefficients are the same, False otherwise. + + """ + if len(self.coef) != len(other.coef): + return False + elif not np.all(self.coef == other.coef): + return False + else: + return True + + def has_samedomain(self, other): + """Check if domains match. + + .. versionadded:: 1.6.0 + + Parameters + ---------- + other : class instance + The other class must have the ``domain`` attribute. + + Returns + ------- + bool : boolean + True if the domains are the same, False otherwise. + + """ + return np.all(self.domain == other.domain) + + def has_samewindow(self, other): + """Check if windows match. + + .. versionadded:: 1.6.0 + + Parameters + ---------- + other : class instance + The other class must have the ``window`` attribute. + + Returns + ------- + bool : boolean + True if the windows are the same, False otherwise. + + """ + return np.all(self.window == other.window) + + def has_sametype(self, other): + """Check if types match. + + .. versionadded:: 1.7.0 + + Parameters + ---------- + other : object + Class instance. + + Returns + ------- + bool : boolean + True if other is same class as self + + """ + return isinstance(other, self.__class__) + + def _get_coefficients(self, other): + """Interpret other as polynomial coefficients. + + The `other` argument is checked to see if it is of the same + class as self with identical domain and window. If so, + return its coefficients, otherwise return `other`. + + .. versionadded:: 1.9.0 + + Parameters + ---------- + other : anything + Object to be checked. + + Returns + ------- + coef: + The coefficients of`other` if it is a compatible instance, + of ABCPolyBase, otherwise `other`. + + Raises + ------ + TypeError: + When `other` is an incompatible instance of ABCPolyBase. + + """ + if isinstance(other, ABCPolyBase): + if not isinstance(other, self.__class__): + raise TypeError("Polynomial types differ") + elif not np.all(self.domain == other.domain): + raise TypeError("Domains differ") + elif not np.all(self.window == other.window): + raise TypeError("Windows differ") + return other.coef + return other + + def __init__(self, coef, domain=None, window=None): + [coef] = pu.as_series([coef], trim=False) + self.coef = coef + + if domain is not None: + [domain] = pu.as_series([domain], trim=False) + if len(domain) != 2: + raise ValueError("Domain has wrong number of elements.") + self.domain = domain + + if window is not None: + [window] = pu.as_series([window], trim=False) + if len(window) != 2: + raise ValueError("Window has wrong number of elements.") + self.window = window + + def __repr__(self): + format = "%s(%s, %s, %s)" + coef = repr(self.coef)[6:-1] + domain = repr(self.domain)[6:-1] + window = repr(self.window)[6:-1] + name = self.__class__.__name__ + return format % (name, coef, domain, window) + + def __str__(self): + format = "%s(%s)" + coef = str(self.coef) + name = self.nickname + return format % (name, coef) + + # Pickle and copy + + def __getstate__(self): + ret = self.__dict__.copy() + ret['coef'] = self.coef.copy() + ret['domain'] = self.domain.copy() + ret['window'] = self.window.copy() + return ret + + def __setstate__(self, dict): + self.__dict__ = dict + + # Call + + def __call__(self, arg): + off, scl = pu.mapparms(self.domain, self.window) + arg = off + scl*arg + return self._val(arg, self.coef) + + def __iter__(self): + return iter(self.coef) + + def __len__(self): + return len(self.coef) + + # Numeric properties. + + def __neg__(self): + return self.__class__(-self.coef, self.domain, self.window) + + def __pos__(self): + return self + + def __add__(self, other): + try: + othercoef = self._get_coefficients(other) + coef = self._add(self.coef, othercoef) + except TypeError as e: + raise e + except: + return NotImplemented + return self.__class__(coef, self.domain, self.window) + + def __sub__(self, other): + try: + othercoef = self._get_coefficients(other) + coef = self._sub(self.coef, othercoef) + except TypeError as e: + raise e + except: + return NotImplemented + return self.__class__(coef, self.domain, self.window) + + def __mul__(self, other): + try: + othercoef = self._get_coefficients(other) + coef = self._mul(self.coef, othercoef) + except TypeError as e: + raise e + except: + return NotImplemented + return self.__class__(coef, self.domain, self.window) + + def __div__(self, other): + # set to __floordiv__, /, for now. + return self.__floordiv__(other) + + def __truediv__(self, other): + # there is no true divide if the rhs is not a Number, although it + # could return the first n elements of an infinite series. + # It is hard to see where n would come from, though. + if not isinstance(other, Number) or isinstance(other, bool): + form = "unsupported types for true division: '%s', '%s'" + raise TypeError(form % (type(self), type(other))) + return self.__floordiv__(other) + + def __floordiv__(self, other): + res = self.__divmod__(other) + if res is NotImplemented: + return res + return res[0] + + def __mod__(self, other): + res = self.__divmod__(other) + if res is NotImplemented: + return res + return res[1] + + def __divmod__(self, other): + try: + othercoef = self._get_coefficients(other) + quo, rem = self._div(self.coef, othercoef) + except (TypeError, ZeroDivisionError) as e: + raise e + except: + return NotImplemented + quo = self.__class__(quo, self.domain, self.window) + rem = self.__class__(rem, self.domain, self.window) + return quo, rem + + def __pow__(self, other): + coef = self._pow(self.coef, other, maxpower = self.maxpower) + res = self.__class__(coef, self.domain, self.window) + return res + + def __radd__(self, other): + try: + coef = self._add(other, self.coef) + except: + return NotImplemented + return self.__class__(coef, self.domain, self.window) + + def __rsub__(self, other): + try: + coef = self._sub(other, self.coef) + except: + return NotImplemented + return self.__class__(coef, self.domain, self.window) + + def __rmul__(self, other): + try: + coef = self._mul(other, self.coef) + except: + return NotImplemented + return self.__class__(coef, self.domain, self.window) + + def __rdiv__(self, other): + # set to __floordiv__ /. + return self.__rfloordiv__(other) + + def __rtruediv__(self, other): + # An instance of ABCPolyBase is not considered a + # Number. + return NotImplemented + + def __rfloordiv__(self, other): + res = self.__rdivmod__(other) + if res is NotImplemented: + return res + return res[0] + + def __rmod__(self, other): + res = self.__rdivmod__(other) + if res is NotImplemented: + return res + return res[1] + + def __rdivmod__(self, other): + try: + quo, rem = self._div(other, self.coef) + except ZeroDivisionError as e: + raise e + except: + return NotImplemented + quo = self.__class__(quo, self.domain, self.window) + rem = self.__class__(rem, self.domain, self.window) + return quo, rem + + # Enhance me + # some augmented arithmetic operations could be added here + + def __eq__(self, other): + res = (isinstance(other, self.__class__) and + np.all(self.domain == other.domain) and + np.all(self.window == other.window) and + (self.coef.shape == other.coef.shape) and + np.all(self.coef == other.coef)) + return res + + def __ne__(self, other): + return not self.__eq__(other) + + # + # Extra methods. + # + + def copy(self): + """Return a copy. + + Returns + ------- + new_series : series + Copy of self. + + """ + return self.__class__(self.coef, self.domain, self.window) + + def degree(self): + """The degree of the series. + + .. versionadded:: 1.5.0 + + Returns + ------- + degree : int + Degree of the series, one less than the number of coefficients. + + """ + return len(self) - 1 + + def cutdeg(self, deg): + """Truncate series to the given degree. + + Reduce the degree of the series to `deg` by discarding the + high order terms. If `deg` is greater than the current degree a + copy of the current series is returned. This can be useful in least + squares where the coefficients of the high degree terms may be very + small. + + .. versionadded:: 1.5.0 + + Parameters + ---------- + deg : non-negative int + The series is reduced to degree `deg` by discarding the high + order terms. The value of `deg` must be a non-negative integer. + + Returns + ------- + new_series : series + New instance of series with reduced degree. + + """ + return self.truncate(deg + 1) + + def trim(self, tol=0): + """Remove trailing coefficients + + Remove trailing coefficients until a coefficient is reached whose + absolute value greater than `tol` or the beginning of the series is + reached. If all the coefficients would be removed the series is set + to ``[0]``. A new series instance is returned with the new + coefficients. The current instance remains unchanged. + + Parameters + ---------- + tol : non-negative number. + All trailing coefficients less than `tol` will be removed. + + Returns + ------- + new_series : series + Contains the new set of coefficients. + + """ + coef = pu.trimcoef(self.coef, tol) + return self.__class__(coef, self.domain, self.window) + + def truncate(self, size): + """Truncate series to length `size`. + + Reduce the series to length `size` by discarding the high + degree terms. The value of `size` must be a positive integer. This + can be useful in least squares where the coefficients of the + high degree terms may be very small. + + Parameters + ---------- + size : positive int + The series is reduced to length `size` by discarding the high + degree terms. The value of `size` must be a positive integer. + + Returns + ------- + new_series : series + New instance of series with truncated coefficients. + + """ + isize = int(size) + if isize != size or isize < 1: + raise ValueError("size must be a positive integer") + if isize >= len(self.coef): + coef = self.coef + else: + coef = self.coef[:isize] + return self.__class__(coef, self.domain, self.window) + + def convert(self, domain=None, kind=None, window=None): + """Convert series to a different kind and/or domain and/or window. + + Parameters + ---------- + domain : array_like, optional + The domain of the converted series. If the value is None, + the default domain of `kind` is used. + kind : class, optional + The polynomial series type class to which the current instance + should be converted. If kind is None, then the class of the + current instance is used. + window : array_like, optional + The window of the converted series. If the value is None, + the default window of `kind` is used. + + Returns + ------- + new_series : series + The returned class can be of different type than the current + instance and/or have a different domain and/or different + window. + + Notes + ----- + Conversion between domains and class types can result in + numerically ill defined series. + + Examples + -------- + + """ + if kind is None: + kind = self.__class__ + if domain is None: + domain = kind.domain + if window is None: + window = kind.window + return self(kind.identity(domain, window=window)) + + def mapparms(self): + """Return the mapping parameters. + + The returned values define a linear map ``off + scl*x`` that is + applied to the input arguments before the series is evaluated. The + map depends on the ``domain`` and ``window``; if the current + ``domain`` is equal to the ``window`` the resulting map is the + identity. If the coefficients of the series instance are to be + used by themselves outside this class, then the linear function + must be substituted for the ``x`` in the standard representation of + the base polynomials. + + Returns + ------- + off, scl : float or complex + The mapping function is defined by ``off + scl*x``. + + Notes + ----- + If the current domain is the interval ``[l1, r1]`` and the window + is ``[l2, r2]``, then the linear mapping function ``L`` is + defined by the equations:: + + L(l1) = l2 + L(r1) = r2 + + """ + return pu.mapparms(self.domain, self.window) + + def integ(self, m=1, k=[], lbnd=None): + """Integrate. + + Return a series instance that is the definite integral of the + current series. + + Parameters + ---------- + m : non-negative int + The number of integrations to perform. + k : array_like + Integration constants. The first constant is applied to the + first integration, the second to the second, and so on. The + list of values must less than or equal to `m` in length and any + missing values are set to zero. + lbnd : Scalar + The lower bound of the definite integral. + + Returns + ------- + new_series : series + A new series representing the integral. The domain is the same + as the domain of the integrated series. + + """ + off, scl = self.mapparms() + if lbnd is None: + lbnd = 0 + else: + lbnd = off + scl*lbnd + coef = self._int(self.coef, m, k, lbnd, 1./scl) + return self.__class__(coef, self.domain, self.window) + + def deriv(self, m=1): + """Differentiate. + + Return a series instance of that is the derivative of the current + series. + + Parameters + ---------- + m : non-negative int + The number of integrations to perform. + + Returns + ------- + new_series : series + A new series representing the derivative. The domain is the same + as the domain of the differentiated series. + + """ + off, scl = self.mapparms() + coef = self._der(self.coef, m, scl) + return self.__class__(coef, self.domain, self.window) + + def roots(self): + """Return the roots of the series polynomial. + + Compute the roots for the series. Note that the accuracy of the + roots decrease the further outside the domain they lie. + + Returns + ------- + roots : ndarray + Array containing the roots of the series. + + """ + roots = self._roots(self.coef) + return pu.mapdomain(roots, self.window, self.domain) + + def linspace(self, n=100, domain=None): + """Return x, y values at equally spaced points in domain. + + Returns the x, y values at `n` linearly spaced points across the + domain. Here y is the value of the polynomial at the points x. By + default the domain is the same as that of the series instance. + This method is intended mostly as a plotting aid. + + .. versionadded:: 1.5.0 + + Parameters + ---------- + n : int, optional + Number of point pairs to return. The default value is 100. + domain : {None, array_like}, optional + If not None, the specified domain is used instead of that of + the calling instance. It should be of the form ``[beg,end]``. + The default is None which case the class domain is used. + + Returns + ------- + x, y : ndarray + x is equal to linspace(self.domain[0], self.domain[1], n) and + y is the series evaluated at element of x. + + """ + if domain is None: + domain = self.domain + x = np.linspace(domain[0], domain[1], n) + y = self(x) + return x, y + + + + @classmethod + def fit(cls, x, y, deg, domain=None, rcond=None, full=False, w=None, + window=None): + """Least squares fit to data. + + Return a series instance that is the least squares fit to the data + `y` sampled at `x`. The domain of the returned instance can be + specified and this will often result in a superior fit with less + chance of ill conditioning. + + Parameters + ---------- + x : array_like, shape (M,) + x-coordinates of the M sample points ``(x[i], y[i])``. + y : array_like, shape (M,) or (M, K) + y-coordinates of the sample points. Several data sets of sample + points sharing the same x-coordinates can be fitted at once by + passing in a 2D-array that contains one dataset per column. + deg : int + Degree of the fitting polynomial. + domain : {None, [beg, end], []}, optional + Domain to use for the returned series. If ``None``, + then a minimal domain that covers the points `x` is chosen. If + ``[]`` the class domain is used. The default value was the + class domain in NumPy 1.4 and ``None`` in later versions. + The ``[]`` option was added in numpy 1.5.0. + rcond : float, optional + Relative condition number of the fit. Singular values smaller + than this relative to the largest singular value will be + ignored. The default value is len(x)*eps, where eps is the + relative precision of the float type, about 2e-16 in most + cases. + full : bool, optional + Switch determining nature of return value. When it is False + (the default) just the coefficients are returned, when True + diagnostic information from the singular value decomposition is + also returned. + w : array_like, shape (M,), optional + Weights. If not None the contribution of each point + ``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the + weights are chosen so that the errors of the products + ``w[i]*y[i]`` all have the same variance. The default value is + None. + + .. versionadded:: 1.5.0 + window : {[beg, end]}, optional + Window to use for the returned series. The default + value is the default class domain + + .. versionadded:: 1.6.0 + + Returns + ------- + new_series : series + A series that represents the least squares fit to the data and + has the domain specified in the call. + + [resid, rank, sv, rcond] : list + These values are only returned if `full` = True + + resid -- sum of squared residuals of the least squares fit + rank -- the numerical rank of the scaled Vandermonde matrix + sv -- singular values of the scaled Vandermonde matrix + rcond -- value of `rcond`. + + For more details, see `linalg.lstsq`. + + """ + if domain is None: + domain = pu.getdomain(x) + elif type(domain) is list and len(domain) == 0: + domain = cls.domain + + if window is None: + window = cls.window + + xnew = pu.mapdomain(x, domain, window) + res = cls._fit(xnew, y, deg, w=w, rcond=rcond, full=full) + if full: + [coef, status] = res + return cls(coef, domain=domain, window=window), status + else: + coef = res + return cls(coef, domain=domain, window=window) + + @classmethod + def fromroots(cls, roots, domain=[], window=None): + """Return series instance that has the specified roots. + + Returns a series representing the product + ``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a + list of roots. + + Parameters + ---------- + roots : array_like + List of roots. + domain : {[], None, array_like}, optional + Domain for the resulting series. If None the domain is the + interval from the smallest root to the largest. If [] the + domain is the class domain. The default is []. + window : {None, array_like}, optional + Window for the returned series. If None the class window is + used. The default is None. + + Returns + ------- + new_series : series + Series with the specified roots. + + """ + [roots] = pu.as_series([roots], trim=False) + if domain is None: + domain = pu.getdomain(roots) + elif type(domain) is list and len(domain) == 0: + domain = cls.domain + + if window is None: + window = cls.window + + deg = len(roots) + off, scl = pu.mapparms(domain, window) + rnew = off + scl*roots + coef = cls._fromroots(rnew) / scl**deg + return cls(coef, domain=domain, window=window) + + @classmethod + def identity(cls, domain=None, window=None): + """Identity function. + + If ``p`` is the returned series, then ``p(x) == x`` for all + values of x. + + Parameters + ---------- + domain : {None, array_like}, optional + If given, the array must be of the form ``[beg, end]``, where + ``beg`` and ``end`` are the endpoints of the domain. If None is + given then the class domain is used. The default is None. + window : {None, array_like}, optional + If given, the resulting array must be if the form + ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of + the window. If None is given then the class window is used. The + default is None. + + Returns + ------- + new_series : series + Series of representing the identity. + + """ + if domain is None: + domain = cls.domain + if window is None: + window = cls.window + off, scl = pu.mapparms(window, domain) + coef = cls._line(off, scl) + return cls(coef, domain, window) + + @classmethod + def basis(cls, deg, domain=None, window=None): + """Series basis polynomial of degree `deg`. + + Returns the series representing the basis polynomial of degree `deg`. + + .. versionadded:: 1.7.0 + + Parameters + ---------- + deg : int + Degree of the basis polynomial for the series. Must be >= 0. + domain : {None, array_like}, optional + If given, the array must be of the form ``[beg, end]``, where + ``beg`` and ``end`` are the endpoints of the domain. If None is + given then the class domain is used. The default is None. + window : {None, array_like}, optional + If given, the resulting array must be if the form + ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of + the window. If None is given then the class window is used. The + default is None. + + Returns + ------- + new_series : series + A series with the coefficient of the `deg` term set to one and + all others zero. + + """ + if domain is None: + domain = cls.domain + if window is None: + window = cls.window + ideg = int(deg) + + if ideg != deg or ideg < 0: + raise ValueError("deg must be non-negative integer") + return cls([0]*ideg + [1], domain, window) + + @classmethod + def cast(cls, series, domain=None, window=None): + """Convert series to series of this class. + + The `series` is expected to be an instance of some polynomial + series of one of the types supported by by the numpy.polynomial + module, but could be some other class that supports the convert + method. + + .. versionadded:: 1.7.0 + + Parameters + ---------- + series : series + The series instance to be converted. + domain : {None, array_like}, optional + If given, the array must be of the form ``[beg, end]``, where + ``beg`` and ``end`` are the endpoints of the domain. If None is + given then the class domain is used. The default is None. + window : {None, array_like}, optional + If given, the resulting array must be if the form + ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of + the window. If None is given then the class window is used. The + default is None. + + Returns + ------- + new_series : series + A series of the same kind as the calling class and equal to + `series` when evaluated. + + See Also + -------- + convert : similar instance method + + """ + if domain is None: + domain = cls.domain + if window is None: + window = cls.window + return series.convert(domain, cls, window) diff --git a/numpy/polynomial/chebyshev.py b/numpy/polynomial/chebyshev.py index 6a2394382..b4acbbeab 100644 --- a/numpy/polynomial/chebyshev.py +++ b/numpy/polynomial/chebyshev.py @@ -87,11 +87,12 @@ References """ from __future__ import division, absolute_import, print_function +import warnings import numpy as np import numpy.linalg as la + from . import polyutils as pu -import warnings -from .polytemplate import polytemplate +from ._polybase import ABCPolyBase __all__ = ['chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', 'chebadd', 'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebpow', @@ -1607,11 +1608,6 @@ def chebfit(x, y, deg, rcond=None, full=False, w=None): where `n` is `deg`. - Since numpy version 1.7.0, chebfit also supports NA. If any of the - elements of `x`, `y`, or `w` are NA, then the corresponding rows of the - linear least squares problem (see Notes) are set to 0. If `y` is 2-D, - then an NA in any row of `y` invalidates that whole row. - Parameters ---------- x : array_like, shape (M,) @@ -1646,10 +1642,15 @@ def chebfit(x, y, deg, rcond=None, full=False, w=None): the coefficients for the data in column k of `y` are in column `k`. - [residuals, rank, singular_values, rcond] : present when `full` = True - Residuals of the least-squares fit, the effective rank of the - scaled Vandermonde matrix and its singular values, and the - specified value of `rcond`. For more details, see `linalg.lstsq`. + [residuals, rank, singular_values, rcond] : list + These values are only returned if `full` = True + + resid -- sum of squared residuals of the least squares fit + rank -- the numerical rank of the scaled Vandermonde matrix + sv -- singular values of the scaled Vandermonde matrix + rcond -- value of `rcond`. + + For more details, see `linalg.lstsq`. Warns ----- @@ -2012,4 +2013,43 @@ def chebpts2(npts): # Chebyshev series class # -exec(polytemplate.substitute(name='Chebyshev', nick='cheb', domain='[-1,1]')) +class Chebyshev(ABCPolyBase): + """A Chebyshev series class. + + The Chebyshev class provides the standard Python numerical methods + '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the + methods listed below. + + Parameters + ---------- + coef : array_like + Chebyshev coefficients in order of increasing degree, i.e., + ``(1, 2, 3)`` gives ``1*T_0(x) + 2*T_1(x) + 3*T_2(x)``. + domain : (2,) array_like, optional + Domain to use. The interval ``[domain[0], domain[1]]`` is mapped + to the interval ``[window[0], window[1]]`` by shifting and scaling. + The default value is [-1, 1]. + window : (2,) array_like, optional + Window, see `domain` for its use. The default value is [-1, 1]. + + .. versionadded:: 1.6.0 + + """ + # Virtual Functions + _add = staticmethod(chebadd) + _sub = staticmethod(chebsub) + _mul = staticmethod(chebmul) + _div = staticmethod(chebdiv) + _pow = staticmethod(chebpow) + _val = staticmethod(chebval) + _int = staticmethod(chebint) + _der = staticmethod(chebder) + _fit = staticmethod(chebfit) + _line = staticmethod(chebline) + _roots = staticmethod(chebroots) + _fromroots = staticmethod(chebfromroots) + + # Virtual properties + nickname = 'cheb' + domain = np.array(chebdomain) + window = np.array(chebdomain) diff --git a/numpy/polynomial/hermite.py b/numpy/polynomial/hermite.py index 4140acfb7..43ede58ac 100644 --- a/numpy/polynomial/hermite.py +++ b/numpy/polynomial/hermite.py @@ -59,11 +59,12 @@ See also """ from __future__ import division, absolute_import, print_function +import warnings import numpy as np import numpy.linalg as la + from . import polyutils as pu -import warnings -from .polytemplate import polytemplate +from ._polybase import ABCPolyBase __all__ = ['hermzero', 'hermone', 'hermx', 'hermdomain', 'hermline', 'hermadd', 'hermsub', 'hermmulx', 'hermmul', 'hermdiv', 'hermpow', @@ -109,7 +110,7 @@ def poly2herm(pol) : Examples -------- - >>> from numpy.polynomial.hermite_e import poly2herme + >>> from numpy.polynomial.hermite import poly2herm >>> poly2herm(np.arange(4)) array([ 1. , 2.75 , 0.5 , 0.375]) @@ -1379,11 +1380,6 @@ def hermfit(x, y, deg, rcond=None, full=False, w=None): where `n` is `deg`. - Since numpy version 1.7.0, hermfit also supports NA. If any of the - elements of `x`, `y`, or `w` are NA, then the corresponding rows of the - linear least squares problem (see Notes) are set to 0. If `y` is 2-D, - then an NA in any row of `y` invalidates that whole row. - Parameters ---------- x : array_like, shape (M,) @@ -1416,10 +1412,15 @@ def hermfit(x, y, deg, rcond=None, full=False, w=None): the coefficients for the data in column k of `y` are in column `k`. - [residuals, rank, singular_values, rcond] : present when `full` = True - Residuals of the least-squares fit, the effective rank of the - scaled Vandermonde matrix and its singular values, and the - specified value of `rcond`. For more details, see `linalg.lstsq`. + [residuals, rank, singular_values, rcond] : list + These values are only returned if `full` = True + + resid -- sum of squared residuals of the least squares fit + rank -- the numerical rank of the scaled Vandermonde matrix + sv -- singular values of the scaled Vandermonde matrix + rcond -- value of `rcond`. + + For more details, see `linalg.lstsq`. Warns ----- @@ -1747,4 +1748,43 @@ def hermweight(x): # Hermite series class # -exec(polytemplate.substitute(name='Hermite', nick='herm', domain='[-1,1]')) +class Hermite(ABCPolyBase): + """An Hermite series class. + + The Hermite class provides the standard Python numerical methods + '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the + attributes and methods listed in the `ABCPolyBase` documentation. + + Parameters + ---------- + coef : array_like + Laguerre coefficients in order of increasing degree, i.e, + ``(1, 2, 3)`` gives ``1*H_0(x) + 2*H_1(X) + 3*H_2(x)``. + domain : (2,) array_like, optional + Domain to use. The interval ``[domain[0], domain[1]]`` is mapped + to the interval ``[window[0], window[1]]`` by shifting and scaling. + The default value is [-1, 1]. + window : (2,) array_like, optional + Window, see `domain` for its use. The default value is [-1, 1]. + + .. versionadded:: 1.6.0 + + """ + # Virtual Functions + _add = staticmethod(hermadd) + _sub = staticmethod(hermsub) + _mul = staticmethod(hermmul) + _div = staticmethod(hermdiv) + _pow = staticmethod(hermpow) + _val = staticmethod(hermval) + _int = staticmethod(hermint) + _der = staticmethod(hermder) + _fit = staticmethod(hermfit) + _line = staticmethod(hermline) + _roots = staticmethod(hermroots) + _fromroots = staticmethod(hermfromroots) + + # Virtual properties + nickname = 'herm' + domain = np.array(hermdomain) + window = np.array(hermdomain) diff --git a/numpy/polynomial/hermite_e.py b/numpy/polynomial/hermite_e.py index 735ca9470..874b42470 100644 --- a/numpy/polynomial/hermite_e.py +++ b/numpy/polynomial/hermite_e.py @@ -59,11 +59,12 @@ See also """ from __future__ import division, absolute_import, print_function +import warnings import numpy as np import numpy.linalg as la + from . import polyutils as pu -import warnings -from .polytemplate import polytemplate +from ._polybase import ABCPolyBase __all__ = ['hermezero', 'hermeone', 'hermex', 'hermedomain', 'hermeline', 'hermeadd', 'hermesub', 'hermemulx', 'hermemul', 'hermediv', 'hermpow', @@ -1375,11 +1376,6 @@ def hermefit(x, y, deg, rcond=None, full=False, w=None): where `n` is `deg`. - Since numpy version 1.7.0, hermefit also supports NA. If any of the - elements of `x`, `y`, or `w` are NA, then the corresponding rows of the - linear least squares problem (see Notes) are set to 0. If `y` is 2-D, - then an NA in any row of `y` invalidates that whole row. - Parameters ---------- x : array_like, shape (M,) @@ -1412,10 +1408,15 @@ def hermefit(x, y, deg, rcond=None, full=False, w=None): the coefficients for the data in column k of `y` are in column `k`. - [residuals, rank, singular_values, rcond] : present when `full` = True - Residuals of the least-squares fit, the effective rank of the - scaled Vandermonde matrix and its singular values, and the - specified value of `rcond`. For more details, see `linalg.lstsq`. + [residuals, rank, singular_values, rcond] : list + These values are only returned if `full` = True + + resid -- sum of squared residuals of the least squares fit + rank -- the numerical rank of the scaled Vandermonde matrix + sv -- singular values of the scaled Vandermonde matrix + rcond -- value of `rcond`. + + For more details, see `linalg.lstsq`. Warns ----- @@ -1743,4 +1744,43 @@ def hermeweight(x): # HermiteE series class # -exec(polytemplate.substitute(name='HermiteE', nick='herme', domain='[-1,1]')) +class HermiteE(ABCPolyBase): + """An HermiteE series class. + + The HermiteE class provides the standard Python numerical methods + '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the + attributes and methods listed in the `ABCPolyBase` documentation. + + Parameters + ---------- + coef : array_like + Laguerre coefficients in order of increasing degree, i.e, + ``(1, 2, 3)`` gives ``1*He_0(x) + 2*He_1(X) + 3*He_2(x)``. + domain : (2,) array_like, optional + Domain to use. The interval ``[domain[0], domain[1]]`` is mapped + to the interval ``[window[0], window[1]]`` by shifting and scaling. + The default value is [-1, 1]. + window : (2,) array_like, optional + Window, see `domain` for its use. The default value is [-1, 1]. + + .. versionadded:: 1.6.0 + + """ + # Virtual Functions + _add = staticmethod(hermeadd) + _sub = staticmethod(hermesub) + _mul = staticmethod(hermemul) + _div = staticmethod(hermediv) + _pow = staticmethod(hermepow) + _val = staticmethod(hermeval) + _int = staticmethod(hermeint) + _der = staticmethod(hermeder) + _fit = staticmethod(hermefit) + _line = staticmethod(hermeline) + _roots = staticmethod(hermeroots) + _fromroots = staticmethod(hermefromroots) + + # Virtual properties + nickname = 'herme' + domain = np.array(hermedomain) + window = np.array(hermedomain) diff --git a/numpy/polynomial/laguerre.py b/numpy/polynomial/laguerre.py index b7ffe9b0c..9d88162ce 100644 --- a/numpy/polynomial/laguerre.py +++ b/numpy/polynomial/laguerre.py @@ -59,11 +59,12 @@ See also """ from __future__ import division, absolute_import, print_function +import warnings import numpy as np import numpy.linalg as la + from . import polyutils as pu -import warnings -from .polytemplate import polytemplate +from ._polybase import ABCPolyBase __all__ = ['lagzero', 'lagone', 'lagx', 'lagdomain', 'lagline', 'lagadd', 'lagsub', 'lagmulx', 'lagmul', 'lagdiv', 'lagpow', @@ -1378,11 +1379,6 @@ def lagfit(x, y, deg, rcond=None, full=False, w=None): where `n` is `deg`. - Since numpy version 1.7.0, lagfit also supports NA. If any of the - elements of `x`, `y`, or `w` are NA, then the corresponding rows of the - linear least squares problem (see Notes) are set to 0. If `y` is 2-D, - then an NA in any row of `y` invalidates that whole row. - Parameters ---------- x : array_like, shape (M,) @@ -1415,10 +1411,15 @@ def lagfit(x, y, deg, rcond=None, full=False, w=None): the coefficients for the data in column k of `y` are in column `k`. - [residuals, rank, singular_values, rcond] : present when `full` = True - Residuals of the least-squares fit, the effective rank of the - scaled Vandermonde matrix and its singular values, and the - specified value of `rcond`. For more details, see `linalg.lstsq`. + [residuals, rank, singular_values, rcond] : list + These values are only returned if `full` = True + + resid -- sum of squared residuals of the least squares fit + rank -- the numerical rank of the scaled Vandermonde matrix + sv -- singular values of the scaled Vandermonde matrix + rcond -- value of `rcond`. + + For more details, see `linalg.lstsq`. Warns ----- @@ -1739,4 +1740,43 @@ def lagweight(x): # Laguerre series class # -exec(polytemplate.substitute(name='Laguerre', nick='lag', domain='[-1,1]')) +class Laguerre(ABCPolyBase): + """A Laguerre series class. + + The Laguerre class provides the standard Python numerical methods + '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the + attributes and methods listed in the `ABCPolyBase` documentation. + + Parameters + ---------- + coef : array_like + Laguerre coefficients in order of increasing degree, i.e, + ``(1, 2, 3)`` gives ``1*L_0(x) + 2*L_1(X) + 3*L_2(x)``. + domain : (2,) array_like, optional + Domain to use. The interval ``[domain[0], domain[1]]`` is mapped + to the interval ``[window[0], window[1]]`` by shifting and scaling. + The default value is [0, 1]. + window : (2,) array_like, optional + Window, see `domain` for its use. The default value is [0, 1]. + + .. versionadded:: 1.6.0 + + """ + # Virtual Functions + _add = staticmethod(lagadd) + _sub = staticmethod(lagsub) + _mul = staticmethod(lagmul) + _div = staticmethod(lagdiv) + _pow = staticmethod(lagpow) + _val = staticmethod(lagval) + _int = staticmethod(lagint) + _der = staticmethod(lagder) + _fit = staticmethod(lagfit) + _line = staticmethod(lagline) + _roots = staticmethod(lagroots) + _fromroots = staticmethod(lagfromroots) + + # Virtual properties + nickname = 'lag' + domain = np.array(lagdomain) + window = np.array(lagdomain) diff --git a/numpy/polynomial/legendre.py b/numpy/polynomial/legendre.py index 8d89c8412..58c130b7e 100644 --- a/numpy/polynomial/legendre.py +++ b/numpy/polynomial/legendre.py @@ -83,11 +83,12 @@ numpy.polynomial.hermite_e """ from __future__ import division, absolute_import, print_function +import warnings import numpy as np import numpy.linalg as la + from . import polyutils as pu -import warnings -from .polytemplate import polytemplate +from ._polybase import ABCPolyBase __all__ = ['legzero', 'legone', 'legx', 'legdomain', 'legline', 'legadd', 'legsub', 'legmulx', 'legmul', 'legdiv', 'legpow', 'legval', @@ -1408,11 +1409,6 @@ def legfit(x, y, deg, rcond=None, full=False, w=None): where `n` is `deg`. - Since numpy version 1.7.0, legfit also supports NA. If any of the - elements of `x`, `y`, or `w` are NA, then the corresponding rows of the - linear least squares problem (see Notes) are set to 0. If `y` is 2-D, - then an NA in any row of `y` invalidates that whole row. - Parameters ---------- x : array_like, shape (M,) @@ -1447,10 +1443,15 @@ def legfit(x, y, deg, rcond=None, full=False, w=None): the coefficients for the data in column k of `y` are in column `k`. - [residuals, rank, singular_values, rcond] : present when `full` = True - Residuals of the least-squares fit, the effective rank of the - scaled Vandermonde matrix and its singular values, and the - specified value of `rcond`. For more details, see `linalg.lstsq`. + [residuals, rank, singular_values, rcond] : list + These values are only returned if `full` = True + + resid -- sum of squared residuals of the least squares fit + rank -- the numerical rank of the scaled Vandermonde matrix + sv -- singular values of the scaled Vandermonde matrix + rcond -- value of `rcond`. + + For more details, see `linalg.lstsq`. Warns ----- @@ -1765,4 +1766,43 @@ def legweight(x): # Legendre series class # -exec(polytemplate.substitute(name='Legendre', nick='leg', domain='[-1,1]')) +class Legendre(ABCPolyBase): + """A Legendre series class. + + The Legendre class provides the standard Python numerical methods + '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the + attributes and methods listed in the `ABCPolyBase` documentation. + + Parameters + ---------- + coef : array_like + Legendre coefficients in order of increasing degree, i.e., + ``(1, 2, 3)`` gives ``1*P_0(x) + 2*P_1(x) + 3*P_2(x)``. + domain : (2,) array_like, optional + Domain to use. The interval ``[domain[0], domain[1]]`` is mapped + to the interval ``[window[0], window[1]]`` by shifting and scaling. + The default value is [-1, 1]. + window : (2,) array_like, optional + Window, see `domain` for its use. The default value is [-1, 1]. + + .. versionadded:: 1.6.0 + + """ + # Virtual Functions + _add = staticmethod(legadd) + _sub = staticmethod(legsub) + _mul = staticmethod(legmul) + _div = staticmethod(legdiv) + _pow = staticmethod(legpow) + _val = staticmethod(legval) + _int = staticmethod(legint) + _der = staticmethod(legder) + _fit = staticmethod(legfit) + _line = staticmethod(legline) + _roots = staticmethod(legroots) + _fromroots = staticmethod(legfromroots) + + # Virtual properties + nickname = 'leg' + domain = np.array(legdomain) + window = np.array(legdomain) diff --git a/numpy/polynomial/polynomial.py b/numpy/polynomial/polynomial.py index 9acdcbe52..92cc83821 100644 --- a/numpy/polynomial/polynomial.py +++ b/numpy/polynomial/polynomial.py @@ -48,7 +48,7 @@ Classes ------- - `Polynomial` -- polynomial class. -See also +See Also -------- `numpy.polynomial` @@ -61,11 +61,12 @@ __all__ = ['polyzero', 'polyone', 'polyx', 'polydomain', 'polyline', 'polyfit', 'polytrim', 'polyroots', 'Polynomial', 'polyval2d', 'polyval3d', 'polygrid2d', 'polygrid3d', 'polyvander2d', 'polyvander3d'] +import warnings import numpy as np import numpy.linalg as la + from . import polyutils as pu -import warnings -from .polytemplate import polytemplate +from ._polybase import ABCPolyBase polytrim = pu.trimcoef @@ -112,7 +113,7 @@ def polyline(off, scl) : Examples -------- - >>> from numpy import polynomial as P + >>> from numpy.polynomial import polynomial as P >>> P.polyline(1,-1) array([ 1, -1]) >>> P.polyval(1, P.polyline(1,-1)) # should be 0 @@ -175,7 +176,7 @@ def polyfromroots(roots) : Examples -------- - >>> import numpy.polynomial as P + >>> from numpy.polynomial import polynomial as P >>> P.polyfromroots((-1,0,1)) # x(x - 1)(x + 1) = x^3 - x array([ 0., -1., 0., 1.]) >>> j = complex(0,1) @@ -224,7 +225,7 @@ def polyadd(c1, c2): Examples -------- - >>> from numpy import polynomial as P + >>> from numpy.polynomial import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> sum = P.polyadd(c1,c2); sum @@ -269,7 +270,7 @@ def polysub(c1, c2): Examples -------- - >>> from numpy import polynomial as P + >>> from numpy.polynomial import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> P.polysub(c1,c2) @@ -351,7 +352,7 @@ def polymul(c1, c2): Examples -------- - >>> import numpy.polynomial as P + >>> from numpy.polynomial import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> P.polymul(c1,c2) @@ -388,7 +389,7 @@ def polydiv(c1, c2): Examples -------- - >>> import numpy.polynomial as P + >>> from numpy.polynomial import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> P.polydiv(c1,c2) @@ -512,7 +513,7 @@ def polyder(c, m=1, scl=1, axis=0): Examples -------- - >>> from numpy import polynomial as P + >>> from numpy.polynomial import polynomial as P >>> c = (1,2,3,4) # 1 + 2x + 3x**2 + 4x**3 >>> P.polyder(c) # (d/dx)(c) = 2 + 6x + 12x**2 array([ 2., 6., 12.]) @@ -623,7 +624,7 @@ def polyint(c, m=1, k=[], lbnd=0, scl=1, axis=0): Examples -------- - >>> from numpy import polynomial as P + >>> from numpy.polynomial import polynomial as P >>> c = (1,2,3) >>> P.polyint(c) # should return array([0, 1, 1, 1]) array([ 0., 1., 1., 1.]) @@ -823,7 +824,7 @@ def polyval2d(x, y, c): Notes ----- - .. versionadded::1.7.0 + .. versionadded:: 1.7.0 """ try: @@ -883,7 +884,7 @@ def polygrid2d(x, y, c): Notes ----- - .. versionadded::1.7.0 + .. versionadded:: 1.7.0 """ c = polyval(x, c) @@ -936,7 +937,7 @@ def polyval3d(x, y, z, c): Notes ----- - .. versionadded::1.7.0 + .. versionadded:: 1.7.0 """ try: @@ -1000,7 +1001,7 @@ def polygrid3d(x, y, z, c): Notes ----- - .. versionadded::1.7.0 + .. versionadded:: 1.7.0 """ c = polyval(x, c) @@ -1173,7 +1174,7 @@ def polyvander3d(x, y, z, deg) : Notes ----- - .. versionadded::1.7.0 + .. versionadded:: 1.7.0 """ ideg = [int(d) for d in deg] @@ -1207,11 +1208,6 @@ def polyfit(x, y, deg, rcond=None, full=False, w=None): where `n` is `deg`. - Since numpy version 1.7.0, polyfit also supports NA. If any of the - elements of `x`, `y`, or `w` are NA, then the corresponding rows of the - linear least squares problem (see Notes) are set to 0. If `y` is 2-D, - then an NA in any row of `y` invalidates that whole row. - Parameters ---------- x : array_like, shape (`M`,) @@ -1249,12 +1245,16 @@ def polyfit(x, y, deg, rcond=None, full=False, w=None): the coefficients in column `k` of `coef` represent the polynomial fit to the data in `y`'s `k`-th column. - [residuals, rank, singular_values, rcond] : present when `full` == True - Sum of the squared residuals (SSR) of the least-squares fit; the - effective rank of the scaled Vandermonde matrix; its singular - values; and the specified value of `rcond`. For more information, - see `linalg.lstsq`. + [residuals, rank, singular_values, rcond] : list + These values are only returned if `full` = True + + resid -- sum of squared residuals of the least squares fit + rank -- the numerical rank of the scaled Vandermonde matrix + sv -- singular values of the scaled Vandermonde matrix + rcond -- value of `rcond`. + For more details, see `linalg.lstsq`. + Raises ------ RankWarning @@ -1310,7 +1310,7 @@ def polyfit(x, y, deg, rcond=None, full=False, w=None): Examples -------- - >>> from numpy import polynomial as P + >>> from numpy.polynomial import polynomial as P >>> x = np.linspace(-1,1,51) # x "data": [-1, -0.96, ..., 0.96, 1] >>> y = x**3 - x + np.random.randn(len(x)) # x^3 - x + N(0,1) "noise" >>> c, stats = P.polyfit(x,y,3,full=True) @@ -1490,4 +1490,43 @@ def polyroots(c): # polynomial class # -exec(polytemplate.substitute(name='Polynomial', nick='poly', domain='[-1,1]')) +class Polynomial(ABCPolyBase): + """A power series class. + + The Polynomial class provides the standard Python numerical methods + '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the + attributes and methods listed in the `ABCPolyBase` documentation. + + Parameters + ---------- + coef : array_like + Polynomial coefficients in order of increasing degree, i.e., + ``(1, 2, 3)`` give ``1 + 2*x + 3*x**2``. + domain : (2,) array_like, optional + Domain to use. The interval ``[domain[0], domain[1]]`` is mapped + to the interval ``[window[0], window[1]]`` by shifting and scaling. + The default value is [-1, 1]. + window : (2,) array_like, optional + Window, see `domain` for its use. The default value is [-1, 1]. + + .. versionadded:: 1.6.0 + + """ + # Virtual Functions + _add = staticmethod(polyadd) + _sub = staticmethod(polysub) + _mul = staticmethod(polymul) + _div = staticmethod(polydiv) + _pow = staticmethod(polypow) + _val = staticmethod(polyval) + _int = staticmethod(polyint) + _der = staticmethod(polyder) + _fit = staticmethod(polyfit) + _line = staticmethod(polyline) + _roots = staticmethod(polyroots) + _fromroots = staticmethod(polyfromroots) + + # Virtual properties + nickname = 'poly' + domain = np.array(polydomain) + window = np.array(polydomain) diff --git a/numpy/polynomial/polytemplate.py b/numpy/polynomial/polytemplate.py index f315915d6..e68dd18ef 100644 --- a/numpy/polynomial/polytemplate.py +++ b/numpy/polynomial/polytemplate.py @@ -13,6 +13,13 @@ from __future__ import division, absolute_import, print_function import string import sys +import warnings +from number import Number + +from numpy import ModuleDeprecationWarning + +warnings.warn("The polytemplate module will be removed in Numpy 1.10.0.", + ModuleDeprecationWarning) polytemplate = string.Template(''' from __future__ import division, absolute_import, print_function @@ -281,15 +288,13 @@ class $name(pu.PolyBase) : return self.__floordiv__(other) def __truediv__(self, other) : - # there is no true divide if the rhs is not a scalar, although it + # there is no true divide if the rhs is not a Number, although it # could return the first n elements of an infinite series. # It is hard to see where n would come from, though. - if np.isscalar(other) : - # this might be overly restrictive - coef = self.coef/other - return self.__class__(coef, self.domain, self.window) - else : - return NotImplemented + if not isinstance(other, Number) or isinstance(other, bool): + form = "unsupported types for true division: '%s', '%s'" + raise TypeError(form % (type(self), type(other))) + return self.__floordiv__(other) def __floordiv__(self, other) : """Returns the quotient.""" @@ -378,20 +383,14 @@ class $name(pu.PolyBase) : return self.__rfloordiv__(other) def __rtruediv__(self, other) : - # there is no true divide if the rhs is not a scalar, although it - # could return the first n elements of an infinite series. - # It is hard to see where n would come from, though. - if len(self.coef) == 1 : - try : - quo, rem = ${nick}div(other, self.coef[0]) - except : - return NotImplemented - return self.__class__(quo, self.domain, self.window) + # An instance of PolyBase is not considered a + # Number. + return NotImplemented def __rfloordiv__(self, other) : try : quo, rem = ${nick}div(other, self.coef) - except : + except: return NotImplemented return self.__class__(quo, self.domain, self.window) @@ -738,7 +737,7 @@ class $name(pu.PolyBase) : then a minimal domain that covers the points `x` is chosen. If ``[]`` the default domain ``$domain`` is used. The default value is $domain in numpy 1.4.x and ``None`` in later versions. - The ``'[]`` value was added in numpy 1.5.0. + The ``[]`` value was added in numpy 1.5.0. rcond : float, optional Relative condition number of the fit. Singular values smaller than this relative to the largest singular value will be @@ -781,10 +780,10 @@ class $name(pu.PolyBase) : """ if domain is None: domain = pu.getdomain(x) - elif domain == []: + elif type(domain) is list and len(domain) == 0: domain = $domain - if window == []: + if type(window) is list and len(window) == 0: window = $domain xnew = pu.mapdomain(x, domain, window) diff --git a/numpy/polynomial/polyutils.py b/numpy/polynomial/polyutils.py index 63743bb40..99f508521 100644 --- a/numpy/polynomial/polyutils.py +++ b/numpy/polynomial/polyutils.py @@ -1,41 +1,53 @@ """ -Utililty objects for the polynomial modules. +Utililty classes and functions for the polynomial modules. This module provides: error and warning objects; a polynomial base class; and some routines used in both the `polynomial` and `chebyshev` modules. Error objects ------------- -- `PolyError` -- base class for this sub-package's errors. -- `PolyDomainError` -- raised when domains are "mismatched." + +.. autosummary:: + :toctree: generated/ + + PolyError base class for this sub-package's errors. + PolyDomainError raised when domains are mismatched. Warning objects --------------- -- `RankWarning` -- raised by a least-squares fit when a rank-deficient - matrix is encountered. + +.. autosummary:: + :toctree: generated/ + + RankWarning raised in least-squares fit for rank-deficient matrix. Base class ---------- -- `PolyBase` -- The base class for the `Polynomial` and `Chebyshev` - classes. + +.. autosummary:: + :toctree: generated/ + + PolyBase Obsolete base class for the polynomial classes. Do not use. Functions --------- -- `as_series` -- turns a list of array_likes into 1-D arrays of common - type. -- `trimseq` -- removes trailing zeros. -- `trimcoef` -- removes trailing coefficients that are less than a given - magnitude (thereby removing the corresponding terms). -- `getdomain` -- returns a domain appropriate for a given set of abscissae. -- `mapdomain` -- maps points between domains. -- `mapparms` -- parameters of the linear map between domains. + +.. autosummary:: + :toctree: generated/ + + as_series convert list of array_likes into 1-D arrays of common type. + trimseq remove trailing zeros. + trimcoef remove small trailing coefficients. + getdomain return the domain appropriate for a given set of abscissae. + mapdomain maps points between domains. + mapparms parameters of the linear map between domains. """ from __future__ import division, absolute_import, print_function -__all__ = ['RankWarning', 'PolyError', 'PolyDomainError', 'PolyBase', - 'as_series', 'trimseq', 'trimcoef', 'getdomain', 'mapdomain', - 'mapparms'] +__all__ = ['RankWarning', 'PolyError', 'PolyDomainError', 'as_series', + 'trimseq', 'trimcoef', 'getdomain', 'mapdomain', 'mapparms', + 'PolyBase'] import warnings import numpy as np @@ -67,6 +79,15 @@ class PolyDomainError(PolyError) : # class PolyBase(object) : + """ + Base class for all polynomial types. + + Deprecated in numpy 1.9.0, use the abstract + ABCPolyBase class instead. Note that the latter + reguires a number of virtual functions to be + implemented. + + """ pass # diff --git a/numpy/polynomial/tests/test_classes.py b/numpy/polynomial/tests/test_classes.py index 09b30a9e9..f9134b8c1 100644 --- a/numpy/polynomial/tests/test_classes.py +++ b/numpy/polynomial/tests/test_classes.py @@ -5,6 +5,9 @@ This tests the convert and cast methods of all the polynomial classes. """ from __future__ import division, absolute_import, print_function +import operator as op +from numbers import Number + import numpy as np from numpy.polynomial import ( Polynomial, Legendre, Chebyshev, Laguerre, @@ -13,6 +16,7 @@ from numpy.testing import ( TestCase, assert_almost_equal, assert_raises, assert_equal, assert_, run_module_suite, dec) from numpy.testing.noseclasses import KnownFailure +from numpy.compat import long classes = ( @@ -37,6 +41,7 @@ def test_class_methods(): yield check_sub, Poly yield check_mul, Poly yield check_floordiv, Poly + yield check_truediv, Poly yield check_mod, Poly yield check_divmod, Poly yield check_pow, Poly @@ -221,12 +226,12 @@ def check_add(Poly): assert_poly_almost_equal(tuple(c2) + p1, p3) assert_poly_almost_equal(p1 + np.array(c2), p3) assert_poly_almost_equal(np.array(c2) + p1, p3) - assert_raises(TypeError, p1.__add__, Poly([0], domain=Poly.domain + 1)) - assert_raises(TypeError, p1.__add__, Poly([0], window=Poly.window + 1)) + assert_raises(TypeError, op.add, p1, Poly([0], domain=Poly.domain + 1)) + assert_raises(TypeError, op.add, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: - assert_raises(TypeError, p1.__add__, Chebyshev([0])) + assert_raises(TypeError, op.add, p1, Chebyshev([0])) else: - assert_raises(TypeError, p1.__add__, Polynomial([0])) + assert_raises(TypeError, op.add, p1, Polynomial([0])) def check_sub(Poly): @@ -243,12 +248,12 @@ def check_sub(Poly): assert_poly_almost_equal(tuple(c2) - p1, -p3) assert_poly_almost_equal(p1 - np.array(c2), p3) assert_poly_almost_equal(np.array(c2) - p1, -p3) - assert_raises(TypeError, p1.__sub__, Poly([0], domain=Poly.domain + 1)) - assert_raises(TypeError, p1.__sub__, Poly([0], window=Poly.window + 1)) + assert_raises(TypeError, op.sub, p1, Poly([0], domain=Poly.domain + 1)) + assert_raises(TypeError, op.sub, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: - assert_raises(TypeError, p1.__sub__, Chebyshev([0])) + assert_raises(TypeError, op.sub, p1, Chebyshev([0])) else: - assert_raises(TypeError, p1.__sub__, Polynomial([0])) + assert_raises(TypeError, op.sub, p1, Polynomial([0])) def check_mul(Poly): @@ -266,12 +271,12 @@ def check_mul(Poly): assert_poly_almost_equal(np.array(c2) * p1, p3) assert_poly_almost_equal(p1 * 2, p1 * Poly([2])) assert_poly_almost_equal(2 * p1, p1 * Poly([2])) - assert_raises(TypeError, p1.__mul__, Poly([0], domain=Poly.domain + 1)) - assert_raises(TypeError, p1.__mul__, Poly([0], window=Poly.window + 1)) + assert_raises(TypeError, op.mul, p1, Poly([0], domain=Poly.domain + 1)) + assert_raises(TypeError, op.mul, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: - assert_raises(TypeError, p1.__mul__, Chebyshev([0])) + assert_raises(TypeError, op.mul, p1, Chebyshev([0])) else: - assert_raises(TypeError, p1.__mul__, Polynomial([0])) + assert_raises(TypeError, op.mul, p1, Polynomial([0])) def check_floordiv(Poly): @@ -293,13 +298,40 @@ def check_floordiv(Poly): assert_poly_almost_equal(2 // p2, Poly([0])) assert_poly_almost_equal(p2 // 2, 0.5*p2) assert_raises( - TypeError, p1.__floordiv__, Poly([0], domain=Poly.domain + 1)) + TypeError, op.floordiv, p1, Poly([0], domain=Poly.domain + 1)) assert_raises( - TypeError, p1.__floordiv__, Poly([0], window=Poly.window + 1)) + TypeError, op.floordiv, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: - assert_raises(TypeError, p1.__floordiv__, Chebyshev([0])) + assert_raises(TypeError, op.floordiv, p1, Chebyshev([0])) else: - assert_raises(TypeError, p1.__floordiv__, Polynomial([0])) + assert_raises(TypeError, op.floordiv, p1, Polynomial([0])) + + +def check_truediv(Poly): + # true division is valid only if the denominator is a Number and + # not a python bool. + p1 = Poly([1,2,3]) + p2 = p1 * 5 + + for stype in np.ScalarType: + if not issubclass(stype, Number) or issubclass(stype, bool): + continue + s = stype(5) + assert_poly_almost_equal(op.truediv(p2, s), p1) + assert_raises(TypeError, op.truediv, s, p2) + for stype in (int, long, float): + s = stype(5) + assert_poly_almost_equal(op.truediv(p2, s), p1) + assert_raises(TypeError, op.truediv, s, p2) + for stype in [complex]: + s = stype(5, 0) + assert_poly_almost_equal(op.truediv(p2, s), p1) + assert_raises(TypeError, op.truediv, s, p2) + for s in [tuple(), list(), dict(), bool(), np.array([1])]: + assert_raises(TypeError, op.truediv, p2, s) + assert_raises(TypeError, op.truediv, s, p2) + for ptype in classes: + assert_raises(TypeError, op.truediv, p2, ptype(1)) def check_mod(Poly): @@ -321,12 +353,12 @@ def check_mod(Poly): assert_poly_almost_equal(np.array(c4) % p2, p3) assert_poly_almost_equal(2 % p2, Poly([2])) assert_poly_almost_equal(p2 % 2, Poly([0])) - assert_raises(TypeError, p1.__mod__, Poly([0], domain=Poly.domain + 1)) - assert_raises(TypeError, p1.__mod__, Poly([0], window=Poly.window + 1)) + assert_raises(TypeError, op.mod, p1, Poly([0], domain=Poly.domain + 1)) + assert_raises(TypeError, op.mod, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: - assert_raises(TypeError, p1.__mod__, Chebyshev([0])) + assert_raises(TypeError, op.mod, p1, Chebyshev([0])) else: - assert_raises(TypeError, p1.__mod__, Polynomial([0])) + assert_raises(TypeError, op.mod, p1, Polynomial([0])) def check_divmod(Poly): @@ -464,8 +496,8 @@ def check_pow(Poly): for i in range(5): assert_poly_almost_equal(tst**i, tgt) tgt = tgt * tst - assert_raises(ValueError, tgt.__pow__, 1.5) - assert_raises(ValueError, tgt.__pow__, -1) + assert_raises(ValueError, op.pow, tgt, 1.5) + assert_raises(ValueError, op.pow, tgt, -1) def check_call(Poly): diff --git a/numpy/random/__init__.py b/numpy/random/__init__.py index 614b25a1c..388267c97 100644 --- a/numpy/random/__init__.py +++ b/numpy/random/__init__.py @@ -106,8 +106,16 @@ def __RandomState_ctor(): """Return a RandomState instance. This function exists solely to assist (un)pickling. + + Note that the state of the RandomState returned here is irrelevant, as this function's + entire purpose is to return a newly allocated RandomState whose state pickle can set. + Consequently the RandomState returned by this function is a freshly allocated copy + with a seed=0. + + See https://github.com/numpy/numpy/issues/4763 for a detailed discussion + """ - return RandomState() + return RandomState(seed=0) from numpy.testing import Tester test = Tester().test diff --git a/numpy/random/mtrand/distributions.c b/numpy/random/mtrand/distributions.c index 4a752ad8c..001e2f6a1 100644 --- a/numpy/random/mtrand/distributions.c +++ b/numpy/random/mtrand/distributions.c @@ -323,23 +323,20 @@ long rk_binomial_btpe(rk_state *state, long n, double p) F = 1.0; if (m < y) { - for (i=m; i<=y; i++) + for (i=m+1; i<=y; i++) { F *= (a/i - s); } } else if (m > y) { - for (i=y; i<=m; i++) + for (i=y+1; i<=m; i++) { F /= (a/i - s); } } - else - { - if (v > F) goto Step10; - goto Step60; - } + if (v > F) goto Step10; + goto Step60; Step52: rho = (k/(nrq))*((k*(k/3.0 + 0.625) + 0.16666666666666666)/nrq + 0.5); @@ -559,7 +556,7 @@ double rk_standard_t(rk_state *state, double df) */ double rk_vonmises(rk_state *state, double mu, double kappa) { - double r, rho, s; + double s; double U, V, W, Y, Z; double result, mod; int neg; @@ -570,9 +567,19 @@ double rk_vonmises(rk_state *state, double mu, double kappa) } else { - r = 1 + sqrt(1 + 4*kappa*kappa); - rho = (r - sqrt(2*r))/(2*kappa); - s = (1 + rho*rho)/(2*rho); + /* with double precision rho is zero until 1.4e-8 */ + if (kappa < 1e-5) { + /* + * second order taylor expansion around kappa = 0 + * precise until relatively large kappas as second order is 0 + */ + s = (1./kappa + kappa); + } + else { + double r = 1 + sqrt(1 + 4*kappa*kappa); + double rho = (r - sqrt(2*r)) / (2*kappa); + s = (1 + rho*rho)/(2*rho); + } while (1) { diff --git a/numpy/random/mtrand/initarray.h b/numpy/random/mtrand/initarray.h index f764895d1..f5e5e5332 100644 --- a/numpy/random/mtrand/initarray.h +++ b/numpy/random/mtrand/initarray.h @@ -1,4 +1,5 @@ #include "Python.h" +#define NO_IMPORT_ARRAY #include "numpy/arrayobject.h" #include "randomkit.h" diff --git a/numpy/random/mtrand/mtrand.c b/numpy/random/mtrand/mtrand.c deleted file mode 100644 index a508efba1..000000000 --- a/numpy/random/mtrand/mtrand.c +++ /dev/null @@ -1,26337 +0,0 @@ -/* Generated by Cython 0.19 on Fri Jun 28 16:46:58 2013 */ - -#define PY_SSIZE_T_CLEAN -#ifndef CYTHON_USE_PYLONG_INTERNALS -#ifdef PYLONG_BITS_IN_DIGIT -#define CYTHON_USE_PYLONG_INTERNALS 0 -#else -#include "pyconfig.h" -#ifdef PYLONG_BITS_IN_DIGIT -#define CYTHON_USE_PYLONG_INTERNALS 1 -#else -#define CYTHON_USE_PYLONG_INTERNALS 0 -#endif -#endif -#endif -#include "Python.h" -#ifndef Py_PYTHON_H - #error Python headers needed to compile C extensions, please install development version of Python. -#elif PY_VERSION_HEX < 0x02040000 - #error Cython requires Python 2.4+. -#else -#include <stddef.h> /* For offsetof */ -#ifndef offsetof -#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) -#endif -#if !defined(WIN32) && !defined(MS_WINDOWS) - #ifndef __stdcall - #define __stdcall - #endif - #ifndef __cdecl - #define __cdecl - #endif - #ifndef __fastcall - #define __fastcall - #endif -#endif -#ifndef DL_IMPORT - #define DL_IMPORT(t) t -#endif -#ifndef DL_EXPORT - #define DL_EXPORT(t) t -#endif -#ifndef PY_LONG_LONG - #define PY_LONG_LONG LONG_LONG -#endif -#ifndef Py_HUGE_VAL - #define Py_HUGE_VAL HUGE_VAL -#endif -#ifdef PYPY_VERSION -#define CYTHON_COMPILING_IN_PYPY 1 -#define CYTHON_COMPILING_IN_CPYTHON 0 -#else -#define CYTHON_COMPILING_IN_PYPY 0 -#define CYTHON_COMPILING_IN_CPYTHON 1 -#endif -#if PY_VERSION_HEX < 0x02050000 - typedef int Py_ssize_t; - #define PY_SSIZE_T_MAX INT_MAX - #define PY_SSIZE_T_MIN INT_MIN - #define PY_FORMAT_SIZE_T "" - #define CYTHON_FORMAT_SSIZE_T "" - #define PyInt_FromSsize_t(z) PyInt_FromLong(z) - #define PyInt_AsSsize_t(o) __Pyx_PyInt_AsInt(o) - #define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \ - (PyErr_Format(PyExc_TypeError, \ - "expected index value, got %.200s", Py_TYPE(o)->tp_name), \ - (PyObject*)0)) - #define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \ - !PyComplex_Check(o)) - #define PyIndex_Check __Pyx_PyIndex_Check - #define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message) - #define __PYX_BUILD_PY_SSIZE_T "i" -#else - #define __PYX_BUILD_PY_SSIZE_T "n" - #define CYTHON_FORMAT_SSIZE_T "z" - #define __Pyx_PyIndex_Check PyIndex_Check -#endif -#if PY_VERSION_HEX < 0x02060000 - #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) - #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) - #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) - #define PyVarObject_HEAD_INIT(type, size) \ - PyObject_HEAD_INIT(type) size, - #define PyType_Modified(t) - typedef struct { - void *buf; - PyObject *obj; - Py_ssize_t len; - Py_ssize_t itemsize; - int readonly; - int ndim; - char *format; - Py_ssize_t *shape; - Py_ssize_t *strides; - Py_ssize_t *suboffsets; - void *internal; - } Py_buffer; - #define PyBUF_SIMPLE 0 - #define PyBUF_WRITABLE 0x0001 - #define PyBUF_FORMAT 0x0004 - #define PyBUF_ND 0x0008 - #define PyBUF_STRIDES (0x0010 | PyBUF_ND) - #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) - #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) - #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) - #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) - #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE) - #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE) - typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); - typedef void (*releasebufferproc)(PyObject *, Py_buffer *); -#endif -#if PY_MAJOR_VERSION < 3 - #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ - PyCode_New(a, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#else - #define __Pyx_BUILTIN_MODULE_NAME "builtins" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ - PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#endif -#if PY_MAJOR_VERSION < 3 && PY_MINOR_VERSION < 6 - #define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict") -#endif -#if PY_MAJOR_VERSION >= 3 - #define Py_TPFLAGS_CHECKTYPES 0 - #define Py_TPFLAGS_HAVE_INDEX 0 -#endif -#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) - #define Py_TPFLAGS_HAVE_NEWBUFFER 0 -#endif -#if PY_VERSION_HEX < 0x02060000 - #define Py_TPFLAGS_HAVE_VERSION_TAG 0 -#endif -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) - #define CYTHON_PEP393_ENABLED 1 - #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ - 0 : _PyUnicode_Ready((PyObject *)(op))) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) - #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) -#else - #define CYTHON_PEP393_ENABLED 0 - #define __Pyx_PyUnicode_READY(op) (0) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) - #define __Pyx_PyUnicode_READ(k, d, i) ((k=k), (Py_UCS4)(((Py_UNICODE*)d)[i])) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBaseString_Type PyUnicode_Type - #define PyStringObject PyUnicodeObject - #define PyString_Type PyUnicode_Type - #define PyString_Check PyUnicode_Check - #define PyString_CheckExact PyUnicode_CheckExact -#endif -#if PY_VERSION_HEX < 0x02060000 - #define PyBytesObject PyStringObject - #define PyBytes_Type PyString_Type - #define PyBytes_Check PyString_Check - #define PyBytes_CheckExact PyString_CheckExact - #define PyBytes_FromString PyString_FromString - #define PyBytes_FromStringAndSize PyString_FromStringAndSize - #define PyBytes_FromFormat PyString_FromFormat - #define PyBytes_DecodeEscape PyString_DecodeEscape - #define PyBytes_AsString PyString_AsString - #define PyBytes_AsStringAndSize PyString_AsStringAndSize - #define PyBytes_Size PyString_Size - #define PyBytes_AS_STRING PyString_AS_STRING - #define PyBytes_GET_SIZE PyString_GET_SIZE - #define PyBytes_Repr PyString_Repr - #define PyBytes_Concat PyString_Concat - #define PyBytes_ConcatAndDel PyString_ConcatAndDel -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) - #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) -#else - #define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \ - PyString_Check(obj) || PyUnicode_Check(obj)) - #define __Pyx_PyBaseString_CheckExact(obj) (Py_TYPE(obj) == &PyBaseString_Type) -#endif -#if PY_VERSION_HEX < 0x02060000 - #define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type) - #define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type) -#endif -#ifndef PySet_CheckExact - #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) -#endif -#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) -#if PY_MAJOR_VERSION >= 3 - #define PyIntObject PyLongObject - #define PyInt_Type PyLong_Type - #define PyInt_Check(op) PyLong_Check(op) - #define PyInt_CheckExact(op) PyLong_CheckExact(op) - #define PyInt_FromString PyLong_FromString - #define PyInt_FromUnicode PyLong_FromUnicode - #define PyInt_FromLong PyLong_FromLong - #define PyInt_FromSize_t PyLong_FromSize_t - #define PyInt_FromSsize_t PyLong_FromSsize_t - #define PyInt_AsLong PyLong_AsLong - #define PyInt_AS_LONG PyLong_AS_LONG - #define PyInt_AsSsize_t PyLong_AsSsize_t - #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask - #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBoolObject PyLongObject -#endif -#if PY_VERSION_HEX < 0x03020000 - typedef long Py_hash_t; - #define __Pyx_PyInt_FromHash_t PyInt_FromLong - #define __Pyx_PyInt_AsHash_t PyInt_AsLong -#else - #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t - #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t -#endif -#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300) - #define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b) - #define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value) - #define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b) -#else - #define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0))) - #define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1))) - #define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \ - (PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \ - (likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \ - (PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1))) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) -#endif -#if PY_VERSION_HEX < 0x02050000 - #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n))) - #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a)) - #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n))) -#else - #define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n)) - #define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a)) - #define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n)) -#endif -#if PY_VERSION_HEX < 0x02050000 - #define __Pyx_NAMESTR(n) ((char *)(n)) - #define __Pyx_DOCSTR(n) ((char *)(n)) -#else - #define __Pyx_NAMESTR(n) (n) - #define __Pyx_DOCSTR(n) (n) -#endif -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif -#ifdef NAN -#define __PYX_NAN() ((float) NAN) -#else -static CYTHON_INLINE float __PYX_NAN() { - /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and - a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is - a quiet NaN. */ - float value; - memset(&value, 0xFF, sizeof(value)); - return value; -} -#endif - - -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif - -#ifndef __PYX_EXTERN_C - #ifdef __cplusplus - #define __PYX_EXTERN_C extern "C" - #else - #define __PYX_EXTERN_C extern - #endif -#endif - -#if defined(WIN32) || defined(MS_WINDOWS) -#define _USE_MATH_DEFINES -#endif -#include <math.h> -#define __PYX_HAVE__mtrand -#define __PYX_HAVE_API__mtrand -#include "string.h" -#include "math.h" -#include "numpy/npy_no_deprecated_api.h" -#include "numpy/arrayobject.h" -#include "mtrand_py_helper.h" -#include "randomkit.h" -#include "distributions.h" -#include "initarray.h" -#ifdef _OPENMP -#include <omp.h> -#endif /* _OPENMP */ - -#ifdef PYREX_WITHOUT_ASSERTIONS -#define CYTHON_WITHOUT_ASSERTIONS -#endif - -#ifndef CYTHON_UNUSED -# if defined(__GNUC__) -# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -#endif -typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; - const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/ - -#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 -#define __PYX_DEFAULT_STRING_ENCODING "" -#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString -#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); -static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); -#define __Pyx_PyBytes_FromString PyBytes_FromString -#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*); -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#else - #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize -#endif -#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s) -#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s) -#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s) -#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s) -#if PY_MAJOR_VERSION < 3 -static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) -{ - const Py_UNICODE *u_end = u; - while (*u_end++) ; - return u_end - u - 1; -} -#else -#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen -#endif -#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) -#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode -#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode -#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) -#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); -static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*); -#if CYTHON_COMPILING_IN_CPYTHON -#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) -#else -#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) -#endif -#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII -static int __Pyx_sys_getdefaultencoding_not_ascii; -static int __Pyx_init_sys_getdefaultencoding_params() { - PyObject* sys = NULL; - PyObject* default_encoding = NULL; - PyObject* ascii_chars_u = NULL; - PyObject* ascii_chars_b = NULL; - sys = PyImport_ImportModule("sys"); - if (sys == NULL) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); - if (default_encoding == NULL) goto bad; - if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) { - __Pyx_sys_getdefaultencoding_not_ascii = 0; - } else { - const char* default_encoding_c = PyBytes_AS_STRING(default_encoding); - char ascii_chars[128]; - int c; - for (c = 0; c < 128; c++) { - ascii_chars[c] = c; - } - __Pyx_sys_getdefaultencoding_not_ascii = 1; - ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); - if (ascii_chars_u == NULL) goto bad; - ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); - if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { - PyErr_Format( - PyExc_ValueError, - "This module compiled with c_string_encoding=ascii, but default encoding '%s' is not a superset of ascii.", - default_encoding_c); - goto bad; - } - } - Py_XDECREF(sys); - Py_XDECREF(default_encoding); - Py_XDECREF(ascii_chars_u); - Py_XDECREF(ascii_chars_b); - return 0; -bad: - Py_XDECREF(sys); - Py_XDECREF(default_encoding); - Py_XDECREF(ascii_chars_u); - Py_XDECREF(ascii_chars_b); - return -1; -} -#endif -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) -#else -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -static char* __PYX_DEFAULT_STRING_ENCODING; -static int __Pyx_init_sys_getdefaultencoding_params() { - PyObject* sys = NULL; - PyObject* default_encoding = NULL; - char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (sys == NULL) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); - if (default_encoding == NULL) goto bad; - default_encoding_c = PyBytes_AS_STRING(default_encoding); - __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); - strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); - Py_DECREF(sys); - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(sys); - Py_XDECREF(default_encoding); - return -1; -} -#endif -#endif - - -#ifdef __GNUC__ - /* Test for GCC > 2.95 */ - #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) - #else /* __GNUC__ > 2 ... */ - #define likely(x) (x) - #define unlikely(x) (x) - #endif /* __GNUC__ > 2 ... */ -#else /* __GNUC__ */ - #define likely(x) (x) - #define unlikely(x) (x) -#endif /* __GNUC__ */ - -static PyObject *__pyx_m; -static PyObject *__pyx_d; -static PyObject *__pyx_b; -static PyObject *__pyx_empty_tuple; -static PyObject *__pyx_empty_bytes; -static int __pyx_lineno; -static int __pyx_clineno = 0; -static const char * __pyx_cfilenm= __FILE__; -static const char *__pyx_filename; - - -static const char *__pyx_f[] = { - "mtrand.pyx", - "numpy.pxd", -}; - -/*--- Type declarations ---*/ -struct __pyx_obj_6mtrand_RandomState; - -/* "mtrand.pyx":107 - * long rk_logseries(rk_state *state, double p) - * - * ctypedef double (* rk_cont0)(rk_state *state) # <<<<<<<<<<<<<< - * ctypedef double (* rk_cont1)(rk_state *state, double a) - * ctypedef double (* rk_cont2)(rk_state *state, double a, double b) - */ -typedef double (*__pyx_t_6mtrand_rk_cont0)(rk_state *); - -/* "mtrand.pyx":108 - * - * ctypedef double (* rk_cont0)(rk_state *state) - * ctypedef double (* rk_cont1)(rk_state *state, double a) # <<<<<<<<<<<<<< - * ctypedef double (* rk_cont2)(rk_state *state, double a, double b) - * ctypedef double (* rk_cont3)(rk_state *state, double a, double b, double c) - */ -typedef double (*__pyx_t_6mtrand_rk_cont1)(rk_state *, double); - -/* "mtrand.pyx":109 - * ctypedef double (* rk_cont0)(rk_state *state) - * ctypedef double (* rk_cont1)(rk_state *state, double a) - * ctypedef double (* rk_cont2)(rk_state *state, double a, double b) # <<<<<<<<<<<<<< - * ctypedef double (* rk_cont3)(rk_state *state, double a, double b, double c) - * - */ -typedef double (*__pyx_t_6mtrand_rk_cont2)(rk_state *, double, double); - -/* "mtrand.pyx":110 - * ctypedef double (* rk_cont1)(rk_state *state, double a) - * ctypedef double (* rk_cont2)(rk_state *state, double a, double b) - * ctypedef double (* rk_cont3)(rk_state *state, double a, double b, double c) # <<<<<<<<<<<<<< - * - * ctypedef long (* rk_disc0)(rk_state *state) - */ -typedef double (*__pyx_t_6mtrand_rk_cont3)(rk_state *, double, double, double); - -/* "mtrand.pyx":112 - * ctypedef double (* rk_cont3)(rk_state *state, double a, double b, double c) - * - * ctypedef long (* rk_disc0)(rk_state *state) # <<<<<<<<<<<<<< - * ctypedef long (* rk_discnp)(rk_state *state, long n, double p) - * ctypedef long (* rk_discdd)(rk_state *state, double n, double p) - */ -typedef long (*__pyx_t_6mtrand_rk_disc0)(rk_state *); - -/* "mtrand.pyx":113 - * - * ctypedef long (* rk_disc0)(rk_state *state) - * ctypedef long (* rk_discnp)(rk_state *state, long n, double p) # <<<<<<<<<<<<<< - * ctypedef long (* rk_discdd)(rk_state *state, double n, double p) - * ctypedef long (* rk_discnmN)(rk_state *state, long n, long m, long N) - */ -typedef long (*__pyx_t_6mtrand_rk_discnp)(rk_state *, long, double); - -/* "mtrand.pyx":114 - * ctypedef long (* rk_disc0)(rk_state *state) - * ctypedef long (* rk_discnp)(rk_state *state, long n, double p) - * ctypedef long (* rk_discdd)(rk_state *state, double n, double p) # <<<<<<<<<<<<<< - * ctypedef long (* rk_discnmN)(rk_state *state, long n, long m, long N) - * ctypedef long (* rk_discd)(rk_state *state, double a) - */ -typedef long (*__pyx_t_6mtrand_rk_discdd)(rk_state *, double, double); - -/* "mtrand.pyx":115 - * ctypedef long (* rk_discnp)(rk_state *state, long n, double p) - * ctypedef long (* rk_discdd)(rk_state *state, double n, double p) - * ctypedef long (* rk_discnmN)(rk_state *state, long n, long m, long N) # <<<<<<<<<<<<<< - * ctypedef long (* rk_discd)(rk_state *state, double a) - * - */ -typedef long (*__pyx_t_6mtrand_rk_discnmN)(rk_state *, long, long, long); - -/* "mtrand.pyx":116 - * ctypedef long (* rk_discdd)(rk_state *state, double n, double p) - * ctypedef long (* rk_discnmN)(rk_state *state, long n, long m, long N) - * ctypedef long (* rk_discd)(rk_state *state, double a) # <<<<<<<<<<<<<< - * - * - */ -typedef long (*__pyx_t_6mtrand_rk_discd)(rk_state *, double); - -/* "mtrand.pyx":525 - * return sum - * - * cdef class RandomState: # <<<<<<<<<<<<<< - * """ - * RandomState(seed=None) - */ -struct __pyx_obj_6mtrand_RandomState { - PyObject_HEAD - rk_state *internal_state; -}; - -#ifndef CYTHON_REFNANNY - #define CYTHON_REFNANNY 0 -#endif -#if CYTHON_REFNANNY - typedef struct { - void (*INCREF)(void*, PyObject*, int); - void (*DECREF)(void*, PyObject*, int); - void (*GOTREF)(void*, PyObject*, int); - void (*GIVEREF)(void*, PyObject*, int); - void* (*SetupContext)(const char*, int, const char*); - void (*FinishContext)(void**); - } __Pyx_RefNannyAPIStruct; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/ - #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; -#ifdef WITH_THREAD - #define __Pyx_RefNannySetupContext(name, acquire_gil) \ - if (acquire_gil) { \ - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ - PyGILState_Release(__pyx_gilstate_save); \ - } else { \ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ - } -#else - #define __Pyx_RefNannySetupContext(name, acquire_gil) \ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) -#endif - #define __Pyx_RefNannyFinishContext() \ - __Pyx_RefNanny->FinishContext(&__pyx_refnanny) - #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) - #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) - #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) - #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) -#else - #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name, acquire_gil) - #define __Pyx_RefNannyFinishContext() - #define __Pyx_INCREF(r) Py_INCREF(r) - #define __Pyx_DECREF(r) Py_DECREF(r) - #define __Pyx_GOTREF(r) - #define __Pyx_GIVEREF(r) - #define __Pyx_XINCREF(r) Py_XINCREF(r) - #define __Pyx_XDECREF(r) Py_XDECREF(r) - #define __Pyx_XGOTREF(r) - #define __Pyx_XGIVEREF(r) -#endif /* CYTHON_REFNANNY */ -#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) -#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro)) - return tp->tp_getattro(obj, attr_name); -#if PY_MAJOR_VERSION < 3 - if (likely(tp->tp_getattr)) - return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); -#endif - return PyObject_GetAttr(obj, attr_name); -} -#else -#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) -#endif - -static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/ - -static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/ - -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ - -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/ - -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/ - -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ - PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ - const char* function_name); /*proto*/ - -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ - -#define __Pyx_GetItemInt(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ - (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Fast(o, i, is_list, wraparound, boundscheck) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -#define __Pyx_GetItemInt_List(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ - (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_List_Fast(o, i, wraparound, boundscheck) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func, is_list, wraparound, boundscheck) \ - (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_GetItemInt_Tuple_Fast(o, i, wraparound, boundscheck) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i))) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, - int is_list, int wraparound, int boundscheck); - -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( - PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, - PyObject** py_start, PyObject** py_stop, PyObject** py_slice, - int has_cstart, int has_cstop, int wraparound); - -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); - -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - -static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/ - -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/ - -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ - -#define __Pyx_PyObject_DelSlice(obj, cstart, cstop, py_start, py_stop, py_slice, has_cstart, has_cstop, wraparound) \ - __Pyx_PyObject_SetSlice(obj, (PyObject*)NULL, cstart, cstop, py_start, py_stop, py_slice, has_cstart, has_cstop, wraparound) -static CYTHON_INLINE int __Pyx_PyObject_SetSlice( - PyObject* obj, PyObject* value, Py_ssize_t cstart, Py_ssize_t cstop, - PyObject** py_start, PyObject** py_stop, PyObject** py_slice, - int has_cstart, int has_cstop, int wraparound); - -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_PyObject_DelAttrStr(o,n) __Pyx_PyObject_SetAttrStr(o,n,NULL) -static CYTHON_INLINE int __Pyx_PyObject_SetAttrStr(PyObject* obj, PyObject* attr_name, PyObject* value) { - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_setattro)) - return tp->tp_setattro(obj, attr_name, value); -#if PY_MAJOR_VERSION < 3 - if (likely(tp->tp_setattr)) - return tp->tp_setattr(obj, PyString_AS_STRING(attr_name), value); -#endif - return PyObject_SetAttr(obj, attr_name, value); -} -#else -#define __Pyx_PyObject_DelAttrStr(o,n) PyObject_DelAttr(o,n) -#define __Pyx_PyObject_SetAttrStr(o,n,v) PyObject_SetAttr(o,n,v) -#endif - -static CYTHON_INLINE int __Pyx_CheckKeywordStrings(PyObject *kwdict, const char* function_name, int kw_allowed); /*proto*/ - -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { - PyListObject* L = (PyListObject*) list; - Py_ssize_t len = Py_SIZE(list); - if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { - Py_INCREF(x); - PyList_SET_ITEM(list, len, x); - Py_SIZE(list) = len+1; - return 0; - } - return PyList_Append(list, x); -} -#else -#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) -#endif - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyList_GetSlice(PyObject* src, Py_ssize_t start, Py_ssize_t stop); -static CYTHON_INLINE PyObject* __Pyx_PyTuple_GetSlice(PyObject* src, Py_ssize_t start, Py_ssize_t stop); -#else -#define __Pyx_PyList_GetSlice(seq, start, stop) PySequence_GetSlice(seq, start, stop) -#define __Pyx_PyTuple_GetSlice(seq, start, stop) PySequence_GetSlice(seq, start, stop) -#endif - -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /*proto*/ - -#ifndef __PYX_FORCE_INIT_THREADS - #define __PYX_FORCE_INIT_THREADS 0 -#endif - -#define __Pyx_SetItemInt(o, i, v, size, to_py_func, is_list, wraparound, boundscheck) \ - (((size) <= sizeof(Py_ssize_t)) ? \ - __Pyx_SetItemInt_Fast(o, i, v, is_list, wraparound, boundscheck) : \ - __Pyx_SetItemInt_Generic(o, to_py_func(i), v)) -static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); -static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, - int is_list, int wraparound, int boundscheck); - -static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ -static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ - -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/ - -static CYTHON_INLINE npy_intp __Pyx_PyInt_from_py_npy_intp(PyObject *); - -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_intp(npy_intp); - -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *); - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *); - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *); - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject *); - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject *); - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *); - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *); - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *); - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject *); - -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *); - -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *); - -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject *); - -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *); - -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *); - -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *); - -static int __Pyx_check_binary_version(void); - -#if !defined(__Pyx_PyIdentifier_FromString) -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) -#else - #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) -#endif -#endif - -static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ - -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/ - -typedef struct { - int code_line; - PyCodeObject* code_object; -} __Pyx_CodeObjectCacheEntry; -struct __Pyx_CodeObjectCache { - int count; - int max_count; - __Pyx_CodeObjectCacheEntry* entries; -}; -static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); -static PyCodeObject *__pyx_find_code_object(int code_line); -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); - -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename); /*proto*/ - -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ - - -/* Module declarations from 'numpy' */ - -/* Module declarations from 'mtrand' */ -static PyTypeObject *__pyx_ptype_6mtrand_dtype = 0; -static PyTypeObject *__pyx_ptype_6mtrand_ndarray = 0; -static PyTypeObject *__pyx_ptype_6mtrand_flatiter = 0; -static PyTypeObject *__pyx_ptype_6mtrand_broadcast = 0; -static PyTypeObject *__pyx_ptype_6mtrand_RandomState = 0; -static PyObject *__pyx_f_6mtrand_cont0_array(rk_state *, __pyx_t_6mtrand_rk_cont0, PyObject *); /*proto*/ -static PyObject *__pyx_f_6mtrand_cont1_array_sc(rk_state *, __pyx_t_6mtrand_rk_cont1, PyObject *, double); /*proto*/ -static PyObject *__pyx_f_6mtrand_cont1_array(rk_state *, __pyx_t_6mtrand_rk_cont1, PyObject *, PyArrayObject *); /*proto*/ -static PyObject *__pyx_f_6mtrand_cont2_array_sc(rk_state *, __pyx_t_6mtrand_rk_cont2, PyObject *, double, double); /*proto*/ -static PyObject *__pyx_f_6mtrand_cont2_array(rk_state *, __pyx_t_6mtrand_rk_cont2, PyObject *, PyArrayObject *, PyArrayObject *); /*proto*/ -static PyObject *__pyx_f_6mtrand_cont3_array_sc(rk_state *, __pyx_t_6mtrand_rk_cont3, PyObject *, double, double, double); /*proto*/ -static PyObject *__pyx_f_6mtrand_cont3_array(rk_state *, __pyx_t_6mtrand_rk_cont3, PyObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *); /*proto*/ -static PyObject *__pyx_f_6mtrand_disc0_array(rk_state *, __pyx_t_6mtrand_rk_disc0, PyObject *); /*proto*/ -static PyObject *__pyx_f_6mtrand_discnp_array_sc(rk_state *, __pyx_t_6mtrand_rk_discnp, PyObject *, long, double); /*proto*/ -static PyObject *__pyx_f_6mtrand_discnp_array(rk_state *, __pyx_t_6mtrand_rk_discnp, PyObject *, PyArrayObject *, PyArrayObject *); /*proto*/ -static PyObject *__pyx_f_6mtrand_discdd_array_sc(rk_state *, __pyx_t_6mtrand_rk_discdd, PyObject *, double, double); /*proto*/ -static PyObject *__pyx_f_6mtrand_discdd_array(rk_state *, __pyx_t_6mtrand_rk_discdd, PyObject *, PyArrayObject *, PyArrayObject *); /*proto*/ -static PyObject *__pyx_f_6mtrand_discnmN_array_sc(rk_state *, __pyx_t_6mtrand_rk_discnmN, PyObject *, long, long, long); /*proto*/ -static PyObject *__pyx_f_6mtrand_discnmN_array(rk_state *, __pyx_t_6mtrand_rk_discnmN, PyObject *, PyArrayObject *, PyArrayObject *, PyArrayObject *); /*proto*/ -static PyObject *__pyx_f_6mtrand_discd_array_sc(rk_state *, __pyx_t_6mtrand_rk_discd, PyObject *, double); /*proto*/ -static PyObject *__pyx_f_6mtrand_discd_array(rk_state *, __pyx_t_6mtrand_rk_discd, PyObject *, PyArrayObject *); /*proto*/ -static double __pyx_f_6mtrand_kahan_sum(double *, npy_intp); /*proto*/ -#define __Pyx_MODULE_NAME "mtrand" -int __pyx_module_is_main_mtrand = 0; - -/* Implementation of 'mtrand' */ -static PyObject *__pyx_builtin_ValueError; -static PyObject *__pyx_builtin_TypeError; -static int __pyx_pf_6mtrand_11RandomState___init__(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_seed); /* proto */ -static void __pyx_pf_6mtrand_11RandomState_2__dealloc__(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_4seed(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_seed); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_6get_state(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_8set_state(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_state); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_10__getstate__(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_12__setstate__(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_state); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_14__reduce__(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_16random_sample(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_18tomaxint(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_20randint(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_low, PyObject *__pyx_v_high, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_22bytes(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, npy_intp __pyx_v_length); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_24choice(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_a, PyObject *__pyx_v_size, PyObject *__pyx_v_replace, PyObject *__pyx_v_p); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_26uniform(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_low, PyObject *__pyx_v_high, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_28rand(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_args); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_30randn(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_args); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_32random_integers(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_low, PyObject *__pyx_v_high, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_34standard_normal(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_36normal(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_loc, PyObject *__pyx_v_scale, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_38beta(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_40exponential(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_scale, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_42standard_exponential(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_44standard_gamma(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_shape, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_46gamma(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_shape, PyObject *__pyx_v_scale, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_48f(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_dfnum, PyObject *__pyx_v_dfden, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_50noncentral_f(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_dfnum, PyObject *__pyx_v_dfden, PyObject *__pyx_v_nonc, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_52chisquare(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_df, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_54noncentral_chisquare(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_df, PyObject *__pyx_v_nonc, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_56standard_cauchy(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_58standard_t(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_df, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_60vonmises(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_mu, PyObject *__pyx_v_kappa, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_62pareto(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_a, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_64weibull(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_a, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_66power(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_a, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_68laplace(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_loc, PyObject *__pyx_v_scale, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_70gumbel(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_loc, PyObject *__pyx_v_scale, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_72logistic(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_loc, PyObject *__pyx_v_scale, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_74lognormal(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_mean, PyObject *__pyx_v_sigma, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_76rayleigh(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_scale, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_78wald(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_mean, PyObject *__pyx_v_scale, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_80triangular(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_left, PyObject *__pyx_v_mode, PyObject *__pyx_v_right, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_82binomial(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_n, PyObject *__pyx_v_p, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_84negative_binomial(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_n, PyObject *__pyx_v_p, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_86poisson(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_lam, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_88zipf(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_a, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_90geometric(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_p, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_92hypergeometric(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_ngood, PyObject *__pyx_v_nbad, PyObject *__pyx_v_nsample, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_94logseries(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_p, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_96multivariate_normal(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_mean, PyObject *__pyx_v_cov, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_98multinomial(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, npy_intp __pyx_v_n, PyObject *__pyx_v_pvals, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_100dirichlet(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_alpha, PyObject *__pyx_v_size); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_102shuffle(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_x); /* proto */ -static PyObject *__pyx_pf_6mtrand_11RandomState_104permutation(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_x); /* proto */ -static PyObject *__pyx_tp_new_6mtrand_RandomState(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static char __pyx_k_1[] = "size is not compatible with inputs"; -static char __pyx_k_9[] = "algorithm must be 'MT19937'"; -static char __pyx_k_13[] = "state must be 624 longs"; -static char __pyx_k_15[] = "low >= high"; -static char __pyx_k_18[] = "a must be 1-dimensional or an integer"; -static char __pyx_k_20[] = "a must be greater than 0"; -static char __pyx_k_22[] = "a must be 1-dimensional"; -static char __pyx_k_24[] = "a must be non-empty"; -static char __pyx_k_26[] = "p must be 1-dimensional"; -static char __pyx_k_28[] = "a and p must have same size"; -static char __pyx_k_30[] = "probabilities are not non-negative"; -static char __pyx_k_32[] = "probabilities do not sum to 1"; -static char __pyx_k_34[] = "Cannot take a larger sample than population when 'replace=False'"; -static char __pyx_k_36[] = "Fewer non-zero entries in p than size"; -static char __pyx_k_44[] = "scale <= 0"; -static char __pyx_k_47[] = "a <= 0"; -static char __pyx_k_49[] = "b <= 0"; -static char __pyx_k_56[] = "shape <= 0"; -static char __pyx_k_66[] = "dfnum <= 0"; -static char __pyx_k_68[] = "dfden <= 0"; -static char __pyx_k_70[] = "dfnum <= 1"; -static char __pyx_k_73[] = "nonc < 0"; -static char __pyx_k_78[] = "df <= 0"; -static char __pyx_k_82[] = "nonc <= 0"; -static char __pyx_k_84[] = "df <= 1"; -static char __pyx_k_89[] = "kappa < 0"; -static char __pyx_k__a[] = "a"; -static char __pyx_k__b[] = "b"; -static char __pyx_k__f[] = "f"; -static char __pyx_k__l[] = "l"; -static char __pyx_k__n[] = "n"; -static char __pyx_k__p[] = "p"; -static char __pyx_k_112[] = "sigma <= 0"; -static char __pyx_k_114[] = "sigma <= 0.0"; -static char __pyx_k_118[] = "scale <= 0.0"; -static char __pyx_k_120[] = "mean <= 0"; -static char __pyx_k_123[] = "mean <= 0.0"; -static char __pyx_k_126[] = "left > mode"; -static char __pyx_k_128[] = "mode > right"; -static char __pyx_k_130[] = "left == right"; -static char __pyx_k_135[] = "n < 0"; -static char __pyx_k_137[] = "p < 0"; -static char __pyx_k_139[] = "p > 1"; -static char __pyx_k_144[] = "n <= 0"; -static char __pyx_k_152[] = "lam < 0"; -static char __pyx_k_154[] = "lam value too large"; -static char __pyx_k_157[] = "lam value too large."; -static char __pyx_k_159[] = "a <= 1.0"; -static char __pyx_k_162[] = "p < 0.0"; -static char __pyx_k_164[] = "p > 1.0"; -static char __pyx_k_168[] = "ngood < 0"; -static char __pyx_k_170[] = "nbad < 0"; -static char __pyx_k_172[] = "nsample < 1"; -static char __pyx_k_174[] = "ngood + nbad < nsample"; -static char __pyx_k_180[] = "p <= 0.0"; -static char __pyx_k_182[] = "p >= 1.0"; -static char __pyx_k_186[] = "mean must be 1 dimensional"; -static char __pyx_k_188[] = "cov must be 2 dimensional and square"; -static char __pyx_k_190[] = "mean and cov must have same length"; -static char __pyx_k_193[] = "numpy.dual"; -static char __pyx_k_194[] = "sum(pvals[:-1]) > 1.0"; -static char __pyx_k_199[] = "standard_exponential"; -static char __pyx_k_200[] = "noncentral_chisquare"; -static char __pyx_k_201[] = "RandomState.random_sample (line 722)"; -static char __pyx_k_202[] = "\n random_sample(size=None)\n\n Return random floats in the half-open interval [0.0, 1.0).\n\n Results are from the \"continuous uniform\" distribution over the\n stated interval. To sample :math:`Unif[a, b), b > a` multiply\n the output of `random_sample` by `(b-a)` and add `a`::\n\n (b - a) * random_sample() + a\n\n Parameters\n ----------\n size : int or tuple of ints, optional\n Defines the shape of the returned array of random floats. If None\n (the default), returns a single float.\n\n Returns\n -------\n out : float or ndarray of floats\n Array of random floats of shape `size` (unless ``size=None``, in which\n case a single float is returned).\n\n Examples\n --------\n >>> np.random.random_sample()\n 0.47108547995356098\n >>> type(np.random.random_sample())\n <type 'float'>\n >>> np.random.random_sample((5,))\n array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428])\n\n Three-by-two array of random numbers from [-5, 0):\n\n >>> 5 * np.random.random_sample((3, 2)) - 5\n array([[-3.99149989, -0.52338984],\n [-2.99091858, -0.79479508],\n [-1.23204345, -1.75224494]])\n\n "; -static char __pyx_k_203[] = "RandomState.tomaxint (line 765)"; -static char __pyx_k_204[] = "\n tomaxint(size=None)\n\n Random integers between 0 and ``sys.maxint``, inclusive.\n\n Return a sample of uniformly distributed random integers in the interval\n [0, ``sys.maxint``].\n\n Parameters\n ----------\n size : tuple of ints, int, optional\n Shape of output. If this is, for example, (m,n,k), m*n*k samples\n are generated. If no shape is specified, a single sample is\n returned.\n\n Returns\n -------\n out : ndarray\n Drawn samples, with shape `size`.\n\n See Also\n --------\n randint : Uniform sampling over a given half-open interval of integers.\n random_integers : Uniform sampling over a given closed interval of\n integers.\n\n Examples\n --------\n >>> RS = np.random.mtrand.RandomState() # need a RandomState object\n >>> RS.tomaxint((2,2,2))\n array([[[1170048599, 1600360186],\n [ 739731006, 1947757578]],\n [[1871712945, 752307660],\n [1601631370, 1479324245]]])\n >>> import sys\n >>> sys.maxint\n 2147483647\n >>> RS.tomaxint((2,2,2)) < sys.maxint\n array([[[ True, True],\n [ True, True]],\n [[ True, True],\n [ True, True]]], dtype=bool)\n\n "; -static char __pyx_k_205[] = "RandomState.randint (line 812)"; -static char __pyx_k_206[] = "\n randint(low, high=None, size=None)\n\n Return random integers from `low` (inclusive) to `high` (exclusive).\n\n Return random integers from the \"discrete uniform\" distribution in the\n \"half-open\" interval [`low`, `high`). If `high` is None (the default),\n then results are from [0, `low`).\n\n Parameters\n ----------\n low : int\n Lowest (signed) integer to be drawn from the distribution (unless\n ``high=None``, in which case this parameter is the *highest* such\n integer).\n high : int, optional\n If provided, one above the largest (signed) integer to be drawn\n from the distribution (see above for behavior if ``high=None``).\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single int is\n returned.\n\n Returns\n -------\n out : int or ndarray of ints\n `size`-shaped array of random integers from the appropriate\n distribution, or a single such random int if `size` not provided.\n\n See Also\n --------\n random.random_integers : similar to `randint`, only for the closed\n interval [`low`, `high`], and 1 is the lowest value if `high` is\n omitted. In particular, this other one is the one to use to generate\n uniformly distributed discrete non-integers.\n\n Examples\n --------\n >>> np.random.randint(2, size=10)\n array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])\n >>> np.random.randint(1, size=10)\n array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n\n Generate a 2 x 4 array of ints between 0 and 4, inclusive:\n\n >>> np.random.randint(5, size=(2, 4))\n array([[4, 0, 2, 1],\n [3, 2, 2, 0]])\n\n "; -static char __pyx_k_207[] = "RandomState.bytes (line 892)"; -static char __pyx_k_208[] = "\n bytes(length)\n\n Return random bytes.\n\n Parameters\n ----------\n length : int\n Number of random bytes.\n\n Returns\n -------\n out : str\n String of length `length`.\n\n Examples\n --------\n >>> np.random.bytes(10)\n ' eh\\x85\\x022SZ\\xbf\\xa4' #random\n\n "; -static char __pyx_k_209[] = "RandomState.choice (line 920)"; -static char __pyx_k_210[] = "\n choice(a, size=None, replace=True, p=None)\n\n Generates a random sample from a given 1-D array\n\n .. versionadded:: 1.7.0\n\n Parameters\n -----------\n a : 1-D array-like or int\n If an ndarray, a random sample is generated from its elements.\n If an int, the random sample is generated as if a was np.arange(n)\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single value is\n returned.\n replace : boolean, optional\n Whether the sample is with or without replacement\n p : 1-D array-like, optional\n The probabilities associated with each entry in a.\n If not given the sample assumes a uniform distribtion over all\n entries in a.\n\n Returns\n --------\n samples : 1-D ndarray, shape (size,)\n The generated random samples\n\n Raises\n -------\n ValueError\n If a is an int and less than zero, if a or p are not 1-dimensional,\n if a is an array-like of size 0, if p is not a vector of\n probabilities, if a and p have different lengths, or if\n replace=False and the sample size is greater than the population\n size\n\n See Also\n ---------\n randint, shuffle, permutation\n\n Examples\n ---------\n Generate a uniform random sample from np.arange(5) of size 3:\n\n >>> np.random.choice(5, 3)\n array([0, 3, 4])\n >>> #This is equivalent to np.random.randint(0,5,3)\n\n Generate a non-uniform random sample from np.arange(5) of size 3:\n\n >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])\n array([3, 3, 0])\n\n Generate a uniform random sample from np.arange(5) of size 3 without\n replacement:\n\n >>> np.random.choice(5, 3, replace=False)\n array([3,1,0])\n "" >>> #This is equivalent to np.random.shuffle(np.arange(5))[:3]\n\n Generate a non-uniform random sample from np.arange(5) of size\n 3 without replacement:\n\n >>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])\n array([2, 3, 0])\n\n Any of the above can be repeated with an arbitrary array-like\n instead of just integers. For instance:\n\n >>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']\n >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])\n array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],\n dtype='|S11')\n\n "; -static char __pyx_k_211[] = "RandomState.uniform (line 1092)"; -static char __pyx_k_212[] = "\n uniform(low=0.0, high=1.0, size=1)\n\n Draw samples from a uniform distribution.\n\n Samples are uniformly distributed over the half-open interval\n ``[low, high)`` (includes low, but excludes high). In other words,\n any value within the given interval is equally likely to be drawn\n by `uniform`.\n\n Parameters\n ----------\n low : float, optional\n Lower boundary of the output interval. All values generated will be\n greater than or equal to low. The default value is 0.\n high : float\n Upper boundary of the output interval. All values generated will be\n less than high. The default value is 1.0.\n size : int or tuple of ints, optional\n Shape of output. If the given size is, for example, (m,n,k),\n m*n*k samples are generated. If no shape is specified, a single sample\n is returned.\n\n Returns\n -------\n out : ndarray\n Drawn samples, with shape `size`.\n\n See Also\n --------\n randint : Discrete uniform distribution, yielding integers.\n random_integers : Discrete uniform distribution over the closed\n interval ``[low, high]``.\n random_sample : Floats uniformly distributed over ``[0, 1)``.\n random : Alias for `random_sample`.\n rand : Convenience function that accepts dimensions as input, e.g.,\n ``rand(2,2)`` would generate a 2-by-2 array of floats,\n uniformly distributed over ``[0, 1)``.\n\n Notes\n -----\n The probability density function of the uniform distribution is\n\n .. math:: p(x) = \\frac{1}{b - a}\n\n anywhere within the interval ``[a, b)``, and zero elsewhere.\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> s = np.random.uniform(-1,0,1000)\n\n All values are w""ithin the given interval:\n\n >>> np.all(s >= -1)\n True\n >>> np.all(s < 0)\n True\n\n Display the histogram of the samples, along with the\n probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, 15, normed=True)\n >>> plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')\n >>> plt.show()\n\n "; -static char __pyx_k_213[] = "RandomState.rand (line 1179)"; -static char __pyx_k_214[] = "\n rand(d0, d1, ..., dn)\n\n Random values in a given shape.\n\n Create an array of the given shape and propagate it with\n random samples from a uniform distribution\n over ``[0, 1)``.\n\n Parameters\n ----------\n d0, d1, ..., dn : int, optional\n The dimensions of the returned array, should all be positive.\n If no argument is given a single Python float is returned.\n\n Returns\n -------\n out : ndarray, shape ``(d0, d1, ..., dn)``\n Random values.\n\n See Also\n --------\n random\n\n Notes\n -----\n This is a convenience function. If you want an interface that\n takes a shape-tuple as the first argument, refer to\n np.random.random_sample .\n\n Examples\n --------\n >>> np.random.rand(3,2)\n array([[ 0.14022471, 0.96360618], #random\n [ 0.37601032, 0.25528411], #random\n [ 0.49313049, 0.94909878]]) #random\n\n "; -static char __pyx_k_215[] = "RandomState.randn (line 1223)"; -static char __pyx_k_216[] = "\n randn(d0, d1, ..., dn)\n\n Return a sample (or samples) from the \"standard normal\" distribution.\n\n If positive, int_like or int-convertible arguments are provided,\n `randn` generates an array of shape ``(d0, d1, ..., dn)``, filled\n with random floats sampled from a univariate \"normal\" (Gaussian)\n distribution of mean 0 and variance 1 (if any of the :math:`d_i` are\n floats, they are first converted to integers by truncation). A single\n float randomly sampled from the distribution is returned if no\n argument is provided.\n\n This is a convenience function. If you want an interface that takes a\n tuple as the first argument, use `numpy.random.standard_normal` instead.\n\n Parameters\n ----------\n d0, d1, ..., dn : int, optional\n The dimensions of the returned array, should be all positive.\n If no argument is given a single Python float is returned.\n\n Returns\n -------\n Z : ndarray or float\n A ``(d0, d1, ..., dn)``-shaped array of floating-point samples from\n the standard normal distribution, or a single such float if\n no parameters were supplied.\n\n See Also\n --------\n random.standard_normal : Similar, but takes a tuple as its argument.\n\n Notes\n -----\n For random samples from :math:`N(\\mu, \\sigma^2)`, use:\n\n ``sigma * np.random.randn(...) + mu``\n\n Examples\n --------\n >>> np.random.randn()\n 2.1923875335537315 #random\n\n Two-by-four array of samples from N(3, 6.25):\n\n >>> 2.5 * np.random.randn(2, 4) + 3\n array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], #random\n [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) #random\n\n "; -static char __pyx_k_217[] = "RandomState.random_integers (line 1280)"; -static char __pyx_k_218[] = "\n random_integers(low, high=None, size=None)\n\n Return random integers between `low` and `high`, inclusive.\n\n Return random integers from the \"discrete uniform\" distribution in the\n closed interval [`low`, `high`]. If `high` is None (the default),\n then results are from [1, `low`].\n\n Parameters\n ----------\n low : int\n Lowest (signed) integer to be drawn from the distribution (unless\n ``high=None``, in which case this parameter is the *highest* such\n integer).\n high : int, optional\n If provided, the largest (signed) integer to be drawn from the\n distribution (see above for behavior if ``high=None``).\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single int is returned.\n\n Returns\n -------\n out : int or ndarray of ints\n `size`-shaped array of random integers from the appropriate\n distribution, or a single such random int if `size` not provided.\n\n See Also\n --------\n random.randint : Similar to `random_integers`, only for the half-open\n interval [`low`, `high`), and 0 is the lowest value if `high` is\n omitted.\n\n Notes\n -----\n To sample from N evenly spaced floating-point numbers between a and b,\n use::\n\n a + (b - a) * (np.random.random_integers(N) - 1) / (N - 1.)\n\n Examples\n --------\n >>> np.random.random_integers(5)\n 4\n >>> type(np.random.random_integers(5))\n <type 'int'>\n >>> np.random.random_integers(5, size=(3.,2.))\n array([[5, 4],\n [3, 3],\n [4, 5]])\n\n Choose five random numbers from the set of five evenly-spaced\n numbers between 0 and 2.5, inclusive (*i.e.*, from the set\n :math:`{0, 5/8, 10/8, 15/8, 20/8}`):\n""\n >>> 2.5 * (np.random.random_integers(5, size=(5,)) - 1) / 4.\n array([ 0.625, 1.25 , 0.625, 0.625, 2.5 ])\n\n Roll two six sided dice 1000 times and sum the results:\n\n >>> d1 = np.random.random_integers(1, 6, 1000)\n >>> d2 = np.random.random_integers(1, 6, 1000)\n >>> dsums = d1 + d2\n\n Display results as a histogram:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(dsums, 11, normed=True)\n >>> plt.show()\n\n "; -static char __pyx_k_219[] = "RandomState.standard_normal (line 1358)"; -static char __pyx_k_220[] = "\n standard_normal(size=None)\n\n Returns samples from a Standard Normal distribution (mean=0, stdev=1).\n\n Parameters\n ----------\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single value is\n returned.\n\n Returns\n -------\n out : float or ndarray\n Drawn samples.\n\n Examples\n --------\n >>> s = np.random.standard_normal(8000)\n >>> s\n array([ 0.6888893 , 0.78096262, -0.89086505, ..., 0.49876311, #random\n -0.38672696, -0.4685006 ]) #random\n >>> s.shape\n (8000,)\n >>> s = np.random.standard_normal(size=(3, 4, 2))\n >>> s.shape\n (3, 4, 2)\n\n "; -static char __pyx_k_221[] = "RandomState.normal (line 1390)"; -static char __pyx_k_222[] = "\n normal(loc=0.0, scale=1.0, size=None)\n\n Draw random samples from a normal (Gaussian) distribution.\n\n The probability density function of the normal distribution, first\n derived by De Moivre and 200 years later by both Gauss and Laplace\n independently [2]_, is often called the bell curve because of\n its characteristic shape (see the example below).\n\n The normal distributions occurs often in nature. For example, it\n describes the commonly occurring distribution of samples influenced\n by a large number of tiny, random disturbances, each with its own\n unique distribution [2]_.\n\n Parameters\n ----------\n loc : float\n Mean (\"centre\") of the distribution.\n scale : float\n Standard deviation (spread or \"width\") of the distribution.\n size : tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n See Also\n --------\n scipy.stats.distributions.norm : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Gaussian distribution is\n\n .. math:: p(x) = \\frac{1}{\\sqrt{ 2 \\pi \\sigma^2 }}\n e^{ - \\frac{ (x - \\mu)^2 } {2 \\sigma^2} },\n\n where :math:`\\mu` is the mean and :math:`\\sigma` the standard deviation.\n The square of the standard deviation, :math:`\\sigma^2`, is called the\n variance.\n\n The function has its peak at the mean, and its \"spread\" increases with\n the standard deviation (the function reaches 0.607 times its maximum at\n :math:`x + \\sigma` and :math:`x - \\sigma` [2]_). This implies that\n `numpy.random.normal` is more likely to return samples lying close to the\n mean, rather than those far away.\n""\n References\n ----------\n .. [1] Wikipedia, \"Normal distribution\",\n http://en.wikipedia.org/wiki/Normal_distribution\n .. [2] P. R. Peebles Jr., \"Central Limit Theorem\" in \"Probability, Random\n Variables and Random Signal Principles\", 4th ed., 2001,\n pp. 51, 51, 125.\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> mu, sigma = 0, 0.1 # mean and standard deviation\n >>> s = np.random.normal(mu, sigma, 1000)\n\n Verify the mean and the variance:\n\n >>> abs(mu - np.mean(s)) < 0.01\n True\n\n >>> abs(sigma - np.std(s, ddof=1)) < 0.01\n True\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, 30, normed=True)\n >>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *\n ... np.exp( - (bins - mu)**2 / (2 * sigma**2) ),\n ... linewidth=2, color='r')\n >>> plt.show()\n\n "; -static char __pyx_k_223[] = "RandomState.standard_exponential (line 1603)"; -static char __pyx_k_224[] = "\n standard_exponential(size=None)\n\n Draw samples from the standard exponential distribution.\n\n `standard_exponential` is identical to the exponential distribution\n with a scale parameter of 1.\n\n Parameters\n ----------\n size : int or tuple of ints\n Shape of the output.\n\n Returns\n -------\n out : float or ndarray\n Drawn samples.\n\n Examples\n --------\n Output a 3x8000 array:\n\n >>> n = np.random.standard_exponential((3, 8000))\n\n "; -static char __pyx_k_225[] = "RandomState.standard_gamma (line 1631)"; -static char __pyx_k_226[] = "\n standard_gamma(shape, size=None)\n\n Draw samples from a Standard Gamma distribution.\n\n Samples are drawn from a Gamma distribution with specified parameters,\n shape (sometimes designated \"k\") and scale=1.\n\n Parameters\n ----------\n shape : float\n Parameter, should be > 0.\n size : int or tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : ndarray or scalar\n The drawn samples.\n\n See Also\n --------\n scipy.stats.distributions.gamma : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Gamma distribution is\n\n .. math:: p(x) = x^{k-1}\\frac{e^{-x/\\theta}}{\\theta^k\\Gamma(k)},\n\n where :math:`k` is the shape and :math:`\\theta` the scale,\n and :math:`\\Gamma` is the Gamma function.\n\n The Gamma distribution is often used to model the times to failure of\n electronic components, and arises naturally in processes for which the\n waiting times between Poisson distributed events are relevant.\n\n References\n ----------\n .. [1] Weisstein, Eric W. \"Gamma Distribution.\" From MathWorld--A\n Wolfram Web Resource.\n http://mathworld.wolfram.com/GammaDistribution.html\n .. [2] Wikipedia, \"Gamma-distribution\",\n http://en.wikipedia.org/wiki/Gamma-distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> shape, scale = 2., 1. # mean and width\n >>> s = np.random.standard_gamma(shape, 1000000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt""\n >>> import scipy.special as sps\n >>> count, bins, ignored = plt.hist(s, 50, normed=True)\n >>> y = bins**(shape-1) * ((np.exp(-bins/scale))/ \\\n ... (sps.gamma(shape) * scale**shape))\n >>> plt.plot(bins, y, linewidth=2, color='r')\n >>> plt.show()\n\n "; -static char __pyx_k_227[] = "RandomState.gamma (line 1713)"; -static char __pyx_k_228[] = "\n gamma(shape, scale=1.0, size=None)\n\n Draw samples from a Gamma distribution.\n\n Samples are drawn from a Gamma distribution with specified parameters,\n `shape` (sometimes designated \"k\") and `scale` (sometimes designated\n \"theta\"), where both parameters are > 0.\n\n Parameters\n ----------\n shape : scalar > 0\n The shape of the gamma distribution.\n scale : scalar > 0, optional\n The scale of the gamma distribution. Default is equal to 1.\n size : shape_tuple, optional\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n out : ndarray, float\n Returns one sample unless `size` parameter is specified.\n\n See Also\n --------\n scipy.stats.distributions.gamma : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Gamma distribution is\n\n .. math:: p(x) = x^{k-1}\\frac{e^{-x/\\theta}}{\\theta^k\\Gamma(k)},\n\n where :math:`k` is the shape and :math:`\\theta` the scale,\n and :math:`\\Gamma` is the Gamma function.\n\n The Gamma distribution is often used to model the times to failure of\n electronic components, and arises naturally in processes for which the\n waiting times between Poisson distributed events are relevant.\n\n References\n ----------\n .. [1] Weisstein, Eric W. \"Gamma Distribution.\" From MathWorld--A\n Wolfram Web Resource.\n http://mathworld.wolfram.com/GammaDistribution.html\n .. [2] Wikipedia, \"Gamma-distribution\",\n http://en.wikipedia.org/wiki/Gamma-distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> shape, scale = 2.,"" 2. # mean and dispersion\n >>> s = np.random.gamma(shape, scale, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> import scipy.special as sps\n >>> count, bins, ignored = plt.hist(s, 50, normed=True)\n >>> y = bins**(shape-1)*(np.exp(-bins/scale) /\n ... (sps.gamma(shape)*scale**shape))\n >>> plt.plot(bins, y, linewidth=2, color='r')\n >>> plt.show()\n\n "; -static char __pyx_k_229[] = "RandomState.f (line 1804)"; -static char __pyx_k_230[] = "\n f(dfnum, dfden, size=None)\n\n Draw samples from a F distribution.\n\n Samples are drawn from an F distribution with specified parameters,\n `dfnum` (degrees of freedom in numerator) and `dfden` (degrees of freedom\n in denominator), where both parameters should be greater than zero.\n\n The random variate of the F distribution (also known as the\n Fisher distribution) is a continuous probability distribution\n that arises in ANOVA tests, and is the ratio of two chi-square\n variates.\n\n Parameters\n ----------\n dfnum : float\n Degrees of freedom in numerator. Should be greater than zero.\n dfden : float\n Degrees of freedom in denominator. Should be greater than zero.\n size : {tuple, int}, optional\n Output shape. If the given shape is, e.g., ``(m, n, k)``,\n then ``m * n * k`` samples are drawn. By default only one sample\n is returned.\n\n Returns\n -------\n samples : {ndarray, scalar}\n Samples from the Fisher distribution.\n\n See Also\n --------\n scipy.stats.distributions.f : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The F statistic is used to compare in-group variances to between-group\n variances. Calculating the distribution depends on the sampling, and\n so it is a function of the respective degrees of freedom in the\n problem. The variable `dfnum` is the number of samples minus one, the\n between-groups degrees of freedom, while `dfden` is the within-groups\n degrees of freedom, the sum of the number of samples in each group\n minus the number of groups.\n\n References\n ----------\n .. [1] Glantz, Stanton A. \"Primer of Biostatistics.\", McGraw-Hill,\n Fifth Edition, 2002.""\n .. [2] Wikipedia, \"F-distribution\",\n http://en.wikipedia.org/wiki/F-distribution\n\n Examples\n --------\n An example from Glantz[1], pp 47-40.\n Two groups, children of diabetics (25 people) and children from people\n without diabetes (25 controls). Fasting blood glucose was measured,\n case group had a mean value of 86.1, controls had a mean value of\n 82.2. Standard deviations were 2.09 and 2.49 respectively. Are these\n data consistent with the null hypothesis that the parents diabetic\n status does not affect their children's blood glucose levels?\n Calculating the F statistic from the data gives a value of 36.01.\n\n Draw samples from the distribution:\n\n >>> dfnum = 1. # between group degrees of freedom\n >>> dfden = 48. # within groups degrees of freedom\n >>> s = np.random.f(dfnum, dfden, 1000)\n\n The lower bound for the top 1% of the samples is :\n\n >>> sort(s)[-10]\n 7.61988120985\n\n So there is about a 1% chance that the F statistic will exceed 7.62,\n the measured value is 36, so the null hypothesis is rejected at the 1%\n level.\n\n "; -static char __pyx_k_231[] = "RandomState.noncentral_f (line 1906)"; -static char __pyx_k_232[] = "\n noncentral_f(dfnum, dfden, nonc, size=None)\n\n Draw samples from the noncentral F distribution.\n\n Samples are drawn from an F distribution with specified parameters,\n `dfnum` (degrees of freedom in numerator) and `dfden` (degrees of\n freedom in denominator), where both parameters > 1.\n `nonc` is the non-centrality parameter.\n\n Parameters\n ----------\n dfnum : int\n Parameter, should be > 1.\n dfden : int\n Parameter, should be > 1.\n nonc : float\n Parameter, should be >= 0.\n size : int or tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : scalar or ndarray\n Drawn samples.\n\n Notes\n -----\n When calculating the power of an experiment (power = probability of\n rejecting the null hypothesis when a specific alternative is true) the\n non-central F statistic becomes important. When the null hypothesis is\n true, the F statistic follows a central F distribution. When the null\n hypothesis is not true, then it follows a non-central F statistic.\n\n References\n ----------\n Weisstein, Eric W. \"Noncentral F-Distribution.\" From MathWorld--A Wolfram\n Web Resource. http://mathworld.wolfram.com/NoncentralF-Distribution.html\n\n Wikipedia, \"Noncentral F distribution\",\n http://en.wikipedia.org/wiki/Noncentral_F-distribution\n\n Examples\n --------\n In a study, testing for a specific alternative to the null hypothesis\n requires use of the Noncentral F distribution. We need to calculate the\n area in the tail of the distribution that exceeds the value of the F\n distribution for the null hypothesis. We'll plot the two probability\n distributions for comp""arison.\n\n >>> dfnum = 3 # between group deg of freedom\n >>> dfden = 20 # within groups degrees of freedom\n >>> nonc = 3.0\n >>> nc_vals = np.random.noncentral_f(dfnum, dfden, nonc, 1000000)\n >>> NF = np.histogram(nc_vals, bins=50, normed=True)\n >>> c_vals = np.random.f(dfnum, dfden, 1000000)\n >>> F = np.histogram(c_vals, bins=50, normed=True)\n >>> plt.plot(F[1][1:], F[0])\n >>> plt.plot(NF[1][1:], NF[0])\n >>> plt.show()\n\n "; -static char __pyx_k_233[] = "RandomState.chisquare (line 2001)"; -static char __pyx_k_234[] = "\n chisquare(df, size=None)\n\n Draw samples from a chi-square distribution.\n\n When `df` independent random variables, each with standard normal\n distributions (mean 0, variance 1), are squared and summed, the\n resulting distribution is chi-square (see Notes). This distribution\n is often used in hypothesis testing.\n\n Parameters\n ----------\n df : int\n Number of degrees of freedom.\n size : tuple of ints, int, optional\n Size of the returned array. By default, a scalar is\n returned.\n\n Returns\n -------\n output : ndarray\n Samples drawn from the distribution, packed in a `size`-shaped\n array.\n\n Raises\n ------\n ValueError\n When `df` <= 0 or when an inappropriate `size` (e.g. ``size=-1``)\n is given.\n\n Notes\n -----\n The variable obtained by summing the squares of `df` independent,\n standard normally distributed random variables:\n\n .. math:: Q = \\sum_{i=0}^{\\mathtt{df}} X^2_i\n\n is chi-square distributed, denoted\n\n .. math:: Q \\sim \\chi^2_k.\n\n The probability density function of the chi-squared distribution is\n\n .. math:: p(x) = \\frac{(1/2)^{k/2}}{\\Gamma(k/2)}\n x^{k/2 - 1} e^{-x/2},\n\n where :math:`\\Gamma` is the gamma function,\n\n .. math:: \\Gamma(x) = \\int_0^{-\\infty} t^{x - 1} e^{-t} dt.\n\n References\n ----------\n `NIST/SEMATECH e-Handbook of Statistical Methods\n <http://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm>`_\n\n Examples\n --------\n >>> np.random.chisquare(2,4)\n array([ 1.89920014, 9.00867716, 3.13710533, 5.62318272])\n\n "; -static char __pyx_k_235[] = "RandomState.noncentral_chisquare (line 2079)"; -static char __pyx_k_236[] = "\n noncentral_chisquare(df, nonc, size=None)\n\n Draw samples from a noncentral chi-square distribution.\n\n The noncentral :math:`\\chi^2` distribution is a generalisation of\n the :math:`\\chi^2` distribution.\n\n Parameters\n ----------\n df : int\n Degrees of freedom, should be >= 1.\n nonc : float\n Non-centrality, should be > 0.\n size : int or tuple of ints\n Shape of the output.\n\n Notes\n -----\n The probability density function for the noncentral Chi-square distribution\n is\n\n .. math:: P(x;df,nonc) = \\sum^{\\infty}_{i=0}\n \\frac{e^{-nonc/2}(nonc/2)^{i}}{i!}P_{Y_{df+2i}}(x),\n\n where :math:`Y_{q}` is the Chi-square with q degrees of freedom.\n\n In Delhi (2007), it is noted that the noncentral chi-square is useful in\n bombing and coverage problems, the probability of killing the point target\n given by the noncentral chi-squared distribution.\n\n References\n ----------\n .. [1] Delhi, M.S. Holla, \"On a noncentral chi-square distribution in the\n analysis of weapon systems effectiveness\", Metrika, Volume 15,\n Number 1 / December, 1970.\n .. [2] Wikipedia, \"Noncentral chi-square distribution\"\n http://en.wikipedia.org/wiki/Noncentral_chi-square_distribution\n\n Examples\n --------\n Draw values from the distribution and plot the histogram\n\n >>> import matplotlib.pyplot as plt\n >>> values = plt.hist(np.random.noncentral_chisquare(3, 20, 100000),\n ... bins=200, normed=True)\n >>> plt.show()\n\n Draw values from a noncentral chisquare with very small noncentrality,\n and compare to a chisquare.\n\n >>> plt.figure()\n >>> values = plt.hist(np.random.noncentral_chisquare(3, .0000001, 100000),\n "" ... bins=np.arange(0., 25, .1), normed=True)\n >>> values2 = plt.hist(np.random.chisquare(3, 100000),\n ... bins=np.arange(0., 25, .1), normed=True)\n >>> plt.plot(values[1][0:-1], values[0]-values2[0], 'ob')\n >>> plt.show()\n\n Demonstrate how large values of non-centrality lead to a more symmetric\n distribution.\n\n >>> plt.figure()\n >>> values = plt.hist(np.random.noncentral_chisquare(3, 20, 100000),\n ... bins=200, normed=True)\n >>> plt.show()\n\n "; -static char __pyx_k_237[] = "RandomState.standard_cauchy (line 2171)"; -static char __pyx_k_238[] = "\n standard_cauchy(size=None)\n\n Standard Cauchy distribution with mode = 0.\n\n Also known as the Lorentz distribution.\n\n Parameters\n ----------\n size : int or tuple of ints\n Shape of the output.\n\n Returns\n -------\n samples : ndarray or scalar\n The drawn samples.\n\n Notes\n -----\n The probability density function for the full Cauchy distribution is\n\n .. math:: P(x; x_0, \\gamma) = \\frac{1}{\\pi \\gamma \\bigl[ 1+\n (\\frac{x-x_0}{\\gamma})^2 \\bigr] }\n\n and the Standard Cauchy distribution just sets :math:`x_0=0` and\n :math:`\\gamma=1`\n\n The Cauchy distribution arises in the solution to the driven harmonic\n oscillator problem, and also describes spectral line broadening. It\n also describes the distribution of values at which a line tilted at\n a random angle will cut the x axis.\n\n When studying hypothesis tests that assume normality, seeing how the\n tests perform on data from a Cauchy distribution is a good indicator of\n their sensitivity to a heavy-tailed distribution, since the Cauchy looks\n very much like a Gaussian distribution, but with heavier tails.\n\n References\n ----------\n .. [1] NIST/SEMATECH e-Handbook of Statistical Methods, \"Cauchy\n Distribution\",\n http://www.itl.nist.gov/div898/handbook/eda/section3/eda3663.htm\n .. [2] Weisstein, Eric W. \"Cauchy Distribution.\" From MathWorld--A\n Wolfram Web Resource.\n http://mathworld.wolfram.com/CauchyDistribution.html\n .. [3] Wikipedia, \"Cauchy distribution\"\n http://en.wikipedia.org/wiki/Cauchy_distribution\n\n Examples\n --------\n Draw samples and plot the distribution:\n\n >>> s = np.random.standard_cauchy(1000000)\n >>> s = s[(s>-25) & (s<""25)] # truncate distribution so it plots well\n >>> plt.hist(s, bins=100)\n >>> plt.show()\n\n "; -static char __pyx_k_239[] = "RandomState.standard_t (line 2232)"; -static char __pyx_k_240[] = "\n standard_t(df, size=None)\n\n Standard Student's t distribution with df degrees of freedom.\n\n A special case of the hyperbolic distribution.\n As `df` gets large, the result resembles that of the standard normal\n distribution (`standard_normal`).\n\n Parameters\n ----------\n df : int\n Degrees of freedom, should be > 0.\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single value is\n returned.\n\n Returns\n -------\n samples : ndarray or scalar\n Drawn samples.\n\n Notes\n -----\n The probability density function for the t distribution is\n\n .. math:: P(x, df) = \\frac{\\Gamma(\\frac{df+1}{2})}{\\sqrt{\\pi df}\n \\Gamma(\\frac{df}{2})}\\Bigl( 1+\\frac{x^2}{df} \\Bigr)^{-(df+1)/2}\n\n The t test is based on an assumption that the data come from a Normal\n distribution. The t test provides a way to test whether the sample mean\n (that is the mean calculated from the data) is a good estimate of the true\n mean.\n\n The derivation of the t-distribution was forst published in 1908 by William\n Gisset while working for the Guinness Brewery in Dublin. Due to proprietary\n issues, he had to publish under a pseudonym, and so he used the name\n Student.\n\n References\n ----------\n .. [1] Dalgaard, Peter, \"Introductory Statistics With R\",\n Springer, 2002.\n .. [2] Wikipedia, \"Student's t-distribution\"\n http://en.wikipedia.org/wiki/Student's_t-distribution\n\n Examples\n --------\n From Dalgaard page 83 [1]_, suppose the daily energy intake for 11\n women in Kj is:\n\n >>> intake = np.array([5260., 5470, 5640, 6180, 6390, 6515, 6805, 7515, \\\n ... 7515, 8230, 8770])\n\n Doe""s their energy intake deviate systematically from the recommended\n value of 7725 kJ?\n\n We have 10 degrees of freedom, so is the sample mean within 95% of the\n recommended value?\n\n >>> s = np.random.standard_t(10, size=100000)\n >>> np.mean(intake)\n 6753.636363636364\n >>> intake.std(ddof=1)\n 1142.1232221373727\n\n Calculate the t statistic, setting the ddof parameter to the unbiased\n value so the divisor in the standard deviation will be degrees of\n freedom, N-1.\n\n >>> t = (np.mean(intake)-7725)/(intake.std(ddof=1)/np.sqrt(len(intake)))\n >>> import matplotlib.pyplot as plt\n >>> h = plt.hist(s, bins=100, normed=True)\n\n For a one-sided t-test, how far out in the distribution does the t\n statistic appear?\n\n >>> >>> np.sum(s<t) / float(len(s))\n 0.0090699999999999999 #random\n\n So the p-value is about 0.009, which says the null hypothesis has a\n probability of about 99% of being true.\n\n "; -static char __pyx_k_241[] = "RandomState.vonmises (line 2333)"; -static char __pyx_k_242[] = "\n vonmises(mu, kappa, size=None)\n\n Draw samples from a von Mises distribution.\n\n Samples are drawn from a von Mises distribution with specified mode\n (mu) and dispersion (kappa), on the interval [-pi, pi].\n\n The von Mises distribution (also known as the circular normal\n distribution) is a continuous probability distribution on the unit\n circle. It may be thought of as the circular analogue of the normal\n distribution.\n\n Parameters\n ----------\n mu : float\n Mode (\"center\") of the distribution.\n kappa : float\n Dispersion of the distribution, has to be >=0.\n size : int or tuple of int\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : scalar or ndarray\n The returned samples, which are in the interval [-pi, pi].\n\n See Also\n --------\n scipy.stats.distributions.vonmises : probability density function,\n distribution, or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the von Mises distribution is\n\n .. math:: p(x) = \\frac{e^{\\kappa cos(x-\\mu)}}{2\\pi I_0(\\kappa)},\n\n where :math:`\\mu` is the mode and :math:`\\kappa` the dispersion,\n and :math:`I_0(\\kappa)` is the modified Bessel function of order 0.\n\n The von Mises is named for Richard Edler von Mises, who was born in\n Austria-Hungary, in what is now the Ukraine. He fled to the United\n States in 1939 and became a professor at Harvard. He worked in\n probability theory, aerodynamics, fluid mechanics, and philosophy of\n science.\n\n References\n ----------\n Abramowitz, M. and Stegun, I. A. (ed.), *Handbook of Mathematical\n Functions*, New York: Dover, 1965.\n\n "" von Mises, R., *Mathematical Theory of Probability and Statistics*,\n New York: Academic Press, 1964.\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> mu, kappa = 0.0, 4.0 # mean and dispersion\n >>> s = np.random.vonmises(mu, kappa, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> import scipy.special as sps\n >>> count, bins, ignored = plt.hist(s, 50, normed=True)\n >>> x = np.arange(-np.pi, np.pi, 2*np.pi/50.)\n >>> y = -np.exp(kappa*np.cos(x-mu))/(2*np.pi*sps.jn(0,kappa))\n >>> plt.plot(x, y/max(y), linewidth=2, color='r')\n >>> plt.show()\n\n "; -static char __pyx_k_243[] = "RandomState.pareto (line 2427)"; -static char __pyx_k_244[] = "\n pareto(a, size=None)\n\n Draw samples from a Pareto II or Lomax distribution with specified shape.\n\n The Lomax or Pareto II distribution is a shifted Pareto distribution. The\n classical Pareto distribution can be obtained from the Lomax distribution\n by adding the location parameter m, see below. The smallest value of the\n Lomax distribution is zero while for the classical Pareto distribution it\n is m, where the standard Pareto distribution has location m=1.\n Lomax can also be considered as a simplified version of the Generalized\n Pareto distribution (available in SciPy), with the scale set to one and\n the location set to zero.\n\n The Pareto distribution must be greater than zero, and is unbounded above.\n It is also known as the \"80-20 rule\". In this distribution, 80 percent of\n the weights are in the lowest 20 percent of the range, while the other 20\n percent fill the remaining 80 percent of the range.\n\n Parameters\n ----------\n shape : float, > 0.\n Shape of the distribution.\n size : tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n See Also\n --------\n scipy.stats.distributions.lomax.pdf : probability density function,\n distribution or cumulative density function, etc.\n scipy.stats.distributions.genpareto.pdf : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Pareto distribution is\n\n .. math:: p(x) = \\frac{am^a}{x^{a+1}}\n\n where :math:`a` is the shape and :math:`m` the location\n\n The Pareto distribution, named after the Italian economist Vilfredo Pareto,\n is a power law probability distribution useful in many real world probl""ems.\n Outside the field of economics it is generally referred to as the Bradford\n distribution. Pareto developed the distribution to describe the\n distribution of wealth in an economy. It has also found use in insurance,\n web page access statistics, oil field sizes, and many other problems,\n including the download frequency for projects in Sourceforge [1]. It is\n one of the so-called \"fat-tailed\" distributions.\n\n\n References\n ----------\n .. [1] Francis Hunt and Paul Johnson, On the Pareto Distribution of\n Sourceforge projects.\n .. [2] Pareto, V. (1896). Course of Political Economy. Lausanne.\n .. [3] Reiss, R.D., Thomas, M.(2001), Statistical Analysis of Extreme\n Values, Birkhauser Verlag, Basel, pp 23-30.\n .. [4] Wikipedia, \"Pareto distribution\",\n http://en.wikipedia.org/wiki/Pareto_distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> a, m = 3., 1. # shape and mode\n >>> s = np.random.pareto(a, 1000) + m\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, 100, normed=True, align='center')\n >>> fit = a*m**a/bins**(a+1)\n >>> plt.plot(bins, max(count)*fit/max(fit),linewidth=2, color='r')\n >>> plt.show()\n\n "; -static char __pyx_k_245[] = "RandomState.weibull (line 2523)"; -static char __pyx_k_246[] = "\n weibull(a, size=None)\n\n Weibull distribution.\n\n Draw samples from a 1-parameter Weibull distribution with the given\n shape parameter `a`.\n\n .. math:: X = (-ln(U))^{1/a}\n\n Here, U is drawn from the uniform distribution over (0,1].\n\n The more common 2-parameter Weibull, including a scale parameter\n :math:`\\lambda` is just :math:`X = \\lambda(-ln(U))^{1/a}`.\n\n Parameters\n ----------\n a : float\n Shape of the distribution.\n size : tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n See Also\n --------\n scipy.stats.distributions.weibull_max\n scipy.stats.distributions.weibull_min\n scipy.stats.distributions.genextreme\n gumbel\n\n Notes\n -----\n The Weibull (or Type III asymptotic extreme value distribution for smallest\n values, SEV Type III, or Rosin-Rammler distribution) is one of a class of\n Generalized Extreme Value (GEV) distributions used in modeling extreme\n value problems. This class includes the Gumbel and Frechet distributions.\n\n The probability density for the Weibull distribution is\n\n .. math:: p(x) = \\frac{a}\n {\\lambda}(\\frac{x}{\\lambda})^{a-1}e^{-(x/\\lambda)^a},\n\n where :math:`a` is the shape and :math:`\\lambda` the scale.\n\n The function has its peak (the mode) at\n :math:`\\lambda(\\frac{a-1}{a})^{1/a}`.\n\n When ``a = 1``, the Weibull distribution reduces to the exponential\n distribution.\n\n References\n ----------\n .. [1] Waloddi Weibull, Professor, Royal Technical University, Stockholm,\n 1939 \"A Statistical Theory Of The Strength Of Materials\",\n Ingeniorsvetenskapsakademiens Handlingar Nr 151, 1939,\n General""stabens Litografiska Anstalts Forlag, Stockholm.\n .. [2] Waloddi Weibull, 1951 \"A Statistical Distribution Function of Wide\n Applicability\", Journal Of Applied Mechanics ASME Paper.\n .. [3] Wikipedia, \"Weibull distribution\",\n http://en.wikipedia.org/wiki/Weibull_distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> a = 5. # shape\n >>> s = np.random.weibull(a, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> x = np.arange(1,100.)/50.\n >>> def weib(x,n,a):\n ... return (a / n) * (x / n)**(a - 1) * np.exp(-(x / n)**a)\n\n >>> count, bins, ignored = plt.hist(np.random.weibull(5.,1000))\n >>> x = np.arange(1,100.)/50.\n >>> scale = count.max()/weib(x, 1., 5.).max()\n >>> plt.plot(x, weib(x, 1., 5.)*scale)\n >>> plt.show()\n\n "; -static char __pyx_k_247[] = "RandomState.power (line 2623)"; -static char __pyx_k_248[] = "\n power(a, size=None)\n\n Draws samples in [0, 1] from a power distribution with positive\n exponent a - 1.\n\n Also known as the power function distribution.\n\n Parameters\n ----------\n a : float\n parameter, > 0\n size : tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : {ndarray, scalar}\n The returned samples lie in [0, 1].\n\n Raises\n ------\n ValueError\n If a<1.\n\n Notes\n -----\n The probability density function is\n\n .. math:: P(x; a) = ax^{a-1}, 0 \\le x \\le 1, a>0.\n\n The power function distribution is just the inverse of the Pareto\n distribution. It may also be seen as a special case of the Beta\n distribution.\n\n It is used, for example, in modeling the over-reporting of insurance\n claims.\n\n References\n ----------\n .. [1] Christian Kleiber, Samuel Kotz, \"Statistical size distributions\n in economics and actuarial sciences\", Wiley, 2003.\n .. [2] Heckert, N. A. and Filliben, James J. (2003). NIST Handbook 148:\n Dataplot Reference Manual, Volume 2: Let Subcommands and Library\n Functions\", National Institute of Standards and Technology Handbook\n Series, June 2003.\n http://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/powpdf.pdf\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> a = 5. # shape\n >>> samples = 1000\n >>> s = np.random.power(a, samples)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, bins=""30)\n >>> x = np.linspace(0, 1, 100)\n >>> y = a*x**(a-1.)\n >>> normed_y = samples*np.diff(bins)[0]*y\n >>> plt.plot(x, normed_y)\n >>> plt.show()\n\n Compare the power function distribution to the inverse of the Pareto.\n\n >>> from scipy import stats\n >>> rvs = np.random.power(5, 1000000)\n >>> rvsp = np.random.pareto(5, 1000000)\n >>> xx = np.linspace(0,1,100)\n >>> powpdf = stats.powerlaw.pdf(xx,5)\n\n >>> plt.figure()\n >>> plt.hist(rvs, bins=50, normed=True)\n >>> plt.plot(xx,powpdf,'r-')\n >>> plt.title('np.random.power(5)')\n\n >>> plt.figure()\n >>> plt.hist(1./(1.+rvsp), bins=50, normed=True)\n >>> plt.plot(xx,powpdf,'r-')\n >>> plt.title('inverse of 1 + np.random.pareto(5)')\n\n >>> plt.figure()\n >>> plt.hist(1./(1.+rvsp), bins=50, normed=True)\n >>> plt.plot(xx,powpdf,'r-')\n >>> plt.title('inverse of stats.pareto(5)')\n\n "; -static char __pyx_k_249[] = "RandomState.laplace (line 2732)"; -static char __pyx_k_250[] = "\n laplace(loc=0.0, scale=1.0, size=None)\n\n Draw samples from the Laplace or double exponential distribution with\n specified location (or mean) and scale (decay).\n\n The Laplace distribution is similar to the Gaussian/normal distribution,\n but is sharper at the peak and has fatter tails. It represents the\n difference between two independent, identically distributed exponential\n random variables.\n\n Parameters\n ----------\n loc : float\n The position, :math:`\\mu`, of the distribution peak.\n scale : float\n :math:`\\lambda`, the exponential decay.\n\n Notes\n -----\n It has the probability density function\n\n .. math:: f(x; \\mu, \\lambda) = \\frac{1}{2\\lambda}\n \\exp\\left(-\\frac{|x - \\mu|}{\\lambda}\\right).\n\n The first law of Laplace, from 1774, states that the frequency of an error\n can be expressed as an exponential function of the absolute magnitude of\n the error, which leads to the Laplace distribution. For many problems in\n Economics and Health sciences, this distribution seems to model the data\n better than the standard Gaussian distribution\n\n\n References\n ----------\n .. [1] Abramowitz, M. and Stegun, I. A. (Eds.). Handbook of Mathematical\n Functions with Formulas, Graphs, and Mathematical Tables, 9th\n printing. New York: Dover, 1972.\n\n .. [2] The Laplace distribution and generalizations\n By Samuel Kotz, Tomasz J. Kozubowski, Krzysztof Podgorski,\n Birkhauser, 2001.\n\n .. [3] Weisstein, Eric W. \"Laplace Distribution.\"\n From MathWorld--A Wolfram Web Resource.\n http://mathworld.wolfram.com/LaplaceDistribution.html\n\n .. [4] Wikipedia, \"Laplace distribution\",\n http://en.wikipedia.org/wik""i/Laplace_distribution\n\n Examples\n --------\n Draw samples from the distribution\n\n >>> loc, scale = 0., 1.\n >>> s = np.random.laplace(loc, scale, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, 30, normed=True)\n >>> x = np.arange(-8., 8., .01)\n >>> pdf = np.exp(-abs(x-loc/scale))/(2.*scale)\n >>> plt.plot(x, pdf)\n\n Plot Gaussian for comparison:\n\n >>> g = (1/(scale * np.sqrt(2 * np.pi)) * \n ... np.exp( - (x - loc)**2 / (2 * scale**2) ))\n >>> plt.plot(x,g)\n\n "; -static char __pyx_k_251[] = "RandomState.gumbel (line 2822)"; -static char __pyx_k_252[] = "\n gumbel(loc=0.0, scale=1.0, size=None)\n\n Gumbel distribution.\n\n Draw samples from a Gumbel distribution with specified location and scale.\n For more information on the Gumbel distribution, see Notes and References\n below.\n\n Parameters\n ----------\n loc : float\n The location of the mode of the distribution.\n scale : float\n The scale parameter of the distribution.\n size : tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n out : ndarray\n The samples\n\n See Also\n --------\n scipy.stats.gumbel_l\n scipy.stats.gumbel_r\n scipy.stats.genextreme\n probability density function, distribution, or cumulative density\n function, etc. for each of the above\n weibull\n\n Notes\n -----\n The Gumbel (or Smallest Extreme Value (SEV) or the Smallest Extreme Value\n Type I) distribution is one of a class of Generalized Extreme Value (GEV)\n distributions used in modeling extreme value problems. The Gumbel is a\n special case of the Extreme Value Type I distribution for maximums from\n distributions with \"exponential-like\" tails.\n\n The probability density for the Gumbel distribution is\n\n .. math:: p(x) = \\frac{e^{-(x - \\mu)/ \\beta}}{\\beta} e^{ -e^{-(x - \\mu)/\n \\beta}},\n\n where :math:`\\mu` is the mode, a location parameter, and :math:`\\beta` is\n the scale parameter.\n\n The Gumbel (named for German mathematician Emil Julius Gumbel) was used\n very early in the hydrology literature, for modeling the occurrence of\n flood events. It is also used for modeling maximum wind speed and rainfall\n rates. It is a \"fat-tailed\" distribution - the ""probability of an event in\n the tail of the distribution is larger than if one used a Gaussian, hence\n the surprisingly frequent occurrence of 100-year floods. Floods were\n initially modeled as a Gaussian process, which underestimated the frequency\n of extreme events.\n\n\n It is one of a class of extreme value distributions, the Generalized\n Extreme Value (GEV) distributions, which also includes the Weibull and\n Frechet.\n\n The function has a mean of :math:`\\mu + 0.57721\\beta` and a variance of\n :math:`\\frac{\\pi^2}{6}\\beta^2`.\n\n References\n ----------\n Gumbel, E. J., *Statistics of Extremes*, New York: Columbia University\n Press, 1958.\n\n Reiss, R.-D. and Thomas, M., *Statistical Analysis of Extreme Values from\n Insurance, Finance, Hydrology and Other Fields*, Basel: Birkhauser Verlag,\n 2001.\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> mu, beta = 0, 0.1 # location and scale\n >>> s = np.random.gumbel(mu, beta, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, 30, normed=True)\n >>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)\n ... * np.exp( -np.exp( -(bins - mu) /beta) ),\n ... linewidth=2, color='r')\n >>> plt.show()\n\n Show how an extreme value distribution can arise from a Gaussian process\n and compare to a Gaussian:\n\n >>> means = []\n >>> maxima = []\n >>> for i in range(0,1000) :\n ... a = np.random.normal(mu, beta, 1000)\n ... means.append(a.mean())\n ... maxima.append(a.max())\n >>> count, bins, ignored = plt.hist(maxima, 30, normed=True)\n >>> beta = np.std(maxima)*np.pi/np.sqrt(6)""\n >>> mu = np.mean(maxima) - 0.57721*beta\n >>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)\n ... * np.exp(-np.exp(-(bins - mu)/beta)),\n ... linewidth=2, color='r')\n >>> plt.plot(bins, 1/(beta * np.sqrt(2 * np.pi))\n ... * np.exp(-(bins - mu)**2 / (2 * beta**2)),\n ... linewidth=2, color='g')\n >>> plt.show()\n\n "; -static char __pyx_k_253[] = "RandomState.logistic (line 2953)"; -static char __pyx_k_254[] = "\n logistic(loc=0.0, scale=1.0, size=None)\n\n Draw samples from a Logistic distribution.\n\n Samples are drawn from a Logistic distribution with specified\n parameters, loc (location or mean, also median), and scale (>0).\n\n Parameters\n ----------\n loc : float\n\n scale : float > 0.\n\n size : {tuple, int}\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : {ndarray, scalar}\n where the values are all integers in [0, n].\n\n See Also\n --------\n scipy.stats.distributions.logistic : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Logistic distribution is\n\n .. math:: P(x) = P(x) = \\frac{e^{-(x-\\mu)/s}}{s(1+e^{-(x-\\mu)/s})^2},\n\n where :math:`\\mu` = location and :math:`s` = scale.\n\n The Logistic distribution is used in Extreme Value problems where it\n can act as a mixture of Gumbel distributions, in Epidemiology, and by\n the World Chess Federation (FIDE) where it is used in the Elo ranking\n system, assuming the performance of each player is a logistically\n distributed random variable.\n\n References\n ----------\n .. [1] Reiss, R.-D. and Thomas M. (2001), Statistical Analysis of Extreme\n Values, from Insurance, Finance, Hydrology and Other Fields,\n Birkhauser Verlag, Basel, pp 132-133.\n .. [2] Weisstein, Eric W. \"Logistic Distribution.\" From\n MathWorld--A Wolfram Web Resource.\n http://mathworld.wolfram.com/LogisticDistribution.html\n .. [3] Wikipedia, \"Logistic-distribution\",\n http://en.wikipedia.org/wiki/Logistic-distribution\n\n Examples\n "" --------\n Draw samples from the distribution:\n\n >>> loc, scale = 10, 1\n >>> s = np.random.logistic(loc, scale, 10000)\n >>> count, bins, ignored = plt.hist(s, bins=50)\n\n # plot against distribution\n\n >>> def logist(x, loc, scale):\n ... return exp((loc-x)/scale)/(scale*(1+exp((loc-x)/scale))**2)\n >>> plt.plot(bins, logist(bins, loc, scale)*count.max()/\\\n ... logist(bins, loc, scale).max())\n >>> plt.show()\n\n "; -static char __pyx_k_255[] = "RandomState.lognormal (line 3041)"; -static char __pyx_k_256[] = "\n lognormal(mean=0.0, sigma=1.0, size=None)\n\n Return samples drawn from a log-normal distribution.\n\n Draw samples from a log-normal distribution with specified mean,\n standard deviation, and array shape. Note that the mean and standard\n deviation are not the values for the distribution itself, but of the\n underlying normal distribution it is derived from.\n\n Parameters\n ----------\n mean : float\n Mean value of the underlying normal distribution\n sigma : float, > 0.\n Standard deviation of the underlying normal distribution\n size : tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : ndarray or float\n The desired samples. An array of the same shape as `size` if given,\n if `size` is None a float is returned.\n\n See Also\n --------\n scipy.stats.lognorm : probability density function, distribution,\n cumulative density function, etc.\n\n Notes\n -----\n A variable `x` has a log-normal distribution if `log(x)` is normally\n distributed. The probability density function for the log-normal\n distribution is:\n\n .. math:: p(x) = \\frac{1}{\\sigma x \\sqrt{2\\pi}}\n e^{(-\\frac{(ln(x)-\\mu)^2}{2\\sigma^2})}\n\n where :math:`\\mu` is the mean and :math:`\\sigma` is the standard\n deviation of the normally distributed logarithm of the variable.\n A log-normal distribution results if a random variable is the *product*\n of a large number of independent, identically-distributed variables in\n the same way that a normal distribution results if the variable is the\n *sum* of a large number of independent, identically-distributed\n variables.\n\n Reference""s\n ----------\n Limpert, E., Stahel, W. A., and Abbt, M., \"Log-normal Distributions\n across the Sciences: Keys and Clues,\" *BioScience*, Vol. 51, No. 5,\n May, 2001. http://stat.ethz.ch/~stahel/lognormal/bioscience.pdf\n\n Reiss, R.D. and Thomas, M., *Statistical Analysis of Extreme Values*,\n Basel: Birkhauser Verlag, 2001, pp. 31-32.\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> mu, sigma = 3., 1. # mean and standard deviation\n >>> s = np.random.lognormal(mu, sigma, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, 100, normed=True, align='mid')\n\n >>> x = np.linspace(min(bins), max(bins), 10000)\n >>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))\n ... / (x * sigma * np.sqrt(2 * np.pi)))\n\n >>> plt.plot(x, pdf, linewidth=2, color='r')\n >>> plt.axis('tight')\n >>> plt.show()\n\n Demonstrate that taking the products of random samples from a uniform\n distribution can be fit well by a log-normal probability density function.\n\n >>> # Generate a thousand samples: each is the product of 100 random\n >>> # values, drawn from a normal distribution.\n >>> b = []\n >>> for i in range(1000):\n ... a = 10. + np.random.random(100)\n ... b.append(np.product(a))\n\n >>> b = np.array(b) / np.min(b) # scale values to be positive\n >>> count, bins, ignored = plt.hist(b, 100, normed=True, align='center')\n >>> sigma = np.std(np.log(b))\n >>> mu = np.mean(np.log(b))\n\n >>> x = np.linspace(min(bins), max(bins), 10000)\n >>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))\n ... / (x * sigma * np.sqrt(2 * np.pi)))\n\n >>> plt.plot(x, pdf, co""lor='r', linewidth=2)\n >>> plt.show()\n\n "; -static char __pyx_k_257[] = "RandomState.rayleigh (line 3162)"; -static char __pyx_k_258[] = "\n rayleigh(scale=1.0, size=None)\n\n Draw samples from a Rayleigh distribution.\n\n The :math:`\\chi` and Weibull distributions are generalizations of the\n Rayleigh.\n\n Parameters\n ----------\n scale : scalar\n Scale, also equals the mode. Should be >= 0.\n size : int or tuple of ints, optional\n Shape of the output. Default is None, in which case a single\n value is returned.\n\n Notes\n -----\n The probability density function for the Rayleigh distribution is\n\n .. math:: P(x;scale) = \\frac{x}{scale^2}e^{\\frac{-x^2}{2 \\cdotp scale^2}}\n\n The Rayleigh distribution arises if the wind speed and wind direction are\n both gaussian variables, then the vector wind velocity forms a Rayleigh\n distribution. The Rayleigh distribution is used to model the expected\n output from wind turbines.\n\n References\n ----------\n .. [1] Brighton Webs Ltd., Rayleigh Distribution,\n http://www.brighton-webs.co.uk/distributions/rayleigh.asp\n .. [2] Wikipedia, \"Rayleigh distribution\"\n http://en.wikipedia.org/wiki/Rayleigh_distribution\n\n Examples\n --------\n Draw values from the distribution and plot the histogram\n\n >>> values = hist(np.random.rayleigh(3, 100000), bins=200, normed=True)\n\n Wave heights tend to follow a Rayleigh distribution. If the mean wave\n height is 1 meter, what fraction of waves are likely to be larger than 3\n meters?\n\n >>> meanvalue = 1\n >>> modevalue = np.sqrt(2 / np.pi) * meanvalue\n >>> s = np.random.rayleigh(modevalue, 1000000)\n\n The percentage of waves larger than 3 meters is:\n\n >>> 100.*sum(s>3)/1000000.\n 0.087300000000000003\n\n "; -static char __pyx_k_259[] = "RandomState.wald (line 3234)"; -static char __pyx_k_260[] = "\n wald(mean, scale, size=None)\n\n Draw samples from a Wald, or Inverse Gaussian, distribution.\n\n As the scale approaches infinity, the distribution becomes more like a\n Gaussian.\n\n Some references claim that the Wald is an Inverse Gaussian with mean=1, but\n this is by no means universal.\n\n The Inverse Gaussian distribution was first studied in relationship to\n Brownian motion. In 1956 M.C.K. Tweedie used the name Inverse Gaussian\n because there is an inverse relationship between the time to cover a unit\n distance and distance covered in unit time.\n\n Parameters\n ----------\n mean : scalar\n Distribution mean, should be > 0.\n scale : scalar\n Scale parameter, should be >= 0.\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single value is\n returned.\n\n Returns\n -------\n samples : ndarray or scalar\n Drawn sample, all greater than zero.\n\n Notes\n -----\n The probability density function for the Wald distribution is\n\n .. math:: P(x;mean,scale) = \\sqrt{\\frac{scale}{2\\pi x^3}}e^\n \\frac{-scale(x-mean)^2}{2\\cdotp mean^2x}\n\n As noted above the Inverse Gaussian distribution first arise from attempts\n to model Brownian Motion. It is also a competitor to the Weibull for use in\n reliability modeling and modeling stock returns and interest rate\n processes.\n\n References\n ----------\n .. [1] Brighton Webs Ltd., Wald Distribution,\n http://www.brighton-webs.co.uk/distributions/wald.asp\n .. [2] Chhikara, Raj S., and Folks, J. Leroy, \"The Inverse Gaussian\n Distribution: Theory : Methodology, and Applications\", CRC Press,\n 1988.\n .. [3] Wikipedia, \"Wald distribu""tion\"\n http://en.wikipedia.org/wiki/Wald_distribution\n\n Examples\n --------\n Draw values from the distribution and plot the histogram:\n\n >>> import matplotlib.pyplot as plt\n >>> h = plt.hist(np.random.wald(3, 2, 100000), bins=200, normed=True)\n >>> plt.show()\n\n "; -static char __pyx_k_261[] = "RandomState.triangular (line 3320)"; -static char __pyx_k_262[] = "\n triangular(left, mode, right, size=None)\n\n Draw samples from the triangular distribution.\n\n The triangular distribution is a continuous probability distribution with\n lower limit left, peak at mode, and upper limit right. Unlike the other\n distributions, these parameters directly define the shape of the pdf.\n\n Parameters\n ----------\n left : scalar\n Lower limit.\n mode : scalar\n The value where the peak of the distribution occurs.\n The value should fulfill the condition ``left <= mode <= right``.\n right : scalar\n Upper limit, should be larger than `left`.\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single value is\n returned.\n\n Returns\n -------\n samples : ndarray or scalar\n The returned samples all lie in the interval [left, right].\n\n Notes\n -----\n The probability density function for the Triangular distribution is\n\n .. math:: P(x;l, m, r) = \\begin{cases}\n \\frac{2(x-l)}{(r-l)(m-l)}& \\text{for $l \\leq x \\leq m$},\\\\\n \\frac{2(m-x)}{(r-l)(r-m)}& \\text{for $m \\leq x \\leq r$},\\\\\n 0& \\text{otherwise}.\n \\end{cases}\n\n The triangular distribution is often used in ill-defined problems where the\n underlying distribution is not known, but some knowledge of the limits and\n mode exists. Often it is used in simulations.\n\n References\n ----------\n .. [1] Wikipedia, \"Triangular distribution\"\n http://en.wikipedia.org/wiki/Triangular_distribution\n\n Examples\n --------\n Draw values from the distribution and plot the histogram:\n\n >>> import matplotlib.pyplot as plt\n >>> h = plt.hist(np.random.triangular(-3, 0, 8, 100000), bins=""200,\n ... normed=True)\n >>> plt.show()\n\n "; -static char __pyx_k_263[] = "RandomState.binomial (line 3408)"; -static char __pyx_k_264[] = "\n binomial(n, p, size=None)\n\n Draw samples from a binomial distribution.\n\n Samples are drawn from a Binomial distribution with specified\n parameters, n trials and p probability of success where\n n an integer >= 0 and p is in the interval [0,1]. (n may be\n input as a float, but it is truncated to an integer in use)\n\n Parameters\n ----------\n n : float (but truncated to an integer)\n parameter, >= 0.\n p : float\n parameter, >= 0 and <=1.\n size : {tuple, int}\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : {ndarray, scalar}\n where the values are all integers in [0, n].\n\n See Also\n --------\n scipy.stats.distributions.binom : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Binomial distribution is\n\n .. math:: P(N) = \\binom{n}{N}p^N(1-p)^{n-N},\n\n where :math:`n` is the number of trials, :math:`p` is the probability\n of success, and :math:`N` is the number of successes.\n\n When estimating the standard error of a proportion in a population by\n using a random sample, the normal distribution works well unless the\n product p*n <=5, where p = population proportion estimate, and n =\n number of samples, in which case the binomial distribution is used\n instead. For example, a sample of 15 people shows 4 who are left\n handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4,\n so the binomial distribution should be used in this case.\n\n References\n ----------\n .. [1] Dalgaard, Peter, \"Introductory Statistics with R\",\n Springer-Verlag, 2002.""\n .. [2] Glantz, Stanton A. \"Primer of Biostatistics.\", McGraw-Hill,\n Fifth Edition, 2002.\n .. [3] Lentner, Marvin, \"Elementary Applied Statistics\", Bogden\n and Quigley, 1972.\n .. [4] Weisstein, Eric W. \"Binomial Distribution.\" From MathWorld--A\n Wolfram Web Resource.\n http://mathworld.wolfram.com/BinomialDistribution.html\n .. [5] Wikipedia, \"Binomial-distribution\",\n http://en.wikipedia.org/wiki/Binomial_distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> n, p = 10, .5 # number of trials, probability of each trial\n >>> s = np.random.binomial(n, p, 1000)\n # result of flipping a coin 10 times, tested 1000 times.\n\n A real world example. A company drills 9 wild-cat oil exploration\n wells, each with an estimated probability of success of 0.1. All nine\n wells fail. What is the probability of that happening?\n\n Let's do 20,000 trials of the model, and count the number that\n generate zero positive results.\n\n >>> sum(np.random.binomial(9,0.1,20000)==0)/20000.\n answer = 0.38885, or 38%.\n\n "; -static char __pyx_k_265[] = "RandomState.negative_binomial (line 3516)"; -static char __pyx_k_266[] = "\n negative_binomial(n, p, size=None)\n\n Draw samples from a negative_binomial distribution.\n\n Samples are drawn from a negative_Binomial distribution with specified\n parameters, `n` trials and `p` probability of success where `n` is an\n integer > 0 and `p` is in the interval [0, 1].\n\n Parameters\n ----------\n n : int\n Parameter, > 0.\n p : float\n Parameter, >= 0 and <=1.\n size : int or tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : int or ndarray of ints\n Drawn samples.\n\n Notes\n -----\n The probability density for the Negative Binomial distribution is\n\n .. math:: P(N;n,p) = \\binom{N+n-1}{n-1}p^{n}(1-p)^{N},\n\n where :math:`n-1` is the number of successes, :math:`p` is the probability\n of success, and :math:`N+n-1` is the number of trials.\n\n The negative binomial distribution gives the probability of n-1 successes\n and N failures in N+n-1 trials, and success on the (N+n)th trial.\n\n If one throws a die repeatedly until the third time a \"1\" appears, then the\n probability distribution of the number of non-\"1\"s that appear before the\n third \"1\" is a negative binomial distribution.\n\n References\n ----------\n .. [1] Weisstein, Eric W. \"Negative Binomial Distribution.\" From\n MathWorld--A Wolfram Web Resource.\n http://mathworld.wolfram.com/NegativeBinomialDistribution.html\n .. [2] Wikipedia, \"Negative binomial distribution\",\n http://en.wikipedia.org/wiki/Negative_binomial_distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n A real world example. A company drills wild-cat oil exploration well""s, each\n with an estimated probability of success of 0.1. What is the probability\n of having one success for each successive well, that is what is the\n probability of a single success after drilling 5 wells, after 6 wells,\n etc.?\n\n >>> s = np.random.negative_binomial(1, 0.1, 100000)\n >>> for i in range(1, 11):\n ... probability = sum(s<i) / 100000.\n ... print i, \"wells drilled, probability of one success =\", probability\n\n "; -static char __pyx_k_267[] = "RandomState.poisson (line 3611)"; -static char __pyx_k_268[] = "\n poisson(lam=1.0, size=None)\n\n Draw samples from a Poisson distribution.\n\n The Poisson distribution is the limit of the Binomial\n distribution for large N.\n\n Parameters\n ----------\n lam : float\n Expectation of interval, should be >= 0.\n size : int or tuple of ints, optional\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Notes\n -----\n The Poisson distribution\n\n .. math:: f(k; \\lambda)=\\frac{\\lambda^k e^{-\\lambda}}{k!}\n\n For events with an expected separation :math:`\\lambda` the Poisson\n distribution :math:`f(k; \\lambda)` describes the probability of\n :math:`k` events occurring within the observed interval :math:`\\lambda`.\n\n Because the output is limited to the range of the C long type, a\n ValueError is raised when `lam` is within 10 sigma of the maximum\n representable value.\n\n References\n ----------\n .. [1] Weisstein, Eric W. \"Poisson Distribution.\" From MathWorld--A Wolfram\n Web Resource. http://mathworld.wolfram.com/PoissonDistribution.html\n .. [2] Wikipedia, \"Poisson distribution\",\n http://en.wikipedia.org/wiki/Poisson_distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> import numpy as np\n >>> s = np.random.poisson(5, 10000)\n\n Display histogram of the sample:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, 14, normed=True)\n >>> plt.show()\n\n "; -static char __pyx_k_269[] = "RandomState.zipf (line 3682)"; -static char __pyx_k_270[] = "\n zipf(a, size=None)\n\n Draw samples from a Zipf distribution.\n\n Samples are drawn from a Zipf distribution with specified parameter\n `a` > 1.\n\n The Zipf distribution (also known as the zeta distribution) is a\n continuous probability distribution that satisfies Zipf's law: the\n frequency of an item is inversely proportional to its rank in a\n frequency table.\n\n Parameters\n ----------\n a : float > 1\n Distribution parameter.\n size : int or tuple of int, optional\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn; a single integer is equivalent in\n its result to providing a mono-tuple, i.e., a 1-D array of length\n *size* is returned. The default is None, in which case a single\n scalar is returned.\n\n Returns\n -------\n samples : scalar or ndarray\n The returned samples are greater than or equal to one.\n\n See Also\n --------\n scipy.stats.distributions.zipf : probability density function,\n distribution, or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Zipf distribution is\n\n .. math:: p(x) = \\frac{x^{-a}}{\\zeta(a)},\n\n where :math:`\\zeta` is the Riemann Zeta function.\n\n It is named for the American linguist George Kingsley Zipf, who noted\n that the frequency of any word in a sample of a language is inversely\n proportional to its rank in the frequency table.\n\n References\n ----------\n Zipf, G. K., *Selected Studies of the Principle of Relative Frequency\n in Language*, Cambridge, MA: Harvard Univ. Press, 1932.\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> a = 2. # parameter\n >>> s = np.random.zipf""(a, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> import scipy.special as sps\n Truncate s values at 50 so plot is interesting\n >>> count, bins, ignored = plt.hist(s[s<50], 50, normed=True)\n >>> x = np.arange(1., 50.)\n >>> y = x**(-a)/sps.zetac(a)\n >>> plt.plot(x, y/max(y), linewidth=2, color='r')\n >>> plt.show()\n\n "; -static char __pyx_k_271[] = "RandomState.geometric (line 3770)"; -static char __pyx_k_272[] = "\n geometric(p, size=None)\n\n Draw samples from the geometric distribution.\n\n Bernoulli trials are experiments with one of two outcomes:\n success or failure (an example of such an experiment is flipping\n a coin). The geometric distribution models the number of trials\n that must be run in order to achieve success. It is therefore\n supported on the positive integers, ``k = 1, 2, ...``.\n\n The probability mass function of the geometric distribution is\n\n .. math:: f(k) = (1 - p)^{k - 1} p\n\n where `p` is the probability of success of an individual trial.\n\n Parameters\n ----------\n p : float\n The probability of success of an individual trial.\n size : tuple of ints\n Number of values to draw from the distribution. The output\n is shaped according to `size`.\n\n Returns\n -------\n out : ndarray\n Samples from the geometric distribution, shaped according to\n `size`.\n\n Examples\n --------\n Draw ten thousand values from the geometric distribution,\n with the probability of an individual success equal to 0.35:\n\n >>> z = np.random.geometric(p=0.35, size=10000)\n\n How many trials succeeded after a single run?\n\n >>> (z == 1).sum() / 10000.\n 0.34889999999999999 #random\n\n "; -static char __pyx_k_273[] = "RandomState.hypergeometric (line 3836)"; -static char __pyx_k_274[] = "\n hypergeometric(ngood, nbad, nsample, size=None)\n\n Draw samples from a Hypergeometric distribution.\n\n Samples are drawn from a Hypergeometric distribution with specified\n parameters, ngood (ways to make a good selection), nbad (ways to make\n a bad selection), and nsample = number of items sampled, which is less\n than or equal to the sum ngood + nbad.\n\n Parameters\n ----------\n ngood : int or array_like\n Number of ways to make a good selection. Must be nonnegative.\n nbad : int or array_like\n Number of ways to make a bad selection. Must be nonnegative.\n nsample : int or array_like\n Number of items sampled. Must be at least 1 and at most\n ``ngood + nbad``.\n size : int or tuple of int\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : ndarray or scalar\n The values are all integers in [0, n].\n\n See Also\n --------\n scipy.stats.distributions.hypergeom : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Hypergeometric distribution is\n\n .. math:: P(x) = \\frac{\\binom{m}{n}\\binom{N-m}{n-x}}{\\binom{N}{n}},\n\n where :math:`0 \\le x \\le m` and :math:`n+m-N \\le x \\le n`\n\n for P(x) the probability of x successes, n = ngood, m = nbad, and\n N = number of samples.\n\n Consider an urn with black and white marbles in it, ngood of them\n black and nbad are white. If you draw nsample balls without\n replacement, then the Hypergeometric distribution describes the\n distribution of black balls in the drawn sample.\n\n Note that this distribution is very similar to the Binomial\n distrib""ution, except that in this case, samples are drawn without\n replacement, whereas in the Binomial case samples are drawn with\n replacement (or the sample space is infinite). As the sample space\n becomes large, this distribution approaches the Binomial.\n\n References\n ----------\n .. [1] Lentner, Marvin, \"Elementary Applied Statistics\", Bogden\n and Quigley, 1972.\n .. [2] Weisstein, Eric W. \"Hypergeometric Distribution.\" From\n MathWorld--A Wolfram Web Resource.\n http://mathworld.wolfram.com/HypergeometricDistribution.html\n .. [3] Wikipedia, \"Hypergeometric-distribution\",\n http://en.wikipedia.org/wiki/Hypergeometric-distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> ngood, nbad, nsamp = 100, 2, 10\n # number of good, number of bad, and number of samples\n >>> s = np.random.hypergeometric(ngood, nbad, nsamp, 1000)\n >>> hist(s)\n # note that it is very unlikely to grab both bad items\n\n Suppose you have an urn with 15 white and 15 black marbles.\n If you pull 15 marbles at random, how likely is it that\n 12 or more of them are one color?\n\n >>> s = np.random.hypergeometric(15, 15, 15, 100000)\n >>> sum(s>=12)/100000. + sum(s<=3)/100000.\n # answer = 0.003 ... pretty unlikely!\n\n "; -static char __pyx_k_275[] = "RandomState.logseries (line 3955)"; -static char __pyx_k_276[] = "\n logseries(p, size=None)\n\n Draw samples from a Logarithmic Series distribution.\n\n Samples are drawn from a Log Series distribution with specified\n parameter, p (probability, 0 < p < 1).\n\n Parameters\n ----------\n loc : float\n\n scale : float > 0.\n\n size : {tuple, int}\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : {ndarray, scalar}\n where the values are all integers in [0, n].\n\n See Also\n --------\n scipy.stats.distributions.logser : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Log Series distribution is\n\n .. math:: P(k) = \\frac{-p^k}{k \\ln(1-p)},\n\n where p = probability.\n\n The Log Series distribution is frequently used to represent species\n richness and occurrence, first proposed by Fisher, Corbet, and\n Williams in 1943 [2]. It may also be used to model the numbers of\n occupants seen in cars [3].\n\n References\n ----------\n .. [1] Buzas, Martin A.; Culver, Stephen J., Understanding regional\n species diversity through the log series distribution of\n occurrences: BIODIVERSITY RESEARCH Diversity & Distributions,\n Volume 5, Number 5, September 1999 , pp. 187-195(9).\n .. [2] Fisher, R.A,, A.S. Corbet, and C.B. Williams. 1943. The\n relation between the number of species and the number of\n individuals in a random sample of an animal population.\n Journal of Animal Ecology, 12:42-58.\n .. [3] D. J. Hand, F. Daly, D. Lunn, E. Ostrowski, A Handbook of Small\n Data Sets, CRC Press, 1994.\n .. [4] Wikipedia, \"Log""arithmic-distribution\",\n http://en.wikipedia.org/wiki/Logarithmic-distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> a = .6\n >>> s = np.random.logseries(a, 10000)\n >>> count, bins, ignored = plt.hist(s)\n\n # plot against distribution\n\n >>> def logseries(k, p):\n ... return -p**k/(k*log(1-p))\n >>> plt.plot(bins, logseries(bins, a)*count.max()/\n logseries(bins, a).max(), 'r')\n >>> plt.show()\n\n "; -static char __pyx_k_277[] = "RandomState.multivariate_normal (line 4050)"; -static char __pyx_k_278[] = "\n multivariate_normal(mean, cov[, size])\n\n Draw random samples from a multivariate normal distribution.\n\n The multivariate normal, multinormal or Gaussian distribution is a\n generalization of the one-dimensional normal distribution to higher\n dimensions. Such a distribution is specified by its mean and\n covariance matrix. These parameters are analogous to the mean\n (average or \"center\") and variance (standard deviation, or \"width,\"\n squared) of the one-dimensional normal distribution.\n\n Parameters\n ----------\n mean : 1-D array_like, of length N\n Mean of the N-dimensional distribution.\n cov : 2-D array_like, of shape (N, N)\n Covariance matrix of the distribution. Must be symmetric and\n positive semi-definite for \"physically meaningful\" results.\n size : int or tuple of ints, optional\n Given a shape of, for example, ``(m,n,k)``, ``m*n*k`` samples are\n generated, and packed in an `m`-by-`n`-by-`k` arrangement. Because\n each sample is `N`-dimensional, the output shape is ``(m,n,k,N)``.\n If no shape is specified, a single (`N`-D) sample is returned.\n\n Returns\n -------\n out : ndarray\n The drawn samples, of shape *size*, if that was provided. If not,\n the shape is ``(N,)``.\n\n In other words, each entry ``out[i,j,...,:]`` is an N-dimensional\n value drawn from the distribution.\n\n Notes\n -----\n The mean is a coordinate in N-dimensional space, which represents the\n location where samples are most likely to be generated. This is\n analogous to the peak of the bell curve for the one-dimensional or\n univariate normal distribution.\n\n Covariance indicates the level to which two variables vary together.\n From the multivariate normal distribution, w""e draw N-dimensional\n samples, :math:`X = [x_1, x_2, ... x_N]`. The covariance matrix\n element :math:`C_{ij}` is the covariance of :math:`x_i` and :math:`x_j`.\n The element :math:`C_{ii}` is the variance of :math:`x_i` (i.e. its\n \"spread\").\n\n Instead of specifying the full covariance matrix, popular\n approximations include:\n\n - Spherical covariance (*cov* is a multiple of the identity matrix)\n - Diagonal covariance (*cov* has non-negative elements, and only on\n the diagonal)\n\n This geometrical property can be seen in two dimensions by plotting\n generated data-points:\n\n >>> mean = [0,0]\n >>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis\n\n >>> import matplotlib.pyplot as plt\n >>> x,y = np.random.multivariate_normal(mean,cov,5000).T\n >>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()\n\n Note that the covariance matrix must be non-negative definite.\n\n References\n ----------\n Papoulis, A., *Probability, Random Variables, and Stochastic Processes*,\n 3rd ed., New York: McGraw-Hill, 1991.\n\n Duda, R. O., Hart, P. E., and Stork, D. G., *Pattern Classification*,\n 2nd ed., New York: Wiley, 2001.\n\n Examples\n --------\n >>> mean = (1,2)\n >>> cov = [[1,0],[1,0]]\n >>> x = np.random.multivariate_normal(mean,cov,(3,3))\n >>> x.shape\n (3, 3, 2)\n\n The following is probably true, given that 0.6 is roughly twice the\n standard deviation:\n\n >>> print list( (x[0,0,:] - mean) < 0.6 )\n [True, True]\n\n "; -static char __pyx_k_279[] = "RandomState.multinomial (line 4182)"; -static char __pyx_k_280[] = "\n multinomial(n, pvals, size=None)\n\n Draw samples from a multinomial distribution.\n\n The multinomial distribution is a multivariate generalisation of the\n binomial distribution. Take an experiment with one of ``p``\n possible outcomes. An example of such an experiment is throwing a dice,\n where the outcome can be 1 through 6. Each sample drawn from the\n distribution represents `n` such experiments. Its values,\n ``X_i = [X_0, X_1, ..., X_p]``, represent the number of times the outcome\n was ``i``.\n\n Parameters\n ----------\n n : int\n Number of experiments.\n pvals : sequence of floats, length p\n Probabilities of each of the ``p`` different outcomes. These\n should sum to 1 (however, the last element is always assumed to\n account for the remaining probability, as long as\n ``sum(pvals[:-1]) <= 1)``.\n size : tuple of ints\n Given a `size` of ``(M, N, K)``, then ``M*N*K`` samples are drawn,\n and the output shape becomes ``(M, N, K, p)``, since each sample\n has shape ``(p,)``.\n\n Examples\n --------\n Throw a dice 20 times:\n\n >>> np.random.multinomial(20, [1/6.]*6, size=1)\n array([[4, 1, 7, 5, 2, 1]])\n\n It landed 4 times on 1, once on 2, etc.\n\n Now, throw the dice 20 times, and 20 times again:\n\n >>> np.random.multinomial(20, [1/6.]*6, size=2)\n array([[3, 4, 3, 3, 4, 3],\n [2, 4, 3, 4, 0, 7]])\n\n For the first run, we threw 3 times 1, 4 times 2, etc. For the second,\n we threw 2 times 1, 4 times 2, etc.\n\n A loaded dice is more likely to land on number 6:\n\n >>> np.random.multinomial(100, [1/7.]*5)\n array([13, 16, 13, 16, 42])\n\n "; -static char __pyx_k_281[] = "RandomState.dirichlet (line 4275)"; -static char __pyx_k_282[] = "\n dirichlet(alpha, size=None)\n\n Draw samples from the Dirichlet distribution.\n\n Draw `size` samples of dimension k from a Dirichlet distribution. A\n Dirichlet-distributed random variable can be seen as a multivariate\n generalization of a Beta distribution. Dirichlet pdf is the conjugate\n prior of a multinomial in Bayesian inference.\n\n Parameters\n ----------\n alpha : array\n Parameter of the distribution (k dimension for sample of\n dimension k).\n size : array\n Number of samples to draw.\n\n Returns\n -------\n samples : ndarray,\n The drawn samples, of shape (alpha.ndim, size).\n\n Notes\n -----\n .. math:: X \\approx \\prod_{i=1}^{k}{x^{\\alpha_i-1}_i}\n\n Uses the following property for computation: for each dimension,\n draw a random sample y_i from a standard gamma generator of shape\n `alpha_i`, then\n :math:`X = \\frac{1}{\\sum_{i=1}^k{y_i}} (y_1, \\ldots, y_n)` is\n Dirichlet distributed.\n\n References\n ----------\n .. [1] David McKay, \"Information Theory, Inference and Learning\n Algorithms,\" chapter 23,\n http://www.inference.phy.cam.ac.uk/mackay/\n .. [2] Wikipedia, \"Dirichlet distribution\",\n http://en.wikipedia.org/wiki/Dirichlet_distribution\n\n Examples\n --------\n Taking an example cited in Wikipedia, this distribution can be used if\n one wanted to cut strings (each of initial length 1.0) into K pieces\n with different lengths, where each piece had, on average, a designated\n average length, but allowing some variation in the relative sizes of the\n pieces.\n\n >>> s = np.random.dirichlet((10, 5, 3), 20).transpose()\n\n >>> plt.barh(range(20), s[0])\n >>> plt.barh(range(20), s[1], left=s[0], color='g')""\n >>> plt.barh(range(20), s[2], left=s[0]+s[1], color='r')\n >>> plt.title(\"Lengths of Strings\")\n\n "; -static char __pyx_k_283[] = "RandomState.shuffle (line 4391)"; -static char __pyx_k_284[] = "\n shuffle(x)\n\n Modify a sequence in-place by shuffling its contents.\n\n Parameters\n ----------\n x : array_like\n The array or list to be shuffled.\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> arr = np.arange(10)\n >>> np.random.shuffle(arr)\n >>> arr\n [1 7 5 2 9 4 3 6 0 8]\n\n This function only shuffles the array along the first index of a\n multi-dimensional array:\n\n >>> arr = np.arange(9).reshape((3, 3))\n >>> np.random.shuffle(arr)\n >>> arr\n array([[3, 4, 5],\n [6, 7, 8],\n [0, 1, 2]])\n\n "; -static char __pyx_k_285[] = "RandomState.permutation (line 4449)"; -static char __pyx_k_286[] = "\n permutation(x)\n\n Randomly permute a sequence, or return a permuted range.\n\n If `x` is a multi-dimensional array, it is only shuffled along its\n first index.\n\n Parameters\n ----------\n x : int or array_like\n If `x` is an integer, randomly permute ``np.arange(x)``.\n If `x` is an array, make a copy and shuffle the elements\n randomly.\n\n Returns\n -------\n out : ndarray\n Permuted sequence or array range.\n\n Examples\n --------\n >>> np.random.permutation(10)\n array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6])\n\n >>> np.random.permutation([1, 4, 9, 12, 15])\n array([15, 1, 9, 4, 12])\n\n >>> arr = np.arange(9).reshape((3, 3))\n >>> np.random.permutation(arr)\n array([[6, 7, 8],\n [0, 1, 2],\n [3, 4, 5]])\n\n "; -static char __pyx_k__df[] = "df"; -static char __pyx_k__mu[] = "mu"; -static char __pyx_k__np[] = "np"; -static char __pyx_k__add[] = "add"; -static char __pyx_k__any[] = "any"; -static char __pyx_k__cov[] = "cov"; -static char __pyx_k__dot[] = "dot"; -static char __pyx_k__int[] = "int"; -static char __pyx_k__lam[] = "lam"; -static char __pyx_k__loc[] = "loc"; -static char __pyx_k__low[] = "low"; -static char __pyx_k__max[] = "max"; -static char __pyx_k__sum[] = "sum"; -static char __pyx_k__svd[] = "svd"; -static char __pyx_k__beta[] = "beta"; -static char __pyx_k__copy[] = "copy"; -static char __pyx_k__high[] = "high"; -static char __pyx_k__intp[] = "intp"; -static char __pyx_k__item[] = "item"; -static char __pyx_k__left[] = "left"; -static char __pyx_k__less[] = "less"; -static char __pyx_k__mean[] = "mean"; -static char __pyx_k__mode[] = "mode"; -static char __pyx_k__nbad[] = "nbad"; -static char __pyx_k__ndim[] = "ndim"; -static char __pyx_k__nonc[] = "nonc"; -static char __pyx_k__prod[] = "prod"; -static char __pyx_k__rand[] = "rand"; -static char __pyx_k__seed[] = "seed"; -static char __pyx_k__side[] = "side"; -static char __pyx_k__size[] = "size"; -static char __pyx_k__sort[] = "sort"; -static char __pyx_k__sqrt[] = "sqrt"; -static char __pyx_k__take[] = "take"; -static char __pyx_k__uint[] = "uint"; -static char __pyx_k__wald[] = "wald"; -static char __pyx_k__zipf[] = "zipf"; -static char __pyx_k___rand[] = "_rand"; -static char __pyx_k__alpha[] = "alpha"; -static char __pyx_k__array[] = "array"; -static char __pyx_k__bytes[] = "bytes"; -static char __pyx_k__dfden[] = "dfden"; -static char __pyx_k__dfnum[] = "dfnum"; -static char __pyx_k__dtype[] = "dtype"; -static char __pyx_k__empty[] = "empty"; -static char __pyx_k__equal[] = "equal"; -static char __pyx_k__gamma[] = "gamma"; -static char __pyx_k__iinfo[] = "iinfo"; -static char __pyx_k__index[] = "index"; -static char __pyx_k__kappa[] = "kappa"; -static char __pyx_k__ndmin[] = "ndmin"; -static char __pyx_k__ngood[] = "ngood"; -static char __pyx_k__numpy[] = "numpy"; -static char __pyx_k__power[] = "power"; -static char __pyx_k__pvals[] = "pvals"; -static char __pyx_k__randn[] = "randn"; -static char __pyx_k__ravel[] = "ravel"; -static char __pyx_k__right[] = "right"; -static char __pyx_k__scale[] = "scale"; -static char __pyx_k__shape[] = "shape"; -static char __pyx_k__sigma[] = "sigma"; -static char __pyx_k__zeros[] = "zeros"; -static char __pyx_k__arange[] = "arange"; -static char __pyx_k__choice[] = "choice"; -static char __pyx_k__cumsum[] = "cumsum"; -static char __pyx_k__double[] = "double"; -static char __pyx_k__gumbel[] = "gumbel"; -static char __pyx_k__normal[] = "normal"; -static char __pyx_k__pareto[] = "pareto"; -static char __pyx_k__random[] = "random"; -static char __pyx_k__reduce[] = "reduce"; -static char __pyx_k__uint32[] = "uint32"; -static char __pyx_k__unique[] = "unique"; -static char __pyx_k__MT19937[] = "MT19937"; -static char __pyx_k__asarray[] = "asarray"; -static char __pyx_k__float64[] = "float64"; -static char __pyx_k__greater[] = "greater"; -static char __pyx_k__integer[] = "integer"; -static char __pyx_k__laplace[] = "laplace"; -static char __pyx_k__ndarray[] = "ndarray"; -static char __pyx_k__nsample[] = "nsample"; -static char __pyx_k__poisson[] = "poisson"; -static char __pyx_k__randint[] = "randint"; -static char __pyx_k__replace[] = "replace"; -static char __pyx_k__shuffle[] = "shuffle"; -static char __pyx_k__uniform[] = "uniform"; -static char __pyx_k__weibull[] = "weibull"; -static char __pyx_k____main__[] = "__main__"; -static char __pyx_k____test__[] = "__test__"; -static char __pyx_k__allclose[] = "allclose"; -static char __pyx_k__binomial[] = "binomial"; -static char __pyx_k__logistic[] = "logistic"; -static char __pyx_k__multiply[] = "multiply"; -static char __pyx_k__operator[] = "operator"; -static char __pyx_k__rayleigh[] = "rayleigh"; -static char __pyx_k__subtract[] = "subtract"; -static char __pyx_k__vonmises[] = "vonmises"; -static char __pyx_k__TypeError[] = "TypeError"; -static char __pyx_k__chisquare[] = "chisquare"; -static char __pyx_k__dirichlet[] = "dirichlet"; -static char __pyx_k__geometric[] = "geometric"; -static char __pyx_k__get_state[] = "get_state"; -static char __pyx_k__lognormal[] = "lognormal"; -static char __pyx_k__logseries[] = "logseries"; -static char __pyx_k__set_state[] = "set_state"; -static char __pyx_k__ValueError[] = "ValueError"; -static char __pyx_k____import__[] = "__import__"; -static char __pyx_k__less_equal[] = "less_equal"; -static char __pyx_k__standard_t[] = "standard_t"; -static char __pyx_k__triangular[] = "triangular"; -static char __pyx_k__exponential[] = "exponential"; -static char __pyx_k__multinomial[] = "multinomial"; -static char __pyx_k__permutation[] = "permutation"; -static char __pyx_k__noncentral_f[] = "noncentral_f"; -static char __pyx_k__return_index[] = "return_index"; -static char __pyx_k__searchsorted[] = "searchsorted"; -static char __pyx_k__greater_equal[] = "greater_equal"; -static char __pyx_k__random_sample[] = "random_sample"; -static char __pyx_k__hypergeometric[] = "hypergeometric"; -static char __pyx_k__standard_gamma[] = "standard_gamma"; -static char __pyx_k__poisson_lam_max[] = "poisson_lam_max"; -static char __pyx_k__random_integers[] = "random_integers"; -static char __pyx_k__standard_cauchy[] = "standard_cauchy"; -static char __pyx_k__standard_normal[] = "standard_normal"; -static char __pyx_k__negative_binomial[] = "negative_binomial"; -static char __pyx_k____RandomState_ctor[] = "__RandomState_ctor"; -static char __pyx_k__multivariate_normal[] = "multivariate_normal"; -static PyObject *__pyx_kp_s_1; -static PyObject *__pyx_kp_s_112; -static PyObject *__pyx_kp_s_114; -static PyObject *__pyx_kp_s_118; -static PyObject *__pyx_kp_s_120; -static PyObject *__pyx_kp_s_123; -static PyObject *__pyx_kp_s_126; -static PyObject *__pyx_kp_s_128; -static PyObject *__pyx_kp_s_13; -static PyObject *__pyx_kp_s_130; -static PyObject *__pyx_kp_s_135; -static PyObject *__pyx_kp_s_137; -static PyObject *__pyx_kp_s_139; -static PyObject *__pyx_kp_s_144; -static PyObject *__pyx_kp_s_15; -static PyObject *__pyx_kp_s_152; -static PyObject *__pyx_kp_s_154; -static PyObject *__pyx_kp_s_157; -static PyObject *__pyx_kp_s_159; -static PyObject *__pyx_kp_s_162; -static PyObject *__pyx_kp_s_164; -static PyObject *__pyx_kp_s_168; -static PyObject *__pyx_kp_s_170; -static PyObject *__pyx_kp_s_172; -static PyObject *__pyx_kp_s_174; -static PyObject *__pyx_kp_s_18; -static PyObject *__pyx_kp_s_180; -static PyObject *__pyx_kp_s_182; -static PyObject *__pyx_kp_s_186; -static PyObject *__pyx_kp_s_188; -static PyObject *__pyx_kp_s_190; -static PyObject *__pyx_n_s_193; -static PyObject *__pyx_kp_s_194; -static PyObject *__pyx_n_s_199; -static PyObject *__pyx_kp_s_20; -static PyObject *__pyx_n_s_200; -static PyObject *__pyx_kp_u_201; -static PyObject *__pyx_kp_u_202; -static PyObject *__pyx_kp_u_203; -static PyObject *__pyx_kp_u_204; -static PyObject *__pyx_kp_u_205; -static PyObject *__pyx_kp_u_206; -static PyObject *__pyx_kp_u_207; -static PyObject *__pyx_kp_u_208; -static PyObject *__pyx_kp_u_209; -static PyObject *__pyx_kp_u_210; -static PyObject *__pyx_kp_u_211; -static PyObject *__pyx_kp_u_212; -static PyObject *__pyx_kp_u_213; -static PyObject *__pyx_kp_u_214; -static PyObject *__pyx_kp_u_215; -static PyObject *__pyx_kp_u_216; -static PyObject *__pyx_kp_u_217; -static PyObject *__pyx_kp_u_218; -static PyObject *__pyx_kp_u_219; -static PyObject *__pyx_kp_s_22; -static PyObject *__pyx_kp_u_220; -static PyObject *__pyx_kp_u_221; -static PyObject *__pyx_kp_u_222; -static PyObject *__pyx_kp_u_223; -static PyObject *__pyx_kp_u_224; -static PyObject *__pyx_kp_u_225; -static PyObject *__pyx_kp_u_226; -static PyObject *__pyx_kp_u_227; -static PyObject *__pyx_kp_u_228; -static PyObject *__pyx_kp_u_229; -static PyObject *__pyx_kp_u_230; -static PyObject *__pyx_kp_u_231; -static PyObject *__pyx_kp_u_232; -static PyObject *__pyx_kp_u_233; -static PyObject *__pyx_kp_u_234; -static PyObject *__pyx_kp_u_235; -static PyObject *__pyx_kp_u_236; -static PyObject *__pyx_kp_u_237; -static PyObject *__pyx_kp_u_238; -static PyObject *__pyx_kp_u_239; -static PyObject *__pyx_kp_s_24; -static PyObject *__pyx_kp_u_240; -static PyObject *__pyx_kp_u_241; -static PyObject *__pyx_kp_u_242; -static PyObject *__pyx_kp_u_243; -static PyObject *__pyx_kp_u_244; -static PyObject *__pyx_kp_u_245; -static PyObject *__pyx_kp_u_246; -static PyObject *__pyx_kp_u_247; -static PyObject *__pyx_kp_u_248; -static PyObject *__pyx_kp_u_249; -static PyObject *__pyx_kp_u_250; -static PyObject *__pyx_kp_u_251; -static PyObject *__pyx_kp_u_252; -static PyObject *__pyx_kp_u_253; -static PyObject *__pyx_kp_u_254; -static PyObject *__pyx_kp_u_255; -static PyObject *__pyx_kp_u_256; -static PyObject *__pyx_kp_u_257; -static PyObject *__pyx_kp_u_258; -static PyObject *__pyx_kp_u_259; -static PyObject *__pyx_kp_s_26; -static PyObject *__pyx_kp_u_260; -static PyObject *__pyx_kp_u_261; -static PyObject *__pyx_kp_u_262; -static PyObject *__pyx_kp_u_263; -static PyObject *__pyx_kp_u_264; -static PyObject *__pyx_kp_u_265; -static PyObject *__pyx_kp_u_266; -static PyObject *__pyx_kp_u_267; -static PyObject *__pyx_kp_u_268; -static PyObject *__pyx_kp_u_269; -static PyObject *__pyx_kp_u_270; -static PyObject *__pyx_kp_u_271; -static PyObject *__pyx_kp_u_272; -static PyObject *__pyx_kp_u_273; -static PyObject *__pyx_kp_u_274; -static PyObject *__pyx_kp_u_275; -static PyObject *__pyx_kp_u_276; -static PyObject *__pyx_kp_u_277; -static PyObject *__pyx_kp_u_278; -static PyObject *__pyx_kp_u_279; -static PyObject *__pyx_kp_s_28; -static PyObject *__pyx_kp_u_280; -static PyObject *__pyx_kp_u_281; -static PyObject *__pyx_kp_u_282; -static PyObject *__pyx_kp_u_283; -static PyObject *__pyx_kp_u_284; -static PyObject *__pyx_kp_u_285; -static PyObject *__pyx_kp_u_286; -static PyObject *__pyx_kp_s_30; -static PyObject *__pyx_kp_s_32; -static PyObject *__pyx_kp_s_34; -static PyObject *__pyx_kp_s_36; -static PyObject *__pyx_kp_s_44; -static PyObject *__pyx_kp_s_47; -static PyObject *__pyx_kp_s_49; -static PyObject *__pyx_kp_s_56; -static PyObject *__pyx_kp_s_66; -static PyObject *__pyx_kp_s_68; -static PyObject *__pyx_kp_s_70; -static PyObject *__pyx_kp_s_73; -static PyObject *__pyx_kp_s_78; -static PyObject *__pyx_kp_s_82; -static PyObject *__pyx_kp_s_84; -static PyObject *__pyx_kp_s_89; -static PyObject *__pyx_kp_s_9; -static PyObject *__pyx_n_s__MT19937; -static PyObject *__pyx_n_s__TypeError; -static PyObject *__pyx_n_s__ValueError; -static PyObject *__pyx_n_s____RandomState_ctor; -static PyObject *__pyx_n_s____import__; -static PyObject *__pyx_n_s____main__; -static PyObject *__pyx_n_s____test__; -static PyObject *__pyx_n_s___rand; -static PyObject *__pyx_n_s__a; -static PyObject *__pyx_n_s__add; -static PyObject *__pyx_n_s__allclose; -static PyObject *__pyx_n_s__alpha; -static PyObject *__pyx_n_s__any; -static PyObject *__pyx_n_s__arange; -static PyObject *__pyx_n_s__array; -static PyObject *__pyx_n_s__asarray; -static PyObject *__pyx_n_s__b; -static PyObject *__pyx_n_s__beta; -static PyObject *__pyx_n_s__binomial; -static PyObject *__pyx_n_s__bytes; -static PyObject *__pyx_n_s__chisquare; -static PyObject *__pyx_n_s__choice; -static PyObject *__pyx_n_s__copy; -static PyObject *__pyx_n_s__cov; -static PyObject *__pyx_n_s__cumsum; -static PyObject *__pyx_n_s__df; -static PyObject *__pyx_n_s__dfden; -static PyObject *__pyx_n_s__dfnum; -static PyObject *__pyx_n_s__dirichlet; -static PyObject *__pyx_n_s__dot; -static PyObject *__pyx_n_s__double; -static PyObject *__pyx_n_s__dtype; -static PyObject *__pyx_n_s__empty; -static PyObject *__pyx_n_s__equal; -static PyObject *__pyx_n_s__exponential; -static PyObject *__pyx_n_s__f; -static PyObject *__pyx_n_s__float64; -static PyObject *__pyx_n_s__gamma; -static PyObject *__pyx_n_s__geometric; -static PyObject *__pyx_n_s__get_state; -static PyObject *__pyx_n_s__greater; -static PyObject *__pyx_n_s__greater_equal; -static PyObject *__pyx_n_s__gumbel; -static PyObject *__pyx_n_s__high; -static PyObject *__pyx_n_s__hypergeometric; -static PyObject *__pyx_n_s__iinfo; -static PyObject *__pyx_n_s__index; -static PyObject *__pyx_n_s__int; -static PyObject *__pyx_n_s__integer; -static PyObject *__pyx_n_s__intp; -static PyObject *__pyx_n_s__item; -static PyObject *__pyx_n_s__kappa; -static PyObject *__pyx_n_s__l; -static PyObject *__pyx_n_s__lam; -static PyObject *__pyx_n_s__laplace; -static PyObject *__pyx_n_s__left; -static PyObject *__pyx_n_s__less; -static PyObject *__pyx_n_s__less_equal; -static PyObject *__pyx_n_s__loc; -static PyObject *__pyx_n_s__logistic; -static PyObject *__pyx_n_s__lognormal; -static PyObject *__pyx_n_s__logseries; -static PyObject *__pyx_n_s__low; -static PyObject *__pyx_n_s__max; -static PyObject *__pyx_n_s__mean; -static PyObject *__pyx_n_s__mode; -static PyObject *__pyx_n_s__mu; -static PyObject *__pyx_n_s__multinomial; -static PyObject *__pyx_n_s__multiply; -static PyObject *__pyx_n_s__multivariate_normal; -static PyObject *__pyx_n_s__n; -static PyObject *__pyx_n_s__nbad; -static PyObject *__pyx_n_s__ndarray; -static PyObject *__pyx_n_s__ndim; -static PyObject *__pyx_n_s__ndmin; -static PyObject *__pyx_n_s__negative_binomial; -static PyObject *__pyx_n_s__ngood; -static PyObject *__pyx_n_s__nonc; -static PyObject *__pyx_n_s__noncentral_f; -static PyObject *__pyx_n_s__normal; -static PyObject *__pyx_n_s__np; -static PyObject *__pyx_n_s__nsample; -static PyObject *__pyx_n_s__numpy; -static PyObject *__pyx_n_s__operator; -static PyObject *__pyx_n_s__p; -static PyObject *__pyx_n_s__pareto; -static PyObject *__pyx_n_s__permutation; -static PyObject *__pyx_n_s__poisson; -static PyObject *__pyx_n_s__poisson_lam_max; -static PyObject *__pyx_n_s__power; -static PyObject *__pyx_n_s__prod; -static PyObject *__pyx_n_s__pvals; -static PyObject *__pyx_n_s__rand; -static PyObject *__pyx_n_s__randint; -static PyObject *__pyx_n_s__randn; -static PyObject *__pyx_n_s__random; -static PyObject *__pyx_n_s__random_integers; -static PyObject *__pyx_n_s__random_sample; -static PyObject *__pyx_n_s__ravel; -static PyObject *__pyx_n_s__rayleigh; -static PyObject *__pyx_n_s__reduce; -static PyObject *__pyx_n_s__replace; -static PyObject *__pyx_n_s__return_index; -static PyObject *__pyx_n_s__right; -static PyObject *__pyx_n_s__scale; -static PyObject *__pyx_n_s__searchsorted; -static PyObject *__pyx_n_s__seed; -static PyObject *__pyx_n_s__set_state; -static PyObject *__pyx_n_s__shape; -static PyObject *__pyx_n_s__shuffle; -static PyObject *__pyx_n_s__side; -static PyObject *__pyx_n_s__sigma; -static PyObject *__pyx_n_s__size; -static PyObject *__pyx_n_s__sort; -static PyObject *__pyx_n_s__sqrt; -static PyObject *__pyx_n_s__standard_cauchy; -static PyObject *__pyx_n_s__standard_gamma; -static PyObject *__pyx_n_s__standard_normal; -static PyObject *__pyx_n_s__standard_t; -static PyObject *__pyx_n_s__subtract; -static PyObject *__pyx_n_s__sum; -static PyObject *__pyx_n_s__svd; -static PyObject *__pyx_n_s__take; -static PyObject *__pyx_n_s__triangular; -static PyObject *__pyx_n_s__uint; -static PyObject *__pyx_n_s__uint32; -static PyObject *__pyx_n_s__uniform; -static PyObject *__pyx_n_s__unique; -static PyObject *__pyx_n_s__vonmises; -static PyObject *__pyx_n_s__wald; -static PyObject *__pyx_n_s__weibull; -static PyObject *__pyx_n_s__zeros; -static PyObject *__pyx_n_s__zipf; -static PyObject *__pyx_int_0; -static PyObject *__pyx_int_1; -static PyObject *__pyx_int_3; -static PyObject *__pyx_int_5; -static PyObject *__pyx_int_10; -static PyObject *__pyx_int_624; -static PyObject *__pyx_k_17; -static PyObject *__pyx_k_40; -static PyObject *__pyx_k_41; -static PyObject *__pyx_k_42; -static PyObject *__pyx_k_43; -static PyObject *__pyx_k_53; -static PyObject *__pyx_k_59; -static PyObject *__pyx_k_98; -static PyObject *__pyx_k_99; -static PyObject *__pyx_k_102; -static PyObject *__pyx_k_103; -static PyObject *__pyx_k_106; -static PyObject *__pyx_k_107; -static PyObject *__pyx_k_110; -static PyObject *__pyx_k_111; -static PyObject *__pyx_k_116; -static PyObject *__pyx_k_151; -static PyObject *__pyx_k_tuple_2; -static PyObject *__pyx_k_tuple_3; -static PyObject *__pyx_k_tuple_4; -static PyObject *__pyx_k_tuple_5; -static PyObject *__pyx_k_tuple_6; -static PyObject *__pyx_k_tuple_7; -static PyObject *__pyx_k_tuple_8; -static PyObject *__pyx_k_slice_11; -static PyObject *__pyx_k_slice_12; -static PyObject *__pyx_k_tuple_10; -static PyObject *__pyx_k_tuple_14; -static PyObject *__pyx_k_tuple_16; -static PyObject *__pyx_k_tuple_19; -static PyObject *__pyx_k_tuple_21; -static PyObject *__pyx_k_tuple_23; -static PyObject *__pyx_k_tuple_25; -static PyObject *__pyx_k_tuple_27; -static PyObject *__pyx_k_tuple_29; -static PyObject *__pyx_k_tuple_31; -static PyObject *__pyx_k_tuple_33; -static PyObject *__pyx_k_tuple_35; -static PyObject *__pyx_k_tuple_37; -static PyObject *__pyx_k_tuple_38; -static PyObject *__pyx_k_tuple_39; -static PyObject *__pyx_k_tuple_45; -static PyObject *__pyx_k_tuple_46; -static PyObject *__pyx_k_tuple_48; -static PyObject *__pyx_k_tuple_50; -static PyObject *__pyx_k_tuple_51; -static PyObject *__pyx_k_tuple_52; -static PyObject *__pyx_k_tuple_54; -static PyObject *__pyx_k_tuple_55; -static PyObject *__pyx_k_tuple_57; -static PyObject *__pyx_k_tuple_58; -static PyObject *__pyx_k_tuple_60; -static PyObject *__pyx_k_tuple_61; -static PyObject *__pyx_k_tuple_62; -static PyObject *__pyx_k_tuple_63; -static PyObject *__pyx_k_tuple_64; -static PyObject *__pyx_k_tuple_65; -static PyObject *__pyx_k_tuple_67; -static PyObject *__pyx_k_tuple_69; -static PyObject *__pyx_k_tuple_71; -static PyObject *__pyx_k_tuple_72; -static PyObject *__pyx_k_tuple_74; -static PyObject *__pyx_k_tuple_75; -static PyObject *__pyx_k_tuple_76; -static PyObject *__pyx_k_tuple_77; -static PyObject *__pyx_k_tuple_79; -static PyObject *__pyx_k_tuple_80; -static PyObject *__pyx_k_tuple_81; -static PyObject *__pyx_k_tuple_83; -static PyObject *__pyx_k_tuple_85; -static PyObject *__pyx_k_tuple_86; -static PyObject *__pyx_k_tuple_87; -static PyObject *__pyx_k_tuple_88; -static PyObject *__pyx_k_tuple_90; -static PyObject *__pyx_k_tuple_91; -static PyObject *__pyx_k_tuple_92; -static PyObject *__pyx_k_tuple_93; -static PyObject *__pyx_k_tuple_94; -static PyObject *__pyx_k_tuple_95; -static PyObject *__pyx_k_tuple_96; -static PyObject *__pyx_k_tuple_97; -static PyObject *__pyx_k_slice_192; -static PyObject *__pyx_k_slice_196; -static PyObject *__pyx_k_tuple_100; -static PyObject *__pyx_k_tuple_101; -static PyObject *__pyx_k_tuple_104; -static PyObject *__pyx_k_tuple_105; -static PyObject *__pyx_k_tuple_108; -static PyObject *__pyx_k_tuple_109; -static PyObject *__pyx_k_tuple_113; -static PyObject *__pyx_k_tuple_115; -static PyObject *__pyx_k_tuple_117; -static PyObject *__pyx_k_tuple_119; -static PyObject *__pyx_k_tuple_121; -static PyObject *__pyx_k_tuple_122; -static PyObject *__pyx_k_tuple_124; -static PyObject *__pyx_k_tuple_125; -static PyObject *__pyx_k_tuple_127; -static PyObject *__pyx_k_tuple_129; -static PyObject *__pyx_k_tuple_131; -static PyObject *__pyx_k_tuple_132; -static PyObject *__pyx_k_tuple_133; -static PyObject *__pyx_k_tuple_134; -static PyObject *__pyx_k_tuple_136; -static PyObject *__pyx_k_tuple_138; -static PyObject *__pyx_k_tuple_140; -static PyObject *__pyx_k_tuple_141; -static PyObject *__pyx_k_tuple_142; -static PyObject *__pyx_k_tuple_143; -static PyObject *__pyx_k_tuple_145; -static PyObject *__pyx_k_tuple_146; -static PyObject *__pyx_k_tuple_147; -static PyObject *__pyx_k_tuple_148; -static PyObject *__pyx_k_tuple_149; -static PyObject *__pyx_k_tuple_150; -static PyObject *__pyx_k_tuple_153; -static PyObject *__pyx_k_tuple_155; -static PyObject *__pyx_k_tuple_156; -static PyObject *__pyx_k_tuple_158; -static PyObject *__pyx_k_tuple_160; -static PyObject *__pyx_k_tuple_161; -static PyObject *__pyx_k_tuple_163; -static PyObject *__pyx_k_tuple_165; -static PyObject *__pyx_k_tuple_166; -static PyObject *__pyx_k_tuple_167; -static PyObject *__pyx_k_tuple_169; -static PyObject *__pyx_k_tuple_171; -static PyObject *__pyx_k_tuple_173; -static PyObject *__pyx_k_tuple_175; -static PyObject *__pyx_k_tuple_176; -static PyObject *__pyx_k_tuple_177; -static PyObject *__pyx_k_tuple_178; -static PyObject *__pyx_k_tuple_179; -static PyObject *__pyx_k_tuple_181; -static PyObject *__pyx_k_tuple_183; -static PyObject *__pyx_k_tuple_184; -static PyObject *__pyx_k_tuple_185; -static PyObject *__pyx_k_tuple_187; -static PyObject *__pyx_k_tuple_189; -static PyObject *__pyx_k_tuple_191; -static PyObject *__pyx_k_tuple_195; -static PyObject *__pyx_k_tuple_197; -static PyObject *__pyx_k_tuple_198; - -/* "mtrand.pyx":129 - * import operator - * - * cdef object cont0_array(rk_state *state, rk_cont0 func, object size): # <<<<<<<<<<<<<< - * cdef double *array_data - * cdef ndarray array "arrayObject" - */ - -static PyObject *__pyx_f_6mtrand_cont0_array(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_cont0 __pyx_v_func, PyObject *__pyx_v_size) { - double *__pyx_v_array_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_length; - npy_intp __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - npy_intp __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cont0_array", 0); - - /* "mtrand.pyx":135 - * cdef npy_intp i - * - * if size is None: # <<<<<<<<<<<<<< - * return func(state) - * else: - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":136 - * - * if size is None: - * return func(state) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, np.float64) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_func(__pyx_v_state)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":138 - * return func(state) - * else: - * array = <ndarray>np.empty(size, np.float64) # <<<<<<<<<<<<<< - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 138; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_4; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":139 - * else: - * array = <ndarray>np.empty(size, np.float64) - * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < length: - */ - __pyx_v_length = PyArray_SIZE(arrayObject); - - /* "mtrand.pyx":140 - * array = <ndarray>np.empty(size, np.float64) - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < length: - * array_data[i] = func(state) - */ - __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":141 - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < length: # <<<<<<<<<<<<<< - * array_data[i] = func(state) - * return array - */ - __pyx_t_5 = __pyx_v_length; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_5; __pyx_v_i++) { - - /* "mtrand.pyx":142 - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < length: - * array_data[i] = func(state) # <<<<<<<<<<<<<< - * return array - * - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state); - } - - /* "mtrand.pyx":143 - * for i from 0 <= i < length: - * array_data[i] = func(state) - * return array # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - } - __pyx_L3:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("mtrand.cont0_array", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":146 - * - * - * cdef object cont1_array_sc(rk_state *state, rk_cont1 func, object size, double a): # <<<<<<<<<<<<<< - * cdef double *array_data - * cdef ndarray array "arrayObject" - */ - -static PyObject *__pyx_f_6mtrand_cont1_array_sc(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_cont1 __pyx_v_func, PyObject *__pyx_v_size, double __pyx_v_a) { - double *__pyx_v_array_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_length; - npy_intp __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - npy_intp __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cont1_array_sc", 0); - - /* "mtrand.pyx":152 - * cdef npy_intp i - * - * if size is None: # <<<<<<<<<<<<<< - * return func(state, a) - * else: - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":153 - * - * if size is None: - * return func(state, a) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, np.float64) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_func(__pyx_v_state, __pyx_v_a)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":155 - * return func(state, a) - * else: - * array = <ndarray>np.empty(size, np.float64) # <<<<<<<<<<<<<< - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_4; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":156 - * else: - * array = <ndarray>np.empty(size, np.float64) - * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < length: - */ - __pyx_v_length = PyArray_SIZE(arrayObject); - - /* "mtrand.pyx":157 - * array = <ndarray>np.empty(size, np.float64) - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < length: - * array_data[i] = func(state, a) - */ - __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":158 - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < length: # <<<<<<<<<<<<<< - * array_data[i] = func(state, a) - * return array - */ - __pyx_t_5 = __pyx_v_length; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_5; __pyx_v_i++) { - - /* "mtrand.pyx":159 - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < length: - * array_data[i] = func(state, a) # <<<<<<<<<<<<<< - * return array - * - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, __pyx_v_a); - } - - /* "mtrand.pyx":160 - * for i from 0 <= i < length: - * array_data[i] = func(state, a) - * return array # <<<<<<<<<<<<<< - * - * cdef object cont1_array(rk_state *state, rk_cont1 func, object size, ndarray oa): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - } - __pyx_L3:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("mtrand.cont1_array_sc", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":162 - * return array - * - * cdef object cont1_array(rk_state *state, rk_cont1 func, object size, ndarray oa): # <<<<<<<<<<<<<< - * cdef double *array_data - * cdef double *oa_data - */ - -static PyObject *__pyx_f_6mtrand_cont1_array(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_cont1 __pyx_v_func, PyObject *__pyx_v_size, PyArrayObject *__pyx_v_oa) { - double *__pyx_v_array_data; - double *__pyx_v_oa_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_length; - npy_intp __pyx_v_i; - PyArrayIterObject *__pyx_v_itera = 0; - PyArrayMultiIterObject *__pyx_v_multi = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - npy_intp __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cont1_array", 0); - - /* "mtrand.pyx":171 - * cdef broadcast multi - * - * if size is None: # <<<<<<<<<<<<<< - * array = <ndarray>PyArray_SimpleNew(PyArray_NDIM(oa), - * PyArray_DIMS(oa) , NPY_DOUBLE) - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":173 - * if size is None: - * array = <ndarray>PyArray_SimpleNew(PyArray_NDIM(oa), - * PyArray_DIMS(oa) , NPY_DOUBLE) # <<<<<<<<<<<<<< - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) - */ - __pyx_t_2 = PyArray_SimpleNew(PyArray_NDIM(__pyx_v_oa), PyArray_DIMS(__pyx_v_oa), NPY_DOUBLE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":174 - * array = <ndarray>PyArray_SimpleNew(PyArray_NDIM(oa), - * PyArray_DIMS(oa) , NPY_DOUBLE) - * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< - * array_data = <double *>PyArray_DATA(array) - * itera = <flatiter>PyArray_IterNew(<object>oa) - */ - __pyx_v_length = PyArray_SIZE(arrayObject); - - /* "mtrand.pyx":175 - * PyArray_DIMS(oa) , NPY_DOUBLE) - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * itera = <flatiter>PyArray_IterNew(<object>oa) - * for i from 0 <= i < length: - */ - __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":176 - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) - * itera = <flatiter>PyArray_IterNew(<object>oa) # <<<<<<<<<<<<<< - * for i from 0 <= i < length: - * array_data[i] = func(state, (<double *>(itera.dataptr))[0]) - */ - __pyx_t_3 = PyArray_IterNew(((PyObject *)__pyx_v_oa)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_itera = ((PyArrayIterObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":177 - * array_data = <double *>PyArray_DATA(array) - * itera = <flatiter>PyArray_IterNew(<object>oa) - * for i from 0 <= i < length: # <<<<<<<<<<<<<< - * array_data[i] = func(state, (<double *>(itera.dataptr))[0]) - * PyArray_ITER_NEXT(itera) - */ - __pyx_t_4 = __pyx_v_length; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - - /* "mtrand.pyx":178 - * itera = <flatiter>PyArray_IterNew(<object>oa) - * for i from 0 <= i < length: - * array_data[i] = func(state, (<double *>(itera.dataptr))[0]) # <<<<<<<<<<<<<< - * PyArray_ITER_NEXT(itera) - * else: - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, (((double *)__pyx_v_itera->dataptr)[0])); - - /* "mtrand.pyx":179 - * for i from 0 <= i < length: - * array_data[i] = func(state, (<double *>(itera.dataptr))[0]) - * PyArray_ITER_NEXT(itera) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, np.float64) - */ - PyArray_ITER_NEXT(__pyx_v_itera); - } - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":181 - * PyArray_ITER_NEXT(itera) - * else: - * array = <ndarray>np.empty(size, np.float64) # <<<<<<<<<<<<<< - * array_data = <double *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(2, <void *>array, - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_5; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":182 - * else: - * array = <ndarray>np.empty(size, np.float64) - * array_data = <double *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * multi = <broadcast>PyArray_MultiIterNew(2, <void *>array, - * <void *>oa) - */ - __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":184 - * array_data = <double *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(2, <void *>array, - * <void *>oa) # <<<<<<<<<<<<<< - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") - */ - __pyx_t_2 = PyArray_MultiIterNew(2, ((void *)arrayObject), ((void *)__pyx_v_oa)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_multi = ((PyArrayMultiIterObject *)__pyx_t_5); - __pyx_t_5 = 0; - - /* "mtrand.pyx":185 - * multi = <broadcast>PyArray_MultiIterNew(2, <void *>array, - * <void *>oa) - * if (multi.size != PyArray_SIZE(array)): # <<<<<<<<<<<<<< - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: - */ - __pyx_t_1 = (__pyx_v_multi->size != PyArray_SIZE(arrayObject)); - if (__pyx_t_1) { - - /* "mtrand.pyx":186 - * <void *>oa) - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":187 - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, oa_data[0]) - */ - __pyx_t_4 = __pyx_v_multi->size; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - - /* "mtrand.pyx":188 - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< - * array_data[i] = func(state, oa_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) - */ - __pyx_v_oa_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 1)); - - /* "mtrand.pyx":189 - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, oa_data[0]) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXTi(multi, 1) - * return array - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, (__pyx_v_oa_data[0])); - - /* "mtrand.pyx":190 - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, oa_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) # <<<<<<<<<<<<<< - * return array - * - */ - PyArray_MultiIter_NEXTi(__pyx_v_multi, 1); - } - } - __pyx_L3:; - - /* "mtrand.pyx":191 - * array_data[i] = func(state, oa_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) - * return array # <<<<<<<<<<<<<< - * - * cdef object cont2_array_sc(rk_state *state, rk_cont2 func, object size, double a, - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.cont1_array", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XDECREF((PyObject *)__pyx_v_itera); - __Pyx_XDECREF((PyObject *)__pyx_v_multi); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":193 - * return array - * - * cdef object cont2_array_sc(rk_state *state, rk_cont2 func, object size, double a, # <<<<<<<<<<<<<< - * double b): - * cdef double *array_data - */ - -static PyObject *__pyx_f_6mtrand_cont2_array_sc(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_cont2 __pyx_v_func, PyObject *__pyx_v_size, double __pyx_v_a, double __pyx_v_b) { - double *__pyx_v_array_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_length; - npy_intp __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - npy_intp __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cont2_array_sc", 0); - - /* "mtrand.pyx":200 - * cdef npy_intp i - * - * if size is None: # <<<<<<<<<<<<<< - * return func(state, a, b) - * else: - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":201 - * - * if size is None: - * return func(state, a, b) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, np.float64) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_func(__pyx_v_state, __pyx_v_a, __pyx_v_b)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":203 - * return func(state, a, b) - * else: - * array = <ndarray>np.empty(size, np.float64) # <<<<<<<<<<<<<< - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_4; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":204 - * else: - * array = <ndarray>np.empty(size, np.float64) - * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < length: - */ - __pyx_v_length = PyArray_SIZE(arrayObject); - - /* "mtrand.pyx":205 - * array = <ndarray>np.empty(size, np.float64) - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < length: - * array_data[i] = func(state, a, b) - */ - __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":206 - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < length: # <<<<<<<<<<<<<< - * array_data[i] = func(state, a, b) - * return array - */ - __pyx_t_5 = __pyx_v_length; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_5; __pyx_v_i++) { - - /* "mtrand.pyx":207 - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < length: - * array_data[i] = func(state, a, b) # <<<<<<<<<<<<<< - * return array - * - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, __pyx_v_a, __pyx_v_b); - } - - /* "mtrand.pyx":208 - * for i from 0 <= i < length: - * array_data[i] = func(state, a, b) - * return array # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - } - __pyx_L3:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("mtrand.cont2_array_sc", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":211 - * - * - * cdef object cont2_array(rk_state *state, rk_cont2 func, object size, # <<<<<<<<<<<<<< - * ndarray oa, ndarray ob): - * cdef double *array_data - */ - -static PyObject *__pyx_f_6mtrand_cont2_array(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_cont2 __pyx_v_func, PyObject *__pyx_v_size, PyArrayObject *__pyx_v_oa, PyArrayObject *__pyx_v_ob) { - double *__pyx_v_array_data; - double *__pyx_v_oa_data; - double *__pyx_v_ob_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_i; - PyArrayMultiIterObject *__pyx_v_multi = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - npy_intp __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cont2_array", 0); - - /* "mtrand.pyx":221 - * cdef broadcast multi - * - * if size is None: # <<<<<<<<<<<<<< - * multi = <broadcast> PyArray_MultiIterNew(2, <void *>oa, <void *>ob) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":222 - * - * if size is None: - * multi = <broadcast> PyArray_MultiIterNew(2, <void *>oa, <void *>ob) # <<<<<<<<<<<<<< - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) - * array_data = <double *>PyArray_DATA(array) - */ - __pyx_t_2 = PyArray_MultiIterNew(2, ((void *)__pyx_v_oa), ((void *)__pyx_v_ob)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_multi = ((PyArrayMultiIterObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":223 - * if size is None: - * multi = <broadcast> PyArray_MultiIterNew(2, <void *>oa, <void *>ob) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) # <<<<<<<<<<<<<< - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: - */ - __pyx_t_3 = PyArray_SimpleNew(__pyx_v_multi->nd, __pyx_v_multi->dimensions, NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":224 - * multi = <broadcast> PyArray_MultiIterNew(2, <void *>oa, <void *>ob) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) - * array_data = <double *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 0) - */ - __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":225 - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 0) - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_t_4 = __pyx_v_multi->size; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - - /* "mtrand.pyx":226 - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 0) # <<<<<<<<<<<<<< - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, oa_data[0], ob_data[0]) - */ - __pyx_v_oa_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 0)); - - /* "mtrand.pyx":227 - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 0) - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< - * array_data[i] = func(state, oa_data[0], ob_data[0]) - * PyArray_MultiIter_NEXT(multi) - */ - __pyx_v_ob_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 1)); - - /* "mtrand.pyx":228 - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 0) - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, oa_data[0], ob_data[0]) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXT(multi) - * else: - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, (__pyx_v_oa_data[0]), (__pyx_v_ob_data[0])); - - /* "mtrand.pyx":229 - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, oa_data[0], ob_data[0]) - * PyArray_MultiIter_NEXT(multi) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, np.float64) - */ - PyArray_MultiIter_NEXT(__pyx_v_multi); - } - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":231 - * PyArray_MultiIter_NEXT(multi) - * else: - * array = <ndarray>np.empty(size, np.float64) # <<<<<<<<<<<<<< - * array_data = <double *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>oa, <void *>ob) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_5; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":232 - * else: - * array = <ndarray>np.empty(size, np.float64) - * array_data = <double *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>oa, <void *>ob) - * if (multi.size != PyArray_SIZE(array)): - */ - __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":233 - * array = <ndarray>np.empty(size, np.float64) - * array_data = <double *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>oa, <void *>ob) # <<<<<<<<<<<<<< - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") - */ - __pyx_t_2 = PyArray_MultiIterNew(3, ((void *)arrayObject), ((void *)__pyx_v_oa), ((void *)__pyx_v_ob)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_multi = ((PyArrayMultiIterObject *)__pyx_t_5); - __pyx_t_5 = 0; - - /* "mtrand.pyx":234 - * array_data = <double *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>oa, <void *>ob) - * if (multi.size != PyArray_SIZE(array)): # <<<<<<<<<<<<<< - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: - */ - __pyx_t_1 = (__pyx_v_multi->size != PyArray_SIZE(arrayObject)); - if (__pyx_t_1) { - - /* "mtrand.pyx":235 - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>oa, <void *>ob) - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":236 - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 2) - */ - __pyx_t_4 = __pyx_v_multi->size; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - - /* "mtrand.pyx":237 - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, oa_data[0], ob_data[0]) - */ - __pyx_v_oa_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 1)); - - /* "mtrand.pyx":238 - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 2) # <<<<<<<<<<<<<< - * array_data[i] = func(state, oa_data[0], ob_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) - */ - __pyx_v_ob_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 2)); - - /* "mtrand.pyx":239 - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, oa_data[0], ob_data[0]) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXTi(multi, 1) - * PyArray_MultiIter_NEXTi(multi, 2) - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, (__pyx_v_oa_data[0]), (__pyx_v_ob_data[0])); - - /* "mtrand.pyx":240 - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, oa_data[0], ob_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXTi(multi, 2) - * return array - */ - PyArray_MultiIter_NEXTi(__pyx_v_multi, 1); - - /* "mtrand.pyx":241 - * array_data[i] = func(state, oa_data[0], ob_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) - * PyArray_MultiIter_NEXTi(multi, 2) # <<<<<<<<<<<<<< - * return array - * - */ - PyArray_MultiIter_NEXTi(__pyx_v_multi, 2); - } - } - __pyx_L3:; - - /* "mtrand.pyx":242 - * PyArray_MultiIter_NEXTi(multi, 1) - * PyArray_MultiIter_NEXTi(multi, 2) - * return array # <<<<<<<<<<<<<< - * - * cdef object cont3_array_sc(rk_state *state, rk_cont3 func, object size, double a, - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.cont2_array", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XDECREF((PyObject *)__pyx_v_multi); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":244 - * return array - * - * cdef object cont3_array_sc(rk_state *state, rk_cont3 func, object size, double a, # <<<<<<<<<<<<<< - * double b, double c): - * - */ - -static PyObject *__pyx_f_6mtrand_cont3_array_sc(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_cont3 __pyx_v_func, PyObject *__pyx_v_size, double __pyx_v_a, double __pyx_v_b, double __pyx_v_c) { - double *__pyx_v_array_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_length; - npy_intp __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - npy_intp __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cont3_array_sc", 0); - - /* "mtrand.pyx":252 - * cdef npy_intp i - * - * if size is None: # <<<<<<<<<<<<<< - * return func(state, a, b, c) - * else: - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":253 - * - * if size is None: - * return func(state, a, b, c) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, np.float64) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyFloat_FromDouble(__pyx_v_func(__pyx_v_state, __pyx_v_a, __pyx_v_b, __pyx_v_c)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":255 - * return func(state, a, b, c) - * else: - * array = <ndarray>np.empty(size, np.float64) # <<<<<<<<<<<<<< - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_4; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":256 - * else: - * array = <ndarray>np.empty(size, np.float64) - * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < length: - */ - __pyx_v_length = PyArray_SIZE(arrayObject); - - /* "mtrand.pyx":257 - * array = <ndarray>np.empty(size, np.float64) - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < length: - * array_data[i] = func(state, a, b, c) - */ - __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":258 - * length = PyArray_SIZE(array) - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < length: # <<<<<<<<<<<<<< - * array_data[i] = func(state, a, b, c) - * return array - */ - __pyx_t_5 = __pyx_v_length; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_5; __pyx_v_i++) { - - /* "mtrand.pyx":259 - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < length: - * array_data[i] = func(state, a, b, c) # <<<<<<<<<<<<<< - * return array - * - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, __pyx_v_a, __pyx_v_b, __pyx_v_c); - } - - /* "mtrand.pyx":260 - * for i from 0 <= i < length: - * array_data[i] = func(state, a, b, c) - * return array # <<<<<<<<<<<<<< - * - * cdef object cont3_array(rk_state *state, rk_cont3 func, object size, ndarray oa, - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - } - __pyx_L3:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("mtrand.cont3_array_sc", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":262 - * return array - * - * cdef object cont3_array(rk_state *state, rk_cont3 func, object size, ndarray oa, # <<<<<<<<<<<<<< - * ndarray ob, ndarray oc): - * - */ - -static PyObject *__pyx_f_6mtrand_cont3_array(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_cont3 __pyx_v_func, PyObject *__pyx_v_size, PyArrayObject *__pyx_v_oa, PyArrayObject *__pyx_v_ob, PyArrayObject *__pyx_v_oc) { - double *__pyx_v_array_data; - double *__pyx_v_oa_data; - double *__pyx_v_ob_data; - double *__pyx_v_oc_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_i; - PyArrayMultiIterObject *__pyx_v_multi = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - npy_intp __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cont3_array", 0); - - /* "mtrand.pyx":274 - * cdef broadcast multi - * - * if size is None: # <<<<<<<<<<<<<< - * multi = <broadcast> PyArray_MultiIterNew(3, <void *>oa, <void *>ob, <void *>oc) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":275 - * - * if size is None: - * multi = <broadcast> PyArray_MultiIterNew(3, <void *>oa, <void *>ob, <void *>oc) # <<<<<<<<<<<<<< - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) - * array_data = <double *>PyArray_DATA(array) - */ - __pyx_t_2 = PyArray_MultiIterNew(3, ((void *)__pyx_v_oa), ((void *)__pyx_v_ob), ((void *)__pyx_v_oc)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_multi = ((PyArrayMultiIterObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":276 - * if size is None: - * multi = <broadcast> PyArray_MultiIterNew(3, <void *>oa, <void *>ob, <void *>oc) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) # <<<<<<<<<<<<<< - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: - */ - __pyx_t_3 = PyArray_SimpleNew(__pyx_v_multi->nd, __pyx_v_multi->dimensions, NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":277 - * multi = <broadcast> PyArray_MultiIterNew(3, <void *>oa, <void *>ob, <void *>oc) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) - * array_data = <double *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 0) - */ - __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":278 - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 0) - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_t_4 = __pyx_v_multi->size; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - - /* "mtrand.pyx":279 - * array_data = <double *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 0) # <<<<<<<<<<<<<< - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * oc_data = <double *>PyArray_MultiIter_DATA(multi, 2) - */ - __pyx_v_oa_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 0)); - - /* "mtrand.pyx":280 - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 0) - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< - * oc_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, oa_data[0], ob_data[0], oc_data[0]) - */ - __pyx_v_ob_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 1)); - - /* "mtrand.pyx":281 - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 0) - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * oc_data = <double *>PyArray_MultiIter_DATA(multi, 2) # <<<<<<<<<<<<<< - * array_data[i] = func(state, oa_data[0], ob_data[0], oc_data[0]) - * PyArray_MultiIter_NEXT(multi) - */ - __pyx_v_oc_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 2)); - - /* "mtrand.pyx":282 - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * oc_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, oa_data[0], ob_data[0], oc_data[0]) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXT(multi) - * else: - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, (__pyx_v_oa_data[0]), (__pyx_v_ob_data[0]), (__pyx_v_oc_data[0])); - - /* "mtrand.pyx":283 - * oc_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, oa_data[0], ob_data[0], oc_data[0]) - * PyArray_MultiIter_NEXT(multi) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, np.float64) - */ - PyArray_MultiIter_NEXT(__pyx_v_multi); - } - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":285 - * PyArray_MultiIter_NEXT(multi) - * else: - * array = <ndarray>np.empty(size, np.float64) # <<<<<<<<<<<<<< - * array_data = <double *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(4, <void*>array, <void *>oa, - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_5; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":286 - * else: - * array = <ndarray>np.empty(size, np.float64) - * array_data = <double *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * multi = <broadcast>PyArray_MultiIterNew(4, <void*>array, <void *>oa, - * <void *>ob, <void *>oc) - */ - __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":288 - * array_data = <double *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(4, <void*>array, <void *>oa, - * <void *>ob, <void *>oc) # <<<<<<<<<<<<<< - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") - */ - __pyx_t_2 = PyArray_MultiIterNew(4, ((void *)arrayObject), ((void *)__pyx_v_oa), ((void *)__pyx_v_ob), ((void *)__pyx_v_oc)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_multi = ((PyArrayMultiIterObject *)__pyx_t_5); - __pyx_t_5 = 0; - - /* "mtrand.pyx":289 - * multi = <broadcast>PyArray_MultiIterNew(4, <void*>array, <void *>oa, - * <void *>ob, <void *>oc) - * if (multi.size != PyArray_SIZE(array)): # <<<<<<<<<<<<<< - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: - */ - __pyx_t_1 = (__pyx_v_multi->size != PyArray_SIZE(arrayObject)); - if (__pyx_t_1) { - - /* "mtrand.pyx":290 - * <void *>ob, <void *>oc) - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_4), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":291 - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 2) - */ - __pyx_t_4 = __pyx_v_multi->size; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - - /* "mtrand.pyx":292 - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * oc_data = <double *>PyArray_MultiIter_DATA(multi, 3) - */ - __pyx_v_oa_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 1)); - - /* "mtrand.pyx":293 - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 2) # <<<<<<<<<<<<<< - * oc_data = <double *>PyArray_MultiIter_DATA(multi, 3) - * array_data[i] = func(state, oa_data[0], ob_data[0], oc_data[0]) - */ - __pyx_v_ob_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 2)); - - /* "mtrand.pyx":294 - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * oc_data = <double *>PyArray_MultiIter_DATA(multi, 3) # <<<<<<<<<<<<<< - * array_data[i] = func(state, oa_data[0], ob_data[0], oc_data[0]) - * PyArray_MultiIter_NEXT(multi) - */ - __pyx_v_oc_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 3)); - - /* "mtrand.pyx":295 - * ob_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * oc_data = <double *>PyArray_MultiIter_DATA(multi, 3) - * array_data[i] = func(state, oa_data[0], ob_data[0], oc_data[0]) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXT(multi) - * return array - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, (__pyx_v_oa_data[0]), (__pyx_v_ob_data[0]), (__pyx_v_oc_data[0])); - - /* "mtrand.pyx":296 - * oc_data = <double *>PyArray_MultiIter_DATA(multi, 3) - * array_data[i] = func(state, oa_data[0], ob_data[0], oc_data[0]) - * PyArray_MultiIter_NEXT(multi) # <<<<<<<<<<<<<< - * return array - * - */ - PyArray_MultiIter_NEXT(__pyx_v_multi); - } - } - __pyx_L3:; - - /* "mtrand.pyx":297 - * array_data[i] = func(state, oa_data[0], ob_data[0], oc_data[0]) - * PyArray_MultiIter_NEXT(multi) - * return array # <<<<<<<<<<<<<< - * - * cdef object disc0_array(rk_state *state, rk_disc0 func, object size): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.cont3_array", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XDECREF((PyObject *)__pyx_v_multi); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":299 - * return array - * - * cdef object disc0_array(rk_state *state, rk_disc0 func, object size): # <<<<<<<<<<<<<< - * cdef long *array_data - * cdef ndarray array "arrayObject" - */ - -static PyObject *__pyx_f_6mtrand_disc0_array(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_disc0 __pyx_v_func, PyObject *__pyx_v_size) { - long *__pyx_v_array_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_length; - npy_intp __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - npy_intp __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("disc0_array", 0); - - /* "mtrand.pyx":305 - * cdef npy_intp i - * - * if size is None: # <<<<<<<<<<<<<< - * return func(state) - * else: - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":306 - * - * if size is None: - * return func(state) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, int) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyInt_FromLong(__pyx_v_func(__pyx_v_state)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 306; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":308 - * return func(state) - * else: - * array = <ndarray>np.empty(size, int) # <<<<<<<<<<<<<< - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_4; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":309 - * else: - * array = <ndarray>np.empty(size, int) - * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: - */ - __pyx_v_length = PyArray_SIZE(arrayObject); - - /* "mtrand.pyx":310 - * array = <ndarray>np.empty(size, int) - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < length: - * array_data[i] = func(state) - */ - __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":311 - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: # <<<<<<<<<<<<<< - * array_data[i] = func(state) - * return array - */ - __pyx_t_5 = __pyx_v_length; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_5; __pyx_v_i++) { - - /* "mtrand.pyx":312 - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: - * array_data[i] = func(state) # <<<<<<<<<<<<<< - * return array - * - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state); - } - - /* "mtrand.pyx":313 - * for i from 0 <= i < length: - * array_data[i] = func(state) - * return array # <<<<<<<<<<<<<< - * - * cdef object discnp_array_sc(rk_state *state, rk_discnp func, object size, long n, double p): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - } - __pyx_L3:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("mtrand.disc0_array", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":315 - * return array - * - * cdef object discnp_array_sc(rk_state *state, rk_discnp func, object size, long n, double p): # <<<<<<<<<<<<<< - * cdef long *array_data - * cdef ndarray array "arrayObject" - */ - -static PyObject *__pyx_f_6mtrand_discnp_array_sc(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_discnp __pyx_v_func, PyObject *__pyx_v_size, long __pyx_v_n, double __pyx_v_p) { - long *__pyx_v_array_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_length; - npy_intp __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - npy_intp __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("discnp_array_sc", 0); - - /* "mtrand.pyx":321 - * cdef npy_intp i - * - * if size is None: # <<<<<<<<<<<<<< - * return func(state, n, p) - * else: - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":322 - * - * if size is None: - * return func(state, n, p) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, int) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyInt_FromLong(__pyx_v_func(__pyx_v_state, __pyx_v_n, __pyx_v_p)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 322; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":324 - * return func(state, n, p) - * else: - * array = <ndarray>np.empty(size, int) # <<<<<<<<<<<<<< - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_4; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":325 - * else: - * array = <ndarray>np.empty(size, int) - * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: - */ - __pyx_v_length = PyArray_SIZE(arrayObject); - - /* "mtrand.pyx":326 - * array = <ndarray>np.empty(size, int) - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < length: - * array_data[i] = func(state, n, p) - */ - __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":327 - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: # <<<<<<<<<<<<<< - * array_data[i] = func(state, n, p) - * return array - */ - __pyx_t_5 = __pyx_v_length; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_5; __pyx_v_i++) { - - /* "mtrand.pyx":328 - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: - * array_data[i] = func(state, n, p) # <<<<<<<<<<<<<< - * return array - * - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, __pyx_v_n, __pyx_v_p); - } - - /* "mtrand.pyx":329 - * for i from 0 <= i < length: - * array_data[i] = func(state, n, p) - * return array # <<<<<<<<<<<<<< - * - * cdef object discnp_array(rk_state *state, rk_discnp func, object size, ndarray on, ndarray op): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - } - __pyx_L3:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("mtrand.discnp_array_sc", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":331 - * return array - * - * cdef object discnp_array(rk_state *state, rk_discnp func, object size, ndarray on, ndarray op): # <<<<<<<<<<<<<< - * cdef long *array_data - * cdef ndarray array "arrayObject" - */ - -static PyObject *__pyx_f_6mtrand_discnp_array(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_discnp __pyx_v_func, PyObject *__pyx_v_size, PyArrayObject *__pyx_v_on, PyArrayObject *__pyx_v_op) { - long *__pyx_v_array_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_i; - double *__pyx_v_op_data; - long *__pyx_v_on_data; - PyArrayMultiIterObject *__pyx_v_multi = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - npy_intp __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("discnp_array", 0); - - /* "mtrand.pyx":340 - * cdef broadcast multi - * - * if size is None: # <<<<<<<<<<<<<< - * multi = <broadcast> PyArray_MultiIterNew(2, <void *>on, <void *>op) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":341 - * - * if size is None: - * multi = <broadcast> PyArray_MultiIterNew(2, <void *>on, <void *>op) # <<<<<<<<<<<<<< - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) - * array_data = <long *>PyArray_DATA(array) - */ - __pyx_t_2 = PyArray_MultiIterNew(2, ((void *)__pyx_v_on), ((void *)__pyx_v_op)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 341; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_multi = ((PyArrayMultiIterObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":342 - * if size is None: - * multi = <broadcast> PyArray_MultiIterNew(2, <void *>on, <void *>op) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) # <<<<<<<<<<<<<< - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: - */ - __pyx_t_3 = PyArray_SimpleNew(__pyx_v_multi->nd, __pyx_v_multi->dimensions, NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 342; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":343 - * multi = <broadcast> PyArray_MultiIterNew(2, <void *>on, <void *>op) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) - * array_data = <long *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * on_data = <long *>PyArray_MultiIter_DATA(multi, 0) - */ - __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":344 - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< - * on_data = <long *>PyArray_MultiIter_DATA(multi, 0) - * op_data = <double *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_t_4 = __pyx_v_multi->size; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - - /* "mtrand.pyx":345 - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: - * on_data = <long *>PyArray_MultiIter_DATA(multi, 0) # <<<<<<<<<<<<<< - * op_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, on_data[0], op_data[0]) - */ - __pyx_v_on_data = ((long *)PyArray_MultiIter_DATA(__pyx_v_multi, 0)); - - /* "mtrand.pyx":346 - * for i from 0 <= i < multi.size: - * on_data = <long *>PyArray_MultiIter_DATA(multi, 0) - * op_data = <double *>PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< - * array_data[i] = func(state, on_data[0], op_data[0]) - * PyArray_MultiIter_NEXT(multi) - */ - __pyx_v_op_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 1)); - - /* "mtrand.pyx":347 - * on_data = <long *>PyArray_MultiIter_DATA(multi, 0) - * op_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, on_data[0], op_data[0]) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXT(multi) - * else: - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, (__pyx_v_on_data[0]), (__pyx_v_op_data[0])); - - /* "mtrand.pyx":348 - * op_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, on_data[0], op_data[0]) - * PyArray_MultiIter_NEXT(multi) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, int) - */ - PyArray_MultiIter_NEXT(__pyx_v_multi); - } - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":350 - * PyArray_MultiIter_NEXT(multi) - * else: - * array = <ndarray>np.empty(size, int) # <<<<<<<<<<<<<< - * array_data = <long *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>on, <void *>op) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_5; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":351 - * else: - * array = <ndarray>np.empty(size, int) - * array_data = <long *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>on, <void *>op) - * if (multi.size != PyArray_SIZE(array)): - */ - __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":352 - * array = <ndarray>np.empty(size, int) - * array_data = <long *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>on, <void *>op) # <<<<<<<<<<<<<< - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") - */ - __pyx_t_2 = PyArray_MultiIterNew(3, ((void *)arrayObject), ((void *)__pyx_v_on), ((void *)__pyx_v_op)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_multi = ((PyArrayMultiIterObject *)__pyx_t_5); - __pyx_t_5 = 0; - - /* "mtrand.pyx":353 - * array_data = <long *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>on, <void *>op) - * if (multi.size != PyArray_SIZE(array)): # <<<<<<<<<<<<<< - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: - */ - __pyx_t_1 = (__pyx_v_multi->size != PyArray_SIZE(arrayObject)); - if (__pyx_t_1) { - - /* "mtrand.pyx":354 - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>on, <void *>op) - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * on_data = <long *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_5), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 354; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 354; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":355 - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< - * on_data = <long *>PyArray_MultiIter_DATA(multi, 1) - * op_data = <double *>PyArray_MultiIter_DATA(multi, 2) - */ - __pyx_t_4 = __pyx_v_multi->size; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - - /* "mtrand.pyx":356 - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: - * on_data = <long *>PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< - * op_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, on_data[0], op_data[0]) - */ - __pyx_v_on_data = ((long *)PyArray_MultiIter_DATA(__pyx_v_multi, 1)); - - /* "mtrand.pyx":357 - * for i from 0 <= i < multi.size: - * on_data = <long *>PyArray_MultiIter_DATA(multi, 1) - * op_data = <double *>PyArray_MultiIter_DATA(multi, 2) # <<<<<<<<<<<<<< - * array_data[i] = func(state, on_data[0], op_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) - */ - __pyx_v_op_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 2)); - - /* "mtrand.pyx":358 - * on_data = <long *>PyArray_MultiIter_DATA(multi, 1) - * op_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, on_data[0], op_data[0]) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXTi(multi, 1) - * PyArray_MultiIter_NEXTi(multi, 2) - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, (__pyx_v_on_data[0]), (__pyx_v_op_data[0])); - - /* "mtrand.pyx":359 - * op_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, on_data[0], op_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXTi(multi, 2) - * - */ - PyArray_MultiIter_NEXTi(__pyx_v_multi, 1); - - /* "mtrand.pyx":360 - * array_data[i] = func(state, on_data[0], op_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) - * PyArray_MultiIter_NEXTi(multi, 2) # <<<<<<<<<<<<<< - * - * return array - */ - PyArray_MultiIter_NEXTi(__pyx_v_multi, 2); - } - } - __pyx_L3:; - - /* "mtrand.pyx":362 - * PyArray_MultiIter_NEXTi(multi, 2) - * - * return array # <<<<<<<<<<<<<< - * - * cdef object discdd_array_sc(rk_state *state, rk_discdd func, object size, double n, double p): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.discnp_array", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XDECREF((PyObject *)__pyx_v_multi); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":364 - * return array - * - * cdef object discdd_array_sc(rk_state *state, rk_discdd func, object size, double n, double p): # <<<<<<<<<<<<<< - * cdef long *array_data - * cdef ndarray array "arrayObject" - */ - -static PyObject *__pyx_f_6mtrand_discdd_array_sc(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_discdd __pyx_v_func, PyObject *__pyx_v_size, double __pyx_v_n, double __pyx_v_p) { - long *__pyx_v_array_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_length; - npy_intp __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - npy_intp __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("discdd_array_sc", 0); - - /* "mtrand.pyx":370 - * cdef npy_intp i - * - * if size is None: # <<<<<<<<<<<<<< - * return func(state, n, p) - * else: - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":371 - * - * if size is None: - * return func(state, n, p) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, int) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyInt_FromLong(__pyx_v_func(__pyx_v_state, __pyx_v_n, __pyx_v_p)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 371; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":373 - * return func(state, n, p) - * else: - * array = <ndarray>np.empty(size, int) # <<<<<<<<<<<<<< - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_4; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":374 - * else: - * array = <ndarray>np.empty(size, int) - * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: - */ - __pyx_v_length = PyArray_SIZE(arrayObject); - - /* "mtrand.pyx":375 - * array = <ndarray>np.empty(size, int) - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < length: - * array_data[i] = func(state, n, p) - */ - __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":376 - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: # <<<<<<<<<<<<<< - * array_data[i] = func(state, n, p) - * return array - */ - __pyx_t_5 = __pyx_v_length; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_5; __pyx_v_i++) { - - /* "mtrand.pyx":377 - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: - * array_data[i] = func(state, n, p) # <<<<<<<<<<<<<< - * return array - * - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, __pyx_v_n, __pyx_v_p); - } - - /* "mtrand.pyx":378 - * for i from 0 <= i < length: - * array_data[i] = func(state, n, p) - * return array # <<<<<<<<<<<<<< - * - * cdef object discdd_array(rk_state *state, rk_discdd func, object size, ndarray on, ndarray op): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - } - __pyx_L3:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("mtrand.discdd_array_sc", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":380 - * return array - * - * cdef object discdd_array(rk_state *state, rk_discdd func, object size, ndarray on, ndarray op): # <<<<<<<<<<<<<< - * cdef long *array_data - * cdef ndarray array "arrayObject" - */ - -static PyObject *__pyx_f_6mtrand_discdd_array(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_discdd __pyx_v_func, PyObject *__pyx_v_size, PyArrayObject *__pyx_v_on, PyArrayObject *__pyx_v_op) { - long *__pyx_v_array_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_i; - double *__pyx_v_op_data; - double *__pyx_v_on_data; - PyArrayMultiIterObject *__pyx_v_multi = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - npy_intp __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("discdd_array", 0); - - /* "mtrand.pyx":389 - * cdef broadcast multi - * - * if size is None: # <<<<<<<<<<<<<< - * multi = <broadcast> PyArray_MultiIterNew(2, <void *>on, <void *>op) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":390 - * - * if size is None: - * multi = <broadcast> PyArray_MultiIterNew(2, <void *>on, <void *>op) # <<<<<<<<<<<<<< - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) - * array_data = <long *>PyArray_DATA(array) - */ - __pyx_t_2 = PyArray_MultiIterNew(2, ((void *)__pyx_v_on), ((void *)__pyx_v_op)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_multi = ((PyArrayMultiIterObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":391 - * if size is None: - * multi = <broadcast> PyArray_MultiIterNew(2, <void *>on, <void *>op) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) # <<<<<<<<<<<<<< - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: - */ - __pyx_t_3 = PyArray_SimpleNew(__pyx_v_multi->nd, __pyx_v_multi->dimensions, NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":392 - * multi = <broadcast> PyArray_MultiIterNew(2, <void *>on, <void *>op) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) - * array_data = <long *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * on_data = <double *>PyArray_MultiIter_DATA(multi, 0) - */ - __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":393 - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< - * on_data = <double *>PyArray_MultiIter_DATA(multi, 0) - * op_data = <double *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_t_4 = __pyx_v_multi->size; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - - /* "mtrand.pyx":394 - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: - * on_data = <double *>PyArray_MultiIter_DATA(multi, 0) # <<<<<<<<<<<<<< - * op_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, on_data[0], op_data[0]) - */ - __pyx_v_on_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 0)); - - /* "mtrand.pyx":395 - * for i from 0 <= i < multi.size: - * on_data = <double *>PyArray_MultiIter_DATA(multi, 0) - * op_data = <double *>PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< - * array_data[i] = func(state, on_data[0], op_data[0]) - * PyArray_MultiIter_NEXT(multi) - */ - __pyx_v_op_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 1)); - - /* "mtrand.pyx":396 - * on_data = <double *>PyArray_MultiIter_DATA(multi, 0) - * op_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, on_data[0], op_data[0]) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXT(multi) - * else: - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, (__pyx_v_on_data[0]), (__pyx_v_op_data[0])); - - /* "mtrand.pyx":397 - * op_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, on_data[0], op_data[0]) - * PyArray_MultiIter_NEXT(multi) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, int) - */ - PyArray_MultiIter_NEXT(__pyx_v_multi); - } - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":399 - * PyArray_MultiIter_NEXT(multi) - * else: - * array = <ndarray>np.empty(size, int) # <<<<<<<<<<<<<< - * array_data = <long *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>on, <void *>op) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_5; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":400 - * else: - * array = <ndarray>np.empty(size, int) - * array_data = <long *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>on, <void *>op) - * if (multi.size != PyArray_SIZE(array)): - */ - __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":401 - * array = <ndarray>np.empty(size, int) - * array_data = <long *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>on, <void *>op) # <<<<<<<<<<<<<< - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") - */ - __pyx_t_2 = PyArray_MultiIterNew(3, ((void *)arrayObject), ((void *)__pyx_v_on), ((void *)__pyx_v_op)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_multi = ((PyArrayMultiIterObject *)__pyx_t_5); - __pyx_t_5 = 0; - - /* "mtrand.pyx":402 - * array_data = <long *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>on, <void *>op) - * if (multi.size != PyArray_SIZE(array)): # <<<<<<<<<<<<<< - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: - */ - __pyx_t_1 = (__pyx_v_multi->size != PyArray_SIZE(arrayObject)); - if (__pyx_t_1) { - - /* "mtrand.pyx":403 - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>on, <void *>op) - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * on_data = <double *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_6), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":404 - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< - * on_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * op_data = <double *>PyArray_MultiIter_DATA(multi, 2) - */ - __pyx_t_4 = __pyx_v_multi->size; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - - /* "mtrand.pyx":405 - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: - * on_data = <double *>PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< - * op_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, on_data[0], op_data[0]) - */ - __pyx_v_on_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 1)); - - /* "mtrand.pyx":406 - * for i from 0 <= i < multi.size: - * on_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * op_data = <double *>PyArray_MultiIter_DATA(multi, 2) # <<<<<<<<<<<<<< - * array_data[i] = func(state, on_data[0], op_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) - */ - __pyx_v_op_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 2)); - - /* "mtrand.pyx":407 - * on_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * op_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, on_data[0], op_data[0]) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXTi(multi, 1) - * PyArray_MultiIter_NEXTi(multi, 2) - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, (__pyx_v_on_data[0]), (__pyx_v_op_data[0])); - - /* "mtrand.pyx":408 - * op_data = <double *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, on_data[0], op_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXTi(multi, 2) - * - */ - PyArray_MultiIter_NEXTi(__pyx_v_multi, 1); - - /* "mtrand.pyx":409 - * array_data[i] = func(state, on_data[0], op_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) - * PyArray_MultiIter_NEXTi(multi, 2) # <<<<<<<<<<<<<< - * - * return array - */ - PyArray_MultiIter_NEXTi(__pyx_v_multi, 2); - } - } - __pyx_L3:; - - /* "mtrand.pyx":411 - * PyArray_MultiIter_NEXTi(multi, 2) - * - * return array # <<<<<<<<<<<<<< - * - * cdef object discnmN_array_sc(rk_state *state, rk_discnmN func, object size, - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.discdd_array", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XDECREF((PyObject *)__pyx_v_multi); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":413 - * return array - * - * cdef object discnmN_array_sc(rk_state *state, rk_discnmN func, object size, # <<<<<<<<<<<<<< - * long n, long m, long N): - * cdef long *array_data - */ - -static PyObject *__pyx_f_6mtrand_discnmN_array_sc(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_discnmN __pyx_v_func, PyObject *__pyx_v_size, long __pyx_v_n, long __pyx_v_m, long __pyx_v_N) { - long *__pyx_v_array_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_length; - npy_intp __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - npy_intp __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("discnmN_array_sc", 0); - - /* "mtrand.pyx":420 - * cdef npy_intp i - * - * if size is None: # <<<<<<<<<<<<<< - * return func(state, n, m, N) - * else: - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":421 - * - * if size is None: - * return func(state, n, m, N) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, int) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyInt_FromLong(__pyx_v_func(__pyx_v_state, __pyx_v_n, __pyx_v_m, __pyx_v_N)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":423 - * return func(state, n, m, N) - * else: - * array = <ndarray>np.empty(size, int) # <<<<<<<<<<<<<< - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_4; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":424 - * else: - * array = <ndarray>np.empty(size, int) - * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: - */ - __pyx_v_length = PyArray_SIZE(arrayObject); - - /* "mtrand.pyx":425 - * array = <ndarray>np.empty(size, int) - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < length: - * array_data[i] = func(state, n, m, N) - */ - __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":426 - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: # <<<<<<<<<<<<<< - * array_data[i] = func(state, n, m, N) - * return array - */ - __pyx_t_5 = __pyx_v_length; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_5; __pyx_v_i++) { - - /* "mtrand.pyx":427 - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: - * array_data[i] = func(state, n, m, N) # <<<<<<<<<<<<<< - * return array - * - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, __pyx_v_n, __pyx_v_m, __pyx_v_N); - } - - /* "mtrand.pyx":428 - * for i from 0 <= i < length: - * array_data[i] = func(state, n, m, N) - * return array # <<<<<<<<<<<<<< - * - * cdef object discnmN_array(rk_state *state, rk_discnmN func, object size, - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - } - __pyx_L3:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("mtrand.discnmN_array_sc", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":430 - * return array - * - * cdef object discnmN_array(rk_state *state, rk_discnmN func, object size, # <<<<<<<<<<<<<< - * ndarray on, ndarray om, ndarray oN): - * cdef long *array_data - */ - -static PyObject *__pyx_f_6mtrand_discnmN_array(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_discnmN __pyx_v_func, PyObject *__pyx_v_size, PyArrayObject *__pyx_v_on, PyArrayObject *__pyx_v_om, PyArrayObject *__pyx_v_oN) { - long *__pyx_v_array_data; - long *__pyx_v_on_data; - long *__pyx_v_om_data; - long *__pyx_v_oN_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_i; - PyArrayMultiIterObject *__pyx_v_multi = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - npy_intp __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("discnmN_array", 0); - - /* "mtrand.pyx":441 - * cdef broadcast multi - * - * if size is None: # <<<<<<<<<<<<<< - * multi = <broadcast> PyArray_MultiIterNew(3, <void *>on, <void *>om, <void *>oN) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":442 - * - * if size is None: - * multi = <broadcast> PyArray_MultiIterNew(3, <void *>on, <void *>om, <void *>oN) # <<<<<<<<<<<<<< - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) - * array_data = <long *>PyArray_DATA(array) - */ - __pyx_t_2 = PyArray_MultiIterNew(3, ((void *)__pyx_v_on), ((void *)__pyx_v_om), ((void *)__pyx_v_oN)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 442; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_multi = ((PyArrayMultiIterObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":443 - * if size is None: - * multi = <broadcast> PyArray_MultiIterNew(3, <void *>on, <void *>om, <void *>oN) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) # <<<<<<<<<<<<<< - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: - */ - __pyx_t_3 = PyArray_SimpleNew(__pyx_v_multi->nd, __pyx_v_multi->dimensions, NPY_LONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":444 - * multi = <broadcast> PyArray_MultiIterNew(3, <void *>on, <void *>om, <void *>oN) - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) - * array_data = <long *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * on_data = <long *>PyArray_MultiIter_DATA(multi, 0) - */ - __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":445 - * array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< - * on_data = <long *>PyArray_MultiIter_DATA(multi, 0) - * om_data = <long *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_t_4 = __pyx_v_multi->size; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - - /* "mtrand.pyx":446 - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < multi.size: - * on_data = <long *>PyArray_MultiIter_DATA(multi, 0) # <<<<<<<<<<<<<< - * om_data = <long *>PyArray_MultiIter_DATA(multi, 1) - * oN_data = <long *>PyArray_MultiIter_DATA(multi, 2) - */ - __pyx_v_on_data = ((long *)PyArray_MultiIter_DATA(__pyx_v_multi, 0)); - - /* "mtrand.pyx":447 - * for i from 0 <= i < multi.size: - * on_data = <long *>PyArray_MultiIter_DATA(multi, 0) - * om_data = <long *>PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< - * oN_data = <long *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, on_data[0], om_data[0], oN_data[0]) - */ - __pyx_v_om_data = ((long *)PyArray_MultiIter_DATA(__pyx_v_multi, 1)); - - /* "mtrand.pyx":448 - * on_data = <long *>PyArray_MultiIter_DATA(multi, 0) - * om_data = <long *>PyArray_MultiIter_DATA(multi, 1) - * oN_data = <long *>PyArray_MultiIter_DATA(multi, 2) # <<<<<<<<<<<<<< - * array_data[i] = func(state, on_data[0], om_data[0], oN_data[0]) - * PyArray_MultiIter_NEXT(multi) - */ - __pyx_v_oN_data = ((long *)PyArray_MultiIter_DATA(__pyx_v_multi, 2)); - - /* "mtrand.pyx":449 - * om_data = <long *>PyArray_MultiIter_DATA(multi, 1) - * oN_data = <long *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, on_data[0], om_data[0], oN_data[0]) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXT(multi) - * else: - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, (__pyx_v_on_data[0]), (__pyx_v_om_data[0]), (__pyx_v_oN_data[0])); - - /* "mtrand.pyx":450 - * oN_data = <long *>PyArray_MultiIter_DATA(multi, 2) - * array_data[i] = func(state, on_data[0], om_data[0], oN_data[0]) - * PyArray_MultiIter_NEXT(multi) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, int) - */ - PyArray_MultiIter_NEXT(__pyx_v_multi); - } - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":452 - * PyArray_MultiIter_NEXT(multi) - * else: - * array = <ndarray>np.empty(size, int) # <<<<<<<<<<<<<< - * array_data = <long *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(4, <void*>array, <void *>on, <void *>om, - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_5; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":453 - * else: - * array = <ndarray>np.empty(size, int) - * array_data = <long *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * multi = <broadcast>PyArray_MultiIterNew(4, <void*>array, <void *>on, <void *>om, - * <void *>oN) - */ - __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":455 - * array_data = <long *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(4, <void*>array, <void *>on, <void *>om, - * <void *>oN) # <<<<<<<<<<<<<< - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") - */ - __pyx_t_2 = PyArray_MultiIterNew(4, ((void *)arrayObject), ((void *)__pyx_v_on), ((void *)__pyx_v_om), ((void *)__pyx_v_oN)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_multi = ((PyArrayMultiIterObject *)__pyx_t_5); - __pyx_t_5 = 0; - - /* "mtrand.pyx":456 - * multi = <broadcast>PyArray_MultiIterNew(4, <void*>array, <void *>on, <void *>om, - * <void *>oN) - * if (multi.size != PyArray_SIZE(array)): # <<<<<<<<<<<<<< - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: - */ - __pyx_t_1 = (__pyx_v_multi->size != PyArray_SIZE(arrayObject)); - if (__pyx_t_1) { - - /* "mtrand.pyx":457 - * <void *>oN) - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * on_data = <long *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_7), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":458 - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< - * on_data = <long *>PyArray_MultiIter_DATA(multi, 1) - * om_data = <long *>PyArray_MultiIter_DATA(multi, 2) - */ - __pyx_t_4 = __pyx_v_multi->size; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - - /* "mtrand.pyx":459 - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: - * on_data = <long *>PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< - * om_data = <long *>PyArray_MultiIter_DATA(multi, 2) - * oN_data = <long *>PyArray_MultiIter_DATA(multi, 3) - */ - __pyx_v_on_data = ((long *)PyArray_MultiIter_DATA(__pyx_v_multi, 1)); - - /* "mtrand.pyx":460 - * for i from 0 <= i < multi.size: - * on_data = <long *>PyArray_MultiIter_DATA(multi, 1) - * om_data = <long *>PyArray_MultiIter_DATA(multi, 2) # <<<<<<<<<<<<<< - * oN_data = <long *>PyArray_MultiIter_DATA(multi, 3) - * array_data[i] = func(state, on_data[0], om_data[0], oN_data[0]) - */ - __pyx_v_om_data = ((long *)PyArray_MultiIter_DATA(__pyx_v_multi, 2)); - - /* "mtrand.pyx":461 - * on_data = <long *>PyArray_MultiIter_DATA(multi, 1) - * om_data = <long *>PyArray_MultiIter_DATA(multi, 2) - * oN_data = <long *>PyArray_MultiIter_DATA(multi, 3) # <<<<<<<<<<<<<< - * array_data[i] = func(state, on_data[0], om_data[0], oN_data[0]) - * PyArray_MultiIter_NEXT(multi) - */ - __pyx_v_oN_data = ((long *)PyArray_MultiIter_DATA(__pyx_v_multi, 3)); - - /* "mtrand.pyx":462 - * om_data = <long *>PyArray_MultiIter_DATA(multi, 2) - * oN_data = <long *>PyArray_MultiIter_DATA(multi, 3) - * array_data[i] = func(state, on_data[0], om_data[0], oN_data[0]) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXT(multi) - * - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, (__pyx_v_on_data[0]), (__pyx_v_om_data[0]), (__pyx_v_oN_data[0])); - - /* "mtrand.pyx":463 - * oN_data = <long *>PyArray_MultiIter_DATA(multi, 3) - * array_data[i] = func(state, on_data[0], om_data[0], oN_data[0]) - * PyArray_MultiIter_NEXT(multi) # <<<<<<<<<<<<<< - * - * return array - */ - PyArray_MultiIter_NEXT(__pyx_v_multi); - } - } - __pyx_L3:; - - /* "mtrand.pyx":465 - * PyArray_MultiIter_NEXT(multi) - * - * return array # <<<<<<<<<<<<<< - * - * cdef object discd_array_sc(rk_state *state, rk_discd func, object size, double a): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.discnmN_array", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XDECREF((PyObject *)__pyx_v_multi); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":467 - * return array - * - * cdef object discd_array_sc(rk_state *state, rk_discd func, object size, double a): # <<<<<<<<<<<<<< - * cdef long *array_data - * cdef ndarray array "arrayObject" - */ - -static PyObject *__pyx_f_6mtrand_discd_array_sc(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_discd __pyx_v_func, PyObject *__pyx_v_size, double __pyx_v_a) { - long *__pyx_v_array_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_length; - npy_intp __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - npy_intp __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("discd_array_sc", 0); - - /* "mtrand.pyx":473 - * cdef npy_intp i - * - * if size is None: # <<<<<<<<<<<<<< - * return func(state, a) - * else: - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":474 - * - * if size is None: - * return func(state, a) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, int) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyInt_FromLong(__pyx_v_func(__pyx_v_state, __pyx_v_a)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 474; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":476 - * return func(state, a) - * else: - * array = <ndarray>np.empty(size, int) # <<<<<<<<<<<<<< - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 476; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_4; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":477 - * else: - * array = <ndarray>np.empty(size, int) - * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: - */ - __pyx_v_length = PyArray_SIZE(arrayObject); - - /* "mtrand.pyx":478 - * array = <ndarray>np.empty(size, int) - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < length: - * array_data[i] = func(state, a) - */ - __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":479 - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: # <<<<<<<<<<<<<< - * array_data[i] = func(state, a) - * return array - */ - __pyx_t_5 = __pyx_v_length; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_5; __pyx_v_i++) { - - /* "mtrand.pyx":480 - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: - * array_data[i] = func(state, a) # <<<<<<<<<<<<<< - * return array - * - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, __pyx_v_a); - } - - /* "mtrand.pyx":481 - * for i from 0 <= i < length: - * array_data[i] = func(state, a) - * return array # <<<<<<<<<<<<<< - * - * cdef object discd_array(rk_state *state, rk_discd func, object size, ndarray oa): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - } - __pyx_L3:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("mtrand.discd_array_sc", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":483 - * return array - * - * cdef object discd_array(rk_state *state, rk_discd func, object size, ndarray oa): # <<<<<<<<<<<<<< - * cdef long *array_data - * cdef double *oa_data - */ - -static PyObject *__pyx_f_6mtrand_discd_array(rk_state *__pyx_v_state, __pyx_t_6mtrand_rk_discd __pyx_v_func, PyObject *__pyx_v_size, PyArrayObject *__pyx_v_oa) { - long *__pyx_v_array_data; - double *__pyx_v_oa_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_length; - npy_intp __pyx_v_i; - PyArrayMultiIterObject *__pyx_v_multi = 0; - PyArrayIterObject *__pyx_v_itera = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - npy_intp __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("discd_array", 0); - - /* "mtrand.pyx":492 - * cdef flatiter itera - * - * if size is None: # <<<<<<<<<<<<<< - * array = <ndarray>PyArray_SimpleNew(PyArray_NDIM(oa), - * PyArray_DIMS(oa), NPY_LONG) - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":494 - * if size is None: - * array = <ndarray>PyArray_SimpleNew(PyArray_NDIM(oa), - * PyArray_DIMS(oa), NPY_LONG) # <<<<<<<<<<<<<< - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) - */ - __pyx_t_2 = PyArray_SimpleNew(PyArray_NDIM(__pyx_v_oa), PyArray_DIMS(__pyx_v_oa), NPY_LONG); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":495 - * array = <ndarray>PyArray_SimpleNew(PyArray_NDIM(oa), - * PyArray_DIMS(oa), NPY_LONG) - * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< - * array_data = <long *>PyArray_DATA(array) - * itera = <flatiter>PyArray_IterNew(<object>oa) - */ - __pyx_v_length = PyArray_SIZE(arrayObject); - - /* "mtrand.pyx":496 - * PyArray_DIMS(oa), NPY_LONG) - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * itera = <flatiter>PyArray_IterNew(<object>oa) - * for i from 0 <= i < length: - */ - __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":497 - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) - * itera = <flatiter>PyArray_IterNew(<object>oa) # <<<<<<<<<<<<<< - * for i from 0 <= i < length: - * array_data[i] = func(state, (<double *>(itera.dataptr))[0]) - */ - __pyx_t_3 = PyArray_IterNew(((PyObject *)__pyx_v_oa)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_itera = ((PyArrayIterObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":498 - * array_data = <long *>PyArray_DATA(array) - * itera = <flatiter>PyArray_IterNew(<object>oa) - * for i from 0 <= i < length: # <<<<<<<<<<<<<< - * array_data[i] = func(state, (<double *>(itera.dataptr))[0]) - * PyArray_ITER_NEXT(itera) - */ - __pyx_t_4 = __pyx_v_length; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - - /* "mtrand.pyx":499 - * itera = <flatiter>PyArray_IterNew(<object>oa) - * for i from 0 <= i < length: - * array_data[i] = func(state, (<double *>(itera.dataptr))[0]) # <<<<<<<<<<<<<< - * PyArray_ITER_NEXT(itera) - * else: - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, (((double *)__pyx_v_itera->dataptr)[0])); - - /* "mtrand.pyx":500 - * for i from 0 <= i < length: - * array_data[i] = func(state, (<double *>(itera.dataptr))[0]) - * PyArray_ITER_NEXT(itera) # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, int) - */ - PyArray_ITER_NEXT(__pyx_v_itera); - } - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":502 - * PyArray_ITER_NEXT(itera) - * else: - * array = <ndarray>np.empty(size, int) # <<<<<<<<<<<<<< - * array_data = <long *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(2, <void *>array, <void *>oa) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_t_5; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":503 - * else: - * array = <ndarray>np.empty(size, int) - * array_data = <long *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * multi = <broadcast>PyArray_MultiIterNew(2, <void *>array, <void *>oa) - * if (multi.size != PyArray_SIZE(array)): - */ - __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":504 - * array = <ndarray>np.empty(size, int) - * array_data = <long *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(2, <void *>array, <void *>oa) # <<<<<<<<<<<<<< - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") - */ - __pyx_t_2 = PyArray_MultiIterNew(2, ((void *)arrayObject), ((void *)__pyx_v_oa)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 504; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_multi = ((PyArrayMultiIterObject *)__pyx_t_5); - __pyx_t_5 = 0; - - /* "mtrand.pyx":505 - * array_data = <long *>PyArray_DATA(array) - * multi = <broadcast>PyArray_MultiIterNew(2, <void *>array, <void *>oa) - * if (multi.size != PyArray_SIZE(array)): # <<<<<<<<<<<<<< - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: - */ - __pyx_t_1 = (__pyx_v_multi->size != PyArray_SIZE(arrayObject)); - if (__pyx_t_1) { - - /* "mtrand.pyx":506 - * multi = <broadcast>PyArray_MultiIterNew(2, <void *>array, <void *>oa) - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_8), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":507 - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, oa_data[0]) - */ - __pyx_t_4 = __pyx_v_multi->size; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_4; __pyx_v_i++) { - - /* "mtrand.pyx":508 - * raise ValueError("size is not compatible with inputs") - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< - * array_data[i] = func(state, oa_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) - */ - __pyx_v_oa_data = ((double *)PyArray_MultiIter_DATA(__pyx_v_multi, 1)); - - /* "mtrand.pyx":509 - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, oa_data[0]) # <<<<<<<<<<<<<< - * PyArray_MultiIter_NEXTi(multi, 1) - * return array - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_func(__pyx_v_state, (__pyx_v_oa_data[0])); - - /* "mtrand.pyx":510 - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - * array_data[i] = func(state, oa_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) # <<<<<<<<<<<<<< - * return array - * - */ - PyArray_MultiIter_NEXTi(__pyx_v_multi, 1); - } - } - __pyx_L3:; - - /* "mtrand.pyx":511 - * array_data[i] = func(state, oa_data[0]) - * PyArray_MultiIter_NEXTi(multi, 1) - * return array # <<<<<<<<<<<<<< - * - * cdef double kahan_sum(double *darr, npy_intp n): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.discd_array", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XDECREF((PyObject *)__pyx_v_multi); - __Pyx_XDECREF((PyObject *)__pyx_v_itera); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":513 - * return array - * - * cdef double kahan_sum(double *darr, npy_intp n): # <<<<<<<<<<<<<< - * cdef double c, y, t, sum - * cdef npy_intp i - */ - -static double __pyx_f_6mtrand_kahan_sum(double *__pyx_v_darr, npy_intp __pyx_v_n) { - double __pyx_v_c; - double __pyx_v_y; - double __pyx_v_t; - double __pyx_v_sum; - npy_intp __pyx_v_i; - double __pyx_r; - __Pyx_RefNannyDeclarations - npy_intp __pyx_t_1; - __Pyx_RefNannySetupContext("kahan_sum", 0); - - /* "mtrand.pyx":516 - * cdef double c, y, t, sum - * cdef npy_intp i - * sum = darr[0] # <<<<<<<<<<<<<< - * c = 0.0 - * for i from 1 <= i < n: - */ - __pyx_v_sum = (__pyx_v_darr[0]); - - /* "mtrand.pyx":517 - * cdef npy_intp i - * sum = darr[0] - * c = 0.0 # <<<<<<<<<<<<<< - * for i from 1 <= i < n: - * y = darr[i] - c - */ - __pyx_v_c = 0.0; - - /* "mtrand.pyx":518 - * sum = darr[0] - * c = 0.0 - * for i from 1 <= i < n: # <<<<<<<<<<<<<< - * y = darr[i] - c - * t = sum + y - */ - __pyx_t_1 = __pyx_v_n; - for (__pyx_v_i = 1; __pyx_v_i < __pyx_t_1; __pyx_v_i++) { - - /* "mtrand.pyx":519 - * c = 0.0 - * for i from 1 <= i < n: - * y = darr[i] - c # <<<<<<<<<<<<<< - * t = sum + y - * c = (t-sum) - y - */ - __pyx_v_y = ((__pyx_v_darr[__pyx_v_i]) - __pyx_v_c); - - /* "mtrand.pyx":520 - * for i from 1 <= i < n: - * y = darr[i] - c - * t = sum + y # <<<<<<<<<<<<<< - * c = (t-sum) - y - * sum = t - */ - __pyx_v_t = (__pyx_v_sum + __pyx_v_y); - - /* "mtrand.pyx":521 - * y = darr[i] - c - * t = sum + y - * c = (t-sum) - y # <<<<<<<<<<<<<< - * sum = t - * return sum - */ - __pyx_v_c = ((__pyx_v_t - __pyx_v_sum) - __pyx_v_y); - - /* "mtrand.pyx":522 - * t = sum + y - * c = (t-sum) - y - * sum = t # <<<<<<<<<<<<<< - * return sum - * - */ - __pyx_v_sum = __pyx_v_t; - } - - /* "mtrand.pyx":523 - * c = (t-sum) - y - * sum = t - * return sum # <<<<<<<<<<<<<< - * - * cdef class RandomState: - */ - __pyx_r = __pyx_v_sum; - goto __pyx_L0; - - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static int __pyx_pw_6mtrand_11RandomState_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_6mtrand_11RandomState_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_seed = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__seed,0}; - PyObject* values[1] = {0}; - - /* "mtrand.pyx":561 - * poisson_lam_max = np.iinfo('l').max - np.sqrt(np.iinfo('l').max)*10 - * - * def __init__(self, seed=None): # <<<<<<<<<<<<<< - * self.internal_state = <rk_state*>PyMem_Malloc(sizeof(rk_state)) - * - */ - values[0] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed); - if (value) { values[0] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_seed = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 561; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState___init__(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_seed); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_6mtrand_11RandomState___init__(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_seed) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__init__", 0); - - /* "mtrand.pyx":562 - * - * def __init__(self, seed=None): - * self.internal_state = <rk_state*>PyMem_Malloc(sizeof(rk_state)) # <<<<<<<<<<<<<< - * - * self.seed(seed) - */ - __pyx_v_self->internal_state = ((rk_state *)PyMem_Malloc((sizeof(rk_state)))); - - /* "mtrand.pyx":564 - * self.internal_state = <rk_state*>PyMem_Malloc(sizeof(rk_state)) - * - * self.seed(seed) # <<<<<<<<<<<<<< - * - * def __dealloc__(self): - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__seed); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 564; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 564; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_seed); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_seed); - __Pyx_GIVEREF(__pyx_v_seed); - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 564; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("mtrand.RandomState.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static void __pyx_pw_6mtrand_11RandomState_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ -static void __pyx_pw_6mtrand_11RandomState_3__dealloc__(PyObject *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_pf_6mtrand_11RandomState_2__dealloc__(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); -} - -/* "mtrand.pyx":566 - * self.seed(seed) - * - * def __dealloc__(self): # <<<<<<<<<<<<<< - * if self.internal_state != NULL: - * PyMem_Free(self.internal_state) - */ - -static void __pyx_pf_6mtrand_11RandomState_2__dealloc__(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self) { - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("__dealloc__", 0); - - /* "mtrand.pyx":567 - * - * def __dealloc__(self): - * if self.internal_state != NULL: # <<<<<<<<<<<<<< - * PyMem_Free(self.internal_state) - * self.internal_state = NULL - */ - __pyx_t_1 = (__pyx_v_self->internal_state != NULL); - if (__pyx_t_1) { - - /* "mtrand.pyx":568 - * def __dealloc__(self): - * if self.internal_state != NULL: - * PyMem_Free(self.internal_state) # <<<<<<<<<<<<<< - * self.internal_state = NULL - * - */ - PyMem_Free(__pyx_v_self->internal_state); - - /* "mtrand.pyx":569 - * if self.internal_state != NULL: - * PyMem_Free(self.internal_state) - * self.internal_state = NULL # <<<<<<<<<<<<<< - * - * def seed(self, seed=None): - */ - __pyx_v_self->internal_state = NULL; - goto __pyx_L3; - } - __pyx_L3:; - - __Pyx_RefNannyFinishContext(); -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_5seed(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_4seed[] = "\n seed(seed=None)\n\n Seed the generator.\n\n This method is called when `RandomState` is initialized. It can be\n called again to re-seed the generator. For details, see `RandomState`.\n\n Parameters\n ----------\n seed : int or array_like, optional\n Seed for `RandomState`.\n\n See Also\n --------\n RandomState\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_5seed(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_seed = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("seed (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__seed,0}; - PyObject* values[1] = {0}; - - /* "mtrand.pyx":571 - * self.internal_state = NULL - * - * def seed(self, seed=None): # <<<<<<<<<<<<<< - * """ - * seed(seed=None) - */ - values[0] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__seed); - if (value) { values[0] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "seed") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_seed = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("seed", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.seed", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_4seed(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_seed); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_4seed(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_seed) { - CYTHON_UNUSED rk_error __pyx_v_errcode; - PyArrayObject *arrayObject_obj = 0; - PyObject *__pyx_v_iseed = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - unsigned long __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("seed", 0); - - /* "mtrand.pyx":592 - * cdef rk_error errcode - * cdef ndarray obj "arrayObject_obj" - * if seed is None: # <<<<<<<<<<<<<< - * errcode = rk_randomseed(self.internal_state) - * elif type(seed) is int: - */ - __pyx_t_1 = (__pyx_v_seed == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":593 - * cdef ndarray obj "arrayObject_obj" - * if seed is None: - * errcode = rk_randomseed(self.internal_state) # <<<<<<<<<<<<<< - * elif type(seed) is int: - * rk_seed(seed, self.internal_state) - */ - __pyx_v_errcode = rk_randomseed(__pyx_v_self->internal_state); - goto __pyx_L3; - } - - /* "mtrand.pyx":594 - * if seed is None: - * errcode = rk_randomseed(self.internal_state) - * elif type(seed) is int: # <<<<<<<<<<<<<< - * rk_seed(seed, self.internal_state) - * elif isinstance(seed, np.integer): - */ - __pyx_t_1 = (((PyObject *)Py_TYPE(__pyx_v_seed)) == ((PyObject *)((PyObject*)(&PyInt_Type)))); - if (__pyx_t_1) { - - /* "mtrand.pyx":595 - * errcode = rk_randomseed(self.internal_state) - * elif type(seed) is int: - * rk_seed(seed, self.internal_state) # <<<<<<<<<<<<<< - * elif isinstance(seed, np.integer): - * iseed = int(seed) - */ - __pyx_t_2 = __Pyx_PyInt_AsUnsignedLong(__pyx_v_seed); if (unlikely((__pyx_t_2 == (unsigned long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 595; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - rk_seed(__pyx_t_2, __pyx_v_self->internal_state); - goto __pyx_L3; - } - - /* "mtrand.pyx":596 - * elif type(seed) is int: - * rk_seed(seed, self.internal_state) - * elif isinstance(seed, np.integer): # <<<<<<<<<<<<<< - * iseed = int(seed) - * rk_seed(iseed, self.internal_state) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 596; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__integer); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 596; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_1 = PyObject_IsInstance(__pyx_v_seed, __pyx_t_4); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 596; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":597 - * rk_seed(seed, self.internal_state) - * elif isinstance(seed, np.integer): - * iseed = int(seed) # <<<<<<<<<<<<<< - * rk_seed(iseed, self.internal_state) - * else: - */ - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_seed); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_seed); - __Pyx_GIVEREF(__pyx_v_seed); - __pyx_t_3 = PyObject_Call(((PyObject *)((PyObject*)(&PyInt_Type))), ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_v_iseed = __pyx_t_3; - __pyx_t_3 = 0; - - /* "mtrand.pyx":598 - * elif isinstance(seed, np.integer): - * iseed = int(seed) - * rk_seed(iseed, self.internal_state) # <<<<<<<<<<<<<< - * else: - * obj = <ndarray>PyArray_ContiguousFromObject(seed, NPY_LONG, 1, 1) - */ - __pyx_t_2 = __Pyx_PyInt_AsUnsignedLong(__pyx_v_iseed); if (unlikely((__pyx_t_2 == (unsigned long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - rk_seed(__pyx_t_2, __pyx_v_self->internal_state); - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":600 - * rk_seed(iseed, self.internal_state) - * else: - * obj = <ndarray>PyArray_ContiguousFromObject(seed, NPY_LONG, 1, 1) # <<<<<<<<<<<<<< - * init_by_array(self.internal_state, <unsigned long *>PyArray_DATA(obj), - * PyArray_DIM(obj, 0)) - */ - __pyx_t_3 = PyArray_ContiguousFromObject(__pyx_v_seed, NPY_LONG, 1, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 600; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - arrayObject_obj = ((PyArrayObject *)__pyx_t_4); - __pyx_t_4 = 0; - - /* "mtrand.pyx":602 - * obj = <ndarray>PyArray_ContiguousFromObject(seed, NPY_LONG, 1, 1) - * init_by_array(self.internal_state, <unsigned long *>PyArray_DATA(obj), - * PyArray_DIM(obj, 0)) # <<<<<<<<<<<<<< - * - * def get_state(self): - */ - init_by_array(__pyx_v_self->internal_state, ((unsigned long *)PyArray_DATA(arrayObject_obj)), PyArray_DIM(arrayObject_obj, 0)); - } - __pyx_L3:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("mtrand.RandomState.seed", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject_obj); - __Pyx_XDECREF(__pyx_v_iseed); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_7get_state(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_6get_state[] = "\n get_state()\n\n Return a tuple representing the internal state of the generator.\n\n For more details, see `set_state`.\n\n Returns\n -------\n out : tuple(str, ndarray of 624 uints, int, int, float)\n The returned tuple has the following items:\n\n 1. the string 'MT19937'.\n 2. a 1-D array of 624 unsigned integer keys.\n 3. an integer ``pos``.\n 4. an integer ``has_gauss``.\n 5. a float ``cached_gaussian``.\n\n See Also\n --------\n set_state\n\n Notes\n -----\n `set_state` and `get_state` are not needed to work with any of the\n random distributions in NumPy. If the internal state is manually altered,\n the user should know exactly what he/she is doing.\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_7get_state(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("get_state (wrapper)", 0); - __pyx_r = __pyx_pf_6mtrand_11RandomState_6get_state(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":604 - * PyArray_DIM(obj, 0)) - * - * def get_state(self): # <<<<<<<<<<<<<< - * """ - * get_state() - */ - -static PyObject *__pyx_pf_6mtrand_11RandomState_6get_state(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self) { - PyArrayObject *arrayObject_state = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("get_state", 0); - - /* "mtrand.pyx":635 - * """ - * cdef ndarray state "arrayObject_state" - * state = <ndarray>np.empty(624, np.uint) # <<<<<<<<<<<<<< - * memcpy(<void*>PyArray_DATA(state), <void*>(self.internal_state.key), 624*sizeof(long)) - * state = <ndarray>np.asarray(state, np.uint32) - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__uint); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_int_624); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_int_624); - __Pyx_GIVEREF(__pyx_int_624); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - arrayObject_state = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "mtrand.pyx":636 - * cdef ndarray state "arrayObject_state" - * state = <ndarray>np.empty(624, np.uint) - * memcpy(<void*>PyArray_DATA(state), <void*>(self.internal_state.key), 624*sizeof(long)) # <<<<<<<<<<<<<< - * state = <ndarray>np.asarray(state, np.uint32) - * return ('MT19937', state, self.internal_state.pos, - */ - memcpy(((void *)PyArray_DATA(arrayObject_state)), ((void *)__pyx_v_self->internal_state->key), (624 * (sizeof(long)))); - - /* "mtrand.pyx":637 - * state = <ndarray>np.empty(624, np.uint) - * memcpy(<void*>PyArray_DATA(state), <void*>(self.internal_state.key), 624*sizeof(long)) - * state = <ndarray>np.asarray(state, np.uint32) # <<<<<<<<<<<<<< - * return ('MT19937', state, self.internal_state.pos, - * self.internal_state.has_gauss, self.internal_state.gauss) - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__asarray); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__uint32); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)arrayObject_state)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)arrayObject_state)); - __Pyx_GIVEREF(((PyObject *)arrayObject_state)); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 637; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)arrayObject_state)); - arrayObject_state = ((PyArrayObject *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "mtrand.pyx":638 - * memcpy(<void*>PyArray_DATA(state), <void*>(self.internal_state.key), 624*sizeof(long)) - * state = <ndarray>np.asarray(state, np.uint32) - * return ('MT19937', state, self.internal_state.pos, # <<<<<<<<<<<<<< - * self.internal_state.has_gauss, self.internal_state.gauss) - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromLong(__pyx_v_self->internal_state->pos); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - - /* "mtrand.pyx":639 - * state = <ndarray>np.asarray(state, np.uint32) - * return ('MT19937', state, self.internal_state.pos, - * self.internal_state.has_gauss, self.internal_state.gauss) # <<<<<<<<<<<<<< - * - * def set_state(self, state): - */ - __pyx_t_2 = PyInt_FromLong(__pyx_v_self->internal_state->has_gauss); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 639; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyFloat_FromDouble(__pyx_v_self->internal_state->gauss); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 639; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(((PyObject *)__pyx_n_s__MT19937)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_n_s__MT19937)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__MT19937)); - __Pyx_INCREF(((PyObject *)arrayObject_state)); - PyTuple_SET_ITEM(__pyx_t_4, 1, ((PyObject *)arrayObject_state)); - __Pyx_GIVEREF(((PyObject *)arrayObject_state)); - PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 3, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 4, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_r = ((PyObject *)__pyx_t_4); - __pyx_t_4 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("mtrand.RandomState.get_state", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject_state); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_9set_state(PyObject *__pyx_v_self, PyObject *__pyx_v_state); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_8set_state[] = "\n set_state(state)\n\n Set the internal state of the generator from a tuple.\n\n For use if one has reason to manually (re-)set the internal state of the\n \"Mersenne Twister\"[1]_ pseudo-random number generating algorithm.\n\n Parameters\n ----------\n state : tuple(str, ndarray of 624 uints, int, int, float)\n The `state` tuple has the following items:\n\n 1. the string 'MT19937', specifying the Mersenne Twister algorithm.\n 2. a 1-D array of 624 unsigned integers ``keys``.\n 3. an integer ``pos``.\n 4. an integer ``has_gauss``.\n 5. a float ``cached_gaussian``.\n\n Returns\n -------\n out : None\n Returns 'None' on success.\n\n See Also\n --------\n get_state\n\n Notes\n -----\n `set_state` and `get_state` are not needed to work with any of the\n random distributions in NumPy. If the internal state is manually altered,\n the user should know exactly what he/she is doing.\n\n For backwards compatibility, the form (str, array of 624 uints, int) is\n also accepted although it is missing some information about the cached\n Gaussian value: ``state = ('MT19937', keys, pos)``.\n\n References\n ----------\n .. [1] M. Matsumoto and T. Nishimura, \"Mersenne Twister: A\n 623-dimensionally equidistributed uniform pseudorandom number\n generator,\" *ACM Trans. on Modeling and Computer Simulation*,\n Vol. 8, No. 1, pp. 3-30, Jan. 1998.\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_9set_state(PyObject *__pyx_v_self, PyObject *__pyx_v_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("set_state (wrapper)", 0); - __pyx_r = __pyx_pf_6mtrand_11RandomState_8set_state(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), ((PyObject *)__pyx_v_state)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":641 - * self.internal_state.has_gauss, self.internal_state.gauss) - * - * def set_state(self, state): # <<<<<<<<<<<<<< - * """ - * set_state(state) - */ - -static PyObject *__pyx_pf_6mtrand_11RandomState_8set_state(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_state) { - PyArrayObject *arrayObject_obj = 0; - int __pyx_v_pos; - PyObject *__pyx_v_algorithm_name = NULL; - PyObject *__pyx_v_key = NULL; - PyObject *__pyx_v_has_gauss = NULL; - PyObject *__pyx_v_cached_gaussian = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *(*__pyx_t_6)(PyObject *); - int __pyx_t_7; - Py_ssize_t __pyx_t_8; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - PyObject *__pyx_t_12 = NULL; - double __pyx_t_13; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("set_state", 0); - - /* "mtrand.pyx":690 - * cdef ndarray obj "arrayObject_obj" - * cdef int pos - * algorithm_name = state[0] # <<<<<<<<<<<<<< - * if algorithm_name != 'MT19937': - * raise ValueError("algorithm must be 'MT19937'") - */ - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_state, 0, sizeof(long), PyInt_FromLong, 0, 0, 1); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 690; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_algorithm_name = __pyx_t_1; - __pyx_t_1 = 0; - - /* "mtrand.pyx":691 - * cdef int pos - * algorithm_name = state[0] - * if algorithm_name != 'MT19937': # <<<<<<<<<<<<<< - * raise ValueError("algorithm must be 'MT19937'") - * key, pos = state[1:3] - */ - __pyx_t_1 = PyObject_RichCompare(__pyx_v_algorithm_name, ((PyObject *)__pyx_n_s__MT19937), Py_NE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 691; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 691; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_2) { - - /* "mtrand.pyx":692 - * algorithm_name = state[0] - * if algorithm_name != 'MT19937': - * raise ValueError("algorithm must be 'MT19937'") # <<<<<<<<<<<<<< - * key, pos = state[1:3] - * if len(state) == 3: - */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_10), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 692; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 692; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":693 - * if algorithm_name != 'MT19937': - * raise ValueError("algorithm must be 'MT19937'") - * key, pos = state[1:3] # <<<<<<<<<<<<<< - * if len(state) == 3: - * has_gauss = 0 - */ - __pyx_t_1 = __Pyx_PyObject_GetSlice(__pyx_v_state, 1, 3, NULL, NULL, &__pyx_k_slice_11, 1, 1, 1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - #if CYTHON_COMPILING_IN_CPYTHON - Py_ssize_t size = Py_SIZE(sequence); - #else - Py_ssize_t size = PySequence_Size(sequence); - #endif - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - #if CYTHON_COMPILING_IN_CPYTHON - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_3 = PyList_GET_ITEM(sequence, 0); - __pyx_t_4 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - #else - __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else - { - Py_ssize_t index = -1; - __pyx_t_5 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; - index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L4_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L4_unpacking_failed; - __Pyx_GOTREF(__pyx_t_4); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = NULL; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L5_unpacking_done; - __pyx_L4_unpacking_failed:; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_L5_unpacking_done:; - } - __pyx_t_7 = __Pyx_PyInt_AsInt(__pyx_t_4); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_key = __pyx_t_3; - __pyx_t_3 = 0; - __pyx_v_pos = __pyx_t_7; - - /* "mtrand.pyx":694 - * raise ValueError("algorithm must be 'MT19937'") - * key, pos = state[1:3] - * if len(state) == 3: # <<<<<<<<<<<<<< - * has_gauss = 0 - * cached_gaussian = 0.0 - */ - __pyx_t_8 = PyObject_Length(__pyx_v_state); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 694; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = (__pyx_t_8 == 3); - if (__pyx_t_2) { - - /* "mtrand.pyx":695 - * key, pos = state[1:3] - * if len(state) == 3: - * has_gauss = 0 # <<<<<<<<<<<<<< - * cached_gaussian = 0.0 - * else: - */ - __Pyx_INCREF(__pyx_int_0); - __pyx_v_has_gauss = __pyx_int_0; - - /* "mtrand.pyx":696 - * if len(state) == 3: - * has_gauss = 0 - * cached_gaussian = 0.0 # <<<<<<<<<<<<<< - * else: - * has_gauss, cached_gaussian = state[3:5] - */ - __pyx_t_1 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 696; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_cached_gaussian = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L6; - } - /*else*/ { - - /* "mtrand.pyx":698 - * cached_gaussian = 0.0 - * else: - * has_gauss, cached_gaussian = state[3:5] # <<<<<<<<<<<<<< - * try: - * obj = <ndarray>PyArray_ContiguousFromObject(key, NPY_ULONG, 1, 1) - */ - __pyx_t_1 = __Pyx_PyObject_GetSlice(__pyx_v_state, 3, 5, NULL, NULL, &__pyx_k_slice_12, 1, 1, 1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - #if CYTHON_COMPILING_IN_CPYTHON - Py_ssize_t size = Py_SIZE(sequence); - #else - Py_ssize_t size = PySequence_Size(sequence); - #endif - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - #if CYTHON_COMPILING_IN_CPYTHON - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_4 = PyList_GET_ITEM(sequence, 0); - __pyx_t_3 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(__pyx_t_3); - #else - __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else - { - Py_ssize_t index = -1; - __pyx_t_5 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; - index = 0; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_4); - index = 1; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L7_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = NULL; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L8_unpacking_done; - __pyx_L7_unpacking_failed:; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_6 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_L8_unpacking_done:; - } - __pyx_v_has_gauss = __pyx_t_4; - __pyx_t_4 = 0; - __pyx_v_cached_gaussian = __pyx_t_3; - __pyx_t_3 = 0; - } - __pyx_L6:; - - /* "mtrand.pyx":699 - * else: - * has_gauss, cached_gaussian = state[3:5] - * try: # <<<<<<<<<<<<<< - * obj = <ndarray>PyArray_ContiguousFromObject(key, NPY_ULONG, 1, 1) - * except TypeError: - */ - { - __Pyx_ExceptionSave(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); - __Pyx_XGOTREF(__pyx_t_9); - __Pyx_XGOTREF(__pyx_t_10); - __Pyx_XGOTREF(__pyx_t_11); - /*try:*/ { - - /* "mtrand.pyx":700 - * has_gauss, cached_gaussian = state[3:5] - * try: - * obj = <ndarray>PyArray_ContiguousFromObject(key, NPY_ULONG, 1, 1) # <<<<<<<<<<<<<< - * except TypeError: - * # compatibility -- could be an older pickle - */ - __pyx_t_1 = PyArray_ContiguousFromObject(__pyx_v_key, NPY_ULONG, 1, 1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 700; __pyx_clineno = __LINE__; goto __pyx_L9_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __pyx_t_1; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - arrayObject_obj = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - } - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - goto __pyx_L16_try_end; - __pyx_L9_error:; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "mtrand.pyx":701 - * try: - * obj = <ndarray>PyArray_ContiguousFromObject(key, NPY_ULONG, 1, 1) - * except TypeError: # <<<<<<<<<<<<<< - * # compatibility -- could be an older pickle - * obj = <ndarray>PyArray_ContiguousFromObject(key, NPY_LONG, 1, 1) - */ - __pyx_t_7 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); - if (__pyx_t_7) { - __Pyx_AddTraceback("mtrand.RandomState.set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_3, &__pyx_t_1, &__pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 701; __pyx_clineno = __LINE__; goto __pyx_L11_except_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_t_4); - - /* "mtrand.pyx":703 - * except TypeError: - * # compatibility -- could be an older pickle - * obj = <ndarray>PyArray_ContiguousFromObject(key, NPY_LONG, 1, 1) # <<<<<<<<<<<<<< - * if PyArray_DIM(obj, 0) != 624: - * raise ValueError("state must be 624 longs") - */ - __pyx_t_5 = PyArray_ContiguousFromObject(__pyx_v_key, NPY_LONG, 1, 1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L11_except_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_12 = __pyx_t_5; - __Pyx_INCREF(__pyx_t_12); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(((PyObject *)arrayObject_obj)); - arrayObject_obj = ((PyArrayObject *)__pyx_t_12); - __pyx_t_12 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - goto __pyx_L10_exception_handled; - } - __pyx_L11_except_error:; - __Pyx_XGIVEREF(__pyx_t_9); - __Pyx_XGIVEREF(__pyx_t_10); - __Pyx_XGIVEREF(__pyx_t_11); - __Pyx_ExceptionReset(__pyx_t_9, __pyx_t_10, __pyx_t_11); - goto __pyx_L1_error; - __pyx_L10_exception_handled:; - __Pyx_XGIVEREF(__pyx_t_9); - __Pyx_XGIVEREF(__pyx_t_10); - __Pyx_XGIVEREF(__pyx_t_11); - __Pyx_ExceptionReset(__pyx_t_9, __pyx_t_10, __pyx_t_11); - __pyx_L16_try_end:; - } - - /* "mtrand.pyx":704 - * # compatibility -- could be an older pickle - * obj = <ndarray>PyArray_ContiguousFromObject(key, NPY_LONG, 1, 1) - * if PyArray_DIM(obj, 0) != 624: # <<<<<<<<<<<<<< - * raise ValueError("state must be 624 longs") - * memcpy(<void*>(self.internal_state.key), <void*>PyArray_DATA(obj), 624*sizeof(long)) - */ - __pyx_t_2 = (PyArray_DIM(arrayObject_obj, 0) != 624); - if (__pyx_t_2) { - - /* "mtrand.pyx":705 - * obj = <ndarray>PyArray_ContiguousFromObject(key, NPY_LONG, 1, 1) - * if PyArray_DIM(obj, 0) != 624: - * raise ValueError("state must be 624 longs") # <<<<<<<<<<<<<< - * memcpy(<void*>(self.internal_state.key), <void*>PyArray_DATA(obj), 624*sizeof(long)) - * self.internal_state.pos = pos - */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_14), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 705; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 705; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L19; - } - __pyx_L19:; - - /* "mtrand.pyx":706 - * if PyArray_DIM(obj, 0) != 624: - * raise ValueError("state must be 624 longs") - * memcpy(<void*>(self.internal_state.key), <void*>PyArray_DATA(obj), 624*sizeof(long)) # <<<<<<<<<<<<<< - * self.internal_state.pos = pos - * self.internal_state.has_gauss = has_gauss - */ - memcpy(((void *)__pyx_v_self->internal_state->key), ((void *)PyArray_DATA(arrayObject_obj)), (624 * (sizeof(long)))); - - /* "mtrand.pyx":707 - * raise ValueError("state must be 624 longs") - * memcpy(<void*>(self.internal_state.key), <void*>PyArray_DATA(obj), 624*sizeof(long)) - * self.internal_state.pos = pos # <<<<<<<<<<<<<< - * self.internal_state.has_gauss = has_gauss - * self.internal_state.gauss = cached_gaussian - */ - __pyx_v_self->internal_state->pos = __pyx_v_pos; - - /* "mtrand.pyx":708 - * memcpy(<void*>(self.internal_state.key), <void*>PyArray_DATA(obj), 624*sizeof(long)) - * self.internal_state.pos = pos - * self.internal_state.has_gauss = has_gauss # <<<<<<<<<<<<<< - * self.internal_state.gauss = cached_gaussian - * - */ - __pyx_t_7 = __Pyx_PyInt_AsInt(__pyx_v_has_gauss); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->internal_state->has_gauss = __pyx_t_7; - - /* "mtrand.pyx":709 - * self.internal_state.pos = pos - * self.internal_state.has_gauss = has_gauss - * self.internal_state.gauss = cached_gaussian # <<<<<<<<<<<<<< - * - * # Pickling support: - */ - __pyx_t_13 = __pyx_PyFloat_AsDouble(__pyx_v_cached_gaussian); if (unlikely((__pyx_t_13 == (double)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 709; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->internal_state->gauss = __pyx_t_13; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_12); - __Pyx_AddTraceback("mtrand.RandomState.set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject_obj); - __Pyx_XDECREF(__pyx_v_algorithm_name); - __Pyx_XDECREF(__pyx_v_key); - __Pyx_XDECREF(__pyx_v_has_gauss); - __Pyx_XDECREF(__pyx_v_cached_gaussian); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_11__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_6mtrand_11RandomState_11__getstate__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getstate__ (wrapper)", 0); - __pyx_r = __pyx_pf_6mtrand_11RandomState_10__getstate__(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":712 - * - * # Pickling support: - * def __getstate__(self): # <<<<<<<<<<<<<< - * return self.get_state() - * - */ - -static PyObject *__pyx_pf_6mtrand_11RandomState_10__getstate__(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getstate__", 0); - - /* "mtrand.pyx":713 - * # Pickling support: - * def __getstate__(self): - * return self.get_state() # <<<<<<<<<<<<<< - * - * def __setstate__(self, state): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__get_state); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 713; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 713; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("mtrand.RandomState.__getstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_13__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_state); /*proto*/ -static PyObject *__pyx_pw_6mtrand_11RandomState_13__setstate__(PyObject *__pyx_v_self, PyObject *__pyx_v_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate__ (wrapper)", 0); - __pyx_r = __pyx_pf_6mtrand_11RandomState_12__setstate__(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), ((PyObject *)__pyx_v_state)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":715 - * return self.get_state() - * - * def __setstate__(self, state): # <<<<<<<<<<<<<< - * self.set_state(state) - * - */ - -static PyObject *__pyx_pf_6mtrand_11RandomState_12__setstate__(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate__", 0); - - /* "mtrand.pyx":716 - * - * def __setstate__(self, state): - * self.set_state(state) # <<<<<<<<<<<<<< - * - * def __reduce__(self): - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__set_state); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 716; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 716; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_state); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_state); - __Pyx_GIVEREF(__pyx_v_state); - __pyx_t_3 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 716; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("mtrand.RandomState.__setstate__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_15__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_6mtrand_11RandomState_15__reduce__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); - __pyx_r = __pyx_pf_6mtrand_11RandomState_14__reduce__(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":718 - * self.set_state(state) - * - * def __reduce__(self): # <<<<<<<<<<<<<< - * return (np.random.__RandomState_ctor, (), self.get_state()) - * - */ - -static PyObject *__pyx_pf_6mtrand_11RandomState_14__reduce__(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce__", 0); - - /* "mtrand.pyx":719 - * - * def __reduce__(self): - * return (np.random.__RandomState_ctor, (), self.get_state()) # <<<<<<<<<<<<<< - * - * # Basic distributions: - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__random); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s____RandomState_ctor); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__get_state); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)__pyx_empty_tuple)); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_empty_tuple)); - __Pyx_GIVEREF(((PyObject *)__pyx_empty_tuple)); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_1 = 0; - __pyx_t_3 = 0; - __pyx_r = ((PyObject *)__pyx_t_2); - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("mtrand.RandomState.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_17random_sample(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_16random_sample[] = "\n random_sample(size=None)\n\n Return random floats in the half-open interval [0.0, 1.0).\n\n Results are from the \"continuous uniform\" distribution over the\n stated interval. To sample :math:`Unif[a, b), b > a` multiply\n the output of `random_sample` by `(b-a)` and add `a`::\n\n (b - a) * random_sample() + a\n\n Parameters\n ----------\n size : int or tuple of ints, optional\n Defines the shape of the returned array of random floats. If None\n (the default), returns a single float.\n\n Returns\n -------\n out : float or ndarray of floats\n Array of random floats of shape `size` (unless ``size=None``, in which\n case a single float is returned).\n\n Examples\n --------\n >>> np.random.random_sample()\n 0.47108547995356098\n >>> type(np.random.random_sample())\n <type 'float'>\n >>> np.random.random_sample((5,))\n array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428])\n\n Three-by-two array of random numbers from [-5, 0):\n\n >>> 5 * np.random.random_sample((3, 2)) - 5\n array([[-3.99149989, -0.52338984],\n [-2.99091858, -0.79479508],\n [-1.23204345, -1.75224494]])\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_17random_sample(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("random_sample (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__size,0}; - PyObject* values[1] = {0}; - - /* "mtrand.pyx":722 - * - * # Basic distributions: - * def random_sample(self, size=None): # <<<<<<<<<<<<<< - * """ - * random_sample(size=None) - */ - values[0] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[0] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "random_sample") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_size = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("random_sample", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.random_sample", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_16random_sample(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_16random_sample(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_size) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("random_sample", 0); - - /* "mtrand.pyx":763 - * - * """ - * return cont0_array(self.internal_state, rk_double, size) # <<<<<<<<<<<<<< - * - * def tomaxint(self, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_f_6mtrand_cont0_array(__pyx_v_self->internal_state, rk_double, __pyx_v_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 763; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("mtrand.RandomState.random_sample", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_19tomaxint(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_18tomaxint[] = "\n tomaxint(size=None)\n\n Random integers between 0 and ``sys.maxint``, inclusive.\n\n Return a sample of uniformly distributed random integers in the interval\n [0, ``sys.maxint``].\n\n Parameters\n ----------\n size : tuple of ints, int, optional\n Shape of output. If this is, for example, (m,n,k), m*n*k samples\n are generated. If no shape is specified, a single sample is\n returned.\n\n Returns\n -------\n out : ndarray\n Drawn samples, with shape `size`.\n\n See Also\n --------\n randint : Uniform sampling over a given half-open interval of integers.\n random_integers : Uniform sampling over a given closed interval of\n integers.\n\n Examples\n --------\n >>> RS = np.random.mtrand.RandomState() # need a RandomState object\n >>> RS.tomaxint((2,2,2))\n array([[[1170048599, 1600360186],\n [ 739731006, 1947757578]],\n [[1871712945, 752307660],\n [1601631370, 1479324245]]])\n >>> import sys\n >>> sys.maxint\n 2147483647\n >>> RS.tomaxint((2,2,2)) < sys.maxint\n array([[[ True, True],\n [ True, True]],\n [[ True, True],\n [ True, True]]], dtype=bool)\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_19tomaxint(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("tomaxint (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__size,0}; - PyObject* values[1] = {0}; - - /* "mtrand.pyx":765 - * return cont0_array(self.internal_state, rk_double, size) - * - * def tomaxint(self, size=None): # <<<<<<<<<<<<<< - * """ - * tomaxint(size=None) - */ - values[0] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[0] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "tomaxint") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_size = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("tomaxint", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 765; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.tomaxint", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_18tomaxint(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_18tomaxint(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_size) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("tomaxint", 0); - - /* "mtrand.pyx":810 - * - * """ - * return disc0_array(self.internal_state, rk_long, size) # <<<<<<<<<<<<<< - * - * def randint(self, low, high=None, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_f_6mtrand_disc0_array(__pyx_v_self->internal_state, rk_long, __pyx_v_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 810; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("mtrand.RandomState.tomaxint", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_21randint(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_20randint[] = "\n randint(low, high=None, size=None)\n\n Return random integers from `low` (inclusive) to `high` (exclusive).\n\n Return random integers from the \"discrete uniform\" distribution in the\n \"half-open\" interval [`low`, `high`). If `high` is None (the default),\n then results are from [0, `low`).\n\n Parameters\n ----------\n low : int\n Lowest (signed) integer to be drawn from the distribution (unless\n ``high=None``, in which case this parameter is the *highest* such\n integer).\n high : int, optional\n If provided, one above the largest (signed) integer to be drawn\n from the distribution (see above for behavior if ``high=None``).\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single int is\n returned.\n\n Returns\n -------\n out : int or ndarray of ints\n `size`-shaped array of random integers from the appropriate\n distribution, or a single such random int if `size` not provided.\n\n See Also\n --------\n random.random_integers : similar to `randint`, only for the closed\n interval [`low`, `high`], and 1 is the lowest value if `high` is\n omitted. In particular, this other one is the one to use to generate\n uniformly distributed discrete non-integers.\n\n Examples\n --------\n >>> np.random.randint(2, size=10)\n array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])\n >>> np.random.randint(1, size=10)\n array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n\n Generate a 2 x 4 array of ints between 0 and 4, inclusive:\n\n >>> np.random.randint(5, size=(2, 4))\n array([[4, 0, 2, 1],\n [3, 2, 2, 0]])\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_21randint(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_low = 0; - PyObject *__pyx_v_high = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("randint (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__low,&__pyx_n_s__high,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - - /* "mtrand.pyx":812 - * return disc0_array(self.internal_state, rk_long, size) - * - * def randint(self, low, high=None, size=None): # <<<<<<<<<<<<<< - * """ - * randint(low, high=None, size=None) - */ - values[1] = ((PyObject *)Py_None); - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__low)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__high); - if (value) { values[1] = value; kw_args--; } - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "randint") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_low = values[0]; - __pyx_v_high = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("randint", 0, 1, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 812; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.randint", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_20randint(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_low, __pyx_v_high, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_20randint(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_low, PyObject *__pyx_v_high, PyObject *__pyx_v_size) { - long __pyx_v_lo; - long __pyx_v_hi; - long __pyx_v_rv; - unsigned long __pyx_v_diff; - long *__pyx_v_array_data; - PyArrayObject *arrayObject = 0; - npy_intp __pyx_v_length; - npy_intp __pyx_v_i; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - long __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - npy_intp __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("randint", 0); - - /* "mtrand.pyx":869 - * cdef npy_intp i - * - * if high is None: # <<<<<<<<<<<<<< - * lo = 0 - * hi = low - */ - __pyx_t_1 = (__pyx_v_high == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":870 - * - * if high is None: - * lo = 0 # <<<<<<<<<<<<<< - * hi = low - * else: - */ - __pyx_v_lo = 0; - - /* "mtrand.pyx":871 - * if high is None: - * lo = 0 - * hi = low # <<<<<<<<<<<<<< - * else: - * lo = low - */ - __pyx_t_2 = __Pyx_PyInt_AsLong(__pyx_v_low); if (unlikely((__pyx_t_2 == (long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 871; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_hi = __pyx_t_2; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":873 - * hi = low - * else: - * lo = low # <<<<<<<<<<<<<< - * hi = high - * - */ - __pyx_t_2 = __Pyx_PyInt_AsLong(__pyx_v_low); if (unlikely((__pyx_t_2 == (long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 873; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_lo = __pyx_t_2; - - /* "mtrand.pyx":874 - * else: - * lo = low - * hi = high # <<<<<<<<<<<<<< - * - * if lo >= hi : - */ - __pyx_t_2 = __Pyx_PyInt_AsLong(__pyx_v_high); if (unlikely((__pyx_t_2 == (long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 874; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_hi = __pyx_t_2; - } - __pyx_L3:; - - /* "mtrand.pyx":876 - * hi = high - * - * if lo >= hi : # <<<<<<<<<<<<<< - * raise ValueError("low >= high") - * - */ - __pyx_t_1 = (__pyx_v_lo >= __pyx_v_hi); - if (__pyx_t_1) { - - /* "mtrand.pyx":877 - * - * if lo >= hi : - * raise ValueError("low >= high") # <<<<<<<<<<<<<< - * - * diff = <unsigned long>hi - <unsigned long>lo - 1UL - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_16), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 877; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 877; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":879 - * raise ValueError("low >= high") - * - * diff = <unsigned long>hi - <unsigned long>lo - 1UL # <<<<<<<<<<<<<< - * if size is None: - * rv = lo + <long>rk_interval(diff, self. internal_state) - */ - __pyx_v_diff = ((((unsigned long)__pyx_v_hi) - ((unsigned long)__pyx_v_lo)) - 1UL); - - /* "mtrand.pyx":880 - * - * diff = <unsigned long>hi - <unsigned long>lo - 1UL - * if size is None: # <<<<<<<<<<<<<< - * rv = lo + <long>rk_interval(diff, self. internal_state) - * return rv - */ - __pyx_t_1 = (__pyx_v_size == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":881 - * diff = <unsigned long>hi - <unsigned long>lo - 1UL - * if size is None: - * rv = lo + <long>rk_interval(diff, self. internal_state) # <<<<<<<<<<<<<< - * return rv - * else: - */ - __pyx_v_rv = (__pyx_v_lo + ((long)rk_interval(__pyx_v_diff, __pyx_v_self->internal_state))); - - /* "mtrand.pyx":882 - * if size is None: - * rv = lo + <long>rk_interval(diff, self. internal_state) - * return rv # <<<<<<<<<<<<<< - * else: - * array = <ndarray>np.empty(size, int) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = PyInt_FromLong(__pyx_v_rv); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 882; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - goto __pyx_L5; - } - /*else*/ { - - /* "mtrand.pyx":884 - * return rv - * else: - * array = <ndarray>np.empty(size, int) # <<<<<<<<<<<<<< - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = __pyx_t_5; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - arrayObject = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":885 - * else: - * array = <ndarray>np.empty(size, int) - * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: - */ - __pyx_v_length = PyArray_SIZE(arrayObject); - - /* "mtrand.pyx":886 - * array = <ndarray>np.empty(size, int) - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) # <<<<<<<<<<<<<< - * for i from 0 <= i < length: - * rv = lo + <long>rk_interval(diff, self. internal_state) - */ - __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); - - /* "mtrand.pyx":887 - * length = PyArray_SIZE(array) - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: # <<<<<<<<<<<<<< - * rv = lo + <long>rk_interval(diff, self. internal_state) - * array_data[i] = rv - */ - __pyx_t_6 = __pyx_v_length; - for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_6; __pyx_v_i++) { - - /* "mtrand.pyx":888 - * array_data = <long *>PyArray_DATA(array) - * for i from 0 <= i < length: - * rv = lo + <long>rk_interval(diff, self. internal_state) # <<<<<<<<<<<<<< - * array_data[i] = rv - * return array - */ - __pyx_v_rv = (__pyx_v_lo + ((long)rk_interval(__pyx_v_diff, __pyx_v_self->internal_state))); - - /* "mtrand.pyx":889 - * for i from 0 <= i < length: - * rv = lo + <long>rk_interval(diff, self. internal_state) - * array_data[i] = rv # <<<<<<<<<<<<<< - * return array - * - */ - (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_rv; - } - - /* "mtrand.pyx":890 - * rv = lo + <long>rk_interval(diff, self. internal_state) - * array_data[i] = rv - * return array # <<<<<<<<<<<<<< - * - * def bytes(self, npy_intp length): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)arrayObject)); - __pyx_r = ((PyObject *)arrayObject); - goto __pyx_L0; - } - __pyx_L5:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.randint", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_23bytes(PyObject *__pyx_v_self, PyObject *__pyx_arg_length); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_22bytes[] = "\n bytes(length)\n\n Return random bytes.\n\n Parameters\n ----------\n length : int\n Number of random bytes.\n\n Returns\n -------\n out : str\n String of length `length`.\n\n Examples\n --------\n >>> np.random.bytes(10)\n ' eh\\x85\\x022SZ\\xbf\\xa4' #random\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_23bytes(PyObject *__pyx_v_self, PyObject *__pyx_arg_length) { - npy_intp __pyx_v_length; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("bytes (wrapper)", 0); - assert(__pyx_arg_length); { - __pyx_v_length = __Pyx_PyInt_from_py_npy_intp(__pyx_arg_length); if (unlikely((__pyx_v_length == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 892; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.bytes", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_22bytes(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), ((npy_intp)__pyx_v_length)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":892 - * return array - * - * def bytes(self, npy_intp length): # <<<<<<<<<<<<<< - * """ - * bytes(length) - */ - -static PyObject *__pyx_pf_6mtrand_11RandomState_22bytes(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, npy_intp __pyx_v_length) { - void *__pyx_v_bytes; - PyObject *__pyx_v_bytestring = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("bytes", 0); - - /* "mtrand.pyx":915 - * """ - * cdef void *bytes - * bytestring = empty_py_bytes(length, &bytes) # <<<<<<<<<<<<<< - * rk_fill(bytes, length, self.internal_state) - * return bytestring - */ - __pyx_t_1 = empty_py_bytes(__pyx_v_length, (&__pyx_v_bytes)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 915; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_bytestring = __pyx_t_1; - __pyx_t_1 = 0; - - /* "mtrand.pyx":916 - * cdef void *bytes - * bytestring = empty_py_bytes(length, &bytes) - * rk_fill(bytes, length, self.internal_state) # <<<<<<<<<<<<<< - * return bytestring - * - */ - rk_fill(__pyx_v_bytes, __pyx_v_length, __pyx_v_self->internal_state); - - /* "mtrand.pyx":917 - * bytestring = empty_py_bytes(length, &bytes) - * rk_fill(bytes, length, self.internal_state) - * return bytestring # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_bytestring); - __pyx_r = __pyx_v_bytestring; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("mtrand.RandomState.bytes", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_bytestring); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_25choice(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_24choice[] = "\n choice(a, size=None, replace=True, p=None)\n\n Generates a random sample from a given 1-D array\n\n .. versionadded:: 1.7.0\n\n Parameters\n -----------\n a : 1-D array-like or int\n If an ndarray, a random sample is generated from its elements.\n If an int, the random sample is generated as if a was np.arange(n)\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single value is\n returned.\n replace : boolean, optional\n Whether the sample is with or without replacement\n p : 1-D array-like, optional\n The probabilities associated with each entry in a.\n If not given the sample assumes a uniform distribtion over all\n entries in a.\n\n Returns\n --------\n samples : 1-D ndarray, shape (size,)\n The generated random samples\n\n Raises\n -------\n ValueError\n If a is an int and less than zero, if a or p are not 1-dimensional,\n if a is an array-like of size 0, if p is not a vector of\n probabilities, if a and p have different lengths, or if\n replace=False and the sample size is greater than the population\n size\n\n See Also\n ---------\n randint, shuffle, permutation\n\n Examples\n ---------\n Generate a uniform random sample from np.arange(5) of size 3:\n\n >>> np.random.choice(5, 3)\n array([0, 3, 4])\n >>> #This is equivalent to np.random.randint(0,5,3)\n\n Generate a non-uniform random sample from np.arange(5) of size 3:\n\n >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])\n array([3, 3, 0])\n\n Generate a uniform random sample from np.arange(5) of size 3 without\n replacement:\n\n >>> np.random.choice(5, 3, replace=False)\n array([3,1,0])\n "" >>> #This is equivalent to np.random.shuffle(np.arange(5))[:3]\n\n Generate a non-uniform random sample from np.arange(5) of size\n 3 without replacement:\n\n >>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])\n array([2, 3, 0])\n\n Any of the above can be repeated with an arbitrary array-like\n instead of just integers. For instance:\n\n >>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']\n >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])\n array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],\n dtype='|S11')\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_25choice(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_a = 0; - PyObject *__pyx_v_size = 0; - PyObject *__pyx_v_replace = 0; - PyObject *__pyx_v_p = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("choice (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__a,&__pyx_n_s__size,&__pyx_n_s__replace,&__pyx_n_s__p,0}; - PyObject* values[4] = {0,0,0,0}; - - /* "mtrand.pyx":920 - * - * - * def choice(self, a, size=None, replace=True, p=None): # <<<<<<<<<<<<<< - * """ - * choice(a, size=None, replace=True, p=None) - */ - values[1] = ((PyObject *)Py_None); - values[2] = __pyx_k_17; - values[3] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__a)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[1] = value; kw_args--; } - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__replace); - if (value) { values[2] = value; kw_args--; } - } - case 3: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p); - if (value) { values[3] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "choice") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 920; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_a = values[0]; - __pyx_v_size = values[1]; - __pyx_v_replace = values[2]; - __pyx_v_p = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("choice", 0, 1, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 920; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.choice", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_24choice(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_a, __pyx_v_size, __pyx_v_replace, __pyx_v_p); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_24choice(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_a, PyObject *__pyx_v_size, PyObject *__pyx_v_replace, PyObject *__pyx_v_p) { - PyObject *__pyx_v_pop_size = NULL; - PyObject *__pyx_v_shape = NULL; - PyObject *__pyx_v_cdf = NULL; - PyObject *__pyx_v_uniform_samples = NULL; - PyObject *__pyx_v_idx = NULL; - PyObject *__pyx_v_n_uniq = NULL; - PyObject *__pyx_v_found = NULL; - PyObject *__pyx_v_flat_found = NULL; - PyObject *__pyx_v_x = NULL; - PyObject *__pyx_v_new = NULL; - CYTHON_UNUSED PyObject *__pyx_v__ = NULL; - PyObject *__pyx_v_unique_indices = NULL; - PyObject *__pyx_v_res = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - int __pyx_t_11; - PyObject *(*__pyx_t_12)(PyObject *); - int __pyx_t_13; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("choice", 0); - __Pyx_INCREF(__pyx_v_a); - __Pyx_INCREF(__pyx_v_size); - __Pyx_INCREF(__pyx_v_p); - - /* "mtrand.pyx":998 - * - * # Format and Verify input - * a = np.array(a, copy=False) # <<<<<<<<<<<<<< - * if a.ndim == 0: - * try: - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__array); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_a); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_a); - __Pyx_GIVEREF(__pyx_v_a); - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_4 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__copy), __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_v_a); - __pyx_v_a = __pyx_t_4; - __pyx_t_4 = 0; - - /* "mtrand.pyx":999 - * # Format and Verify input - * a = np.array(a, copy=False) - * if a.ndim == 0: # <<<<<<<<<<<<<< - * try: - * # __index__ must return an integer by python rules. - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_a, __pyx_n_s__ndim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 999; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_4, __pyx_int_0, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 999; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 999; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_5) { - - /* "mtrand.pyx":1000 - * a = np.array(a, copy=False) - * if a.ndim == 0: - * try: # <<<<<<<<<<<<<< - * # __index__ must return an integer by python rules. - * pop_size = operator.index(a.item()) - */ - { - __Pyx_ExceptionSave(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); - __Pyx_XGOTREF(__pyx_t_6); - __Pyx_XGOTREF(__pyx_t_7); - __Pyx_XGOTREF(__pyx_t_8); - /*try:*/ { - - /* "mtrand.pyx":1002 - * try: - * # __index__ must return an integer by python rules. - * pop_size = operator.index(a.item()) # <<<<<<<<<<<<<< - * except TypeError: - * raise ValueError("a must be 1-dimensional or an integer") - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__operator); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1002; __pyx_clineno = __LINE__; goto __pyx_L4_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__index); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1002; __pyx_clineno = __LINE__; goto __pyx_L4_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_a, __pyx_n_s__item); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1002; __pyx_clineno = __LINE__; goto __pyx_L4_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1002; __pyx_clineno = __LINE__; goto __pyx_L4_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1002; __pyx_clineno = __LINE__; goto __pyx_L4_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1002; __pyx_clineno = __LINE__; goto __pyx_L4_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_v_pop_size = __pyx_t_1; - __pyx_t_1 = 0; - } - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - goto __pyx_L11_try_end; - __pyx_L4_error:; - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":1003 - * # __index__ must return an integer by python rules. - * pop_size = operator.index(a.item()) - * except TypeError: # <<<<<<<<<<<<<< - * raise ValueError("a must be 1-dimensional or an integer") - * if pop_size <= 0: - */ - __pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); - if (__pyx_t_9) { - __Pyx_AddTraceback("mtrand.RandomState.choice", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_3, &__pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1003; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_t_4); - - /* "mtrand.pyx":1004 - * pop_size = operator.index(a.item()) - * except TypeError: - * raise ValueError("a must be 1-dimensional or an integer") # <<<<<<<<<<<<<< - * if pop_size <= 0: - * raise ValueError("a must be greater than 0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_19), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1004; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1004; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - goto __pyx_L5_exception_handled; - } - __pyx_L6_except_error:; - __Pyx_XGIVEREF(__pyx_t_6); - __Pyx_XGIVEREF(__pyx_t_7); - __Pyx_XGIVEREF(__pyx_t_8); - __Pyx_ExceptionReset(__pyx_t_6, __pyx_t_7, __pyx_t_8); - goto __pyx_L1_error; - __pyx_L5_exception_handled:; - __Pyx_XGIVEREF(__pyx_t_6); - __Pyx_XGIVEREF(__pyx_t_7); - __Pyx_XGIVEREF(__pyx_t_8); - __Pyx_ExceptionReset(__pyx_t_6, __pyx_t_7, __pyx_t_8); - __pyx_L11_try_end:; - } - - /* "mtrand.pyx":1005 - * except TypeError: - * raise ValueError("a must be 1-dimensional or an integer") - * if pop_size <= 0: # <<<<<<<<<<<<<< - * raise ValueError("a must be greater than 0") - * elif a.ndim != 1: - */ - __pyx_t_4 = PyObject_RichCompare(__pyx_v_pop_size, __pyx_int_0, Py_LE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1005; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1005; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_5) { - - /* "mtrand.pyx":1006 - * raise ValueError("a must be 1-dimensional or an integer") - * if pop_size <= 0: - * raise ValueError("a must be greater than 0") # <<<<<<<<<<<<<< - * elif a.ndim != 1: - * raise ValueError("a must be 1-dimensional") - */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_21), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1006; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1006; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; - } - __pyx_L14:; - goto __pyx_L3; - } - - /* "mtrand.pyx":1007 - * if pop_size <= 0: - * raise ValueError("a must be greater than 0") - * elif a.ndim != 1: # <<<<<<<<<<<<<< - * raise ValueError("a must be 1-dimensional") - * else: - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_a, __pyx_n_s__ndim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1007; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_4, __pyx_int_1, Py_NE); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1007; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1007; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_5) { - - /* "mtrand.pyx":1008 - * raise ValueError("a must be greater than 0") - * elif a.ndim != 1: - * raise ValueError("a must be 1-dimensional") # <<<<<<<<<<<<<< - * else: - * pop_size = a.shape[0] - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_23), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1008; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1008; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":1010 - * raise ValueError("a must be 1-dimensional") - * else: - * pop_size = a.shape[0] # <<<<<<<<<<<<<< - * if pop_size is 0: - * raise ValueError("a must be non-empty") - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_a, __pyx_n_s__shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1010; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_GetItemInt(__pyx_t_3, 0, sizeof(long), PyInt_FromLong, 0, 0, 1); if (!__pyx_t_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1010; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_pop_size = __pyx_t_4; - __pyx_t_4 = 0; - - /* "mtrand.pyx":1011 - * else: - * pop_size = a.shape[0] - * if pop_size is 0: # <<<<<<<<<<<<<< - * raise ValueError("a must be non-empty") - * - */ - __pyx_t_5 = (__pyx_v_pop_size == __pyx_int_0); - if (__pyx_t_5) { - - /* "mtrand.pyx":1012 - * pop_size = a.shape[0] - * if pop_size is 0: - * raise ValueError("a must be non-empty") # <<<<<<<<<<<<<< - * - * if None != p: - */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_25), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1012; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1012; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L15; - } - __pyx_L15:; - } - __pyx_L3:; - - /* "mtrand.pyx":1014 - * raise ValueError("a must be non-empty") - * - * if None != p: # <<<<<<<<<<<<<< - * p = np.array(p, dtype=np.double, ndmin=1, copy=False) - * if p.ndim != 1: - */ - __pyx_t_4 = PyObject_RichCompare(Py_None, __pyx_v_p, Py_NE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1014; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1014; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_5) { - - /* "mtrand.pyx":1015 - * - * if None != p: - * p = np.array(p, dtype=np.double, ndmin=1, copy=False) # <<<<<<<<<<<<<< - * if p.ndim != 1: - * raise ValueError("p must be 1-dimensional") - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1015; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__array); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1015; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1015; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_p); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_p); - __Pyx_GIVEREF(__pyx_v_p); - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1015; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1015; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_10 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__double); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1015; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__dtype), __pyx_t_10) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1015; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__ndmin), __pyx_int_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1015; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_10 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1015; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_n_s__copy), __pyx_t_10) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1015; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_1)); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1015; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_v_p); - __pyx_v_p = __pyx_t_10; - __pyx_t_10 = 0; - - /* "mtrand.pyx":1016 - * if None != p: - * p = np.array(p, dtype=np.double, ndmin=1, copy=False) - * if p.ndim != 1: # <<<<<<<<<<<<<< - * raise ValueError("p must be 1-dimensional") - * if p.size != pop_size: - */ - __pyx_t_10 = __Pyx_PyObject_GetAttrStr(__pyx_v_p, __pyx_n_s__ndim); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1016; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_1 = PyObject_RichCompare(__pyx_t_10, __pyx_int_1, Py_NE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1016; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1016; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_5) { - - /* "mtrand.pyx":1017 - * p = np.array(p, dtype=np.double, ndmin=1, copy=False) - * if p.ndim != 1: - * raise ValueError("p must be 1-dimensional") # <<<<<<<<<<<<<< - * if p.size != pop_size: - * raise ValueError("a and p must have same size") - */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_27), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1017; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1017; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17; - } - __pyx_L17:; - - /* "mtrand.pyx":1018 - * if p.ndim != 1: - * raise ValueError("p must be 1-dimensional") - * if p.size != pop_size: # <<<<<<<<<<<<<< - * raise ValueError("a and p must have same size") - * if np.any(p < 0): - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_p, __pyx_n_s__size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1018; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_10 = PyObject_RichCompare(__pyx_t_1, __pyx_v_pop_size, Py_NE); __Pyx_XGOTREF(__pyx_t_10); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1018; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1018; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - if (__pyx_t_5) { - - /* "mtrand.pyx":1019 - * raise ValueError("p must be 1-dimensional") - * if p.size != pop_size: - * raise ValueError("a and p must have same size") # <<<<<<<<<<<<<< - * if np.any(p < 0): - * raise ValueError("probabilities are not non-negative") - */ - __pyx_t_10 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_29), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1019; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_Raise(__pyx_t_10, 0, 0, 0); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1019; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L18; - } - __pyx_L18:; - - /* "mtrand.pyx":1020 - * if p.size != pop_size: - * raise ValueError("a and p must have same size") - * if np.any(p < 0): # <<<<<<<<<<<<<< - * raise ValueError("probabilities are not non-negative") - * if not np.allclose(p.sum(), 1): - */ - __pyx_t_10 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1020; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_10, __pyx_n_s__any); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1020; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = PyObject_RichCompare(__pyx_v_p, __pyx_int_0, Py_LT); __Pyx_XGOTREF(__pyx_t_10); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1020; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1020; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_10); - __Pyx_GIVEREF(__pyx_t_10); - __pyx_t_10 = 0; - __pyx_t_10 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1020; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1020; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - if (__pyx_t_5) { - - /* "mtrand.pyx":1021 - * raise ValueError("a and p must have same size") - * if np.any(p < 0): - * raise ValueError("probabilities are not non-negative") # <<<<<<<<<<<<<< - * if not np.allclose(p.sum(), 1): - * raise ValueError("probabilities do not sum to 1") - */ - __pyx_t_10 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_31), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1021; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_Raise(__pyx_t_10, 0, 0, 0); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1021; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L19; - } - __pyx_L19:; - - /* "mtrand.pyx":1022 - * if np.any(p < 0): - * raise ValueError("probabilities are not non-negative") - * if not np.allclose(p.sum(), 1): # <<<<<<<<<<<<<< - * raise ValueError("probabilities do not sum to 1") - * - */ - __pyx_t_10 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1022; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_10, __pyx_n_s__allclose); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1022; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = __Pyx_PyObject_GetAttrStr(__pyx_v_p, __pyx_n_s__sum); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1022; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_1 = PyObject_Call(__pyx_t_10, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1022; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1022; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_INCREF(__pyx_int_1); - PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_int_1); - __Pyx_GIVEREF(__pyx_int_1); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_10), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1022; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_10)); __pyx_t_10 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1022; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_11 = (!__pyx_t_5); - if (__pyx_t_11) { - - /* "mtrand.pyx":1023 - * raise ValueError("probabilities are not non-negative") - * if not np.allclose(p.sum(), 1): - * raise ValueError("probabilities do not sum to 1") # <<<<<<<<<<<<<< - * - * shape = size - */ - __pyx_t_1 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_33), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1023; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1023; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L20; - } - __pyx_L20:; - goto __pyx_L16; - } - __pyx_L16:; - - /* "mtrand.pyx":1025 - * raise ValueError("probabilities do not sum to 1") - * - * shape = size # <<<<<<<<<<<<<< - * if shape is not None: - * size = np.prod(shape, dtype=np.intp) - */ - __Pyx_INCREF(__pyx_v_size); - __pyx_v_shape = __pyx_v_size; - - /* "mtrand.pyx":1026 - * - * shape = size - * if shape is not None: # <<<<<<<<<<<<<< - * size = np.prod(shape, dtype=np.intp) - * else: - */ - __pyx_t_11 = (__pyx_v_shape != Py_None); - if (__pyx_t_11) { - - /* "mtrand.pyx":1027 - * shape = size - * if shape is not None: - * size = np.prod(shape, dtype=np.intp) # <<<<<<<<<<<<<< - * else: - * size = 1 - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_10 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__prod); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_shape); - __Pyx_GIVEREF(__pyx_v_shape); - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__intp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__dtype), __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_10, ((PyObject *)__pyx_t_1), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_v_size); - __pyx_v_size = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L21; - } - /*else*/ { - - /* "mtrand.pyx":1029 - * size = np.prod(shape, dtype=np.intp) - * else: - * size = 1 # <<<<<<<<<<<<<< - * - * # Actual sampling - */ - __Pyx_INCREF(__pyx_int_1); - __Pyx_DECREF(__pyx_v_size); - __pyx_v_size = __pyx_int_1; - } - __pyx_L21:; - - /* "mtrand.pyx":1032 - * - * # Actual sampling - * if replace: # <<<<<<<<<<<<<< - * if None != p: - * cdf = p.cumsum() - */ - __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_v_replace); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1032; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__pyx_t_11) { - - /* "mtrand.pyx":1033 - * # Actual sampling - * if replace: - * if None != p: # <<<<<<<<<<<<<< - * cdf = p.cumsum() - * cdf /= cdf[-1] - */ - __pyx_t_2 = PyObject_RichCompare(Py_None, __pyx_v_p, Py_NE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1033; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1033; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_11) { - - /* "mtrand.pyx":1034 - * if replace: - * if None != p: - * cdf = p.cumsum() # <<<<<<<<<<<<<< - * cdf /= cdf[-1] - * uniform_samples = self.random_sample(shape) - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_p, __pyx_n_s__cumsum); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1034; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1034; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_cdf = __pyx_t_4; - __pyx_t_4 = 0; - - /* "mtrand.pyx":1035 - * if None != p: - * cdf = p.cumsum() - * cdf /= cdf[-1] # <<<<<<<<<<<<<< - * uniform_samples = self.random_sample(shape) - * idx = cdf.searchsorted(uniform_samples, side='right') - */ - __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_cdf, -1, sizeof(long), PyInt_FromLong, 0, 1, 1); if (!__pyx_t_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1035; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyNumber_InPlaceDivide(__pyx_v_cdf, __pyx_t_4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1035; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_v_cdf); - __pyx_v_cdf = __pyx_t_2; - __pyx_t_2 = 0; - - /* "mtrand.pyx":1036 - * cdf = p.cumsum() - * cdf /= cdf[-1] - * uniform_samples = self.random_sample(shape) # <<<<<<<<<<<<<< - * idx = cdf.searchsorted(uniform_samples, side='right') - * idx = np.array(idx, copy=False) # searchsorted returns a scalar - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__random_sample); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1036; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1036; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_shape); - __Pyx_GIVEREF(__pyx_v_shape); - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1036; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_v_uniform_samples = __pyx_t_1; - __pyx_t_1 = 0; - - /* "mtrand.pyx":1037 - * cdf /= cdf[-1] - * uniform_samples = self.random_sample(shape) - * idx = cdf.searchsorted(uniform_samples, side='right') # <<<<<<<<<<<<<< - * idx = np.array(idx, copy=False) # searchsorted returns a scalar - * else: - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_cdf, __pyx_n_s__searchsorted); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_uniform_samples); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_uniform_samples); - __Pyx_GIVEREF(__pyx_v_uniform_samples); - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__side), ((PyObject *)__pyx_n_s__right)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_10 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_v_idx = __pyx_t_10; - __pyx_t_10 = 0; - - /* "mtrand.pyx":1038 - * uniform_samples = self.random_sample(shape) - * idx = cdf.searchsorted(uniform_samples, side='right') - * idx = np.array(idx, copy=False) # searchsorted returns a scalar # <<<<<<<<<<<<<< - * else: - * idx = self.randint(0, pop_size, size=shape) - */ - __pyx_t_10 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1038; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_10, __pyx_n_s__array); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1038; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = PyTuple_New(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1038; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_INCREF(__pyx_v_idx); - PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_v_idx); - __Pyx_GIVEREF(__pyx_v_idx); - __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1038; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_4)); - __pyx_t_1 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1038; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_t_4, ((PyObject *)__pyx_n_s__copy), __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1038; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_10), ((PyObject *)__pyx_t_4)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1038; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_10)); __pyx_t_10 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_v_idx); - __pyx_v_idx = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L23; - } - /*else*/ { - - /* "mtrand.pyx":1040 - * idx = np.array(idx, copy=False) # searchsorted returns a scalar - * else: - * idx = self.randint(0, pop_size, size=shape) # <<<<<<<<<<<<<< - * else: - * if size > pop_size: - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__randint); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1040; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1040; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __Pyx_INCREF(__pyx_v_pop_size); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_v_pop_size); - __Pyx_GIVEREF(__pyx_v_pop_size); - __pyx_t_10 = PyDict_New(); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1040; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_10)); - if (PyDict_SetItem(__pyx_t_10, ((PyObject *)__pyx_n_s__size), __pyx_v_shape) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1040; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_10)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1040; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_10)); __pyx_t_10 = 0; - __pyx_v_idx = __pyx_t_2; - __pyx_t_2 = 0; - } - __pyx_L23:; - goto __pyx_L22; - } - /*else*/ { - - /* "mtrand.pyx":1042 - * idx = self.randint(0, pop_size, size=shape) - * else: - * if size > pop_size: # <<<<<<<<<<<<<< - * raise ValueError("Cannot take a larger sample than " - * "population when 'replace=False'") - */ - __pyx_t_2 = PyObject_RichCompare(__pyx_v_size, __pyx_v_pop_size, Py_GT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1042; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1042; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_11) { - - /* "mtrand.pyx":1043 - * else: - * if size > pop_size: - * raise ValueError("Cannot take a larger sample than " # <<<<<<<<<<<<<< - * "population when 'replace=False'") - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_35), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L24; - } - __pyx_L24:; - - /* "mtrand.pyx":1046 - * "population when 'replace=False'") - * - * if None != p: # <<<<<<<<<<<<<< - * if np.sum(p > 0) < size: - * raise ValueError("Fewer non-zero entries in p than size") - */ - __pyx_t_2 = PyObject_RichCompare(Py_None, __pyx_v_p, Py_NE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1046; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1046; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_11) { - - /* "mtrand.pyx":1047 - * - * if None != p: - * if np.sum(p > 0) < size: # <<<<<<<<<<<<<< - * raise ValueError("Fewer non-zero entries in p than size") - * n_uniq = 0 - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1047; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_10 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__sum); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1047; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_RichCompare(__pyx_v_p, __pyx_int_0, Py_GT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1047; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1047; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_10, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1047; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_4 = PyObject_RichCompare(__pyx_t_2, __pyx_v_size, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1047; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1047; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_11) { - - /* "mtrand.pyx":1048 - * if None != p: - * if np.sum(p > 0) < size: - * raise ValueError("Fewer non-zero entries in p than size") # <<<<<<<<<<<<<< - * n_uniq = 0 - * p = p.copy() - */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_37), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1048; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1048; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L26; - } - __pyx_L26:; - - /* "mtrand.pyx":1049 - * if np.sum(p > 0) < size: - * raise ValueError("Fewer non-zero entries in p than size") - * n_uniq = 0 # <<<<<<<<<<<<<< - * p = p.copy() - * found = np.zeros(shape, dtype=np.int) - */ - __Pyx_INCREF(__pyx_int_0); - __pyx_v_n_uniq = __pyx_int_0; - - /* "mtrand.pyx":1050 - * raise ValueError("Fewer non-zero entries in p than size") - * n_uniq = 0 - * p = p.copy() # <<<<<<<<<<<<<< - * found = np.zeros(shape, dtype=np.int) - * flat_found = found.ravel() - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_p, __pyx_n_s__copy); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_v_p); - __pyx_v_p = __pyx_t_2; - __pyx_t_2 = 0; - - /* "mtrand.pyx":1051 - * n_uniq = 0 - * p = p.copy() - * found = np.zeros(shape, dtype=np.int) # <<<<<<<<<<<<<< - * flat_found = found.ravel() - * while n_uniq < size: - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1051; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__zeros); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1051; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1051; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); - __Pyx_GIVEREF(__pyx_v_shape); - __pyx_t_10 = PyDict_New(); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1051; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_10)); - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1051; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__int); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1051; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_t_10, ((PyObject *)__pyx_n_s__dtype), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1051; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_10)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1051; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_10)); __pyx_t_10 = 0; - __pyx_v_found = __pyx_t_3; - __pyx_t_3 = 0; - - /* "mtrand.pyx":1052 - * p = p.copy() - * found = np.zeros(shape, dtype=np.int) - * flat_found = found.ravel() # <<<<<<<<<<<<<< - * while n_uniq < size: - * x = self.rand(size - n_uniq) - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_found, __pyx_n_s__ravel); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1052; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_10 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1052; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_flat_found = __pyx_t_10; - __pyx_t_10 = 0; - - /* "mtrand.pyx":1053 - * found = np.zeros(shape, dtype=np.int) - * flat_found = found.ravel() - * while n_uniq < size: # <<<<<<<<<<<<<< - * x = self.rand(size - n_uniq) - * if n_uniq > 0: - */ - while (1) { - __pyx_t_10 = PyObject_RichCompare(__pyx_v_n_uniq, __pyx_v_size, Py_LT); __Pyx_XGOTREF(__pyx_t_10); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1053; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1053; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - if (!__pyx_t_11) break; - - /* "mtrand.pyx":1054 - * flat_found = found.ravel() - * while n_uniq < size: - * x = self.rand(size - n_uniq) # <<<<<<<<<<<<<< - * if n_uniq > 0: - * p[flat_found[0:n_uniq]] = 0 - */ - __pyx_t_10 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__rand); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_3 = PyNumber_Subtract(__pyx_v_size, __pyx_v_n_uniq); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_10, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_v_x); - __pyx_v_x = __pyx_t_3; - __pyx_t_3 = 0; - - /* "mtrand.pyx":1055 - * while n_uniq < size: - * x = self.rand(size - n_uniq) - * if n_uniq > 0: # <<<<<<<<<<<<<< - * p[flat_found[0:n_uniq]] = 0 - * cdf = np.cumsum(p) - */ - __pyx_t_3 = PyObject_RichCompare(__pyx_v_n_uniq, __pyx_int_0, Py_GT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1055; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1055; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_11) { - - /* "mtrand.pyx":1056 - * x = self.rand(size - n_uniq) - * if n_uniq > 0: - * p[flat_found[0:n_uniq]] = 0 # <<<<<<<<<<<<<< - * cdf = np.cumsum(p) - * cdf /= cdf[-1] - */ - __pyx_t_3 = __Pyx_PyObject_GetSlice(__pyx_v_flat_found, 0, 0, NULL, &__pyx_v_n_uniq, NULL, 1, 0, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1056; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - if (PyObject_SetItem(__pyx_v_p, __pyx_t_3, __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1056; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L29; - } - __pyx_L29:; - - /* "mtrand.pyx":1057 - * if n_uniq > 0: - * p[flat_found[0:n_uniq]] = 0 - * cdf = np.cumsum(p) # <<<<<<<<<<<<<< - * cdf /= cdf[-1] - * new = cdf.searchsorted(x, side='right') - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1057; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__cumsum); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1057; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1057; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_p); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_p); - __Pyx_GIVEREF(__pyx_v_p); - __pyx_t_10 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1057; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_v_cdf); - __pyx_v_cdf = __pyx_t_10; - __pyx_t_10 = 0; - - /* "mtrand.pyx":1058 - * p[flat_found[0:n_uniq]] = 0 - * cdf = np.cumsum(p) - * cdf /= cdf[-1] # <<<<<<<<<<<<<< - * new = cdf.searchsorted(x, side='right') - * _, unique_indices = np.unique(new, return_index=True) - */ - __pyx_t_10 = __Pyx_GetItemInt(__pyx_v_cdf, -1, sizeof(long), PyInt_FromLong, 0, 1, 1); if (!__pyx_t_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1058; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_3 = __Pyx_PyNumber_InPlaceDivide(__pyx_v_cdf, __pyx_t_10); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1058; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(__pyx_v_cdf); - __pyx_v_cdf = __pyx_t_3; - __pyx_t_3 = 0; - - /* "mtrand.pyx":1059 - * cdf = np.cumsum(p) - * cdf /= cdf[-1] - * new = cdf.searchsorted(x, side='right') # <<<<<<<<<<<<<< - * _, unique_indices = np.unique(new, return_index=True) - * unique_indices.sort() - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_cdf, __pyx_n_s__searchsorted); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_10 = PyTuple_New(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_INCREF(__pyx_v_x); - PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_v_x); - __Pyx_GIVEREF(__pyx_v_x); - __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - if (PyDict_SetItem(__pyx_t_2, ((PyObject *)__pyx_n_s__side), ((PyObject *)__pyx_n_s__right)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_10), ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1059; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_10)); __pyx_t_10 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_v_new); - __pyx_v_new = __pyx_t_4; - __pyx_t_4 = 0; - - /* "mtrand.pyx":1060 - * cdf /= cdf[-1] - * new = cdf.searchsorted(x, side='right') - * _, unique_indices = np.unique(new, return_index=True) # <<<<<<<<<<<<<< - * unique_indices.sort() - * new = new.take(unique_indices) - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__unique); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_new); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_new); - __Pyx_GIVEREF(__pyx_v_new); - __pyx_t_10 = PyDict_New(); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_10)); - __pyx_t_3 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - if (PyDict_SetItem(__pyx_t_10, ((PyObject *)__pyx_n_s__return_index), __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_4), ((PyObject *)__pyx_t_10)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_10)); __pyx_t_10 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_3))) || (PyList_CheckExact(__pyx_t_3))) { - PyObject* sequence = __pyx_t_3; - #if CYTHON_COMPILING_IN_CPYTHON - Py_ssize_t size = Py_SIZE(sequence); - #else - Py_ssize_t size = PySequence_Size(sequence); - #endif - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - #if CYTHON_COMPILING_IN_CPYTHON - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_10 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_10 = PyList_GET_ITEM(sequence, 0); - __pyx_t_4 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_10); - __Pyx_INCREF(__pyx_t_4); - #else - __pyx_t_10 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - #endif - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else - { - Py_ssize_t index = -1; - __pyx_t_2 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_12 = Py_TYPE(__pyx_t_2)->tp_iternext; - index = 0; __pyx_t_10 = __pyx_t_12(__pyx_t_2); if (unlikely(!__pyx_t_10)) goto __pyx_L30_unpacking_failed; - __Pyx_GOTREF(__pyx_t_10); - index = 1; __pyx_t_4 = __pyx_t_12(__pyx_t_2); if (unlikely(!__pyx_t_4)) goto __pyx_L30_unpacking_failed; - __Pyx_GOTREF(__pyx_t_4); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_12(__pyx_t_2), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_12 = NULL; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - goto __pyx_L31_unpacking_done; - __pyx_L30_unpacking_failed:; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_12 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1060; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_L31_unpacking_done:; - } - __Pyx_XDECREF(__pyx_v__); - __pyx_v__ = __pyx_t_10; - __pyx_t_10 = 0; - __Pyx_XDECREF(__pyx_v_unique_indices); - __pyx_v_unique_indices = __pyx_t_4; - __pyx_t_4 = 0; - - /* "mtrand.pyx":1061 - * new = cdf.searchsorted(x, side='right') - * _, unique_indices = np.unique(new, return_index=True) - * unique_indices.sort() # <<<<<<<<<<<<<< - * new = new.take(unique_indices) - * flat_found[n_uniq:n_uniq + new.size] = new - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_unique_indices, __pyx_n_s__sort); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":1062 - * _, unique_indices = np.unique(new, return_index=True) - * unique_indices.sort() - * new = new.take(unique_indices) # <<<<<<<<<<<<<< - * flat_found[n_uniq:n_uniq + new.size] = new - * n_uniq += new.size - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_new, __pyx_n_s__take); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1062; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1062; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_unique_indices); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_unique_indices); - __Pyx_GIVEREF(__pyx_v_unique_indices); - __pyx_t_10 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1062; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_v_new); - __pyx_v_new = __pyx_t_10; - __pyx_t_10 = 0; - - /* "mtrand.pyx":1063 - * unique_indices.sort() - * new = new.take(unique_indices) - * flat_found[n_uniq:n_uniq + new.size] = new # <<<<<<<<<<<<<< - * n_uniq += new.size - * idx = found - */ - __pyx_t_10 = __Pyx_PyObject_GetAttrStr(__pyx_v_new, __pyx_n_s__size); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1063; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_3 = PyNumber_Add(__pyx_v_n_uniq, __pyx_t_10); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1063; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - if (__Pyx_PyObject_SetSlice(__pyx_v_flat_found, __pyx_v_new, 0, 0, &__pyx_v_n_uniq, &__pyx_t_3, NULL, 0, 0, 1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1063; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "mtrand.pyx":1064 - * new = new.take(unique_indices) - * flat_found[n_uniq:n_uniq + new.size] = new - * n_uniq += new.size # <<<<<<<<<<<<<< - * idx = found - * else: - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_new, __pyx_n_s__size); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1064; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_10 = PyNumber_InPlaceAdd(__pyx_v_n_uniq, __pyx_t_3); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1064; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_v_n_uniq); - __pyx_v_n_uniq = __pyx_t_10; - __pyx_t_10 = 0; - } - - /* "mtrand.pyx":1065 - * flat_found[n_uniq:n_uniq + new.size] = new - * n_uniq += new.size - * idx = found # <<<<<<<<<<<<<< - * else: - * idx = self.permutation(pop_size)[:size] - */ - __Pyx_INCREF(__pyx_v_found); - __pyx_v_idx = __pyx_v_found; - goto __pyx_L25; - } - /*else*/ { - - /* "mtrand.pyx":1067 - * idx = found - * else: - * idx = self.permutation(pop_size)[:size] # <<<<<<<<<<<<<< - * if shape is not None: - * idx.shape = shape - */ - __pyx_t_10 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__permutation); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1067; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1067; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_pop_size); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_pop_size); - __Pyx_GIVEREF(__pyx_v_pop_size); - __pyx_t_4 = PyObject_Call(__pyx_t_10, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1067; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_GetSlice(__pyx_t_4, 0, 0, NULL, &__pyx_v_size, NULL, 0, 0, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1067; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_idx = __pyx_t_3; - __pyx_t_3 = 0; - - /* "mtrand.pyx":1068 - * else: - * idx = self.permutation(pop_size)[:size] - * if shape is not None: # <<<<<<<<<<<<<< - * idx.shape = shape - * - */ - __pyx_t_11 = (__pyx_v_shape != Py_None); - if (__pyx_t_11) { - - /* "mtrand.pyx":1069 - * idx = self.permutation(pop_size)[:size] - * if shape is not None: - * idx.shape = shape # <<<<<<<<<<<<<< - * - * if shape is None and isinstance(idx, np.ndarray): - */ - if (__Pyx_PyObject_SetAttrStr(__pyx_v_idx, __pyx_n_s__shape, __pyx_v_shape) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1069; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L32; - } - __pyx_L32:; - } - __pyx_L25:; - } - __pyx_L22:; - - /* "mtrand.pyx":1071 - * idx.shape = shape - * - * if shape is None and isinstance(idx, np.ndarray): # <<<<<<<<<<<<<< - * # In most cases a scalar will have been made an array - * idx = idx.item(0) - */ - __pyx_t_11 = (__pyx_v_shape == Py_None); - if (__pyx_t_11) { - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1071; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__ndarray); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1071; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_5 = PyObject_IsInstance(__pyx_v_idx, __pyx_t_4); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1071; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_13 = __pyx_t_5; - } else { - __pyx_t_13 = __pyx_t_11; - } - if (__pyx_t_13) { - - /* "mtrand.pyx":1073 - * if shape is None and isinstance(idx, np.ndarray): - * # In most cases a scalar will have been made an array - * idx = idx.item(0) # <<<<<<<<<<<<<< - * - * #Use samples as indices for a if a is array-like - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_idx, __pyx_n_s__item); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1073; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_k_tuple_38), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1073; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_v_idx); - __pyx_v_idx = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L33; - } - __pyx_L33:; - - /* "mtrand.pyx":1076 - * - * #Use samples as indices for a if a is array-like - * if a.ndim == 0: # <<<<<<<<<<<<<< - * return idx - * - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_a, __pyx_n_s__ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1076; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_int_0, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1076; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_13 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_13 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1076; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_13) { - - /* "mtrand.pyx":1077 - * #Use samples as indices for a if a is array-like - * if a.ndim == 0: - * return idx # <<<<<<<<<<<<<< - * - * if shape is not None and idx.ndim == 0: - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_idx); - __pyx_r = __pyx_v_idx; - goto __pyx_L0; - goto __pyx_L34; - } - __pyx_L34:; - - /* "mtrand.pyx":1079 - * return idx - * - * if shape is not None and idx.ndim == 0: # <<<<<<<<<<<<<< - * # If size == () then the user requested a 0-d array as opposed to - * # a scalar object when size is None. However a[idx] is always a - */ - __pyx_t_13 = (__pyx_v_shape != Py_None); - if (__pyx_t_13) { - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_idx, __pyx_n_s__ndim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1079; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_RichCompare(__pyx_t_4, __pyx_int_0, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1079; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1079; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_5 = __pyx_t_11; - } else { - __pyx_t_5 = __pyx_t_13; - } - if (__pyx_t_5) { - - /* "mtrand.pyx":1085 - * # array, taking into account that np.array(item) may not work - * # for object arrays. - * res = np.empty((), dtype=a.dtype) # <<<<<<<<<<<<<< - * res[()] = a[idx] - * return res - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1085; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__empty); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1085; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1085; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - __pyx_t_10 = __Pyx_PyObject_GetAttrStr(__pyx_v_a, __pyx_n_s__dtype); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1085; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__dtype), __pyx_t_10) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1085; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_k_tuple_39), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1085; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_v_res = __pyx_t_10; - __pyx_t_10 = 0; - - /* "mtrand.pyx":1086 - * # for object arrays. - * res = np.empty((), dtype=a.dtype) - * res[()] = a[idx] # <<<<<<<<<<<<<< - * return res - * - */ - __pyx_t_10 = PyObject_GetItem(__pyx_v_a, __pyx_v_idx); if (!__pyx_t_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1086; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - if (PyObject_SetItem(__pyx_v_res, ((PyObject *)__pyx_empty_tuple), __pyx_t_10) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1086; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - - /* "mtrand.pyx":1087 - * res = np.empty((), dtype=a.dtype) - * res[()] = a[idx] - * return res # <<<<<<<<<<<<<< - * - * return a[idx] - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_res); - __pyx_r = __pyx_v_res; - goto __pyx_L0; - goto __pyx_L35; - } - __pyx_L35:; - - /* "mtrand.pyx":1089 - * return res - * - * return a[idx] # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_10 = PyObject_GetItem(__pyx_v_a, __pyx_v_idx); if (!__pyx_t_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1089; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __pyx_r = __pyx_t_10; - __pyx_t_10 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("mtrand.RandomState.choice", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_pop_size); - __Pyx_XDECREF(__pyx_v_shape); - __Pyx_XDECREF(__pyx_v_cdf); - __Pyx_XDECREF(__pyx_v_uniform_samples); - __Pyx_XDECREF(__pyx_v_idx); - __Pyx_XDECREF(__pyx_v_n_uniq); - __Pyx_XDECREF(__pyx_v_found); - __Pyx_XDECREF(__pyx_v_flat_found); - __Pyx_XDECREF(__pyx_v_x); - __Pyx_XDECREF(__pyx_v_new); - __Pyx_XDECREF(__pyx_v__); - __Pyx_XDECREF(__pyx_v_unique_indices); - __Pyx_XDECREF(__pyx_v_res); - __Pyx_XDECREF(__pyx_v_a); - __Pyx_XDECREF(__pyx_v_size); - __Pyx_XDECREF(__pyx_v_p); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_27uniform(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_26uniform[] = "\n uniform(low=0.0, high=1.0, size=1)\n\n Draw samples from a uniform distribution.\n\n Samples are uniformly distributed over the half-open interval\n ``[low, high)`` (includes low, but excludes high). In other words,\n any value within the given interval is equally likely to be drawn\n by `uniform`.\n\n Parameters\n ----------\n low : float, optional\n Lower boundary of the output interval. All values generated will be\n greater than or equal to low. The default value is 0.\n high : float\n Upper boundary of the output interval. All values generated will be\n less than high. The default value is 1.0.\n size : int or tuple of ints, optional\n Shape of output. If the given size is, for example, (m,n,k),\n m*n*k samples are generated. If no shape is specified, a single sample\n is returned.\n\n Returns\n -------\n out : ndarray\n Drawn samples, with shape `size`.\n\n See Also\n --------\n randint : Discrete uniform distribution, yielding integers.\n random_integers : Discrete uniform distribution over the closed\n interval ``[low, high]``.\n random_sample : Floats uniformly distributed over ``[0, 1)``.\n random : Alias for `random_sample`.\n rand : Convenience function that accepts dimensions as input, e.g.,\n ``rand(2,2)`` would generate a 2-by-2 array of floats,\n uniformly distributed over ``[0, 1)``.\n\n Notes\n -----\n The probability density function of the uniform distribution is\n\n .. math:: p(x) = \\frac{1}{b - a}\n\n anywhere within the interval ``[a, b)``, and zero elsewhere.\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> s = np.random.uniform(-1,0,1000)\n\n All values are w""ithin the given interval:\n\n >>> np.all(s >= -1)\n True\n >>> np.all(s < 0)\n True\n\n Display the histogram of the samples, along with the\n probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, 15, normed=True)\n >>> plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_27uniform(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_low = 0; - PyObject *__pyx_v_high = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("uniform (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__low,&__pyx_n_s__high,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - values[0] = __pyx_k_40; - values[1] = __pyx_k_41; - - /* "mtrand.pyx":1092 - * - * - * def uniform(self, low=0.0, high=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * uniform(low=0.0, high=1.0, size=1) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__low); - if (value) { values[0] = value; kw_args--; } - } - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__high); - if (value) { values[1] = value; kw_args--; } - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "uniform") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1092; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_low = values[0]; - __pyx_v_high = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("uniform", 0, 0, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1092; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.uniform", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_26uniform(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_low, __pyx_v_high, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_26uniform(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_low, PyObject *__pyx_v_high, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_olow = 0; - PyArrayObject *__pyx_v_ohigh = 0; - PyArrayObject *__pyx_v_odiff = 0; - double __pyx_v_flow; - double __pyx_v_fhigh; - PyObject *__pyx_v_temp = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("uniform", 0); - - /* "mtrand.pyx":1166 - * cdef object temp - * - * flow = PyFloat_AsDouble(low) # <<<<<<<<<<<<<< - * fhigh = PyFloat_AsDouble(high) - * if not PyErr_Occurred(): - */ - __pyx_v_flow = PyFloat_AsDouble(__pyx_v_low); - - /* "mtrand.pyx":1167 - * - * flow = PyFloat_AsDouble(low) - * fhigh = PyFloat_AsDouble(high) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * return cont2_array_sc(self.internal_state, rk_uniform, size, flow, fhigh-flow) - */ - __pyx_v_fhigh = PyFloat_AsDouble(__pyx_v_high); - - /* "mtrand.pyx":1168 - * flow = PyFloat_AsDouble(low) - * fhigh = PyFloat_AsDouble(high) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_uniform, size, flow, fhigh-flow) - * PyErr_Clear() - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":1169 - * fhigh = PyFloat_AsDouble(high) - * if not PyErr_Occurred(): - * return cont2_array_sc(self.internal_state, rk_uniform, size, flow, fhigh-flow) # <<<<<<<<<<<<<< - * PyErr_Clear() - * olow = <ndarray>PyArray_FROM_OTF(low, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array_sc(__pyx_v_self->internal_state, rk_uniform, __pyx_v_size, __pyx_v_flow, (__pyx_v_fhigh - __pyx_v_flow)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1169; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":1170 - * if not PyErr_Occurred(): - * return cont2_array_sc(self.internal_state, rk_uniform, size, flow, fhigh-flow) - * PyErr_Clear() # <<<<<<<<<<<<<< - * olow = <ndarray>PyArray_FROM_OTF(low, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * ohigh = <ndarray>PyArray_FROM_OTF(high, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":1171 - * return cont2_array_sc(self.internal_state, rk_uniform, size, flow, fhigh-flow) - * PyErr_Clear() - * olow = <ndarray>PyArray_FROM_OTF(low, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * ohigh = <ndarray>PyArray_FROM_OTF(high, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * temp = np.subtract(ohigh, olow) - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_low, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1171; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_olow = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":1172 - * PyErr_Clear() - * olow = <ndarray>PyArray_FROM_OTF(low, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * ohigh = <ndarray>PyArray_FROM_OTF(high, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * temp = np.subtract(ohigh, olow) - * Py_INCREF(temp) # needed to get around Pyrex's automatic reference-counting - */ - __pyx_t_3 = PyArray_FROM_OTF(__pyx_v_high, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_ohigh = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":1173 - * olow = <ndarray>PyArray_FROM_OTF(low, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * ohigh = <ndarray>PyArray_FROM_OTF(high, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * temp = np.subtract(ohigh, olow) # <<<<<<<<<<<<<< - * Py_INCREF(temp) # needed to get around Pyrex's automatic reference-counting - * # rules because EnsureArray steals a reference - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__subtract); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)__pyx_v_ohigh)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_ohigh)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_ohigh)); - __Pyx_INCREF(((PyObject *)__pyx_v_olow)); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_v_olow)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_olow)); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_v_temp = __pyx_t_4; - __pyx_t_4 = 0; - - /* "mtrand.pyx":1174 - * ohigh = <ndarray>PyArray_FROM_OTF(high, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * temp = np.subtract(ohigh, olow) - * Py_INCREF(temp) # needed to get around Pyrex's automatic reference-counting # <<<<<<<<<<<<<< - * # rules because EnsureArray steals a reference - * odiff = <ndarray>PyArray_EnsureArray(temp) - */ - Py_INCREF(__pyx_v_temp); - - /* "mtrand.pyx":1176 - * Py_INCREF(temp) # needed to get around Pyrex's automatic reference-counting - * # rules because EnsureArray steals a reference - * odiff = <ndarray>PyArray_EnsureArray(temp) # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_uniform, size, olow, odiff) - * - */ - __pyx_t_4 = PyArray_EnsureArray(__pyx_v_temp); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1176; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __pyx_t_4; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_odiff = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":1177 - * # rules because EnsureArray steals a reference - * odiff = <ndarray>PyArray_EnsureArray(temp) - * return cont2_array(self.internal_state, rk_uniform, size, olow, odiff) # <<<<<<<<<<<<<< - * - * def rand(self, *args): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array(__pyx_v_self->internal_state, rk_uniform, __pyx_v_size, __pyx_v_olow, __pyx_v_odiff); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1177; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("mtrand.RandomState.uniform", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_olow); - __Pyx_XDECREF((PyObject *)__pyx_v_ohigh); - __Pyx_XDECREF((PyObject *)__pyx_v_odiff); - __Pyx_XDECREF(__pyx_v_temp); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_29rand(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_28rand[] = "\n rand(d0, d1, ..., dn)\n\n Random values in a given shape.\n\n Create an array of the given shape and propagate it with\n random samples from a uniform distribution\n over ``[0, 1)``.\n\n Parameters\n ----------\n d0, d1, ..., dn : int, optional\n The dimensions of the returned array, should all be positive.\n If no argument is given a single Python float is returned.\n\n Returns\n -------\n out : ndarray, shape ``(d0, d1, ..., dn)``\n Random values.\n\n See Also\n --------\n random\n\n Notes\n -----\n This is a convenience function. If you want an interface that\n takes a shape-tuple as the first argument, refer to\n np.random.random_sample .\n\n Examples\n --------\n >>> np.random.rand(3,2)\n array([[ 0.14022471, 0.96360618], #random\n [ 0.37601032, 0.25528411], #random\n [ 0.49313049, 0.94909878]]) #random\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_29rand(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_args = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("rand (wrapper)", 0); - if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "rand", 0))) return NULL; - __Pyx_INCREF(__pyx_args); - __pyx_v_args = __pyx_args; - __pyx_r = __pyx_pf_6mtrand_11RandomState_28rand(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_args); - __Pyx_XDECREF(__pyx_v_args); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":1179 - * return cont2_array(self.internal_state, rk_uniform, size, olow, odiff) - * - * def rand(self, *args): # <<<<<<<<<<<<<< - * """ - * rand(d0, d1, ..., dn) - */ - -static PyObject *__pyx_pf_6mtrand_11RandomState_28rand(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_args) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("rand", 0); - - /* "mtrand.pyx":1218 - * - * """ - * if len(args) == 0: # <<<<<<<<<<<<<< - * return self.random_sample() - * else: - */ - __pyx_t_1 = PyTuple_GET_SIZE(((PyObject *)__pyx_v_args)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = (__pyx_t_1 == 0); - if (__pyx_t_2) { - - /* "mtrand.pyx":1219 - * """ - * if len(args) == 0: - * return self.random_sample() # <<<<<<<<<<<<<< - * else: - * return self.random_sample(size=args) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__random_sample); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":1221 - * return self.random_sample() - * else: - * return self.random_sample(size=args) # <<<<<<<<<<<<<< - * - * def randn(self, *args): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__random_sample); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_3)); - if (PyDict_SetItem(__pyx_t_3, ((PyObject *)__pyx_n_s__size), ((PyObject *)__pyx_v_args)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_empty_tuple), ((PyObject *)__pyx_t_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - } - __pyx_L3:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.rand", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_31randn(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_30randn[] = "\n randn(d0, d1, ..., dn)\n\n Return a sample (or samples) from the \"standard normal\" distribution.\n\n If positive, int_like or int-convertible arguments are provided,\n `randn` generates an array of shape ``(d0, d1, ..., dn)``, filled\n with random floats sampled from a univariate \"normal\" (Gaussian)\n distribution of mean 0 and variance 1 (if any of the :math:`d_i` are\n floats, they are first converted to integers by truncation). A single\n float randomly sampled from the distribution is returned if no\n argument is provided.\n\n This is a convenience function. If you want an interface that takes a\n tuple as the first argument, use `numpy.random.standard_normal` instead.\n\n Parameters\n ----------\n d0, d1, ..., dn : int, optional\n The dimensions of the returned array, should be all positive.\n If no argument is given a single Python float is returned.\n\n Returns\n -------\n Z : ndarray or float\n A ``(d0, d1, ..., dn)``-shaped array of floating-point samples from\n the standard normal distribution, or a single such float if\n no parameters were supplied.\n\n See Also\n --------\n random.standard_normal : Similar, but takes a tuple as its argument.\n\n Notes\n -----\n For random samples from :math:`N(\\mu, \\sigma^2)`, use:\n\n ``sigma * np.random.randn(...) + mu``\n\n Examples\n --------\n >>> np.random.randn()\n 2.1923875335537315 #random\n\n Two-by-four array of samples from N(3, 6.25):\n\n >>> 2.5 * np.random.randn(2, 4) + 3\n array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], #random\n [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) #random\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_31randn(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_args = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("randn (wrapper)", 0); - if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "randn", 0))) return NULL; - __Pyx_INCREF(__pyx_args); - __pyx_v_args = __pyx_args; - __pyx_r = __pyx_pf_6mtrand_11RandomState_30randn(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_args); - __Pyx_XDECREF(__pyx_v_args); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":1223 - * return self.random_sample(size=args) - * - * def randn(self, *args): # <<<<<<<<<<<<<< - * """ - * randn(d0, d1, ..., dn) - */ - -static PyObject *__pyx_pf_6mtrand_11RandomState_30randn(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_args) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("randn", 0); - - /* "mtrand.pyx":1275 - * - * """ - * if len(args) == 0: # <<<<<<<<<<<<<< - * return self.standard_normal() - * else: - */ - __pyx_t_1 = PyTuple_GET_SIZE(((PyObject *)__pyx_v_args)); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1275; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = (__pyx_t_1 == 0); - if (__pyx_t_2) { - - /* "mtrand.pyx":1276 - * """ - * if len(args) == 0: - * return self.standard_normal() # <<<<<<<<<<<<<< - * else: - * return self.standard_normal(args) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__standard_normal); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":1278 - * return self.standard_normal() - * else: - * return self.standard_normal(args) # <<<<<<<<<<<<<< - * - * def random_integers(self, low, high=None, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__standard_normal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(((PyObject *)__pyx_v_args)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_args)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_args)); - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - } - __pyx_L3:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.randn", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_33random_integers(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_32random_integers[] = "\n random_integers(low, high=None, size=None)\n\n Return random integers between `low` and `high`, inclusive.\n\n Return random integers from the \"discrete uniform\" distribution in the\n closed interval [`low`, `high`]. If `high` is None (the default),\n then results are from [1, `low`].\n\n Parameters\n ----------\n low : int\n Lowest (signed) integer to be drawn from the distribution (unless\n ``high=None``, in which case this parameter is the *highest* such\n integer).\n high : int, optional\n If provided, the largest (signed) integer to be drawn from the\n distribution (see above for behavior if ``high=None``).\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single int is returned.\n\n Returns\n -------\n out : int or ndarray of ints\n `size`-shaped array of random integers from the appropriate\n distribution, or a single such random int if `size` not provided.\n\n See Also\n --------\n random.randint : Similar to `random_integers`, only for the half-open\n interval [`low`, `high`), and 0 is the lowest value if `high` is\n omitted.\n\n Notes\n -----\n To sample from N evenly spaced floating-point numbers between a and b,\n use::\n\n a + (b - a) * (np.random.random_integers(N) - 1) / (N - 1.)\n\n Examples\n --------\n >>> np.random.random_integers(5)\n 4\n >>> type(np.random.random_integers(5))\n <type 'int'>\n >>> np.random.random_integers(5, size=(3.,2.))\n array([[5, 4],\n [3, 3],\n [4, 5]])\n\n Choose five random numbers from the set of five evenly-spaced\n numbers between 0 and 2.5, inclusive (*i.e.*, from the set\n :math:`{0, 5/8, 10/8, 15/8, 20/8}`):\n""\n >>> 2.5 * (np.random.random_integers(5, size=(5,)) - 1) / 4.\n array([ 0.625, 1.25 , 0.625, 0.625, 2.5 ])\n\n Roll two six sided dice 1000 times and sum the results:\n\n >>> d1 = np.random.random_integers(1, 6, 1000)\n >>> d2 = np.random.random_integers(1, 6, 1000)\n >>> dsums = d1 + d2\n\n Display results as a histogram:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(dsums, 11, normed=True)\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_33random_integers(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_low = 0; - PyObject *__pyx_v_high = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("random_integers (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__low,&__pyx_n_s__high,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - - /* "mtrand.pyx":1280 - * return self.standard_normal(args) - * - * def random_integers(self, low, high=None, size=None): # <<<<<<<<<<<<<< - * """ - * random_integers(low, high=None, size=None) - */ - values[1] = ((PyObject *)Py_None); - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__low)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__high); - if (value) { values[1] = value; kw_args--; } - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "random_integers") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1280; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_low = values[0]; - __pyx_v_high = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("random_integers", 0, 1, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1280; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.random_integers", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_32random_integers(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_low, __pyx_v_high, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_32random_integers(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_low, PyObject *__pyx_v_high, PyObject *__pyx_v_size) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("random_integers", 0); - __Pyx_INCREF(__pyx_v_low); - __Pyx_INCREF(__pyx_v_high); - - /* "mtrand.pyx":1352 - * - * """ - * if high is None: # <<<<<<<<<<<<<< - * high = low - * low = 1 - */ - __pyx_t_1 = (__pyx_v_high == Py_None); - if (__pyx_t_1) { - - /* "mtrand.pyx":1353 - * """ - * if high is None: - * high = low # <<<<<<<<<<<<<< - * low = 1 - * return self.randint(low, high+1, size) - */ - __Pyx_INCREF(__pyx_v_low); - __Pyx_DECREF(__pyx_v_high); - __pyx_v_high = __pyx_v_low; - - /* "mtrand.pyx":1354 - * if high is None: - * high = low - * low = 1 # <<<<<<<<<<<<<< - * return self.randint(low, high+1, size) - * - */ - __Pyx_INCREF(__pyx_int_1); - __Pyx_DECREF(__pyx_v_low); - __pyx_v_low = __pyx_int_1; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":1355 - * high = low - * low = 1 - * return self.randint(low, high+1, size) # <<<<<<<<<<<<<< - * - * # Complicated, continuous distributions: - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__randint); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Add(__pyx_v_high, __pyx_int_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_low); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_low); - __Pyx_GIVEREF(__pyx_v_low); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1355; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("mtrand.RandomState.random_integers", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_low); - __Pyx_XDECREF(__pyx_v_high); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_35standard_normal(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_34standard_normal[] = "\n standard_normal(size=None)\n\n Returns samples from a Standard Normal distribution (mean=0, stdev=1).\n\n Parameters\n ----------\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single value is\n returned.\n\n Returns\n -------\n out : float or ndarray\n Drawn samples.\n\n Examples\n --------\n >>> s = np.random.standard_normal(8000)\n >>> s\n array([ 0.6888893 , 0.78096262, -0.89086505, ..., 0.49876311, #random\n -0.38672696, -0.4685006 ]) #random\n >>> s.shape\n (8000,)\n >>> s = np.random.standard_normal(size=(3, 4, 2))\n >>> s.shape\n (3, 4, 2)\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_35standard_normal(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("standard_normal (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__size,0}; - PyObject* values[1] = {0}; - - /* "mtrand.pyx":1358 - * - * # Complicated, continuous distributions: - * def standard_normal(self, size=None): # <<<<<<<<<<<<<< - * """ - * standard_normal(size=None) - */ - values[0] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[0] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "standard_normal") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1358; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_size = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("standard_normal", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1358; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.standard_normal", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_34standard_normal(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_34standard_normal(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_size) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("standard_normal", 0); - - /* "mtrand.pyx":1388 - * - * """ - * return cont0_array(self.internal_state, rk_gauss, size) # <<<<<<<<<<<<<< - * - * def normal(self, loc=0.0, scale=1.0, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_f_6mtrand_cont0_array(__pyx_v_self->internal_state, rk_gauss, __pyx_v_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1388; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("mtrand.RandomState.standard_normal", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_37normal(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_36normal[] = "\n normal(loc=0.0, scale=1.0, size=None)\n\n Draw random samples from a normal (Gaussian) distribution.\n\n The probability density function of the normal distribution, first\n derived by De Moivre and 200 years later by both Gauss and Laplace\n independently [2]_, is often called the bell curve because of\n its characteristic shape (see the example below).\n\n The normal distributions occurs often in nature. For example, it\n describes the commonly occurring distribution of samples influenced\n by a large number of tiny, random disturbances, each with its own\n unique distribution [2]_.\n\n Parameters\n ----------\n loc : float\n Mean (\"centre\") of the distribution.\n scale : float\n Standard deviation (spread or \"width\") of the distribution.\n size : tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n See Also\n --------\n scipy.stats.distributions.norm : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Gaussian distribution is\n\n .. math:: p(x) = \\frac{1}{\\sqrt{ 2 \\pi \\sigma^2 }}\n e^{ - \\frac{ (x - \\mu)^2 } {2 \\sigma^2} },\n\n where :math:`\\mu` is the mean and :math:`\\sigma` the standard deviation.\n The square of the standard deviation, :math:`\\sigma^2`, is called the\n variance.\n\n The function has its peak at the mean, and its \"spread\" increases with\n the standard deviation (the function reaches 0.607 times its maximum at\n :math:`x + \\sigma` and :math:`x - \\sigma` [2]_). This implies that\n `numpy.random.normal` is more likely to return samples lying close to the\n mean, rather than those far away.\n""\n References\n ----------\n .. [1] Wikipedia, \"Normal distribution\",\n http://en.wikipedia.org/wiki/Normal_distribution\n .. [2] P. R. Peebles Jr., \"Central Limit Theorem\" in \"Probability, Random\n Variables and Random Signal Principles\", 4th ed., 2001,\n pp. 51, 51, 125.\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> mu, sigma = 0, 0.1 # mean and standard deviation\n >>> s = np.random.normal(mu, sigma, 1000)\n\n Verify the mean and the variance:\n\n >>> abs(mu - np.mean(s)) < 0.01\n True\n\n >>> abs(sigma - np.std(s, ddof=1)) < 0.01\n True\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, 30, normed=True)\n >>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *\n ... np.exp( - (bins - mu)**2 / (2 * sigma**2) ),\n ... linewidth=2, color='r')\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_37normal(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_loc = 0; - PyObject *__pyx_v_scale = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("normal (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__loc,&__pyx_n_s__scale,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - values[0] = __pyx_k_42; - values[1] = __pyx_k_43; - - /* "mtrand.pyx":1390 - * return cont0_array(self.internal_state, rk_gauss, size) - * - * def normal(self, loc=0.0, scale=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * normal(loc=0.0, scale=1.0, size=None) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__loc); - if (value) { values[0] = value; kw_args--; } - } - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__scale); - if (value) { values[1] = value; kw_args--; } - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "normal") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1390; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_loc = values[0]; - __pyx_v_scale = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("normal", 0, 0, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1390; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.normal", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_36normal(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_loc, __pyx_v_scale, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_36normal(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_loc, PyObject *__pyx_v_scale, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_oloc = 0; - PyArrayObject *__pyx_v_oscale = 0; - double __pyx_v_floc; - double __pyx_v_fscale; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("normal", 0); - - /* "mtrand.pyx":1475 - * cdef double floc, fscale - * - * floc = PyFloat_AsDouble(loc) # <<<<<<<<<<<<<< - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): - */ - __pyx_v_floc = PyFloat_AsDouble(__pyx_v_loc); - - /* "mtrand.pyx":1476 - * - * floc = PyFloat_AsDouble(loc) - * fscale = PyFloat_AsDouble(scale) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fscale <= 0: - */ - __pyx_v_fscale = PyFloat_AsDouble(__pyx_v_scale); - - /* "mtrand.pyx":1477 - * floc = PyFloat_AsDouble(loc) - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fscale <= 0: - * raise ValueError("scale <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":1478 - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): - * if fscale <= 0: # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont2_array_sc(self.internal_state, rk_normal, size, floc, fscale) - */ - __pyx_t_1 = (__pyx_v_fscale <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":1479 - * if not PyErr_Occurred(): - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_normal, size, floc, fscale) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_45), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":1480 - * if fscale <= 0: - * raise ValueError("scale <= 0") - * return cont2_array_sc(self.internal_state, rk_normal, size, floc, fscale) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array_sc(__pyx_v_self->internal_state, rk_normal, __pyx_v_size, __pyx_v_floc, __pyx_v_fscale); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1480; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":1482 - * return cont2_array_sc(self.internal_state, rk_normal, size, floc, fscale) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * oloc = <ndarray>PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":1484 - * PyErr_Clear() - * - * oloc = <ndarray>PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1484; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_oloc = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":1485 - * - * oloc = <ndarray>PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oscale, 0)): - * raise ValueError("scale <= 0") - */ - __pyx_t_3 = PyArray_FROM_OTF(__pyx_v_scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_oscale = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":1486 - * oloc = <ndarray>PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0)): # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont2_array(self.internal_state, rk_normal, size, oloc, oscale) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_oscale)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oscale)); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":1487 - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0)): - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_normal, size, oloc, oscale) - * - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_46), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1487; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1487; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":1488 - * if np.any(np.less_equal(oscale, 0)): - * raise ValueError("scale <= 0") - * return cont2_array(self.internal_state, rk_normal, size, oloc, oscale) # <<<<<<<<<<<<<< - * - * def beta(self, a, b, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_5 = __pyx_f_6mtrand_cont2_array(__pyx_v_self->internal_state, rk_normal, __pyx_v_size, __pyx_v_oloc, __pyx_v_oscale); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.normal", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_oloc); - __Pyx_XDECREF((PyObject *)__pyx_v_oscale); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_39beta(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_38beta[] = "\n beta(a, b, size=None)\n\n The Beta distribution over ``[0, 1]``.\n\n The Beta distribution is a special case of the Dirichlet distribution,\n and is related to the Gamma distribution. It has the probability\n distribution function\n\n .. math:: f(x; a,b) = \\frac{1}{B(\\alpha, \\beta)} x^{\\alpha - 1}\n (1 - x)^{\\beta - 1},\n\n where the normalisation, B, is the beta function,\n\n .. math:: B(\\alpha, \\beta) = \\int_0^1 t^{\\alpha - 1}\n (1 - t)^{\\beta - 1} dt.\n\n It is often seen in Bayesian inference and order statistics.\n\n Parameters\n ----------\n a : float\n Alpha, non-negative.\n b : float\n Beta, non-negative.\n size : tuple of ints, optional\n The number of samples to draw. The output is packed according to\n the size given.\n\n Returns\n -------\n out : ndarray\n Array of the given shape, containing values drawn from a\n Beta distribution.\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_39beta(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_a = 0; - PyObject *__pyx_v_b = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("beta (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__a,&__pyx_n_s__b,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - - /* "mtrand.pyx":1490 - * return cont2_array(self.internal_state, rk_normal, size, oloc, oscale) - * - * def beta(self, a, b, size=None): # <<<<<<<<<<<<<< - * """ - * beta(a, b, size=None) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__a)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__b)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("beta", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1490; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "beta") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1490; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_a = values[0]; - __pyx_v_b = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("beta", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1490; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.beta", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_38beta(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_a, __pyx_v_b, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_38beta(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_oa = 0; - PyArrayObject *__pyx_v_ob = 0; - double __pyx_v_fa; - double __pyx_v_fb; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("beta", 0); - - /* "mtrand.pyx":1530 - * cdef double fa, fb - * - * fa = PyFloat_AsDouble(a) # <<<<<<<<<<<<<< - * fb = PyFloat_AsDouble(b) - * if not PyErr_Occurred(): - */ - __pyx_v_fa = PyFloat_AsDouble(__pyx_v_a); - - /* "mtrand.pyx":1531 - * - * fa = PyFloat_AsDouble(a) - * fb = PyFloat_AsDouble(b) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fa <= 0: - */ - __pyx_v_fb = PyFloat_AsDouble(__pyx_v_b); - - /* "mtrand.pyx":1532 - * fa = PyFloat_AsDouble(a) - * fb = PyFloat_AsDouble(b) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fa <= 0: - * raise ValueError("a <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":1533 - * fb = PyFloat_AsDouble(b) - * if not PyErr_Occurred(): - * if fa <= 0: # <<<<<<<<<<<<<< - * raise ValueError("a <= 0") - * if fb <= 0: - */ - __pyx_t_1 = (__pyx_v_fa <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":1534 - * if not PyErr_Occurred(): - * if fa <= 0: - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * if fb <= 0: - * raise ValueError("b <= 0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_48), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1534; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1534; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":1535 - * if fa <= 0: - * raise ValueError("a <= 0") - * if fb <= 0: # <<<<<<<<<<<<<< - * raise ValueError("b <= 0") - * return cont2_array_sc(self.internal_state, rk_beta, size, fa, fb) - */ - __pyx_t_1 = (__pyx_v_fb <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":1536 - * raise ValueError("a <= 0") - * if fb <= 0: - * raise ValueError("b <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_beta, size, fa, fb) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_50), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":1537 - * if fb <= 0: - * raise ValueError("b <= 0") - * return cont2_array_sc(self.internal_state, rk_beta, size, fa, fb) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array_sc(__pyx_v_self->internal_state, rk_beta, __pyx_v_size, __pyx_v_fa, __pyx_v_fb); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":1539 - * return cont2_array_sc(self.internal_state, rk_beta, size, fa, fb) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":1541 - * PyErr_Clear() - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * ob = <ndarray>PyArray_FROM_OTF(b, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 0)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_a, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1541; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_oa = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":1542 - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * ob = <ndarray>PyArray_FROM_OTF(b, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oa, 0)): - * raise ValueError("a <= 0") - */ - __pyx_t_3 = PyArray_FROM_OTF(__pyx_v_b, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_ob = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":1543 - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * ob = <ndarray>PyArray_FROM_OTF(b, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 0)): # <<<<<<<<<<<<<< - * raise ValueError("a <= 0") - * if np.any(np.less_equal(ob, 0)): - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)__pyx_v_oa)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_oa)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oa)); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1543; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":1544 - * ob = <ndarray>PyArray_FROM_OTF(b, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 0)): - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * if np.any(np.less_equal(ob, 0)): - * raise ValueError("b <= 0") - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_51), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1544; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1544; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":1545 - * if np.any(np.less_equal(oa, 0)): - * raise ValueError("a <= 0") - * if np.any(np.less_equal(ob, 0)): # <<<<<<<<<<<<<< - * raise ValueError("b <= 0") - * return cont2_array(self.internal_state, rk_beta, size, oa, ob) - */ - __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_ob)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_ob)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_ob)); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1545; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":1546 - * raise ValueError("a <= 0") - * if np.any(np.less_equal(ob, 0)): - * raise ValueError("b <= 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_beta, size, oa, ob) - * - */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_52), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; - - /* "mtrand.pyx":1547 - * if np.any(np.less_equal(ob, 0)): - * raise ValueError("b <= 0") - * return cont2_array(self.internal_state, rk_beta, size, oa, ob) # <<<<<<<<<<<<<< - * - * def exponential(self, scale=1.0, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = __pyx_f_6mtrand_cont2_array(__pyx_v_self->internal_state, rk_beta, __pyx_v_size, __pyx_v_oa, __pyx_v_ob); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1547; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.beta", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_oa); - __Pyx_XDECREF((PyObject *)__pyx_v_ob); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_41exponential(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_40exponential[] = "\n exponential(scale=1.0, size=None)\n\n Exponential distribution.\n\n Its probability density function is\n\n .. math:: f(x; \\frac{1}{\\beta}) = \\frac{1}{\\beta} \\exp(-\\frac{x}{\\beta}),\n\n for ``x > 0`` and 0 elsewhere. :math:`\\beta` is the scale parameter,\n which is the inverse of the rate parameter :math:`\\lambda = 1/\\beta`.\n The rate parameter is an alternative, widely used parameterization\n of the exponential distribution [3]_.\n\n The exponential distribution is a continuous analogue of the\n geometric distribution. It describes many common situations, such as\n the size of raindrops measured over many rainstorms [1]_, or the time\n between page requests to Wikipedia [2]_.\n\n Parameters\n ----------\n scale : float\n The scale parameter, :math:`\\beta = 1/\\lambda`.\n size : tuple of ints\n Number of samples to draw. The output is shaped\n according to `size`.\n\n References\n ----------\n .. [1] Peyton Z. Peebles Jr., \"Probability, Random Variables and\n Random Signal Principles\", 4th ed, 2001, p. 57.\n .. [2] \"Poisson Process\", Wikipedia,\n http://en.wikipedia.org/wiki/Poisson_process\n .. [3] \"Exponential Distribution, Wikipedia,\n http://en.wikipedia.org/wiki/Exponential_distribution\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_41exponential(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_scale = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("exponential (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__scale,&__pyx_n_s__size,0}; - PyObject* values[2] = {0,0}; - values[0] = __pyx_k_53; - - /* "mtrand.pyx":1549 - * return cont2_array(self.internal_state, rk_beta, size, oa, ob) - * - * def exponential(self, scale=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * exponential(scale=1.0, size=None) - */ - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__scale); - if (value) { values[0] = value; kw_args--; } - } - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "exponential") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1549; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_scale = values[0]; - __pyx_v_size = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("exponential", 0, 0, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1549; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.exponential", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_40exponential(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_scale, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_40exponential(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_scale, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_oscale = 0; - double __pyx_v_fscale; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("exponential", 0); - - /* "mtrand.pyx":1590 - * cdef double fscale - * - * fscale = PyFloat_AsDouble(scale) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fscale <= 0: - */ - __pyx_v_fscale = PyFloat_AsDouble(__pyx_v_scale); - - /* "mtrand.pyx":1591 - * - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fscale <= 0: - * raise ValueError("scale <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":1592 - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): - * if fscale <= 0: # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont1_array_sc(self.internal_state, rk_exponential, size, fscale) - */ - __pyx_t_1 = (__pyx_v_fscale <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":1593 - * if not PyErr_Occurred(): - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_exponential, size, fscale) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_54), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":1594 - * if fscale <= 0: - * raise ValueError("scale <= 0") - * return cont1_array_sc(self.internal_state, rk_exponential, size, fscale) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont1_array_sc(__pyx_v_self->internal_state, rk_exponential, __pyx_v_size, __pyx_v_fscale); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1594; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":1596 - * return cont1_array_sc(self.internal_state, rk_exponential, size, fscale) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * oscale = <ndarray> PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":1598 - * PyErr_Clear() - * - * oscale = <ndarray> PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_oscale = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":1599 - * - * oscale = <ndarray> PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont1_array(self.internal_state, rk_exponential, size, oscale) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_oscale)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1599; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":1600 - * oscale = <ndarray> PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_exponential, size, oscale) - * - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_55), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1600; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1600; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":1601 - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") - * return cont1_array(self.internal_state, rk_exponential, size, oscale) # <<<<<<<<<<<<<< - * - * def standard_exponential(self, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __pyx_f_6mtrand_cont1_array(__pyx_v_self->internal_state, rk_exponential, __pyx_v_size, __pyx_v_oscale); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1601; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.exponential", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_oscale); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_43standard_exponential(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_42standard_exponential[] = "\n standard_exponential(size=None)\n\n Draw samples from the standard exponential distribution.\n\n `standard_exponential` is identical to the exponential distribution\n with a scale parameter of 1.\n\n Parameters\n ----------\n size : int or tuple of ints\n Shape of the output.\n\n Returns\n -------\n out : float or ndarray\n Drawn samples.\n\n Examples\n --------\n Output a 3x8000 array:\n\n >>> n = np.random.standard_exponential((3, 8000))\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_43standard_exponential(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("standard_exponential (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__size,0}; - PyObject* values[1] = {0}; - - /* "mtrand.pyx":1603 - * return cont1_array(self.internal_state, rk_exponential, size, oscale) - * - * def standard_exponential(self, size=None): # <<<<<<<<<<<<<< - * """ - * standard_exponential(size=None) - */ - values[0] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[0] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "standard_exponential") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1603; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_size = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("standard_exponential", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1603; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.standard_exponential", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_42standard_exponential(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_42standard_exponential(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_size) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("standard_exponential", 0); - - /* "mtrand.pyx":1629 - * - * """ - * return cont0_array(self.internal_state, rk_standard_exponential, size) # <<<<<<<<<<<<<< - * - * def standard_gamma(self, shape, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_f_6mtrand_cont0_array(__pyx_v_self->internal_state, rk_standard_exponential, __pyx_v_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1629; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("mtrand.RandomState.standard_exponential", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_45standard_gamma(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_44standard_gamma[] = "\n standard_gamma(shape, size=None)\n\n Draw samples from a Standard Gamma distribution.\n\n Samples are drawn from a Gamma distribution with specified parameters,\n shape (sometimes designated \"k\") and scale=1.\n\n Parameters\n ----------\n shape : float\n Parameter, should be > 0.\n size : int or tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : ndarray or scalar\n The drawn samples.\n\n See Also\n --------\n scipy.stats.distributions.gamma : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Gamma distribution is\n\n .. math:: p(x) = x^{k-1}\\frac{e^{-x/\\theta}}{\\theta^k\\Gamma(k)},\n\n where :math:`k` is the shape and :math:`\\theta` the scale,\n and :math:`\\Gamma` is the Gamma function.\n\n The Gamma distribution is often used to model the times to failure of\n electronic components, and arises naturally in processes for which the\n waiting times between Poisson distributed events are relevant.\n\n References\n ----------\n .. [1] Weisstein, Eric W. \"Gamma Distribution.\" From MathWorld--A\n Wolfram Web Resource.\n http://mathworld.wolfram.com/GammaDistribution.html\n .. [2] Wikipedia, \"Gamma-distribution\",\n http://en.wikipedia.org/wiki/Gamma-distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> shape, scale = 2., 1. # mean and width\n >>> s = np.random.standard_gamma(shape, 1000000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt""\n >>> import scipy.special as sps\n >>> count, bins, ignored = plt.hist(s, 50, normed=True)\n >>> y = bins**(shape-1) * ((np.exp(-bins/scale))/ \\\n ... (sps.gamma(shape) * scale**shape))\n >>> plt.plot(bins, y, linewidth=2, color='r')\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_45standard_gamma(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_shape = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("standard_gamma (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__shape,&__pyx_n_s__size,0}; - PyObject* values[2] = {0,0}; - - /* "mtrand.pyx":1631 - * return cont0_array(self.internal_state, rk_standard_exponential, size) - * - * def standard_gamma(self, shape, size=None): # <<<<<<<<<<<<<< - * """ - * standard_gamma(shape, size=None) - */ - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shape)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "standard_gamma") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1631; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_shape = values[0]; - __pyx_v_size = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("standard_gamma", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1631; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.standard_gamma", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_44standard_gamma(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_shape, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_44standard_gamma(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_shape, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_oshape = 0; - double __pyx_v_fshape; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("standard_gamma", 0); - - /* "mtrand.pyx":1701 - * cdef double fshape - * - * fshape = PyFloat_AsDouble(shape) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fshape <= 0: - */ - __pyx_v_fshape = PyFloat_AsDouble(__pyx_v_shape); - - /* "mtrand.pyx":1702 - * - * fshape = PyFloat_AsDouble(shape) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fshape <= 0: - * raise ValueError("shape <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":1703 - * fshape = PyFloat_AsDouble(shape) - * if not PyErr_Occurred(): - * if fshape <= 0: # <<<<<<<<<<<<<< - * raise ValueError("shape <= 0") - * return cont1_array_sc(self.internal_state, rk_standard_gamma, size, fshape) - */ - __pyx_t_1 = (__pyx_v_fshape <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":1704 - * if not PyErr_Occurred(): - * if fshape <= 0: - * raise ValueError("shape <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_standard_gamma, size, fshape) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_57), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1704; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1704; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":1705 - * if fshape <= 0: - * raise ValueError("shape <= 0") - * return cont1_array_sc(self.internal_state, rk_standard_gamma, size, fshape) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont1_array_sc(__pyx_v_self->internal_state, rk_standard_gamma, __pyx_v_size, __pyx_v_fshape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1705; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":1707 - * return cont1_array_sc(self.internal_state, rk_standard_gamma, size, fshape) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * oshape = <ndarray> PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oshape, 0.0)): - */ - PyErr_Clear(); - - /* "mtrand.pyx":1708 - * - * PyErr_Clear() - * oshape = <ndarray> PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oshape, 0.0)): - * raise ValueError("shape <= 0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_oshape = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":1709 - * PyErr_Clear() - * oshape = <ndarray> PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oshape, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("shape <= 0") - * return cont1_array(self.internal_state, rk_standard_gamma, size, oshape) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1709; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1709; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1709; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1709; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1709; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1709; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_oshape)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_oshape)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oshape)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1709; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1709; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1709; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1709; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":1710 - * oshape = <ndarray> PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oshape, 0.0)): - * raise ValueError("shape <= 0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_standard_gamma, size, oshape) - * - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_58), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1710; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1710; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":1711 - * if np.any(np.less_equal(oshape, 0.0)): - * raise ValueError("shape <= 0") - * return cont1_array(self.internal_state, rk_standard_gamma, size, oshape) # <<<<<<<<<<<<<< - * - * def gamma(self, shape, scale=1.0, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __pyx_f_6mtrand_cont1_array(__pyx_v_self->internal_state, rk_standard_gamma, __pyx_v_size, __pyx_v_oshape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1711; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.standard_gamma", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_oshape); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_47gamma(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_46gamma[] = "\n gamma(shape, scale=1.0, size=None)\n\n Draw samples from a Gamma distribution.\n\n Samples are drawn from a Gamma distribution with specified parameters,\n `shape` (sometimes designated \"k\") and `scale` (sometimes designated\n \"theta\"), where both parameters are > 0.\n\n Parameters\n ----------\n shape : scalar > 0\n The shape of the gamma distribution.\n scale : scalar > 0, optional\n The scale of the gamma distribution. Default is equal to 1.\n size : shape_tuple, optional\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n out : ndarray, float\n Returns one sample unless `size` parameter is specified.\n\n See Also\n --------\n scipy.stats.distributions.gamma : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Gamma distribution is\n\n .. math:: p(x) = x^{k-1}\\frac{e^{-x/\\theta}}{\\theta^k\\Gamma(k)},\n\n where :math:`k` is the shape and :math:`\\theta` the scale,\n and :math:`\\Gamma` is the Gamma function.\n\n The Gamma distribution is often used to model the times to failure of\n electronic components, and arises naturally in processes for which the\n waiting times between Poisson distributed events are relevant.\n\n References\n ----------\n .. [1] Weisstein, Eric W. \"Gamma Distribution.\" From MathWorld--A\n Wolfram Web Resource.\n http://mathworld.wolfram.com/GammaDistribution.html\n .. [2] Wikipedia, \"Gamma-distribution\",\n http://en.wikipedia.org/wiki/Gamma-distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> shape, scale = 2.,"" 2. # mean and dispersion\n >>> s = np.random.gamma(shape, scale, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> import scipy.special as sps\n >>> count, bins, ignored = plt.hist(s, 50, normed=True)\n >>> y = bins**(shape-1)*(np.exp(-bins/scale) /\n ... (sps.gamma(shape)*scale**shape))\n >>> plt.plot(bins, y, linewidth=2, color='r')\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_47gamma(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_shape = 0; - PyObject *__pyx_v_scale = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("gamma (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__shape,&__pyx_n_s__scale,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - values[1] = __pyx_k_59; - - /* "mtrand.pyx":1713 - * return cont1_array(self.internal_state, rk_standard_gamma, size, oshape) - * - * def gamma(self, shape, scale=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * gamma(shape, scale=1.0, size=None) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__shape)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__scale); - if (value) { values[1] = value; kw_args--; } - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "gamma") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1713; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_shape = values[0]; - __pyx_v_scale = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("gamma", 0, 1, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1713; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.gamma", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_46gamma(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_shape, __pyx_v_scale, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_46gamma(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_shape, PyObject *__pyx_v_scale, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_oshape = 0; - PyArrayObject *__pyx_v_oscale = 0; - double __pyx_v_fshape; - double __pyx_v_fscale; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("gamma", 0); - - /* "mtrand.pyx":1786 - * cdef double fshape, fscale - * - * fshape = PyFloat_AsDouble(shape) # <<<<<<<<<<<<<< - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): - */ - __pyx_v_fshape = PyFloat_AsDouble(__pyx_v_shape); - - /* "mtrand.pyx":1787 - * - * fshape = PyFloat_AsDouble(shape) - * fscale = PyFloat_AsDouble(scale) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fshape <= 0: - */ - __pyx_v_fscale = PyFloat_AsDouble(__pyx_v_scale); - - /* "mtrand.pyx":1788 - * fshape = PyFloat_AsDouble(shape) - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fshape <= 0: - * raise ValueError("shape <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":1789 - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): - * if fshape <= 0: # <<<<<<<<<<<<<< - * raise ValueError("shape <= 0") - * if fscale <= 0: - */ - __pyx_t_1 = (__pyx_v_fshape <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":1790 - * if not PyErr_Occurred(): - * if fshape <= 0: - * raise ValueError("shape <= 0") # <<<<<<<<<<<<<< - * if fscale <= 0: - * raise ValueError("scale <= 0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_60), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":1791 - * if fshape <= 0: - * raise ValueError("shape <= 0") - * if fscale <= 0: # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont2_array_sc(self.internal_state, rk_gamma, size, fshape, fscale) - */ - __pyx_t_1 = (__pyx_v_fscale <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":1792 - * raise ValueError("shape <= 0") - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_gamma, size, fshape, fscale) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_61), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":1793 - * if fscale <= 0: - * raise ValueError("scale <= 0") - * return cont2_array_sc(self.internal_state, rk_gamma, size, fshape, fscale) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array_sc(__pyx_v_self->internal_state, rk_gamma, __pyx_v_size, __pyx_v_fshape, __pyx_v_fscale); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1793; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":1795 - * return cont2_array_sc(self.internal_state, rk_gamma, size, fshape, fscale) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * oshape = <ndarray>PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":1796 - * - * PyErr_Clear() - * oshape = <ndarray>PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oshape, 0.0)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1796; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_oshape = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":1797 - * PyErr_Clear() - * oshape = <ndarray>PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oshape, 0.0)): - * raise ValueError("shape <= 0") - */ - __pyx_t_3 = PyArray_FROM_OTF(__pyx_v_scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_oscale = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":1798 - * oshape = <ndarray>PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oshape, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("shape <= 0") - * if np.any(np.less_equal(oscale, 0.0)): - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_oshape)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_oshape)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oshape)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":1799 - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oshape, 0.0)): - * raise ValueError("shape <= 0") # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_62), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":1800 - * if np.any(np.less_equal(oshape, 0.0)): - * raise ValueError("shape <= 0") - * if np.any(np.less_equal(oscale, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont2_array(self.internal_state, rk_gamma, size, oshape, oscale) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_oscale)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":1801 - * raise ValueError("shape <= 0") - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_gamma, size, oshape, oscale) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_63), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; - - /* "mtrand.pyx":1802 - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") - * return cont2_array(self.internal_state, rk_gamma, size, oshape, oscale) # <<<<<<<<<<<<<< - * - * def f(self, dfnum, dfden, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array(__pyx_v_self->internal_state, rk_gamma, __pyx_v_size, __pyx_v_oshape, __pyx_v_oscale); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.gamma", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_oshape); - __Pyx_XDECREF((PyObject *)__pyx_v_oscale); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_49f(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_48f[] = "\n f(dfnum, dfden, size=None)\n\n Draw samples from a F distribution.\n\n Samples are drawn from an F distribution with specified parameters,\n `dfnum` (degrees of freedom in numerator) and `dfden` (degrees of freedom\n in denominator), where both parameters should be greater than zero.\n\n The random variate of the F distribution (also known as the\n Fisher distribution) is a continuous probability distribution\n that arises in ANOVA tests, and is the ratio of two chi-square\n variates.\n\n Parameters\n ----------\n dfnum : float\n Degrees of freedom in numerator. Should be greater than zero.\n dfden : float\n Degrees of freedom in denominator. Should be greater than zero.\n size : {tuple, int}, optional\n Output shape. If the given shape is, e.g., ``(m, n, k)``,\n then ``m * n * k`` samples are drawn. By default only one sample\n is returned.\n\n Returns\n -------\n samples : {ndarray, scalar}\n Samples from the Fisher distribution.\n\n See Also\n --------\n scipy.stats.distributions.f : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The F statistic is used to compare in-group variances to between-group\n variances. Calculating the distribution depends on the sampling, and\n so it is a function of the respective degrees of freedom in the\n problem. The variable `dfnum` is the number of samples minus one, the\n between-groups degrees of freedom, while `dfden` is the within-groups\n degrees of freedom, the sum of the number of samples in each group\n minus the number of groups.\n\n References\n ----------\n .. [1] Glantz, Stanton A. \"Primer of Biostatistics.\", McGraw-Hill,\n Fifth Edition, 2002.""\n .. [2] Wikipedia, \"F-distribution\",\n http://en.wikipedia.org/wiki/F-distribution\n\n Examples\n --------\n An example from Glantz[1], pp 47-40.\n Two groups, children of diabetics (25 people) and children from people\n without diabetes (25 controls). Fasting blood glucose was measured,\n case group had a mean value of 86.1, controls had a mean value of\n 82.2. Standard deviations were 2.09 and 2.49 respectively. Are these\n data consistent with the null hypothesis that the parents diabetic\n status does not affect their children's blood glucose levels?\n Calculating the F statistic from the data gives a value of 36.01.\n\n Draw samples from the distribution:\n\n >>> dfnum = 1. # between group degrees of freedom\n >>> dfden = 48. # within groups degrees of freedom\n >>> s = np.random.f(dfnum, dfden, 1000)\n\n The lower bound for the top 1% of the samples is :\n\n >>> sort(s)[-10]\n 7.61988120985\n\n So there is about a 1% chance that the F statistic will exceed 7.62,\n the measured value is 36, so the null hypothesis is rejected at the 1%\n level.\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_49f(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_dfnum = 0; - PyObject *__pyx_v_dfden = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("f (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__dfnum,&__pyx_n_s__dfden,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - - /* "mtrand.pyx":1804 - * return cont2_array(self.internal_state, rk_gamma, size, oshape, oscale) - * - * def f(self, dfnum, dfden, size=None): # <<<<<<<<<<<<<< - * """ - * f(dfnum, dfden, size=None) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__dfnum)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__dfden)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("f", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1804; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "f") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1804; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_dfnum = values[0]; - __pyx_v_dfden = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("f", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1804; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.f", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_48f(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_dfnum, __pyx_v_dfden, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_48f(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_dfnum, PyObject *__pyx_v_dfden, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_odfnum = 0; - PyArrayObject *__pyx_v_odfden = 0; - double __pyx_v_fdfnum; - double __pyx_v_fdfden; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("f", 0); - - /* "mtrand.pyx":1887 - * cdef double fdfnum, fdfden - * - * fdfnum = PyFloat_AsDouble(dfnum) # <<<<<<<<<<<<<< - * fdfden = PyFloat_AsDouble(dfden) - * if not PyErr_Occurred(): - */ - __pyx_v_fdfnum = PyFloat_AsDouble(__pyx_v_dfnum); - - /* "mtrand.pyx":1888 - * - * fdfnum = PyFloat_AsDouble(dfnum) - * fdfden = PyFloat_AsDouble(dfden) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fdfnum <= 0: - */ - __pyx_v_fdfden = PyFloat_AsDouble(__pyx_v_dfden); - - /* "mtrand.pyx":1889 - * fdfnum = PyFloat_AsDouble(dfnum) - * fdfden = PyFloat_AsDouble(dfden) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fdfnum <= 0: - * raise ValueError("shape <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":1890 - * fdfden = PyFloat_AsDouble(dfden) - * if not PyErr_Occurred(): - * if fdfnum <= 0: # <<<<<<<<<<<<<< - * raise ValueError("shape <= 0") - * if fdfden <= 0: - */ - __pyx_t_1 = (__pyx_v_fdfnum <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":1891 - * if not PyErr_Occurred(): - * if fdfnum <= 0: - * raise ValueError("shape <= 0") # <<<<<<<<<<<<<< - * if fdfden <= 0: - * raise ValueError("scale <= 0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_64), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1891; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1891; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":1892 - * if fdfnum <= 0: - * raise ValueError("shape <= 0") - * if fdfden <= 0: # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont2_array_sc(self.internal_state, rk_f, size, fdfnum, fdfden) - */ - __pyx_t_1 = (__pyx_v_fdfden <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":1893 - * raise ValueError("shape <= 0") - * if fdfden <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_f, size, fdfnum, fdfden) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_65), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":1894 - * if fdfden <= 0: - * raise ValueError("scale <= 0") - * return cont2_array_sc(self.internal_state, rk_f, size, fdfnum, fdfden) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array_sc(__pyx_v_self->internal_state, rk_f, __pyx_v_size, __pyx_v_fdfnum, __pyx_v_fdfden); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1894; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":1896 - * return cont2_array_sc(self.internal_state, rk_f, size, fdfnum, fdfden) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * odfnum = <ndarray>PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":1898 - * PyErr_Clear() - * - * odfnum = <ndarray>PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * odfden = <ndarray>PyArray_FROM_OTF(dfden, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(odfnum, 0.0)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1898; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_odfnum = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":1899 - * - * odfnum = <ndarray>PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * odfden = <ndarray>PyArray_FROM_OTF(dfden, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(odfnum, 0.0)): - * raise ValueError("dfnum <= 0") - */ - __pyx_t_3 = PyArray_FROM_OTF(__pyx_v_dfden, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1899; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_odfden = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":1900 - * odfnum = <ndarray>PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * odfden = <ndarray>PyArray_FROM_OTF(dfden, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(odfnum, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("dfnum <= 0") - * if np.any(np.less_equal(odfden, 0.0)): - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_odfnum)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_odfnum)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_odfnum)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1900; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":1901 - * odfden = <ndarray>PyArray_FROM_OTF(dfden, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(odfnum, 0.0)): - * raise ValueError("dfnum <= 0") # <<<<<<<<<<<<<< - * if np.any(np.less_equal(odfden, 0.0)): - * raise ValueError("dfden <= 0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_67), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1901; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1901; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":1902 - * if np.any(np.less_equal(odfnum, 0.0)): - * raise ValueError("dfnum <= 0") - * if np.any(np.less_equal(odfden, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("dfden <= 0") - * return cont2_array(self.internal_state, rk_f, size, odfnum, odfden) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1902; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1902; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1902; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1902; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1902; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1902; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(((PyObject *)__pyx_v_odfden)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_odfden)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_odfden)); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1902; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1902; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1902; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1902; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":1903 - * raise ValueError("dfnum <= 0") - * if np.any(np.less_equal(odfden, 0.0)): - * raise ValueError("dfden <= 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_f, size, odfnum, odfden) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_69), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1903; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1903; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; - - /* "mtrand.pyx":1904 - * if np.any(np.less_equal(odfden, 0.0)): - * raise ValueError("dfden <= 0") - * return cont2_array(self.internal_state, rk_f, size, odfnum, odfden) # <<<<<<<<<<<<<< - * - * def noncentral_f(self, dfnum, dfden, nonc, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array(__pyx_v_self->internal_state, rk_f, __pyx_v_size, __pyx_v_odfnum, __pyx_v_odfden); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1904; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.f", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_odfnum); - __Pyx_XDECREF((PyObject *)__pyx_v_odfden); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_51noncentral_f(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_50noncentral_f[] = "\n noncentral_f(dfnum, dfden, nonc, size=None)\n\n Draw samples from the noncentral F distribution.\n\n Samples are drawn from an F distribution with specified parameters,\n `dfnum` (degrees of freedom in numerator) and `dfden` (degrees of\n freedom in denominator), where both parameters > 1.\n `nonc` is the non-centrality parameter.\n\n Parameters\n ----------\n dfnum : int\n Parameter, should be > 1.\n dfden : int\n Parameter, should be > 1.\n nonc : float\n Parameter, should be >= 0.\n size : int or tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : scalar or ndarray\n Drawn samples.\n\n Notes\n -----\n When calculating the power of an experiment (power = probability of\n rejecting the null hypothesis when a specific alternative is true) the\n non-central F statistic becomes important. When the null hypothesis is\n true, the F statistic follows a central F distribution. When the null\n hypothesis is not true, then it follows a non-central F statistic.\n\n References\n ----------\n Weisstein, Eric W. \"Noncentral F-Distribution.\" From MathWorld--A Wolfram\n Web Resource. http://mathworld.wolfram.com/NoncentralF-Distribution.html\n\n Wikipedia, \"Noncentral F distribution\",\n http://en.wikipedia.org/wiki/Noncentral_F-distribution\n\n Examples\n --------\n In a study, testing for a specific alternative to the null hypothesis\n requires use of the Noncentral F distribution. We need to calculate the\n area in the tail of the distribution that exceeds the value of the F\n distribution for the null hypothesis. We'll plot the two probability\n distributions for comp""arison.\n\n >>> dfnum = 3 # between group deg of freedom\n >>> dfden = 20 # within groups degrees of freedom\n >>> nonc = 3.0\n >>> nc_vals = np.random.noncentral_f(dfnum, dfden, nonc, 1000000)\n >>> NF = np.histogram(nc_vals, bins=50, normed=True)\n >>> c_vals = np.random.f(dfnum, dfden, 1000000)\n >>> F = np.histogram(c_vals, bins=50, normed=True)\n >>> plt.plot(F[1][1:], F[0])\n >>> plt.plot(NF[1][1:], NF[0])\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_51noncentral_f(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_dfnum = 0; - PyObject *__pyx_v_dfden = 0; - PyObject *__pyx_v_nonc = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("noncentral_f (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__dfnum,&__pyx_n_s__dfden,&__pyx_n_s__nonc,&__pyx_n_s__size,0}; - PyObject* values[4] = {0,0,0,0}; - - /* "mtrand.pyx":1906 - * return cont2_array(self.internal_state, rk_f, size, odfnum, odfden) - * - * def noncentral_f(self, dfnum, dfden, nonc, size=None): # <<<<<<<<<<<<<< - * """ - * noncentral_f(dfnum, dfden, nonc, size=None) - */ - values[3] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__dfnum)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__dfden)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("noncentral_f", 0, 3, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1906; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nonc)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("noncentral_f", 0, 3, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1906; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 3: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[3] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "noncentral_f") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1906; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_dfnum = values[0]; - __pyx_v_dfden = values[1]; - __pyx_v_nonc = values[2]; - __pyx_v_size = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("noncentral_f", 0, 3, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1906; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.noncentral_f", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_50noncentral_f(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_dfnum, __pyx_v_dfden, __pyx_v_nonc, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_50noncentral_f(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_dfnum, PyObject *__pyx_v_dfden, PyObject *__pyx_v_nonc, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_odfnum = 0; - PyArrayObject *__pyx_v_odfden = 0; - PyArrayObject *__pyx_v_ononc = 0; - double __pyx_v_fdfnum; - double __pyx_v_fdfden; - double __pyx_v_fnonc; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("noncentral_f", 0); - - /* "mtrand.pyx":1973 - * cdef double fdfnum, fdfden, fnonc - * - * fdfnum = PyFloat_AsDouble(dfnum) # <<<<<<<<<<<<<< - * fdfden = PyFloat_AsDouble(dfden) - * fnonc = PyFloat_AsDouble(nonc) - */ - __pyx_v_fdfnum = PyFloat_AsDouble(__pyx_v_dfnum); - - /* "mtrand.pyx":1974 - * - * fdfnum = PyFloat_AsDouble(dfnum) - * fdfden = PyFloat_AsDouble(dfden) # <<<<<<<<<<<<<< - * fnonc = PyFloat_AsDouble(nonc) - * if not PyErr_Occurred(): - */ - __pyx_v_fdfden = PyFloat_AsDouble(__pyx_v_dfden); - - /* "mtrand.pyx":1975 - * fdfnum = PyFloat_AsDouble(dfnum) - * fdfden = PyFloat_AsDouble(dfden) - * fnonc = PyFloat_AsDouble(nonc) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fdfnum <= 1: - */ - __pyx_v_fnonc = PyFloat_AsDouble(__pyx_v_nonc); - - /* "mtrand.pyx":1976 - * fdfden = PyFloat_AsDouble(dfden) - * fnonc = PyFloat_AsDouble(nonc) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fdfnum <= 1: - * raise ValueError("dfnum <= 1") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":1977 - * fnonc = PyFloat_AsDouble(nonc) - * if not PyErr_Occurred(): - * if fdfnum <= 1: # <<<<<<<<<<<<<< - * raise ValueError("dfnum <= 1") - * if fdfden <= 0: - */ - __pyx_t_1 = (__pyx_v_fdfnum <= 1.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":1978 - * if not PyErr_Occurred(): - * if fdfnum <= 1: - * raise ValueError("dfnum <= 1") # <<<<<<<<<<<<<< - * if fdfden <= 0: - * raise ValueError("dfden <= 0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_71), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1978; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1978; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":1979 - * if fdfnum <= 1: - * raise ValueError("dfnum <= 1") - * if fdfden <= 0: # <<<<<<<<<<<<<< - * raise ValueError("dfden <= 0") - * if fnonc < 0: - */ - __pyx_t_1 = (__pyx_v_fdfden <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":1980 - * raise ValueError("dfnum <= 1") - * if fdfden <= 0: - * raise ValueError("dfden <= 0") # <<<<<<<<<<<<<< - * if fnonc < 0: - * raise ValueError("nonc < 0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_72), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1980; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1980; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":1981 - * if fdfden <= 0: - * raise ValueError("dfden <= 0") - * if fnonc < 0: # <<<<<<<<<<<<<< - * raise ValueError("nonc < 0") - * return cont3_array_sc(self.internal_state, rk_noncentral_f, size, - */ - __pyx_t_1 = (__pyx_v_fnonc < 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":1982 - * raise ValueError("dfden <= 0") - * if fnonc < 0: - * raise ValueError("nonc < 0") # <<<<<<<<<<<<<< - * return cont3_array_sc(self.internal_state, rk_noncentral_f, size, - * fdfnum, fdfden, fnonc) - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_74), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1982; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1982; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":1983 - * if fnonc < 0: - * raise ValueError("nonc < 0") - * return cont3_array_sc(self.internal_state, rk_noncentral_f, size, # <<<<<<<<<<<<<< - * fdfnum, fdfden, fnonc) - * - */ - __Pyx_XDECREF(__pyx_r); - - /* "mtrand.pyx":1984 - * raise ValueError("nonc < 0") - * return cont3_array_sc(self.internal_state, rk_noncentral_f, size, - * fdfnum, fdfden, fnonc) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __pyx_t_2 = __pyx_f_6mtrand_cont3_array_sc(__pyx_v_self->internal_state, rk_noncentral_f, __pyx_v_size, __pyx_v_fdfnum, __pyx_v_fdfden, __pyx_v_fnonc); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1983; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":1986 - * fdfnum, fdfden, fnonc) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * odfnum = <ndarray>PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":1988 - * PyErr_Clear() - * - * odfnum = <ndarray>PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * odfden = <ndarray>PyArray_FROM_OTF(dfden, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * ononc = <ndarray>PyArray_FROM_OTF(nonc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1988; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_odfnum = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":1989 - * - * odfnum = <ndarray>PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * odfden = <ndarray>PyArray_FROM_OTF(dfden, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * ononc = <ndarray>PyArray_FROM_OTF(nonc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * - */ - __pyx_t_3 = PyArray_FROM_OTF(__pyx_v_dfden, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1989; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_odfden = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":1990 - * odfnum = <ndarray>PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * odfden = <ndarray>PyArray_FROM_OTF(dfden, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * ononc = <ndarray>PyArray_FROM_OTF(nonc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * - * if np.any(np.less_equal(odfnum, 1.0)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_nonc, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1990; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_ononc = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":1992 - * ononc = <ndarray>PyArray_FROM_OTF(nonc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * - * if np.any(np.less_equal(odfnum, 1.0)): # <<<<<<<<<<<<<< - * raise ValueError("dfnum <= 1") - * if np.any(np.less_equal(odfden, 0.0)): - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_odfnum)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_odfnum)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_odfnum)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1992; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":1993 - * - * if np.any(np.less_equal(odfnum, 1.0)): - * raise ValueError("dfnum <= 1") # <<<<<<<<<<<<<< - * if np.any(np.less_equal(odfden, 0.0)): - * raise ValueError("dfden <= 0") - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_75), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1993; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1993; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; - - /* "mtrand.pyx":1994 - * if np.any(np.less_equal(odfnum, 1.0)): - * raise ValueError("dfnum <= 1") - * if np.any(np.less_equal(odfden, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("dfden <= 0") - * if np.any(np.less(ononc, 0.0)): - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1994; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1994; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1994; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1994; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1994; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1994; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(((PyObject *)__pyx_v_odfden)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_odfden)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_odfden)); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1994; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1994; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1994; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1994; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":1995 - * raise ValueError("dfnum <= 1") - * if np.any(np.less_equal(odfden, 0.0)): - * raise ValueError("dfden <= 0") # <<<<<<<<<<<<<< - * if np.any(np.less(ononc, 0.0)): - * raise ValueError("nonc < 0") - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_76), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1995; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1995; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; - } - __pyx_L8:; - - /* "mtrand.pyx":1996 - * if np.any(np.less_equal(odfden, 0.0)): - * raise ValueError("dfden <= 0") - * if np.any(np.less(ononc, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("nonc < 0") - * return cont3_array(self.internal_state, rk_noncentral_f, size, odfnum, - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1996; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1996; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1996; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1996; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1996; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1996; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)__pyx_v_ononc)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_ononc)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_ononc)); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1996; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1996; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1996; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1996; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":1997 - * raise ValueError("dfden <= 0") - * if np.any(np.less(ononc, 0.0)): - * raise ValueError("nonc < 0") # <<<<<<<<<<<<<< - * return cont3_array(self.internal_state, rk_noncentral_f, size, odfnum, - * odfden, ononc) - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_77), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1997; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1997; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L9; - } - __pyx_L9:; - - /* "mtrand.pyx":1998 - * if np.any(np.less(ononc, 0.0)): - * raise ValueError("nonc < 0") - * return cont3_array(self.internal_state, rk_noncentral_f, size, odfnum, # <<<<<<<<<<<<<< - * odfden, ononc) - * - */ - __Pyx_XDECREF(__pyx_r); - - /* "mtrand.pyx":1999 - * raise ValueError("nonc < 0") - * return cont3_array(self.internal_state, rk_noncentral_f, size, odfnum, - * odfden, ononc) # <<<<<<<<<<<<<< - * - * def chisquare(self, df, size=None): - */ - __pyx_t_3 = __pyx_f_6mtrand_cont3_array(__pyx_v_self->internal_state, rk_noncentral_f, __pyx_v_size, __pyx_v_odfnum, __pyx_v_odfden, __pyx_v_ononc); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.noncentral_f", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_odfnum); - __Pyx_XDECREF((PyObject *)__pyx_v_odfden); - __Pyx_XDECREF((PyObject *)__pyx_v_ononc); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_53chisquare(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_52chisquare[] = "\n chisquare(df, size=None)\n\n Draw samples from a chi-square distribution.\n\n When `df` independent random variables, each with standard normal\n distributions (mean 0, variance 1), are squared and summed, the\n resulting distribution is chi-square (see Notes). This distribution\n is often used in hypothesis testing.\n\n Parameters\n ----------\n df : int\n Number of degrees of freedom.\n size : tuple of ints, int, optional\n Size of the returned array. By default, a scalar is\n returned.\n\n Returns\n -------\n output : ndarray\n Samples drawn from the distribution, packed in a `size`-shaped\n array.\n\n Raises\n ------\n ValueError\n When `df` <= 0 or when an inappropriate `size` (e.g. ``size=-1``)\n is given.\n\n Notes\n -----\n The variable obtained by summing the squares of `df` independent,\n standard normally distributed random variables:\n\n .. math:: Q = \\sum_{i=0}^{\\mathtt{df}} X^2_i\n\n is chi-square distributed, denoted\n\n .. math:: Q \\sim \\chi^2_k.\n\n The probability density function of the chi-squared distribution is\n\n .. math:: p(x) = \\frac{(1/2)^{k/2}}{\\Gamma(k/2)}\n x^{k/2 - 1} e^{-x/2},\n\n where :math:`\\Gamma` is the gamma function,\n\n .. math:: \\Gamma(x) = \\int_0^{-\\infty} t^{x - 1} e^{-t} dt.\n\n References\n ----------\n `NIST/SEMATECH e-Handbook of Statistical Methods\n <http://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm>`_\n\n Examples\n --------\n >>> np.random.chisquare(2,4)\n array([ 1.89920014, 9.00867716, 3.13710533, 5.62318272])\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_53chisquare(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_df = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("chisquare (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__df,&__pyx_n_s__size,0}; - PyObject* values[2] = {0,0}; - - /* "mtrand.pyx":2001 - * odfden, ononc) - * - * def chisquare(self, df, size=None): # <<<<<<<<<<<<<< - * """ - * chisquare(df, size=None) - */ - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__df)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "chisquare") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2001; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_df = values[0]; - __pyx_v_size = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("chisquare", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2001; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.chisquare", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_52chisquare(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_df, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_52chisquare(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_df, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_odf = 0; - double __pyx_v_fdf; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("chisquare", 0); - - /* "mtrand.pyx":2066 - * cdef double fdf - * - * fdf = PyFloat_AsDouble(df) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fdf <= 0: - */ - __pyx_v_fdf = PyFloat_AsDouble(__pyx_v_df); - - /* "mtrand.pyx":2067 - * - * fdf = PyFloat_AsDouble(df) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fdf <= 0: - * raise ValueError("df <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":2068 - * fdf = PyFloat_AsDouble(df) - * if not PyErr_Occurred(): - * if fdf <= 0: # <<<<<<<<<<<<<< - * raise ValueError("df <= 0") - * return cont1_array_sc(self.internal_state, rk_chisquare, size, fdf) - */ - __pyx_t_1 = (__pyx_v_fdf <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":2069 - * if not PyErr_Occurred(): - * if fdf <= 0: - * raise ValueError("df <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_chisquare, size, fdf) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_79), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2069; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2069; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":2070 - * if fdf <= 0: - * raise ValueError("df <= 0") - * return cont1_array_sc(self.internal_state, rk_chisquare, size, fdf) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont1_array_sc(__pyx_v_self->internal_state, rk_chisquare, __pyx_v_size, __pyx_v_fdf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2070; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":2072 - * return cont1_array_sc(self.internal_state, rk_chisquare, size, fdf) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * odf = <ndarray>PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":2074 - * PyErr_Clear() - * - * odf = <ndarray>PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(odf, 0.0)): - * raise ValueError("df <= 0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_df, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2074; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_odf = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":2075 - * - * odf = <ndarray>PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(odf, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("df <= 0") - * return cont1_array(self.internal_state, rk_chisquare, size, odf) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2075; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2075; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2075; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2075; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2075; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2075; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_odf)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_odf)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_odf)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2075; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2075; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2075; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2075; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":2076 - * odf = <ndarray>PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(odf, 0.0)): - * raise ValueError("df <= 0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_chisquare, size, odf) - * - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_80), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2076; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2076; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":2077 - * if np.any(np.less_equal(odf, 0.0)): - * raise ValueError("df <= 0") - * return cont1_array(self.internal_state, rk_chisquare, size, odf) # <<<<<<<<<<<<<< - * - * def noncentral_chisquare(self, df, nonc, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __pyx_f_6mtrand_cont1_array(__pyx_v_self->internal_state, rk_chisquare, __pyx_v_size, __pyx_v_odf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.chisquare", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_odf); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_55noncentral_chisquare(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_54noncentral_chisquare[] = "\n noncentral_chisquare(df, nonc, size=None)\n\n Draw samples from a noncentral chi-square distribution.\n\n The noncentral :math:`\\chi^2` distribution is a generalisation of\n the :math:`\\chi^2` distribution.\n\n Parameters\n ----------\n df : int\n Degrees of freedom, should be >= 1.\n nonc : float\n Non-centrality, should be > 0.\n size : int or tuple of ints\n Shape of the output.\n\n Notes\n -----\n The probability density function for the noncentral Chi-square distribution\n is\n\n .. math:: P(x;df,nonc) = \\sum^{\\infty}_{i=0}\n \\frac{e^{-nonc/2}(nonc/2)^{i}}{i!}P_{Y_{df+2i}}(x),\n\n where :math:`Y_{q}` is the Chi-square with q degrees of freedom.\n\n In Delhi (2007), it is noted that the noncentral chi-square is useful in\n bombing and coverage problems, the probability of killing the point target\n given by the noncentral chi-squared distribution.\n\n References\n ----------\n .. [1] Delhi, M.S. Holla, \"On a noncentral chi-square distribution in the\n analysis of weapon systems effectiveness\", Metrika, Volume 15,\n Number 1 / December, 1970.\n .. [2] Wikipedia, \"Noncentral chi-square distribution\"\n http://en.wikipedia.org/wiki/Noncentral_chi-square_distribution\n\n Examples\n --------\n Draw values from the distribution and plot the histogram\n\n >>> import matplotlib.pyplot as plt\n >>> values = plt.hist(np.random.noncentral_chisquare(3, 20, 100000),\n ... bins=200, normed=True)\n >>> plt.show()\n\n Draw values from a noncentral chisquare with very small noncentrality,\n and compare to a chisquare.\n\n >>> plt.figure()\n >>> values = plt.hist(np.random.noncentral_chisquare(3, .0000001, 100000),\n "" ... bins=np.arange(0., 25, .1), normed=True)\n >>> values2 = plt.hist(np.random.chisquare(3, 100000),\n ... bins=np.arange(0., 25, .1), normed=True)\n >>> plt.plot(values[1][0:-1], values[0]-values2[0], 'ob')\n >>> plt.show()\n\n Demonstrate how large values of non-centrality lead to a more symmetric\n distribution.\n\n >>> plt.figure()\n >>> values = plt.hist(np.random.noncentral_chisquare(3, 20, 100000),\n ... bins=200, normed=True)\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_55noncentral_chisquare(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_df = 0; - PyObject *__pyx_v_nonc = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("noncentral_chisquare (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__df,&__pyx_n_s__nonc,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - - /* "mtrand.pyx":2079 - * return cont1_array(self.internal_state, rk_chisquare, size, odf) - * - * def noncentral_chisquare(self, df, nonc, size=None): # <<<<<<<<<<<<<< - * """ - * noncentral_chisquare(df, nonc, size=None) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__df)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nonc)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("noncentral_chisquare", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2079; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "noncentral_chisquare") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2079; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_df = values[0]; - __pyx_v_nonc = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("noncentral_chisquare", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2079; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.noncentral_chisquare", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_54noncentral_chisquare(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_df, __pyx_v_nonc, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_54noncentral_chisquare(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_df, PyObject *__pyx_v_nonc, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_odf = 0; - PyArrayObject *__pyx_v_ononc = 0; - double __pyx_v_fdf; - double __pyx_v_fnonc; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("noncentral_chisquare", 0); - - /* "mtrand.pyx":2150 - * cdef ndarray odf, ononc - * cdef double fdf, fnonc - * fdf = PyFloat_AsDouble(df) # <<<<<<<<<<<<<< - * fnonc = PyFloat_AsDouble(nonc) - * if not PyErr_Occurred(): - */ - __pyx_v_fdf = PyFloat_AsDouble(__pyx_v_df); - - /* "mtrand.pyx":2151 - * cdef double fdf, fnonc - * fdf = PyFloat_AsDouble(df) - * fnonc = PyFloat_AsDouble(nonc) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fdf <= 1: - */ - __pyx_v_fnonc = PyFloat_AsDouble(__pyx_v_nonc); - - /* "mtrand.pyx":2152 - * fdf = PyFloat_AsDouble(df) - * fnonc = PyFloat_AsDouble(nonc) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fdf <= 1: - * raise ValueError("df <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":2153 - * fnonc = PyFloat_AsDouble(nonc) - * if not PyErr_Occurred(): - * if fdf <= 1: # <<<<<<<<<<<<<< - * raise ValueError("df <= 0") - * if fnonc <= 0: - */ - __pyx_t_1 = (__pyx_v_fdf <= 1.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":2154 - * if not PyErr_Occurred(): - * if fdf <= 1: - * raise ValueError("df <= 0") # <<<<<<<<<<<<<< - * if fnonc <= 0: - * raise ValueError("nonc <= 0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_81), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":2155 - * if fdf <= 1: - * raise ValueError("df <= 0") - * if fnonc <= 0: # <<<<<<<<<<<<<< - * raise ValueError("nonc <= 0") - * return cont2_array_sc(self.internal_state, rk_noncentral_chisquare, - */ - __pyx_t_1 = (__pyx_v_fnonc <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":2156 - * raise ValueError("df <= 0") - * if fnonc <= 0: - * raise ValueError("nonc <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_noncentral_chisquare, - * size, fdf, fnonc) - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_83), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":2157 - * if fnonc <= 0: - * raise ValueError("nonc <= 0") - * return cont2_array_sc(self.internal_state, rk_noncentral_chisquare, # <<<<<<<<<<<<<< - * size, fdf, fnonc) - * - */ - __Pyx_XDECREF(__pyx_r); - - /* "mtrand.pyx":2158 - * raise ValueError("nonc <= 0") - * return cont2_array_sc(self.internal_state, rk_noncentral_chisquare, - * size, fdf, fnonc) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __pyx_t_2 = __pyx_f_6mtrand_cont2_array_sc(__pyx_v_self->internal_state, rk_noncentral_chisquare, __pyx_v_size, __pyx_v_fdf, __pyx_v_fnonc); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":2160 - * size, fdf, fnonc) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * odf = <ndarray>PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":2162 - * PyErr_Clear() - * - * odf = <ndarray>PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * ononc = <ndarray>PyArray_FROM_OTF(nonc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(odf, 0.0)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_df, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_odf = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":2163 - * - * odf = <ndarray>PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * ononc = <ndarray>PyArray_FROM_OTF(nonc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(odf, 0.0)): - * raise ValueError("df <= 1") - */ - __pyx_t_3 = PyArray_FROM_OTF(__pyx_v_nonc, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_ononc = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":2164 - * odf = <ndarray>PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * ononc = <ndarray>PyArray_FROM_OTF(nonc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(odf, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("df <= 1") - * if np.any(np.less_equal(ononc, 0.0)): - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_odf)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_odf)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_odf)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":2165 - * ononc = <ndarray>PyArray_FROM_OTF(nonc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(odf, 0.0)): - * raise ValueError("df <= 1") # <<<<<<<<<<<<<< - * if np.any(np.less_equal(ononc, 0.0)): - * raise ValueError("nonc < 0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_85), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":2166 - * if np.any(np.less_equal(odf, 0.0)): - * raise ValueError("df <= 1") - * if np.any(np.less_equal(ononc, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("nonc < 0") - * return cont2_array(self.internal_state, rk_noncentral_chisquare, size, - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(((PyObject *)__pyx_v_ononc)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_ononc)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_ononc)); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":2167 - * raise ValueError("df <= 1") - * if np.any(np.less_equal(ononc, 0.0)): - * raise ValueError("nonc < 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_noncentral_chisquare, size, - * odf, ononc) - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_86), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; - - /* "mtrand.pyx":2168 - * if np.any(np.less_equal(ononc, 0.0)): - * raise ValueError("nonc < 0") - * return cont2_array(self.internal_state, rk_noncentral_chisquare, size, # <<<<<<<<<<<<<< - * odf, ononc) - * - */ - __Pyx_XDECREF(__pyx_r); - - /* "mtrand.pyx":2169 - * raise ValueError("nonc < 0") - * return cont2_array(self.internal_state, rk_noncentral_chisquare, size, - * odf, ononc) # <<<<<<<<<<<<<< - * - * def standard_cauchy(self, size=None): - */ - __pyx_t_2 = __pyx_f_6mtrand_cont2_array(__pyx_v_self->internal_state, rk_noncentral_chisquare, __pyx_v_size, __pyx_v_odf, __pyx_v_ononc); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.noncentral_chisquare", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_odf); - __Pyx_XDECREF((PyObject *)__pyx_v_ononc); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_57standard_cauchy(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_56standard_cauchy[] = "\n standard_cauchy(size=None)\n\n Standard Cauchy distribution with mode = 0.\n\n Also known as the Lorentz distribution.\n\n Parameters\n ----------\n size : int or tuple of ints\n Shape of the output.\n\n Returns\n -------\n samples : ndarray or scalar\n The drawn samples.\n\n Notes\n -----\n The probability density function for the full Cauchy distribution is\n\n .. math:: P(x; x_0, \\gamma) = \\frac{1}{\\pi \\gamma \\bigl[ 1+\n (\\frac{x-x_0}{\\gamma})^2 \\bigr] }\n\n and the Standard Cauchy distribution just sets :math:`x_0=0` and\n :math:`\\gamma=1`\n\n The Cauchy distribution arises in the solution to the driven harmonic\n oscillator problem, and also describes spectral line broadening. It\n also describes the distribution of values at which a line tilted at\n a random angle will cut the x axis.\n\n When studying hypothesis tests that assume normality, seeing how the\n tests perform on data from a Cauchy distribution is a good indicator of\n their sensitivity to a heavy-tailed distribution, since the Cauchy looks\n very much like a Gaussian distribution, but with heavier tails.\n\n References\n ----------\n .. [1] NIST/SEMATECH e-Handbook of Statistical Methods, \"Cauchy\n Distribution\",\n http://www.itl.nist.gov/div898/handbook/eda/section3/eda3663.htm\n .. [2] Weisstein, Eric W. \"Cauchy Distribution.\" From MathWorld--A\n Wolfram Web Resource.\n http://mathworld.wolfram.com/CauchyDistribution.html\n .. [3] Wikipedia, \"Cauchy distribution\"\n http://en.wikipedia.org/wiki/Cauchy_distribution\n\n Examples\n --------\n Draw samples and plot the distribution:\n\n >>> s = np.random.standard_cauchy(1000000)\n >>> s = s[(s>-25) & (s<""25)] # truncate distribution so it plots well\n >>> plt.hist(s, bins=100)\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_57standard_cauchy(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("standard_cauchy (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__size,0}; - PyObject* values[1] = {0}; - - /* "mtrand.pyx":2171 - * odf, ononc) - * - * def standard_cauchy(self, size=None): # <<<<<<<<<<<<<< - * """ - * standard_cauchy(size=None) - */ - values[0] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[0] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "standard_cauchy") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2171; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_size = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("standard_cauchy", 0, 0, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2171; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.standard_cauchy", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_56standard_cauchy(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_56standard_cauchy(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_size) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("standard_cauchy", 0); - - /* "mtrand.pyx":2230 - * - * """ - * return cont0_array(self.internal_state, rk_standard_cauchy, size) # <<<<<<<<<<<<<< - * - * def standard_t(self, df, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_f_6mtrand_cont0_array(__pyx_v_self->internal_state, rk_standard_cauchy, __pyx_v_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("mtrand.RandomState.standard_cauchy", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_59standard_t(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_58standard_t[] = "\n standard_t(df, size=None)\n\n Standard Student's t distribution with df degrees of freedom.\n\n A special case of the hyperbolic distribution.\n As `df` gets large, the result resembles that of the standard normal\n distribution (`standard_normal`).\n\n Parameters\n ----------\n df : int\n Degrees of freedom, should be > 0.\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single value is\n returned.\n\n Returns\n -------\n samples : ndarray or scalar\n Drawn samples.\n\n Notes\n -----\n The probability density function for the t distribution is\n\n .. math:: P(x, df) = \\frac{\\Gamma(\\frac{df+1}{2})}{\\sqrt{\\pi df}\n \\Gamma(\\frac{df}{2})}\\Bigl( 1+\\frac{x^2}{df} \\Bigr)^{-(df+1)/2}\n\n The t test is based on an assumption that the data come from a Normal\n distribution. The t test provides a way to test whether the sample mean\n (that is the mean calculated from the data) is a good estimate of the true\n mean.\n\n The derivation of the t-distribution was forst published in 1908 by William\n Gisset while working for the Guinness Brewery in Dublin. Due to proprietary\n issues, he had to publish under a pseudonym, and so he used the name\n Student.\n\n References\n ----------\n .. [1] Dalgaard, Peter, \"Introductory Statistics With R\",\n Springer, 2002.\n .. [2] Wikipedia, \"Student's t-distribution\"\n http://en.wikipedia.org/wiki/Student's_t-distribution\n\n Examples\n --------\n From Dalgaard page 83 [1]_, suppose the daily energy intake for 11\n women in Kj is:\n\n >>> intake = np.array([5260., 5470, 5640, 6180, 6390, 6515, 6805, 7515, \\\n ... 7515, 8230, 8770])\n\n Doe""s their energy intake deviate systematically from the recommended\n value of 7725 kJ?\n\n We have 10 degrees of freedom, so is the sample mean within 95% of the\n recommended value?\n\n >>> s = np.random.standard_t(10, size=100000)\n >>> np.mean(intake)\n 6753.636363636364\n >>> intake.std(ddof=1)\n 1142.1232221373727\n\n Calculate the t statistic, setting the ddof parameter to the unbiased\n value so the divisor in the standard deviation will be degrees of\n freedom, N-1.\n\n >>> t = (np.mean(intake)-7725)/(intake.std(ddof=1)/np.sqrt(len(intake)))\n >>> import matplotlib.pyplot as plt\n >>> h = plt.hist(s, bins=100, normed=True)\n\n For a one-sided t-test, how far out in the distribution does the t\n statistic appear?\n\n >>> >>> np.sum(s<t) / float(len(s))\n 0.0090699999999999999 #random\n\n So the p-value is about 0.009, which says the null hypothesis has a\n probability of about 99% of being true.\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_59standard_t(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_df = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("standard_t (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__df,&__pyx_n_s__size,0}; - PyObject* values[2] = {0,0}; - - /* "mtrand.pyx":2232 - * return cont0_array(self.internal_state, rk_standard_cauchy, size) - * - * def standard_t(self, df, size=None): # <<<<<<<<<<<<<< - * """ - * standard_t(df, size=None) - */ - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__df)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "standard_t") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_df = values[0]; - __pyx_v_size = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("standard_t", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2232; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.standard_t", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_58standard_t(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_df, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_58standard_t(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_df, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_odf = 0; - double __pyx_v_fdf; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("standard_t", 0); - - /* "mtrand.pyx":2320 - * cdef double fdf - * - * fdf = PyFloat_AsDouble(df) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fdf <= 0: - */ - __pyx_v_fdf = PyFloat_AsDouble(__pyx_v_df); - - /* "mtrand.pyx":2321 - * - * fdf = PyFloat_AsDouble(df) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fdf <= 0: - * raise ValueError("df <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":2322 - * fdf = PyFloat_AsDouble(df) - * if not PyErr_Occurred(): - * if fdf <= 0: # <<<<<<<<<<<<<< - * raise ValueError("df <= 0") - * return cont1_array_sc(self.internal_state, rk_standard_t, size, fdf) - */ - __pyx_t_1 = (__pyx_v_fdf <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":2323 - * if not PyErr_Occurred(): - * if fdf <= 0: - * raise ValueError("df <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_standard_t, size, fdf) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_87), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2323; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2323; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":2324 - * if fdf <= 0: - * raise ValueError("df <= 0") - * return cont1_array_sc(self.internal_state, rk_standard_t, size, fdf) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont1_array_sc(__pyx_v_self->internal_state, rk_standard_t, __pyx_v_size, __pyx_v_fdf); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2324; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":2326 - * return cont1_array_sc(self.internal_state, rk_standard_t, size, fdf) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * odf = <ndarray> PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":2328 - * PyErr_Clear() - * - * odf = <ndarray> PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(odf, 0.0)): - * raise ValueError("df <= 0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_df, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_odf = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":2329 - * - * odf = <ndarray> PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(odf, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("df <= 0") - * return cont1_array(self.internal_state, rk_standard_t, size, odf) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_odf)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_odf)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_odf)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2329; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":2330 - * odf = <ndarray> PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(odf, 0.0)): - * raise ValueError("df <= 0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_standard_t, size, odf) - * - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_88), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2330; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2330; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":2331 - * if np.any(np.less_equal(odf, 0.0)): - * raise ValueError("df <= 0") - * return cont1_array(self.internal_state, rk_standard_t, size, odf) # <<<<<<<<<<<<<< - * - * def vonmises(self, mu, kappa, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __pyx_f_6mtrand_cont1_array(__pyx_v_self->internal_state, rk_standard_t, __pyx_v_size, __pyx_v_odf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.standard_t", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_odf); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_61vonmises(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_60vonmises[] = "\n vonmises(mu, kappa, size=None)\n\n Draw samples from a von Mises distribution.\n\n Samples are drawn from a von Mises distribution with specified mode\n (mu) and dispersion (kappa), on the interval [-pi, pi].\n\n The von Mises distribution (also known as the circular normal\n distribution) is a continuous probability distribution on the unit\n circle. It may be thought of as the circular analogue of the normal\n distribution.\n\n Parameters\n ----------\n mu : float\n Mode (\"center\") of the distribution.\n kappa : float\n Dispersion of the distribution, has to be >=0.\n size : int or tuple of int\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : scalar or ndarray\n The returned samples, which are in the interval [-pi, pi].\n\n See Also\n --------\n scipy.stats.distributions.vonmises : probability density function,\n distribution, or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the von Mises distribution is\n\n .. math:: p(x) = \\frac{e^{\\kappa cos(x-\\mu)}}{2\\pi I_0(\\kappa)},\n\n where :math:`\\mu` is the mode and :math:`\\kappa` the dispersion,\n and :math:`I_0(\\kappa)` is the modified Bessel function of order 0.\n\n The von Mises is named for Richard Edler von Mises, who was born in\n Austria-Hungary, in what is now the Ukraine. He fled to the United\n States in 1939 and became a professor at Harvard. He worked in\n probability theory, aerodynamics, fluid mechanics, and philosophy of\n science.\n\n References\n ----------\n Abramowitz, M. and Stegun, I. A. (ed.), *Handbook of Mathematical\n Functions*, New York: Dover, 1965.\n\n "" von Mises, R., *Mathematical Theory of Probability and Statistics*,\n New York: Academic Press, 1964.\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> mu, kappa = 0.0, 4.0 # mean and dispersion\n >>> s = np.random.vonmises(mu, kappa, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> import scipy.special as sps\n >>> count, bins, ignored = plt.hist(s, 50, normed=True)\n >>> x = np.arange(-np.pi, np.pi, 2*np.pi/50.)\n >>> y = -np.exp(kappa*np.cos(x-mu))/(2*np.pi*sps.jn(0,kappa))\n >>> plt.plot(x, y/max(y), linewidth=2, color='r')\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_61vonmises(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_mu = 0; - PyObject *__pyx_v_kappa = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("vonmises (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__mu,&__pyx_n_s__kappa,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - - /* "mtrand.pyx":2333 - * return cont1_array(self.internal_state, rk_standard_t, size, odf) - * - * def vonmises(self, mu, kappa, size=None): # <<<<<<<<<<<<<< - * """ - * vonmises(mu, kappa, size=None) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__mu)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__kappa)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("vonmises", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2333; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "vonmises") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2333; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_mu = values[0]; - __pyx_v_kappa = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("vonmises", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2333; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.vonmises", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_60vonmises(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_mu, __pyx_v_kappa, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_60vonmises(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_mu, PyObject *__pyx_v_kappa, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_omu = 0; - PyArrayObject *__pyx_v_okappa = 0; - double __pyx_v_fmu; - double __pyx_v_fkappa; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("vonmises", 0); - - /* "mtrand.pyx":2412 - * cdef double fmu, fkappa - * - * fmu = PyFloat_AsDouble(mu) # <<<<<<<<<<<<<< - * fkappa = PyFloat_AsDouble(kappa) - * if not PyErr_Occurred(): - */ - __pyx_v_fmu = PyFloat_AsDouble(__pyx_v_mu); - - /* "mtrand.pyx":2413 - * - * fmu = PyFloat_AsDouble(mu) - * fkappa = PyFloat_AsDouble(kappa) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fkappa < 0: - */ - __pyx_v_fkappa = PyFloat_AsDouble(__pyx_v_kappa); - - /* "mtrand.pyx":2414 - * fmu = PyFloat_AsDouble(mu) - * fkappa = PyFloat_AsDouble(kappa) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fkappa < 0: - * raise ValueError("kappa < 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":2415 - * fkappa = PyFloat_AsDouble(kappa) - * if not PyErr_Occurred(): - * if fkappa < 0: # <<<<<<<<<<<<<< - * raise ValueError("kappa < 0") - * return cont2_array_sc(self.internal_state, rk_vonmises, size, fmu, fkappa) - */ - __pyx_t_1 = (__pyx_v_fkappa < 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":2416 - * if not PyErr_Occurred(): - * if fkappa < 0: - * raise ValueError("kappa < 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_vonmises, size, fmu, fkappa) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_90), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":2417 - * if fkappa < 0: - * raise ValueError("kappa < 0") - * return cont2_array_sc(self.internal_state, rk_vonmises, size, fmu, fkappa) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array_sc(__pyx_v_self->internal_state, rk_vonmises, __pyx_v_size, __pyx_v_fmu, __pyx_v_fkappa); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2417; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":2419 - * return cont2_array_sc(self.internal_state, rk_vonmises, size, fmu, fkappa) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * omu = <ndarray> PyArray_FROM_OTF(mu, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":2421 - * PyErr_Clear() - * - * omu = <ndarray> PyArray_FROM_OTF(mu, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * okappa = <ndarray> PyArray_FROM_OTF(kappa, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less(okappa, 0.0)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_mu, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2421; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_omu = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":2422 - * - * omu = <ndarray> PyArray_FROM_OTF(mu, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * okappa = <ndarray> PyArray_FROM_OTF(kappa, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less(okappa, 0.0)): - * raise ValueError("kappa < 0") - */ - __pyx_t_3 = PyArray_FROM_OTF(__pyx_v_kappa, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2422; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_okappa = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":2423 - * omu = <ndarray> PyArray_FROM_OTF(mu, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * okappa = <ndarray> PyArray_FROM_OTF(kappa, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less(okappa, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("kappa < 0") - * return cont2_array(self.internal_state, rk_vonmises, size, omu, okappa) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_okappa)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_okappa)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_okappa)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2423; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":2424 - * okappa = <ndarray> PyArray_FROM_OTF(kappa, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less(okappa, 0.0)): - * raise ValueError("kappa < 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_vonmises, size, omu, okappa) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_91), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":2425 - * if np.any(np.less(okappa, 0.0)): - * raise ValueError("kappa < 0") - * return cont2_array(self.internal_state, rk_vonmises, size, omu, okappa) # <<<<<<<<<<<<<< - * - * def pareto(self, a, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array(__pyx_v_self->internal_state, rk_vonmises, __pyx_v_size, __pyx_v_omu, __pyx_v_okappa); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2425; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.vonmises", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_omu); - __Pyx_XDECREF((PyObject *)__pyx_v_okappa); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_63pareto(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_62pareto[] = "\n pareto(a, size=None)\n\n Draw samples from a Pareto II or Lomax distribution with specified shape.\n\n The Lomax or Pareto II distribution is a shifted Pareto distribution. The\n classical Pareto distribution can be obtained from the Lomax distribution\n by adding the location parameter m, see below. The smallest value of the\n Lomax distribution is zero while for the classical Pareto distribution it\n is m, where the standard Pareto distribution has location m=1.\n Lomax can also be considered as a simplified version of the Generalized\n Pareto distribution (available in SciPy), with the scale set to one and\n the location set to zero.\n\n The Pareto distribution must be greater than zero, and is unbounded above.\n It is also known as the \"80-20 rule\". In this distribution, 80 percent of\n the weights are in the lowest 20 percent of the range, while the other 20\n percent fill the remaining 80 percent of the range.\n\n Parameters\n ----------\n shape : float, > 0.\n Shape of the distribution.\n size : tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n See Also\n --------\n scipy.stats.distributions.lomax.pdf : probability density function,\n distribution or cumulative density function, etc.\n scipy.stats.distributions.genpareto.pdf : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Pareto distribution is\n\n .. math:: p(x) = \\frac{am^a}{x^{a+1}}\n\n where :math:`a` is the shape and :math:`m` the location\n\n The Pareto distribution, named after the Italian economist Vilfredo Pareto,\n is a power law probability distribution useful in many real world probl""ems.\n Outside the field of economics it is generally referred to as the Bradford\n distribution. Pareto developed the distribution to describe the\n distribution of wealth in an economy. It has also found use in insurance,\n web page access statistics, oil field sizes, and many other problems,\n including the download frequency for projects in Sourceforge [1]. It is\n one of the so-called \"fat-tailed\" distributions.\n\n\n References\n ----------\n .. [1] Francis Hunt and Paul Johnson, On the Pareto Distribution of\n Sourceforge projects.\n .. [2] Pareto, V. (1896). Course of Political Economy. Lausanne.\n .. [3] Reiss, R.D., Thomas, M.(2001), Statistical Analysis of Extreme\n Values, Birkhauser Verlag, Basel, pp 23-30.\n .. [4] Wikipedia, \"Pareto distribution\",\n http://en.wikipedia.org/wiki/Pareto_distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> a, m = 3., 1. # shape and mode\n >>> s = np.random.pareto(a, 1000) + m\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, 100, normed=True, align='center')\n >>> fit = a*m**a/bins**(a+1)\n >>> plt.plot(bins, max(count)*fit/max(fit),linewidth=2, color='r')\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_63pareto(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_a = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("pareto (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__a,&__pyx_n_s__size,0}; - PyObject* values[2] = {0,0}; - - /* "mtrand.pyx":2427 - * return cont2_array(self.internal_state, rk_vonmises, size, omu, okappa) - * - * def pareto(self, a, size=None): # <<<<<<<<<<<<<< - * """ - * pareto(a, size=None) - */ - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__a)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "pareto") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2427; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_a = values[0]; - __pyx_v_size = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("pareto", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2427; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.pareto", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_62pareto(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_a, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_62pareto(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_a, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_oa = 0; - double __pyx_v_fa; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("pareto", 0); - - /* "mtrand.pyx":2510 - * cdef double fa - * - * fa = PyFloat_AsDouble(a) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fa <= 0: - */ - __pyx_v_fa = PyFloat_AsDouble(__pyx_v_a); - - /* "mtrand.pyx":2511 - * - * fa = PyFloat_AsDouble(a) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fa <= 0: - * raise ValueError("a <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":2512 - * fa = PyFloat_AsDouble(a) - * if not PyErr_Occurred(): - * if fa <= 0: # <<<<<<<<<<<<<< - * raise ValueError("a <= 0") - * return cont1_array_sc(self.internal_state, rk_pareto, size, fa) - */ - __pyx_t_1 = (__pyx_v_fa <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":2513 - * if not PyErr_Occurred(): - * if fa <= 0: - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_pareto, size, fa) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_92), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":2514 - * if fa <= 0: - * raise ValueError("a <= 0") - * return cont1_array_sc(self.internal_state, rk_pareto, size, fa) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont1_array_sc(__pyx_v_self->internal_state, rk_pareto, __pyx_v_size, __pyx_v_fa); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":2516 - * return cont1_array_sc(self.internal_state, rk_pareto, size, fa) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":2518 - * PyErr_Clear() - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oa, 0.0)): - * raise ValueError("a <= 0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_a, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2518; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_oa = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":2519 - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("a <= 0") - * return cont1_array(self.internal_state, rk_pareto, size, oa) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_oa)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_oa)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oa)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":2520 - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 0.0)): - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_pareto, size, oa) - * - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_93), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2520; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2520; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":2521 - * if np.any(np.less_equal(oa, 0.0)): - * raise ValueError("a <= 0") - * return cont1_array(self.internal_state, rk_pareto, size, oa) # <<<<<<<<<<<<<< - * - * def weibull(self, a, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __pyx_f_6mtrand_cont1_array(__pyx_v_self->internal_state, rk_pareto, __pyx_v_size, __pyx_v_oa); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.pareto", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_oa); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_65weibull(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_64weibull[] = "\n weibull(a, size=None)\n\n Weibull distribution.\n\n Draw samples from a 1-parameter Weibull distribution with the given\n shape parameter `a`.\n\n .. math:: X = (-ln(U))^{1/a}\n\n Here, U is drawn from the uniform distribution over (0,1].\n\n The more common 2-parameter Weibull, including a scale parameter\n :math:`\\lambda` is just :math:`X = \\lambda(-ln(U))^{1/a}`.\n\n Parameters\n ----------\n a : float\n Shape of the distribution.\n size : tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n See Also\n --------\n scipy.stats.distributions.weibull_max\n scipy.stats.distributions.weibull_min\n scipy.stats.distributions.genextreme\n gumbel\n\n Notes\n -----\n The Weibull (or Type III asymptotic extreme value distribution for smallest\n values, SEV Type III, or Rosin-Rammler distribution) is one of a class of\n Generalized Extreme Value (GEV) distributions used in modeling extreme\n value problems. This class includes the Gumbel and Frechet distributions.\n\n The probability density for the Weibull distribution is\n\n .. math:: p(x) = \\frac{a}\n {\\lambda}(\\frac{x}{\\lambda})^{a-1}e^{-(x/\\lambda)^a},\n\n where :math:`a` is the shape and :math:`\\lambda` the scale.\n\n The function has its peak (the mode) at\n :math:`\\lambda(\\frac{a-1}{a})^{1/a}`.\n\n When ``a = 1``, the Weibull distribution reduces to the exponential\n distribution.\n\n References\n ----------\n .. [1] Waloddi Weibull, Professor, Royal Technical University, Stockholm,\n 1939 \"A Statistical Theory Of The Strength Of Materials\",\n Ingeniorsvetenskapsakademiens Handlingar Nr 151, 1939,\n General""stabens Litografiska Anstalts Forlag, Stockholm.\n .. [2] Waloddi Weibull, 1951 \"A Statistical Distribution Function of Wide\n Applicability\", Journal Of Applied Mechanics ASME Paper.\n .. [3] Wikipedia, \"Weibull distribution\",\n http://en.wikipedia.org/wiki/Weibull_distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> a = 5. # shape\n >>> s = np.random.weibull(a, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> x = np.arange(1,100.)/50.\n >>> def weib(x,n,a):\n ... return (a / n) * (x / n)**(a - 1) * np.exp(-(x / n)**a)\n\n >>> count, bins, ignored = plt.hist(np.random.weibull(5.,1000))\n >>> x = np.arange(1,100.)/50.\n >>> scale = count.max()/weib(x, 1., 5.).max()\n >>> plt.plot(x, weib(x, 1., 5.)*scale)\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_65weibull(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_a = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("weibull (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__a,&__pyx_n_s__size,0}; - PyObject* values[2] = {0,0}; - - /* "mtrand.pyx":2523 - * return cont1_array(self.internal_state, rk_pareto, size, oa) - * - * def weibull(self, a, size=None): # <<<<<<<<<<<<<< - * """ - * weibull(a, size=None) - */ - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__a)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "weibull") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2523; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_a = values[0]; - __pyx_v_size = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("weibull", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2523; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.weibull", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_64weibull(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_a, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_64weibull(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_a, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_oa = 0; - double __pyx_v_fa; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("weibull", 0); - - /* "mtrand.pyx":2610 - * cdef double fa - * - * fa = PyFloat_AsDouble(a) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fa <= 0: - */ - __pyx_v_fa = PyFloat_AsDouble(__pyx_v_a); - - /* "mtrand.pyx":2611 - * - * fa = PyFloat_AsDouble(a) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fa <= 0: - * raise ValueError("a <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":2612 - * fa = PyFloat_AsDouble(a) - * if not PyErr_Occurred(): - * if fa <= 0: # <<<<<<<<<<<<<< - * raise ValueError("a <= 0") - * return cont1_array_sc(self.internal_state, rk_weibull, size, fa) - */ - __pyx_t_1 = (__pyx_v_fa <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":2613 - * if not PyErr_Occurred(): - * if fa <= 0: - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_weibull, size, fa) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_94), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2613; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2613; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":2614 - * if fa <= 0: - * raise ValueError("a <= 0") - * return cont1_array_sc(self.internal_state, rk_weibull, size, fa) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont1_array_sc(__pyx_v_self->internal_state, rk_weibull, __pyx_v_size, __pyx_v_fa); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":2616 - * return cont1_array_sc(self.internal_state, rk_weibull, size, fa) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":2618 - * PyErr_Clear() - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oa, 0.0)): - * raise ValueError("a <= 0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_a, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2618; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_oa = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":2619 - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("a <= 0") - * return cont1_array(self.internal_state, rk_weibull, size, oa) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_oa)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_oa)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oa)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2619; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":2620 - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 0.0)): - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_weibull, size, oa) - * - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_95), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2620; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2620; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":2621 - * if np.any(np.less_equal(oa, 0.0)): - * raise ValueError("a <= 0") - * return cont1_array(self.internal_state, rk_weibull, size, oa) # <<<<<<<<<<<<<< - * - * def power(self, a, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __pyx_f_6mtrand_cont1_array(__pyx_v_self->internal_state, rk_weibull, __pyx_v_size, __pyx_v_oa); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2621; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.weibull", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_oa); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_67power(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_66power[] = "\n power(a, size=None)\n\n Draws samples in [0, 1] from a power distribution with positive\n exponent a - 1.\n\n Also known as the power function distribution.\n\n Parameters\n ----------\n a : float\n parameter, > 0\n size : tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : {ndarray, scalar}\n The returned samples lie in [0, 1].\n\n Raises\n ------\n ValueError\n If a<1.\n\n Notes\n -----\n The probability density function is\n\n .. math:: P(x; a) = ax^{a-1}, 0 \\le x \\le 1, a>0.\n\n The power function distribution is just the inverse of the Pareto\n distribution. It may also be seen as a special case of the Beta\n distribution.\n\n It is used, for example, in modeling the over-reporting of insurance\n claims.\n\n References\n ----------\n .. [1] Christian Kleiber, Samuel Kotz, \"Statistical size distributions\n in economics and actuarial sciences\", Wiley, 2003.\n .. [2] Heckert, N. A. and Filliben, James J. (2003). NIST Handbook 148:\n Dataplot Reference Manual, Volume 2: Let Subcommands and Library\n Functions\", National Institute of Standards and Technology Handbook\n Series, June 2003.\n http://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/powpdf.pdf\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> a = 5. # shape\n >>> samples = 1000\n >>> s = np.random.power(a, samples)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, bins=""30)\n >>> x = np.linspace(0, 1, 100)\n >>> y = a*x**(a-1.)\n >>> normed_y = samples*np.diff(bins)[0]*y\n >>> plt.plot(x, normed_y)\n >>> plt.show()\n\n Compare the power function distribution to the inverse of the Pareto.\n\n >>> from scipy import stats\n >>> rvs = np.random.power(5, 1000000)\n >>> rvsp = np.random.pareto(5, 1000000)\n >>> xx = np.linspace(0,1,100)\n >>> powpdf = stats.powerlaw.pdf(xx,5)\n\n >>> plt.figure()\n >>> plt.hist(rvs, bins=50, normed=True)\n >>> plt.plot(xx,powpdf,'r-')\n >>> plt.title('np.random.power(5)')\n\n >>> plt.figure()\n >>> plt.hist(1./(1.+rvsp), bins=50, normed=True)\n >>> plt.plot(xx,powpdf,'r-')\n >>> plt.title('inverse of 1 + np.random.pareto(5)')\n\n >>> plt.figure()\n >>> plt.hist(1./(1.+rvsp), bins=50, normed=True)\n >>> plt.plot(xx,powpdf,'r-')\n >>> plt.title('inverse of stats.pareto(5)')\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_67power(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_a = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("power (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__a,&__pyx_n_s__size,0}; - PyObject* values[2] = {0,0}; - - /* "mtrand.pyx":2623 - * return cont1_array(self.internal_state, rk_weibull, size, oa) - * - * def power(self, a, size=None): # <<<<<<<<<<<<<< - * """ - * power(a, size=None) - */ - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__a)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "power") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2623; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_a = values[0]; - __pyx_v_size = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("power", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2623; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.power", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_66power(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_a, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_66power(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_a, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_oa = 0; - double __pyx_v_fa; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("power", 0); - - /* "mtrand.pyx":2719 - * cdef double fa - * - * fa = PyFloat_AsDouble(a) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fa <= 0: - */ - __pyx_v_fa = PyFloat_AsDouble(__pyx_v_a); - - /* "mtrand.pyx":2720 - * - * fa = PyFloat_AsDouble(a) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fa <= 0: - * raise ValueError("a <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":2721 - * fa = PyFloat_AsDouble(a) - * if not PyErr_Occurred(): - * if fa <= 0: # <<<<<<<<<<<<<< - * raise ValueError("a <= 0") - * return cont1_array_sc(self.internal_state, rk_power, size, fa) - */ - __pyx_t_1 = (__pyx_v_fa <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":2722 - * if not PyErr_Occurred(): - * if fa <= 0: - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_power, size, fa) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_96), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":2723 - * if fa <= 0: - * raise ValueError("a <= 0") - * return cont1_array_sc(self.internal_state, rk_power, size, fa) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont1_array_sc(__pyx_v_self->internal_state, rk_power, __pyx_v_size, __pyx_v_fa); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":2725 - * return cont1_array_sc(self.internal_state, rk_power, size, fa) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":2727 - * PyErr_Clear() - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oa, 0.0)): - * raise ValueError("a <= 0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_a, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2727; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_oa = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":2728 - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("a <= 0") - * return cont1_array(self.internal_state, rk_power, size, oa) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2728; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2728; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2728; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2728; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2728; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2728; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_oa)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_oa)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oa)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2728; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2728; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2728; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2728; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":2729 - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 0.0)): - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_power, size, oa) - * - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_97), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2729; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2729; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":2730 - * if np.any(np.less_equal(oa, 0.0)): - * raise ValueError("a <= 0") - * return cont1_array(self.internal_state, rk_power, size, oa) # <<<<<<<<<<<<<< - * - * def laplace(self, loc=0.0, scale=1.0, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __pyx_f_6mtrand_cont1_array(__pyx_v_self->internal_state, rk_power, __pyx_v_size, __pyx_v_oa); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2730; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.power", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_oa); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_69laplace(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_68laplace[] = "\n laplace(loc=0.0, scale=1.0, size=None)\n\n Draw samples from the Laplace or double exponential distribution with\n specified location (or mean) and scale (decay).\n\n The Laplace distribution is similar to the Gaussian/normal distribution,\n but is sharper at the peak and has fatter tails. It represents the\n difference between two independent, identically distributed exponential\n random variables.\n\n Parameters\n ----------\n loc : float\n The position, :math:`\\mu`, of the distribution peak.\n scale : float\n :math:`\\lambda`, the exponential decay.\n\n Notes\n -----\n It has the probability density function\n\n .. math:: f(x; \\mu, \\lambda) = \\frac{1}{2\\lambda}\n \\exp\\left(-\\frac{|x - \\mu|}{\\lambda}\\right).\n\n The first law of Laplace, from 1774, states that the frequency of an error\n can be expressed as an exponential function of the absolute magnitude of\n the error, which leads to the Laplace distribution. For many problems in\n Economics and Health sciences, this distribution seems to model the data\n better than the standard Gaussian distribution\n\n\n References\n ----------\n .. [1] Abramowitz, M. and Stegun, I. A. (Eds.). Handbook of Mathematical\n Functions with Formulas, Graphs, and Mathematical Tables, 9th\n printing. New York: Dover, 1972.\n\n .. [2] The Laplace distribution and generalizations\n By Samuel Kotz, Tomasz J. Kozubowski, Krzysztof Podgorski,\n Birkhauser, 2001.\n\n .. [3] Weisstein, Eric W. \"Laplace Distribution.\"\n From MathWorld--A Wolfram Web Resource.\n http://mathworld.wolfram.com/LaplaceDistribution.html\n\n .. [4] Wikipedia, \"Laplace distribution\",\n http://en.wikipedia.org/wik""i/Laplace_distribution\n\n Examples\n --------\n Draw samples from the distribution\n\n >>> loc, scale = 0., 1.\n >>> s = np.random.laplace(loc, scale, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, 30, normed=True)\n >>> x = np.arange(-8., 8., .01)\n >>> pdf = np.exp(-abs(x-loc/scale))/(2.*scale)\n >>> plt.plot(x, pdf)\n\n Plot Gaussian for comparison:\n\n >>> g = (1/(scale * np.sqrt(2 * np.pi)) * \n ... np.exp( - (x - loc)**2 / (2 * scale**2) ))\n >>> plt.plot(x,g)\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_69laplace(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_loc = 0; - PyObject *__pyx_v_scale = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("laplace (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__loc,&__pyx_n_s__scale,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - values[0] = __pyx_k_98; - values[1] = __pyx_k_99; - - /* "mtrand.pyx":2732 - * return cont1_array(self.internal_state, rk_power, size, oa) - * - * def laplace(self, loc=0.0, scale=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * laplace(loc=0.0, scale=1.0, size=None) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__loc); - if (value) { values[0] = value; kw_args--; } - } - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__scale); - if (value) { values[1] = value; kw_args--; } - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "laplace") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2732; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_loc = values[0]; - __pyx_v_scale = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("laplace", 0, 0, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2732; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.laplace", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_68laplace(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_loc, __pyx_v_scale, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_68laplace(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_loc, PyObject *__pyx_v_scale, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_oloc = 0; - PyArrayObject *__pyx_v_oscale = 0; - double __pyx_v_floc; - double __pyx_v_fscale; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("laplace", 0); - - /* "mtrand.pyx":2808 - * cdef double floc, fscale - * - * floc = PyFloat_AsDouble(loc) # <<<<<<<<<<<<<< - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): - */ - __pyx_v_floc = PyFloat_AsDouble(__pyx_v_loc); - - /* "mtrand.pyx":2809 - * - * floc = PyFloat_AsDouble(loc) - * fscale = PyFloat_AsDouble(scale) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fscale <= 0: - */ - __pyx_v_fscale = PyFloat_AsDouble(__pyx_v_scale); - - /* "mtrand.pyx":2810 - * floc = PyFloat_AsDouble(loc) - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fscale <= 0: - * raise ValueError("scale <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":2811 - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): - * if fscale <= 0: # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont2_array_sc(self.internal_state, rk_laplace, size, floc, fscale) - */ - __pyx_t_1 = (__pyx_v_fscale <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":2812 - * if not PyErr_Occurred(): - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_laplace, size, floc, fscale) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_100), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":2813 - * if fscale <= 0: - * raise ValueError("scale <= 0") - * return cont2_array_sc(self.internal_state, rk_laplace, size, floc, fscale) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array_sc(__pyx_v_self->internal_state, rk_laplace, __pyx_v_size, __pyx_v_floc, __pyx_v_fscale); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2813; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":2815 - * return cont2_array_sc(self.internal_state, rk_laplace, size, floc, fscale) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":2816 - * - * PyErr_Clear() - * oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_6mtrand_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_oloc = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":2817 - * PyErr_Clear() - * oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_6mtrand_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2817; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_oscale = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":2818 - * oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont2_array(self.internal_state, rk_laplace, size, oloc, oscale) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2818; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2818; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2818; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2818; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2818; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2818; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_oscale)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2818; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2818; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2818; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2818; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":2819 - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_laplace, size, oloc, oscale) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_101), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":2820 - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") - * return cont2_array(self.internal_state, rk_laplace, size, oloc, oscale) # <<<<<<<<<<<<<< - * - * def gumbel(self, loc=0.0, scale=1.0, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array(__pyx_v_self->internal_state, rk_laplace, __pyx_v_size, __pyx_v_oloc, __pyx_v_oscale); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2820; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.laplace", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_oloc); - __Pyx_XDECREF((PyObject *)__pyx_v_oscale); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_71gumbel(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_70gumbel[] = "\n gumbel(loc=0.0, scale=1.0, size=None)\n\n Gumbel distribution.\n\n Draw samples from a Gumbel distribution with specified location and scale.\n For more information on the Gumbel distribution, see Notes and References\n below.\n\n Parameters\n ----------\n loc : float\n The location of the mode of the distribution.\n scale : float\n The scale parameter of the distribution.\n size : tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n out : ndarray\n The samples\n\n See Also\n --------\n scipy.stats.gumbel_l\n scipy.stats.gumbel_r\n scipy.stats.genextreme\n probability density function, distribution, or cumulative density\n function, etc. for each of the above\n weibull\n\n Notes\n -----\n The Gumbel (or Smallest Extreme Value (SEV) or the Smallest Extreme Value\n Type I) distribution is one of a class of Generalized Extreme Value (GEV)\n distributions used in modeling extreme value problems. The Gumbel is a\n special case of the Extreme Value Type I distribution for maximums from\n distributions with \"exponential-like\" tails.\n\n The probability density for the Gumbel distribution is\n\n .. math:: p(x) = \\frac{e^{-(x - \\mu)/ \\beta}}{\\beta} e^{ -e^{-(x - \\mu)/\n \\beta}},\n\n where :math:`\\mu` is the mode, a location parameter, and :math:`\\beta` is\n the scale parameter.\n\n The Gumbel (named for German mathematician Emil Julius Gumbel) was used\n very early in the hydrology literature, for modeling the occurrence of\n flood events. It is also used for modeling maximum wind speed and rainfall\n rates. It is a \"fat-tailed\" distribution - the ""probability of an event in\n the tail of the distribution is larger than if one used a Gaussian, hence\n the surprisingly frequent occurrence of 100-year floods. Floods were\n initially modeled as a Gaussian process, which underestimated the frequency\n of extreme events.\n\n\n It is one of a class of extreme value distributions, the Generalized\n Extreme Value (GEV) distributions, which also includes the Weibull and\n Frechet.\n\n The function has a mean of :math:`\\mu + 0.57721\\beta` and a variance of\n :math:`\\frac{\\pi^2}{6}\\beta^2`.\n\n References\n ----------\n Gumbel, E. J., *Statistics of Extremes*, New York: Columbia University\n Press, 1958.\n\n Reiss, R.-D. and Thomas, M., *Statistical Analysis of Extreme Values from\n Insurance, Finance, Hydrology and Other Fields*, Basel: Birkhauser Verlag,\n 2001.\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> mu, beta = 0, 0.1 # location and scale\n >>> s = np.random.gumbel(mu, beta, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, 30, normed=True)\n >>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)\n ... * np.exp( -np.exp( -(bins - mu) /beta) ),\n ... linewidth=2, color='r')\n >>> plt.show()\n\n Show how an extreme value distribution can arise from a Gaussian process\n and compare to a Gaussian:\n\n >>> means = []\n >>> maxima = []\n >>> for i in range(0,1000) :\n ... a = np.random.normal(mu, beta, 1000)\n ... means.append(a.mean())\n ... maxima.append(a.max())\n >>> count, bins, ignored = plt.hist(maxima, 30, normed=True)\n >>> beta = np.std(maxima)*np.pi/np.sqrt(6)""\n >>> mu = np.mean(maxima) - 0.57721*beta\n >>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)\n ... * np.exp(-np.exp(-(bins - mu)/beta)),\n ... linewidth=2, color='r')\n >>> plt.plot(bins, 1/(beta * np.sqrt(2 * np.pi))\n ... * np.exp(-(bins - mu)**2 / (2 * beta**2)),\n ... linewidth=2, color='g')\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_71gumbel(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_loc = 0; - PyObject *__pyx_v_scale = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("gumbel (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__loc,&__pyx_n_s__scale,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - values[0] = __pyx_k_102; - values[1] = __pyx_k_103; - - /* "mtrand.pyx":2822 - * return cont2_array(self.internal_state, rk_laplace, size, oloc, oscale) - * - * def gumbel(self, loc=0.0, scale=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * gumbel(loc=0.0, scale=1.0, size=None) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__loc); - if (value) { values[0] = value; kw_args--; } - } - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__scale); - if (value) { values[1] = value; kw_args--; } - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "gumbel") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2822; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_loc = values[0]; - __pyx_v_scale = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("gumbel", 0, 0, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2822; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.gumbel", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_70gumbel(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_loc, __pyx_v_scale, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_70gumbel(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_loc, PyObject *__pyx_v_scale, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_oloc = 0; - PyArrayObject *__pyx_v_oscale = 0; - double __pyx_v_floc; - double __pyx_v_fscale; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("gumbel", 0); - - /* "mtrand.pyx":2939 - * cdef double floc, fscale - * - * floc = PyFloat_AsDouble(loc) # <<<<<<<<<<<<<< - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): - */ - __pyx_v_floc = PyFloat_AsDouble(__pyx_v_loc); - - /* "mtrand.pyx":2940 - * - * floc = PyFloat_AsDouble(loc) - * fscale = PyFloat_AsDouble(scale) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fscale <= 0: - */ - __pyx_v_fscale = PyFloat_AsDouble(__pyx_v_scale); - - /* "mtrand.pyx":2941 - * floc = PyFloat_AsDouble(loc) - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fscale <= 0: - * raise ValueError("scale <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":2942 - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): - * if fscale <= 0: # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont2_array_sc(self.internal_state, rk_gumbel, size, floc, fscale) - */ - __pyx_t_1 = (__pyx_v_fscale <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":2943 - * if not PyErr_Occurred(): - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_gumbel, size, floc, fscale) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_104), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2943; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2943; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":2944 - * if fscale <= 0: - * raise ValueError("scale <= 0") - * return cont2_array_sc(self.internal_state, rk_gumbel, size, floc, fscale) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array_sc(__pyx_v_self->internal_state, rk_gumbel, __pyx_v_size, __pyx_v_floc, __pyx_v_fscale); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":2946 - * return cont2_array_sc(self.internal_state, rk_gumbel, size, floc, fscale) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":2947 - * - * PyErr_Clear() - * oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2947; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_6mtrand_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2947; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_oloc = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":2948 - * PyErr_Clear() - * oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2948; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_6mtrand_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2948; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_oscale = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":2949 - * oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont2_array(self.internal_state, rk_gumbel, size, oloc, oscale) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_oscale)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":2950 - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_gumbel, size, oloc, oscale) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_105), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":2951 - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") - * return cont2_array(self.internal_state, rk_gumbel, size, oloc, oscale) # <<<<<<<<<<<<<< - * - * def logistic(self, loc=0.0, scale=1.0, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array(__pyx_v_self->internal_state, rk_gumbel, __pyx_v_size, __pyx_v_oloc, __pyx_v_oscale); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2951; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.gumbel", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_oloc); - __Pyx_XDECREF((PyObject *)__pyx_v_oscale); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_73logistic(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_72logistic[] = "\n logistic(loc=0.0, scale=1.0, size=None)\n\n Draw samples from a Logistic distribution.\n\n Samples are drawn from a Logistic distribution with specified\n parameters, loc (location or mean, also median), and scale (>0).\n\n Parameters\n ----------\n loc : float\n\n scale : float > 0.\n\n size : {tuple, int}\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : {ndarray, scalar}\n where the values are all integers in [0, n].\n\n See Also\n --------\n scipy.stats.distributions.logistic : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Logistic distribution is\n\n .. math:: P(x) = P(x) = \\frac{e^{-(x-\\mu)/s}}{s(1+e^{-(x-\\mu)/s})^2},\n\n where :math:`\\mu` = location and :math:`s` = scale.\n\n The Logistic distribution is used in Extreme Value problems where it\n can act as a mixture of Gumbel distributions, in Epidemiology, and by\n the World Chess Federation (FIDE) where it is used in the Elo ranking\n system, assuming the performance of each player is a logistically\n distributed random variable.\n\n References\n ----------\n .. [1] Reiss, R.-D. and Thomas M. (2001), Statistical Analysis of Extreme\n Values, from Insurance, Finance, Hydrology and Other Fields,\n Birkhauser Verlag, Basel, pp 132-133.\n .. [2] Weisstein, Eric W. \"Logistic Distribution.\" From\n MathWorld--A Wolfram Web Resource.\n http://mathworld.wolfram.com/LogisticDistribution.html\n .. [3] Wikipedia, \"Logistic-distribution\",\n http://en.wikipedia.org/wiki/Logistic-distribution\n\n Examples\n "" --------\n Draw samples from the distribution:\n\n >>> loc, scale = 10, 1\n >>> s = np.random.logistic(loc, scale, 10000)\n >>> count, bins, ignored = plt.hist(s, bins=50)\n\n # plot against distribution\n\n >>> def logist(x, loc, scale):\n ... return exp((loc-x)/scale)/(scale*(1+exp((loc-x)/scale))**2)\n >>> plt.plot(bins, logist(bins, loc, scale)*count.max()/\\\n ... logist(bins, loc, scale).max())\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_73logistic(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_loc = 0; - PyObject *__pyx_v_scale = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("logistic (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__loc,&__pyx_n_s__scale,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - values[0] = __pyx_k_106; - values[1] = __pyx_k_107; - - /* "mtrand.pyx":2953 - * return cont2_array(self.internal_state, rk_gumbel, size, oloc, oscale) - * - * def logistic(self, loc=0.0, scale=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * logistic(loc=0.0, scale=1.0, size=None) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__loc); - if (value) { values[0] = value; kw_args--; } - } - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__scale); - if (value) { values[1] = value; kw_args--; } - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "logistic") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2953; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_loc = values[0]; - __pyx_v_scale = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("logistic", 0, 0, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2953; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.logistic", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_72logistic(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_loc, __pyx_v_scale, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_72logistic(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_loc, PyObject *__pyx_v_scale, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_oloc = 0; - PyArrayObject *__pyx_v_oscale = 0; - double __pyx_v_floc; - double __pyx_v_fscale; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("logistic", 0); - - /* "mtrand.pyx":3027 - * cdef double floc, fscale - * - * floc = PyFloat_AsDouble(loc) # <<<<<<<<<<<<<< - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): - */ - __pyx_v_floc = PyFloat_AsDouble(__pyx_v_loc); - - /* "mtrand.pyx":3028 - * - * floc = PyFloat_AsDouble(loc) - * fscale = PyFloat_AsDouble(scale) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fscale <= 0: - */ - __pyx_v_fscale = PyFloat_AsDouble(__pyx_v_scale); - - /* "mtrand.pyx":3029 - * floc = PyFloat_AsDouble(loc) - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fscale <= 0: - * raise ValueError("scale <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":3030 - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): - * if fscale <= 0: # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont2_array_sc(self.internal_state, rk_logistic, size, floc, fscale) - */ - __pyx_t_1 = (__pyx_v_fscale <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3031 - * if not PyErr_Occurred(): - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_logistic, size, floc, fscale) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_108), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3031; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3031; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":3032 - * if fscale <= 0: - * raise ValueError("scale <= 0") - * return cont2_array_sc(self.internal_state, rk_logistic, size, floc, fscale) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array_sc(__pyx_v_self->internal_state, rk_logistic, __pyx_v_size, __pyx_v_floc, __pyx_v_fscale); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3032; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":3034 - * return cont2_array_sc(self.internal_state, rk_logistic, size, floc, fscale) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":3035 - * - * PyErr_Clear() - * oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3035; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_6mtrand_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3035; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_oloc = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":3036 - * PyErr_Clear() - * oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3036; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_6mtrand_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3036; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_oscale = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":3037 - * oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont2_array(self.internal_state, rk_logistic, size, oloc, oscale) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_oscale)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3038 - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_logistic, size, oloc, oscale) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_109), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3038; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3038; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":3039 - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") - * return cont2_array(self.internal_state, rk_logistic, size, oloc, oscale) # <<<<<<<<<<<<<< - * - * def lognormal(self, mean=0.0, sigma=1.0, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array(__pyx_v_self->internal_state, rk_logistic, __pyx_v_size, __pyx_v_oloc, __pyx_v_oscale); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3039; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.logistic", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_oloc); - __Pyx_XDECREF((PyObject *)__pyx_v_oscale); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_75lognormal(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_74lognormal[] = "\n lognormal(mean=0.0, sigma=1.0, size=None)\n\n Return samples drawn from a log-normal distribution.\n\n Draw samples from a log-normal distribution with specified mean,\n standard deviation, and array shape. Note that the mean and standard\n deviation are not the values for the distribution itself, but of the\n underlying normal distribution it is derived from.\n\n Parameters\n ----------\n mean : float\n Mean value of the underlying normal distribution\n sigma : float, > 0.\n Standard deviation of the underlying normal distribution\n size : tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : ndarray or float\n The desired samples. An array of the same shape as `size` if given,\n if `size` is None a float is returned.\n\n See Also\n --------\n scipy.stats.lognorm : probability density function, distribution,\n cumulative density function, etc.\n\n Notes\n -----\n A variable `x` has a log-normal distribution if `log(x)` is normally\n distributed. The probability density function for the log-normal\n distribution is:\n\n .. math:: p(x) = \\frac{1}{\\sigma x \\sqrt{2\\pi}}\n e^{(-\\frac{(ln(x)-\\mu)^2}{2\\sigma^2})}\n\n where :math:`\\mu` is the mean and :math:`\\sigma` is the standard\n deviation of the normally distributed logarithm of the variable.\n A log-normal distribution results if a random variable is the *product*\n of a large number of independent, identically-distributed variables in\n the same way that a normal distribution results if the variable is the\n *sum* of a large number of independent, identically-distributed\n variables.\n\n Reference""s\n ----------\n Limpert, E., Stahel, W. A., and Abbt, M., \"Log-normal Distributions\n across the Sciences: Keys and Clues,\" *BioScience*, Vol. 51, No. 5,\n May, 2001. http://stat.ethz.ch/~stahel/lognormal/bioscience.pdf\n\n Reiss, R.D. and Thomas, M., *Statistical Analysis of Extreme Values*,\n Basel: Birkhauser Verlag, 2001, pp. 31-32.\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> mu, sigma = 3., 1. # mean and standard deviation\n >>> s = np.random.lognormal(mu, sigma, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, 100, normed=True, align='mid')\n\n >>> x = np.linspace(min(bins), max(bins), 10000)\n >>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))\n ... / (x * sigma * np.sqrt(2 * np.pi)))\n\n >>> plt.plot(x, pdf, linewidth=2, color='r')\n >>> plt.axis('tight')\n >>> plt.show()\n\n Demonstrate that taking the products of random samples from a uniform\n distribution can be fit well by a log-normal probability density function.\n\n >>> # Generate a thousand samples: each is the product of 100 random\n >>> # values, drawn from a normal distribution.\n >>> b = []\n >>> for i in range(1000):\n ... a = 10. + np.random.random(100)\n ... b.append(np.product(a))\n\n >>> b = np.array(b) / np.min(b) # scale values to be positive\n >>> count, bins, ignored = plt.hist(b, 100, normed=True, align='center')\n >>> sigma = np.std(np.log(b))\n >>> mu = np.mean(np.log(b))\n\n >>> x = np.linspace(min(bins), max(bins), 10000)\n >>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))\n ... / (x * sigma * np.sqrt(2 * np.pi)))\n\n >>> plt.plot(x, pdf, co""lor='r', linewidth=2)\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_75lognormal(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_mean = 0; - PyObject *__pyx_v_sigma = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("lognormal (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__mean,&__pyx_n_s__sigma,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - values[0] = __pyx_k_110; - values[1] = __pyx_k_111; - - /* "mtrand.pyx":3041 - * return cont2_array(self.internal_state, rk_logistic, size, oloc, oscale) - * - * def lognormal(self, mean=0.0, sigma=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * lognormal(mean=0.0, sigma=1.0, size=None) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__mean); - if (value) { values[0] = value; kw_args--; } - } - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__sigma); - if (value) { values[1] = value; kw_args--; } - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "lognormal") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3041; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_mean = values[0]; - __pyx_v_sigma = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("lognormal", 0, 0, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3041; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.lognormal", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_74lognormal(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_mean, __pyx_v_sigma, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_74lognormal(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_mean, PyObject *__pyx_v_sigma, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_omean = 0; - PyArrayObject *__pyx_v_osigma = 0; - double __pyx_v_fmean; - double __pyx_v_fsigma; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("lognormal", 0); - - /* "mtrand.pyx":3146 - * cdef double fmean, fsigma - * - * fmean = PyFloat_AsDouble(mean) # <<<<<<<<<<<<<< - * fsigma = PyFloat_AsDouble(sigma) - * - */ - __pyx_v_fmean = PyFloat_AsDouble(__pyx_v_mean); - - /* "mtrand.pyx":3147 - * - * fmean = PyFloat_AsDouble(mean) - * fsigma = PyFloat_AsDouble(sigma) # <<<<<<<<<<<<<< - * - * if not PyErr_Occurred(): - */ - __pyx_v_fsigma = PyFloat_AsDouble(__pyx_v_sigma); - - /* "mtrand.pyx":3149 - * fsigma = PyFloat_AsDouble(sigma) - * - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fsigma <= 0: - * raise ValueError("sigma <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":3150 - * - * if not PyErr_Occurred(): - * if fsigma <= 0: # <<<<<<<<<<<<<< - * raise ValueError("sigma <= 0") - * return cont2_array_sc(self.internal_state, rk_lognormal, size, fmean, fsigma) - */ - __pyx_t_1 = (__pyx_v_fsigma <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3151 - * if not PyErr_Occurred(): - * if fsigma <= 0: - * raise ValueError("sigma <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_lognormal, size, fmean, fsigma) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_113), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":3152 - * if fsigma <= 0: - * raise ValueError("sigma <= 0") - * return cont2_array_sc(self.internal_state, rk_lognormal, size, fmean, fsigma) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array_sc(__pyx_v_self->internal_state, rk_lognormal, __pyx_v_size, __pyx_v_fmean, __pyx_v_fsigma); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":3154 - * return cont2_array_sc(self.internal_state, rk_lognormal, size, fmean, fsigma) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * omean = PyArray_FROM_OTF(mean, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":3156 - * PyErr_Clear() - * - * omean = PyArray_FROM_OTF(mean, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * osigma = PyArray_FROM_OTF(sigma, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(osigma, 0.0)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_mean, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_6mtrand_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_omean = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":3157 - * - * omean = PyArray_FROM_OTF(mean, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * osigma = PyArray_FROM_OTF(sigma, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(osigma, 0.0)): - * raise ValueError("sigma <= 0.0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_sigma, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_6mtrand_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_osigma = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":3158 - * omean = PyArray_FROM_OTF(mean, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * osigma = PyArray_FROM_OTF(sigma, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(osigma, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("sigma <= 0.0") - * return cont2_array(self.internal_state, rk_lognormal, size, omean, osigma) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_osigma)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_osigma)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_osigma)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3159 - * osigma = PyArray_FROM_OTF(sigma, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(osigma, 0.0)): - * raise ValueError("sigma <= 0.0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_lognormal, size, omean, osigma) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_115), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":3160 - * if np.any(np.less_equal(osigma, 0.0)): - * raise ValueError("sigma <= 0.0") - * return cont2_array(self.internal_state, rk_lognormal, size, omean, osigma) # <<<<<<<<<<<<<< - * - * def rayleigh(self, scale=1.0, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array(__pyx_v_self->internal_state, rk_lognormal, __pyx_v_size, __pyx_v_omean, __pyx_v_osigma); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.lognormal", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_omean); - __Pyx_XDECREF((PyObject *)__pyx_v_osigma); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_77rayleigh(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_76rayleigh[] = "\n rayleigh(scale=1.0, size=None)\n\n Draw samples from a Rayleigh distribution.\n\n The :math:`\\chi` and Weibull distributions are generalizations of the\n Rayleigh.\n\n Parameters\n ----------\n scale : scalar\n Scale, also equals the mode. Should be >= 0.\n size : int or tuple of ints, optional\n Shape of the output. Default is None, in which case a single\n value is returned.\n\n Notes\n -----\n The probability density function for the Rayleigh distribution is\n\n .. math:: P(x;scale) = \\frac{x}{scale^2}e^{\\frac{-x^2}{2 \\cdotp scale^2}}\n\n The Rayleigh distribution arises if the wind speed and wind direction are\n both gaussian variables, then the vector wind velocity forms a Rayleigh\n distribution. The Rayleigh distribution is used to model the expected\n output from wind turbines.\n\n References\n ----------\n .. [1] Brighton Webs Ltd., Rayleigh Distribution,\n http://www.brighton-webs.co.uk/distributions/rayleigh.asp\n .. [2] Wikipedia, \"Rayleigh distribution\"\n http://en.wikipedia.org/wiki/Rayleigh_distribution\n\n Examples\n --------\n Draw values from the distribution and plot the histogram\n\n >>> values = hist(np.random.rayleigh(3, 100000), bins=200, normed=True)\n\n Wave heights tend to follow a Rayleigh distribution. If the mean wave\n height is 1 meter, what fraction of waves are likely to be larger than 3\n meters?\n\n >>> meanvalue = 1\n >>> modevalue = np.sqrt(2 / np.pi) * meanvalue\n >>> s = np.random.rayleigh(modevalue, 1000000)\n\n The percentage of waves larger than 3 meters is:\n\n >>> 100.*sum(s>3)/1000000.\n 0.087300000000000003\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_77rayleigh(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_scale = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("rayleigh (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__scale,&__pyx_n_s__size,0}; - PyObject* values[2] = {0,0}; - values[0] = __pyx_k_116; - - /* "mtrand.pyx":3162 - * return cont2_array(self.internal_state, rk_lognormal, size, omean, osigma) - * - * def rayleigh(self, scale=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * rayleigh(scale=1.0, size=None) - */ - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__scale); - if (value) { values[0] = value; kw_args--; } - } - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "rayleigh") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3162; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_scale = values[0]; - __pyx_v_size = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("rayleigh", 0, 0, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3162; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.rayleigh", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_76rayleigh(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_scale, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_76rayleigh(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_scale, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_oscale = 0; - double __pyx_v_fscale; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("rayleigh", 0); - - /* "mtrand.pyx":3220 - * cdef double fscale - * - * fscale = PyFloat_AsDouble(scale) # <<<<<<<<<<<<<< - * - * if not PyErr_Occurred(): - */ - __pyx_v_fscale = PyFloat_AsDouble(__pyx_v_scale); - - /* "mtrand.pyx":3222 - * fscale = PyFloat_AsDouble(scale) - * - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fscale <= 0: - * raise ValueError("scale <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":3223 - * - * if not PyErr_Occurred(): - * if fscale <= 0: # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont1_array_sc(self.internal_state, rk_rayleigh, size, fscale) - */ - __pyx_t_1 = (__pyx_v_fscale <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3224 - * if not PyErr_Occurred(): - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_rayleigh, size, fscale) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_117), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":3225 - * if fscale <= 0: - * raise ValueError("scale <= 0") - * return cont1_array_sc(self.internal_state, rk_rayleigh, size, fscale) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont1_array_sc(__pyx_v_self->internal_state, rk_rayleigh, __pyx_v_size, __pyx_v_fscale); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":3227 - * return cont1_array_sc(self.internal_state, rk_rayleigh, size, fscale) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":3229 - * PyErr_Clear() - * - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0.0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3229; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_oscale = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":3230 - * - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0.0") - * return cont1_array(self.internal_state, rk_rayleigh, size, oscale) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_oscale)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3231 - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0.0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_rayleigh, size, oscale) - * - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_119), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":3232 - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0.0") - * return cont1_array(self.internal_state, rk_rayleigh, size, oscale) # <<<<<<<<<<<<<< - * - * def wald(self, mean, scale, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __pyx_f_6mtrand_cont1_array(__pyx_v_self->internal_state, rk_rayleigh, __pyx_v_size, __pyx_v_oscale); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.rayleigh", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_oscale); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_79wald(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_78wald[] = "\n wald(mean, scale, size=None)\n\n Draw samples from a Wald, or Inverse Gaussian, distribution.\n\n As the scale approaches infinity, the distribution becomes more like a\n Gaussian.\n\n Some references claim that the Wald is an Inverse Gaussian with mean=1, but\n this is by no means universal.\n\n The Inverse Gaussian distribution was first studied in relationship to\n Brownian motion. In 1956 M.C.K. Tweedie used the name Inverse Gaussian\n because there is an inverse relationship between the time to cover a unit\n distance and distance covered in unit time.\n\n Parameters\n ----------\n mean : scalar\n Distribution mean, should be > 0.\n scale : scalar\n Scale parameter, should be >= 0.\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single value is\n returned.\n\n Returns\n -------\n samples : ndarray or scalar\n Drawn sample, all greater than zero.\n\n Notes\n -----\n The probability density function for the Wald distribution is\n\n .. math:: P(x;mean,scale) = \\sqrt{\\frac{scale}{2\\pi x^3}}e^\n \\frac{-scale(x-mean)^2}{2\\cdotp mean^2x}\n\n As noted above the Inverse Gaussian distribution first arise from attempts\n to model Brownian Motion. It is also a competitor to the Weibull for use in\n reliability modeling and modeling stock returns and interest rate\n processes.\n\n References\n ----------\n .. [1] Brighton Webs Ltd., Wald Distribution,\n http://www.brighton-webs.co.uk/distributions/wald.asp\n .. [2] Chhikara, Raj S., and Folks, J. Leroy, \"The Inverse Gaussian\n Distribution: Theory : Methodology, and Applications\", CRC Press,\n 1988.\n .. [3] Wikipedia, \"Wald distribu""tion\"\n http://en.wikipedia.org/wiki/Wald_distribution\n\n Examples\n --------\n Draw values from the distribution and plot the histogram:\n\n >>> import matplotlib.pyplot as plt\n >>> h = plt.hist(np.random.wald(3, 2, 100000), bins=200, normed=True)\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_79wald(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_mean = 0; - PyObject *__pyx_v_scale = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("wald (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__mean,&__pyx_n_s__scale,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - - /* "mtrand.pyx":3234 - * return cont1_array(self.internal_state, rk_rayleigh, size, oscale) - * - * def wald(self, mean, scale, size=None): # <<<<<<<<<<<<<< - * """ - * wald(mean, scale, size=None) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__mean)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__scale)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("wald", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3234; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "wald") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3234; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_mean = values[0]; - __pyx_v_scale = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("wald", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3234; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.wald", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_78wald(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_mean, __pyx_v_scale, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_78wald(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_mean, PyObject *__pyx_v_scale, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_omean = 0; - PyArrayObject *__pyx_v_oscale = 0; - double __pyx_v_fmean; - double __pyx_v_fscale; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("wald", 0); - - /* "mtrand.pyx":3300 - * cdef double fmean, fscale - * - * fmean = PyFloat_AsDouble(mean) # <<<<<<<<<<<<<< - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): - */ - __pyx_v_fmean = PyFloat_AsDouble(__pyx_v_mean); - - /* "mtrand.pyx":3301 - * - * fmean = PyFloat_AsDouble(mean) - * fscale = PyFloat_AsDouble(scale) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fmean <= 0: - */ - __pyx_v_fscale = PyFloat_AsDouble(__pyx_v_scale); - - /* "mtrand.pyx":3302 - * fmean = PyFloat_AsDouble(mean) - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fmean <= 0: - * raise ValueError("mean <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":3303 - * fscale = PyFloat_AsDouble(scale) - * if not PyErr_Occurred(): - * if fmean <= 0: # <<<<<<<<<<<<<< - * raise ValueError("mean <= 0") - * if fscale <= 0: - */ - __pyx_t_1 = (__pyx_v_fmean <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3304 - * if not PyErr_Occurred(): - * if fmean <= 0: - * raise ValueError("mean <= 0") # <<<<<<<<<<<<<< - * if fscale <= 0: - * raise ValueError("scale <= 0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_121), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3304; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3304; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":3305 - * if fmean <= 0: - * raise ValueError("mean <= 0") - * if fscale <= 0: # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0") - * return cont2_array_sc(self.internal_state, rk_wald, size, fmean, fscale) - */ - __pyx_t_1 = (__pyx_v_fscale <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3306 - * raise ValueError("mean <= 0") - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_wald, size, fmean, fscale) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_122), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3306; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3306; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":3307 - * if fscale <= 0: - * raise ValueError("scale <= 0") - * return cont2_array_sc(self.internal_state, rk_wald, size, fmean, fscale) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array_sc(__pyx_v_self->internal_state, rk_wald, __pyx_v_size, __pyx_v_fmean, __pyx_v_fscale); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3307; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":3309 - * return cont2_array_sc(self.internal_state, rk_wald, size, fmean, fscale) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * omean = PyArray_FROM_OTF(mean, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":3310 - * - * PyErr_Clear() - * omean = PyArray_FROM_OTF(mean, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(omean,0.0)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_mean, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_6mtrand_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3310; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_omean = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":3311 - * PyErr_Clear() - * omean = PyArray_FROM_OTF(mean, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(omean,0.0)): - * raise ValueError("mean <= 0.0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_6mtrand_ndarray))))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3311; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_oscale = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":3312 - * omean = PyArray_FROM_OTF(mean, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(omean,0.0)): # <<<<<<<<<<<<<< - * raise ValueError("mean <= 0.0") - * elif np.any(np.less_equal(oscale,0.0)): - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_omean)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_omean)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_omean)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3313 - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(omean,0.0)): - * raise ValueError("mean <= 0.0") # <<<<<<<<<<<<<< - * elif np.any(np.less_equal(oscale,0.0)): - * raise ValueError("scale <= 0.0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_124), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - - /* "mtrand.pyx":3314 - * if np.any(np.less_equal(omean,0.0)): - * raise ValueError("mean <= 0.0") - * elif np.any(np.less_equal(oscale,0.0)): # <<<<<<<<<<<<<< - * raise ValueError("scale <= 0.0") - * return cont2_array(self.internal_state, rk_wald, size, omean, oscale) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3314; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3314; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3314; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3314; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3314; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3314; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_oscale)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oscale)); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3314; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3314; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3314; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3314; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3315 - * raise ValueError("mean <= 0.0") - * elif np.any(np.less_equal(oscale,0.0)): - * raise ValueError("scale <= 0.0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_wald, size, omean, oscale) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_125), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3315; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3315; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":3316 - * elif np.any(np.less_equal(oscale,0.0)): - * raise ValueError("scale <= 0.0") - * return cont2_array(self.internal_state, rk_wald, size, omean, oscale) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_cont2_array(__pyx_v_self->internal_state, rk_wald, __pyx_v_size, __pyx_v_omean, __pyx_v_oscale); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3316; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.wald", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_omean); - __Pyx_XDECREF((PyObject *)__pyx_v_oscale); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_81triangular(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_80triangular[] = "\n triangular(left, mode, right, size=None)\n\n Draw samples from the triangular distribution.\n\n The triangular distribution is a continuous probability distribution with\n lower limit left, peak at mode, and upper limit right. Unlike the other\n distributions, these parameters directly define the shape of the pdf.\n\n Parameters\n ----------\n left : scalar\n Lower limit.\n mode : scalar\n The value where the peak of the distribution occurs.\n The value should fulfill the condition ``left <= mode <= right``.\n right : scalar\n Upper limit, should be larger than `left`.\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single value is\n returned.\n\n Returns\n -------\n samples : ndarray or scalar\n The returned samples all lie in the interval [left, right].\n\n Notes\n -----\n The probability density function for the Triangular distribution is\n\n .. math:: P(x;l, m, r) = \\begin{cases}\n \\frac{2(x-l)}{(r-l)(m-l)}& \\text{for $l \\leq x \\leq m$},\\\\\n \\frac{2(m-x)}{(r-l)(r-m)}& \\text{for $m \\leq x \\leq r$},\\\\\n 0& \\text{otherwise}.\n \\end{cases}\n\n The triangular distribution is often used in ill-defined problems where the\n underlying distribution is not known, but some knowledge of the limits and\n mode exists. Often it is used in simulations.\n\n References\n ----------\n .. [1] Wikipedia, \"Triangular distribution\"\n http://en.wikipedia.org/wiki/Triangular_distribution\n\n Examples\n --------\n Draw values from the distribution and plot the histogram:\n\n >>> import matplotlib.pyplot as plt\n >>> h = plt.hist(np.random.triangular(-3, 0, 8, 100000), bins=""200,\n ... normed=True)\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_81triangular(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_left = 0; - PyObject *__pyx_v_mode = 0; - PyObject *__pyx_v_right = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("triangular (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__left,&__pyx_n_s__mode,&__pyx_n_s__right,&__pyx_n_s__size,0}; - PyObject* values[4] = {0,0,0,0}; - - /* "mtrand.pyx":3320 - * - * - * def triangular(self, left, mode, right, size=None): # <<<<<<<<<<<<<< - * """ - * triangular(left, mode, right, size=None) - */ - values[3] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__left)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__mode)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("triangular", 0, 3, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3320; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__right)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("triangular", 0, 3, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3320; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 3: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[3] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "triangular") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3320; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_left = values[0]; - __pyx_v_mode = values[1]; - __pyx_v_right = values[2]; - __pyx_v_size = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("triangular", 0, 3, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3320; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.triangular", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_80triangular(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_left, __pyx_v_mode, __pyx_v_right, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_80triangular(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_left, PyObject *__pyx_v_mode, PyObject *__pyx_v_right, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_oleft = 0; - PyArrayObject *__pyx_v_omode = 0; - PyArrayObject *__pyx_v_oright = 0; - double __pyx_v_fleft; - double __pyx_v_fmode; - double __pyx_v_fright; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("triangular", 0); - - /* "mtrand.pyx":3380 - * cdef double fleft, fmode, fright - * - * fleft = PyFloat_AsDouble(left) # <<<<<<<<<<<<<< - * fright = PyFloat_AsDouble(right) - * fmode = PyFloat_AsDouble(mode) - */ - __pyx_v_fleft = PyFloat_AsDouble(__pyx_v_left); - - /* "mtrand.pyx":3381 - * - * fleft = PyFloat_AsDouble(left) - * fright = PyFloat_AsDouble(right) # <<<<<<<<<<<<<< - * fmode = PyFloat_AsDouble(mode) - * if not PyErr_Occurred(): - */ - __pyx_v_fright = PyFloat_AsDouble(__pyx_v_right); - - /* "mtrand.pyx":3382 - * fleft = PyFloat_AsDouble(left) - * fright = PyFloat_AsDouble(right) - * fmode = PyFloat_AsDouble(mode) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fleft > fmode: - */ - __pyx_v_fmode = PyFloat_AsDouble(__pyx_v_mode); - - /* "mtrand.pyx":3383 - * fright = PyFloat_AsDouble(right) - * fmode = PyFloat_AsDouble(mode) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fleft > fmode: - * raise ValueError("left > mode") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":3384 - * fmode = PyFloat_AsDouble(mode) - * if not PyErr_Occurred(): - * if fleft > fmode: # <<<<<<<<<<<<<< - * raise ValueError("left > mode") - * if fmode > fright: - */ - __pyx_t_1 = (__pyx_v_fleft > __pyx_v_fmode); - if (__pyx_t_1) { - - /* "mtrand.pyx":3385 - * if not PyErr_Occurred(): - * if fleft > fmode: - * raise ValueError("left > mode") # <<<<<<<<<<<<<< - * if fmode > fright: - * raise ValueError("mode > right") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_127), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":3386 - * if fleft > fmode: - * raise ValueError("left > mode") - * if fmode > fright: # <<<<<<<<<<<<<< - * raise ValueError("mode > right") - * if fleft == fright: - */ - __pyx_t_1 = (__pyx_v_fmode > __pyx_v_fright); - if (__pyx_t_1) { - - /* "mtrand.pyx":3387 - * raise ValueError("left > mode") - * if fmode > fright: - * raise ValueError("mode > right") # <<<<<<<<<<<<<< - * if fleft == fright: - * raise ValueError("left == right") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_129), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3387; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3387; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":3388 - * if fmode > fright: - * raise ValueError("mode > right") - * if fleft == fright: # <<<<<<<<<<<<<< - * raise ValueError("left == right") - * return cont3_array_sc(self.internal_state, rk_triangular, size, fleft, - */ - __pyx_t_1 = (__pyx_v_fleft == __pyx_v_fright); - if (__pyx_t_1) { - - /* "mtrand.pyx":3389 - * raise ValueError("mode > right") - * if fleft == fright: - * raise ValueError("left == right") # <<<<<<<<<<<<<< - * return cont3_array_sc(self.internal_state, rk_triangular, size, fleft, - * fmode, fright) - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_131), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3389; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3389; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":3390 - * if fleft == fright: - * raise ValueError("left == right") - * return cont3_array_sc(self.internal_state, rk_triangular, size, fleft, # <<<<<<<<<<<<<< - * fmode, fright) - * - */ - __Pyx_XDECREF(__pyx_r); - - /* "mtrand.pyx":3391 - * raise ValueError("left == right") - * return cont3_array_sc(self.internal_state, rk_triangular, size, fleft, - * fmode, fright) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __pyx_t_2 = __pyx_f_6mtrand_cont3_array_sc(__pyx_v_self->internal_state, rk_triangular, __pyx_v_size, __pyx_v_fleft, __pyx_v_fmode, __pyx_v_fright); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":3393 - * fmode, fright) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * oleft = <ndarray>PyArray_FROM_OTF(left, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * omode = <ndarray>PyArray_FROM_OTF(mode, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":3394 - * - * PyErr_Clear() - * oleft = <ndarray>PyArray_FROM_OTF(left, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * omode = <ndarray>PyArray_FROM_OTF(mode, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oright = <ndarray>PyArray_FROM_OTF(right, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_left, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3394; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_oleft = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":3395 - * PyErr_Clear() - * oleft = <ndarray>PyArray_FROM_OTF(left, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * omode = <ndarray>PyArray_FROM_OTF(mode, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * oright = <ndarray>PyArray_FROM_OTF(right, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * - */ - __pyx_t_3 = PyArray_FROM_OTF(__pyx_v_mode, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_omode = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":3396 - * oleft = <ndarray>PyArray_FROM_OTF(left, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * omode = <ndarray>PyArray_FROM_OTF(mode, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * oright = <ndarray>PyArray_FROM_OTF(right, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * - * if np.any(np.greater(oleft, omode)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_right, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_oright = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":3398 - * oright = <ndarray>PyArray_FROM_OTF(right, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * - * if np.any(np.greater(oleft, omode)): # <<<<<<<<<<<<<< - * raise ValueError("left > mode") - * if np.any(np.greater(omode, oright)): - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__greater); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(((PyObject *)__pyx_v_oleft)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_oleft)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oleft)); - __Pyx_INCREF(((PyObject *)__pyx_v_omode)); - PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)__pyx_v_omode)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_omode)); - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3398; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3399 - * - * if np.any(np.greater(oleft, omode)): - * raise ValueError("left > mode") # <<<<<<<<<<<<<< - * if np.any(np.greater(omode, oright)): - * raise ValueError("mode > right") - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_132), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; - - /* "mtrand.pyx":3400 - * if np.any(np.greater(oleft, omode)): - * raise ValueError("left > mode") - * if np.any(np.greater(omode, oright)): # <<<<<<<<<<<<<< - * raise ValueError("mode > right") - * if np.any(np.equal(oleft, oright)): - */ - __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3400; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3400; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3400; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__greater); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3400; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3400; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_omode)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_omode)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_omode)); - __Pyx_INCREF(((PyObject *)__pyx_v_oright)); - PyTuple_SET_ITEM(__pyx_t_5, 1, ((PyObject *)__pyx_v_oright)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oright)); - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3400; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3400; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3400; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3400; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3401 - * raise ValueError("left > mode") - * if np.any(np.greater(omode, oright)): - * raise ValueError("mode > right") # <<<<<<<<<<<<<< - * if np.any(np.equal(oleft, oright)): - * raise ValueError("left == right") - */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_133), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; - } - __pyx_L8:; - - /* "mtrand.pyx":3402 - * if np.any(np.greater(omode, oright)): - * raise ValueError("mode > right") - * if np.any(np.equal(oleft, oright)): # <<<<<<<<<<<<<< - * raise ValueError("left == right") - * return cont3_array(self.internal_state, rk_triangular, size, oleft, - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__any); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__equal); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(((PyObject *)__pyx_v_oleft)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_oleft)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oleft)); - __Pyx_INCREF(((PyObject *)__pyx_v_oright)); - PyTuple_SET_ITEM(__pyx_t_4, 1, ((PyObject *)__pyx_v_oright)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oright)); - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3402; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3403 - * raise ValueError("mode > right") - * if np.any(np.equal(oleft, oright)): - * raise ValueError("left == right") # <<<<<<<<<<<<<< - * return cont3_array(self.internal_state, rk_triangular, size, oleft, - * omode, oright) - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_134), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L9; - } - __pyx_L9:; - - /* "mtrand.pyx":3404 - * if np.any(np.equal(oleft, oright)): - * raise ValueError("left == right") - * return cont3_array(self.internal_state, rk_triangular, size, oleft, # <<<<<<<<<<<<<< - * omode, oright) - * - */ - __Pyx_XDECREF(__pyx_r); - - /* "mtrand.pyx":3405 - * raise ValueError("left == right") - * return cont3_array(self.internal_state, rk_triangular, size, oleft, - * omode, oright) # <<<<<<<<<<<<<< - * - * # Complicated, discrete distributions: - */ - __pyx_t_2 = __pyx_f_6mtrand_cont3_array(__pyx_v_self->internal_state, rk_triangular, __pyx_v_size, __pyx_v_oleft, __pyx_v_omode, __pyx_v_oright); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3404; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.triangular", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_oleft); - __Pyx_XDECREF((PyObject *)__pyx_v_omode); - __Pyx_XDECREF((PyObject *)__pyx_v_oright); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_83binomial(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_82binomial[] = "\n binomial(n, p, size=None)\n\n Draw samples from a binomial distribution.\n\n Samples are drawn from a Binomial distribution with specified\n parameters, n trials and p probability of success where\n n an integer >= 0 and p is in the interval [0,1]. (n may be\n input as a float, but it is truncated to an integer in use)\n\n Parameters\n ----------\n n : float (but truncated to an integer)\n parameter, >= 0.\n p : float\n parameter, >= 0 and <=1.\n size : {tuple, int}\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : {ndarray, scalar}\n where the values are all integers in [0, n].\n\n See Also\n --------\n scipy.stats.distributions.binom : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Binomial distribution is\n\n .. math:: P(N) = \\binom{n}{N}p^N(1-p)^{n-N},\n\n where :math:`n` is the number of trials, :math:`p` is the probability\n of success, and :math:`N` is the number of successes.\n\n When estimating the standard error of a proportion in a population by\n using a random sample, the normal distribution works well unless the\n product p*n <=5, where p = population proportion estimate, and n =\n number of samples, in which case the binomial distribution is used\n instead. For example, a sample of 15 people shows 4 who are left\n handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4,\n so the binomial distribution should be used in this case.\n\n References\n ----------\n .. [1] Dalgaard, Peter, \"Introductory Statistics with R\",\n Springer-Verlag, 2002.""\n .. [2] Glantz, Stanton A. \"Primer of Biostatistics.\", McGraw-Hill,\n Fifth Edition, 2002.\n .. [3] Lentner, Marvin, \"Elementary Applied Statistics\", Bogden\n and Quigley, 1972.\n .. [4] Weisstein, Eric W. \"Binomial Distribution.\" From MathWorld--A\n Wolfram Web Resource.\n http://mathworld.wolfram.com/BinomialDistribution.html\n .. [5] Wikipedia, \"Binomial-distribution\",\n http://en.wikipedia.org/wiki/Binomial_distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> n, p = 10, .5 # number of trials, probability of each trial\n >>> s = np.random.binomial(n, p, 1000)\n # result of flipping a coin 10 times, tested 1000 times.\n\n A real world example. A company drills 9 wild-cat oil exploration\n wells, each with an estimated probability of success of 0.1. All nine\n wells fail. What is the probability of that happening?\n\n Let's do 20,000 trials of the model, and count the number that\n generate zero positive results.\n\n >>> sum(np.random.binomial(9,0.1,20000)==0)/20000.\n answer = 0.38885, or 38%.\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_83binomial(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_n = 0; - PyObject *__pyx_v_p = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("binomial (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n,&__pyx_n_s__p,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - - /* "mtrand.pyx":3408 - * - * # Complicated, discrete distributions: - * def binomial(self, n, p, size=None): # <<<<<<<<<<<<<< - * """ - * binomial(n, p, size=None) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("binomial", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3408; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "binomial") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3408; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_n = values[0]; - __pyx_v_p = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("binomial", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3408; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.binomial", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_82binomial(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_n, __pyx_v_p, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_82binomial(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_n, PyObject *__pyx_v_p, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_on = 0; - PyArrayObject *__pyx_v_op = 0; - long __pyx_v_ln; - double __pyx_v_fp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("binomial", 0); - - /* "mtrand.pyx":3493 - * cdef double fp - * - * fp = PyFloat_AsDouble(p) # <<<<<<<<<<<<<< - * ln = PyInt_AsLong(n) - * if not PyErr_Occurred(): - */ - __pyx_v_fp = PyFloat_AsDouble(__pyx_v_p); - - /* "mtrand.pyx":3494 - * - * fp = PyFloat_AsDouble(p) - * ln = PyInt_AsLong(n) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if ln < 0: - */ - __pyx_v_ln = PyInt_AsLong(__pyx_v_n); - - /* "mtrand.pyx":3495 - * fp = PyFloat_AsDouble(p) - * ln = PyInt_AsLong(n) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if ln < 0: - * raise ValueError("n < 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":3496 - * ln = PyInt_AsLong(n) - * if not PyErr_Occurred(): - * if ln < 0: # <<<<<<<<<<<<<< - * raise ValueError("n < 0") - * if fp < 0: - */ - __pyx_t_1 = (__pyx_v_ln < 0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3497 - * if not PyErr_Occurred(): - * if ln < 0: - * raise ValueError("n < 0") # <<<<<<<<<<<<<< - * if fp < 0: - * raise ValueError("p < 0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_136), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":3498 - * if ln < 0: - * raise ValueError("n < 0") - * if fp < 0: # <<<<<<<<<<<<<< - * raise ValueError("p < 0") - * elif fp > 1: - */ - __pyx_t_1 = (__pyx_v_fp < 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3499 - * raise ValueError("n < 0") - * if fp < 0: - * raise ValueError("p < 0") # <<<<<<<<<<<<<< - * elif fp > 1: - * raise ValueError("p > 1") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_138), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - - /* "mtrand.pyx":3500 - * if fp < 0: - * raise ValueError("p < 0") - * elif fp > 1: # <<<<<<<<<<<<<< - * raise ValueError("p > 1") - * return discnp_array_sc(self.internal_state, rk_binomial, size, ln, fp) - */ - __pyx_t_1 = (__pyx_v_fp > 1.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3501 - * raise ValueError("p < 0") - * elif fp > 1: - * raise ValueError("p > 1") # <<<<<<<<<<<<<< - * return discnp_array_sc(self.internal_state, rk_binomial, size, ln, fp) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_140), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3501; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3501; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":3502 - * elif fp > 1: - * raise ValueError("p > 1") - * return discnp_array_sc(self.internal_state, rk_binomial, size, ln, fp) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_discnp_array_sc(__pyx_v_self->internal_state, rk_binomial, __pyx_v_size, __pyx_v_ln, __pyx_v_fp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":3504 - * return discnp_array_sc(self.internal_state, rk_binomial, size, ln, fp) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * on = <ndarray>PyArray_FROM_OTF(n, NPY_LONG, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":3506 - * PyErr_Clear() - * - * on = <ndarray>PyArray_FROM_OTF(n, NPY_LONG, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less(n, 0)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_n, NPY_LONG, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_on = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":3507 - * - * on = <ndarray>PyArray_FROM_OTF(n, NPY_LONG, NPY_ARRAY_ALIGNED) - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less(n, 0)): - * raise ValueError("n < 0") - */ - __pyx_t_3 = PyArray_FROM_OTF(__pyx_v_p, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3507; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_op = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":3508 - * on = <ndarray>PyArray_FROM_OTF(n, NPY_LONG, NPY_ARRAY_ALIGNED) - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less(n, 0)): # <<<<<<<<<<<<<< - * raise ValueError("n < 0") - * if np.any(np.less(p, 0)): - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_n); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_n); - __Pyx_GIVEREF(__pyx_v_n); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3509 - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less(n, 0)): - * raise ValueError("n < 0") # <<<<<<<<<<<<<< - * if np.any(np.less(p, 0)): - * raise ValueError("p < 0") - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_141), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":3510 - * if np.any(np.less(n, 0)): - * raise ValueError("n < 0") - * if np.any(np.less(p, 0)): # <<<<<<<<<<<<<< - * raise ValueError("p < 0") - * if np.any(np.greater(p, 1)): - */ - __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__less); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(__pyx_v_p); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_p); - __Pyx_GIVEREF(__pyx_v_p); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3511 - * raise ValueError("n < 0") - * if np.any(np.less(p, 0)): - * raise ValueError("p < 0") # <<<<<<<<<<<<<< - * if np.any(np.greater(p, 1)): - * raise ValueError("p > 1") - */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_142), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; - - /* "mtrand.pyx":3512 - * if np.any(np.less(p, 0)): - * raise ValueError("p < 0") - * if np.any(np.greater(p, 1)): # <<<<<<<<<<<<<< - * raise ValueError("p > 1") - * return discnp_array(self.internal_state, rk_binomial, size, on, op) - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__any); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__greater); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_p); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_p); - __Pyx_GIVEREF(__pyx_v_p); - __Pyx_INCREF(__pyx_int_1); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_int_1); - __Pyx_GIVEREF(__pyx_int_1); - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3513 - * raise ValueError("p < 0") - * if np.any(np.greater(p, 1)): - * raise ValueError("p > 1") # <<<<<<<<<<<<<< - * return discnp_array(self.internal_state, rk_binomial, size, on, op) - * - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_143), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; - } - __pyx_L8:; - - /* "mtrand.pyx":3514 - * if np.any(np.greater(p, 1)): - * raise ValueError("p > 1") - * return discnp_array(self.internal_state, rk_binomial, size, on, op) # <<<<<<<<<<<<<< - * - * def negative_binomial(self, n, p, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __pyx_f_6mtrand_discnp_array(__pyx_v_self->internal_state, rk_binomial, __pyx_v_size, __pyx_v_on, __pyx_v_op); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.binomial", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_on); - __Pyx_XDECREF((PyObject *)__pyx_v_op); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_85negative_binomial(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_84negative_binomial[] = "\n negative_binomial(n, p, size=None)\n\n Draw samples from a negative_binomial distribution.\n\n Samples are drawn from a negative_Binomial distribution with specified\n parameters, `n` trials and `p` probability of success where `n` is an\n integer > 0 and `p` is in the interval [0, 1].\n\n Parameters\n ----------\n n : int\n Parameter, > 0.\n p : float\n Parameter, >= 0 and <=1.\n size : int or tuple of ints\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : int or ndarray of ints\n Drawn samples.\n\n Notes\n -----\n The probability density for the Negative Binomial distribution is\n\n .. math:: P(N;n,p) = \\binom{N+n-1}{n-1}p^{n}(1-p)^{N},\n\n where :math:`n-1` is the number of successes, :math:`p` is the probability\n of success, and :math:`N+n-1` is the number of trials.\n\n The negative binomial distribution gives the probability of n-1 successes\n and N failures in N+n-1 trials, and success on the (N+n)th trial.\n\n If one throws a die repeatedly until the third time a \"1\" appears, then the\n probability distribution of the number of non-\"1\"s that appear before the\n third \"1\" is a negative binomial distribution.\n\n References\n ----------\n .. [1] Weisstein, Eric W. \"Negative Binomial Distribution.\" From\n MathWorld--A Wolfram Web Resource.\n http://mathworld.wolfram.com/NegativeBinomialDistribution.html\n .. [2] Wikipedia, \"Negative binomial distribution\",\n http://en.wikipedia.org/wiki/Negative_binomial_distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n A real world example. A company drills wild-cat oil exploration well""s, each\n with an estimated probability of success of 0.1. What is the probability\n of having one success for each successive well, that is what is the\n probability of a single success after drilling 5 wells, after 6 wells,\n etc.?\n\n >>> s = np.random.negative_binomial(1, 0.1, 100000)\n >>> for i in range(1, 11):\n ... probability = sum(s<i) / 100000.\n ... print i, \"wells drilled, probability of one success =\", probability\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_85negative_binomial(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_n = 0; - PyObject *__pyx_v_p = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("negative_binomial (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n,&__pyx_n_s__p,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - - /* "mtrand.pyx":3516 - * return discnp_array(self.internal_state, rk_binomial, size, on, op) - * - * def negative_binomial(self, n, p, size=None): # <<<<<<<<<<<<<< - * """ - * negative_binomial(n, p, size=None) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("negative_binomial", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "negative_binomial") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_n = values[0]; - __pyx_v_p = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("negative_binomial", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.negative_binomial", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_84negative_binomial(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_n, __pyx_v_p, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_84negative_binomial(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_n, PyObject *__pyx_v_p, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_on = 0; - PyArrayObject *__pyx_v_op = 0; - double __pyx_v_fn; - double __pyx_v_fp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("negative_binomial", 0); - - /* "mtrand.pyx":3586 - * cdef double fp - * - * fp = PyFloat_AsDouble(p) # <<<<<<<<<<<<<< - * fn = PyFloat_AsDouble(n) - * if not PyErr_Occurred(): - */ - __pyx_v_fp = PyFloat_AsDouble(__pyx_v_p); - - /* "mtrand.pyx":3587 - * - * fp = PyFloat_AsDouble(p) - * fn = PyFloat_AsDouble(n) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fn <= 0: - */ - __pyx_v_fn = PyFloat_AsDouble(__pyx_v_n); - - /* "mtrand.pyx":3588 - * fp = PyFloat_AsDouble(p) - * fn = PyFloat_AsDouble(n) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fn <= 0: - * raise ValueError("n <= 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":3589 - * fn = PyFloat_AsDouble(n) - * if not PyErr_Occurred(): - * if fn <= 0: # <<<<<<<<<<<<<< - * raise ValueError("n <= 0") - * if fp < 0: - */ - __pyx_t_1 = (__pyx_v_fn <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3590 - * if not PyErr_Occurred(): - * if fn <= 0: - * raise ValueError("n <= 0") # <<<<<<<<<<<<<< - * if fp < 0: - * raise ValueError("p < 0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_145), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":3591 - * if fn <= 0: - * raise ValueError("n <= 0") - * if fp < 0: # <<<<<<<<<<<<<< - * raise ValueError("p < 0") - * elif fp > 1: - */ - __pyx_t_1 = (__pyx_v_fp < 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3592 - * raise ValueError("n <= 0") - * if fp < 0: - * raise ValueError("p < 0") # <<<<<<<<<<<<<< - * elif fp > 1: - * raise ValueError("p > 1") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_146), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - - /* "mtrand.pyx":3593 - * if fp < 0: - * raise ValueError("p < 0") - * elif fp > 1: # <<<<<<<<<<<<<< - * raise ValueError("p > 1") - * return discdd_array_sc(self.internal_state, rk_negative_binomial, - */ - __pyx_t_1 = (__pyx_v_fp > 1.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3594 - * raise ValueError("p < 0") - * elif fp > 1: - * raise ValueError("p > 1") # <<<<<<<<<<<<<< - * return discdd_array_sc(self.internal_state, rk_negative_binomial, - * size, fn, fp) - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_147), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3594; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3594; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":3595 - * elif fp > 1: - * raise ValueError("p > 1") - * return discdd_array_sc(self.internal_state, rk_negative_binomial, # <<<<<<<<<<<<<< - * size, fn, fp) - * - */ - __Pyx_XDECREF(__pyx_r); - - /* "mtrand.pyx":3596 - * raise ValueError("p > 1") - * return discdd_array_sc(self.internal_state, rk_negative_binomial, - * size, fn, fp) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __pyx_t_2 = __pyx_f_6mtrand_discdd_array_sc(__pyx_v_self->internal_state, rk_negative_binomial, __pyx_v_size, __pyx_v_fn, __pyx_v_fp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3595; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":3598 - * size, fn, fp) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * on = <ndarray>PyArray_FROM_OTF(n, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":3600 - * PyErr_Clear() - * - * on = <ndarray>PyArray_FROM_OTF(n, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(n, 0)): - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_n, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3600; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_on = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":3601 - * - * on = <ndarray>PyArray_FROM_OTF(n, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(n, 0)): - * raise ValueError("n <= 0") - */ - __pyx_t_3 = PyArray_FROM_OTF(__pyx_v_p, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3601; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_op = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":3602 - * on = <ndarray>PyArray_FROM_OTF(n, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(n, 0)): # <<<<<<<<<<<<<< - * raise ValueError("n <= 0") - * if np.any(np.less(p, 0)): - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_n); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_n); - __Pyx_GIVEREF(__pyx_v_n); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3603 - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(n, 0)): - * raise ValueError("n <= 0") # <<<<<<<<<<<<<< - * if np.any(np.less(p, 0)): - * raise ValueError("p < 0") - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_148), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3603; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3603; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":3604 - * if np.any(np.less_equal(n, 0)): - * raise ValueError("n <= 0") - * if np.any(np.less(p, 0)): # <<<<<<<<<<<<<< - * raise ValueError("p < 0") - * if np.any(np.greater(p, 1)): - */ - __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__less); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(__pyx_v_p); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_p); - __Pyx_GIVEREF(__pyx_v_p); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3605 - * raise ValueError("n <= 0") - * if np.any(np.less(p, 0)): - * raise ValueError("p < 0") # <<<<<<<<<<<<<< - * if np.any(np.greater(p, 1)): - * raise ValueError("p > 1") - */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_149), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3605; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3605; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; - - /* "mtrand.pyx":3606 - * if np.any(np.less(p, 0)): - * raise ValueError("p < 0") - * if np.any(np.greater(p, 1)): # <<<<<<<<<<<<<< - * raise ValueError("p > 1") - * return discdd_array(self.internal_state, rk_negative_binomial, size, - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__any); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__greater); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_p); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_p); - __Pyx_GIVEREF(__pyx_v_p); - __Pyx_INCREF(__pyx_int_1); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_int_1); - __Pyx_GIVEREF(__pyx_int_1); - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3606; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3607 - * raise ValueError("p < 0") - * if np.any(np.greater(p, 1)): - * raise ValueError("p > 1") # <<<<<<<<<<<<<< - * return discdd_array(self.internal_state, rk_negative_binomial, size, - * on, op) - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_150), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3607; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3607; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; - } - __pyx_L8:; - - /* "mtrand.pyx":3608 - * if np.any(np.greater(p, 1)): - * raise ValueError("p > 1") - * return discdd_array(self.internal_state, rk_negative_binomial, size, # <<<<<<<<<<<<<< - * on, op) - * - */ - __Pyx_XDECREF(__pyx_r); - - /* "mtrand.pyx":3609 - * raise ValueError("p > 1") - * return discdd_array(self.internal_state, rk_negative_binomial, size, - * on, op) # <<<<<<<<<<<<<< - * - * def poisson(self, lam=1.0, size=None): - */ - __pyx_t_3 = __pyx_f_6mtrand_discdd_array(__pyx_v_self->internal_state, rk_negative_binomial, __pyx_v_size, __pyx_v_on, __pyx_v_op); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.negative_binomial", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_on); - __Pyx_XDECREF((PyObject *)__pyx_v_op); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_87poisson(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_86poisson[] = "\n poisson(lam=1.0, size=None)\n\n Draw samples from a Poisson distribution.\n\n The Poisson distribution is the limit of the Binomial\n distribution for large N.\n\n Parameters\n ----------\n lam : float\n Expectation of interval, should be >= 0.\n size : int or tuple of ints, optional\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Notes\n -----\n The Poisson distribution\n\n .. math:: f(k; \\lambda)=\\frac{\\lambda^k e^{-\\lambda}}{k!}\n\n For events with an expected separation :math:`\\lambda` the Poisson\n distribution :math:`f(k; \\lambda)` describes the probability of\n :math:`k` events occurring within the observed interval :math:`\\lambda`.\n\n Because the output is limited to the range of the C long type, a\n ValueError is raised when `lam` is within 10 sigma of the maximum\n representable value.\n\n References\n ----------\n .. [1] Weisstein, Eric W. \"Poisson Distribution.\" From MathWorld--A Wolfram\n Web Resource. http://mathworld.wolfram.com/PoissonDistribution.html\n .. [2] Wikipedia, \"Poisson distribution\",\n http://en.wikipedia.org/wiki/Poisson_distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> import numpy as np\n >>> s = np.random.poisson(5, 10000)\n\n Display histogram of the sample:\n\n >>> import matplotlib.pyplot as plt\n >>> count, bins, ignored = plt.hist(s, 14, normed=True)\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_87poisson(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_lam = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("poisson (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__lam,&__pyx_n_s__size,0}; - PyObject* values[2] = {0,0}; - values[0] = __pyx_k_151; - - /* "mtrand.pyx":3611 - * on, op) - * - * def poisson(self, lam=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * poisson(lam=1.0, size=None) - */ - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__lam); - if (value) { values[0] = value; kw_args--; } - } - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "poisson") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3611; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_lam = values[0]; - __pyx_v_size = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("poisson", 0, 0, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3611; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.poisson", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_86poisson(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_lam, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_86poisson(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_lam, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_olam = 0; - double __pyx_v_flam; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("poisson", 0); - - /* "mtrand.pyx":3665 - * cdef ndarray olam - * cdef double flam - * flam = PyFloat_AsDouble(lam) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if lam < 0: - */ - __pyx_v_flam = PyFloat_AsDouble(__pyx_v_lam); - - /* "mtrand.pyx":3666 - * cdef double flam - * flam = PyFloat_AsDouble(lam) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if lam < 0: - * raise ValueError("lam < 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":3667 - * flam = PyFloat_AsDouble(lam) - * if not PyErr_Occurred(): - * if lam < 0: # <<<<<<<<<<<<<< - * raise ValueError("lam < 0") - * if lam > self.poisson_lam_max: - */ - __pyx_t_2 = PyObject_RichCompare(__pyx_v_lam, __pyx_int_0, Py_LT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3667; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3667; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3668 - * if not PyErr_Occurred(): - * if lam < 0: - * raise ValueError("lam < 0") # <<<<<<<<<<<<<< - * if lam > self.poisson_lam_max: - * raise ValueError("lam value too large") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_153), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3668; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3668; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":3669 - * if lam < 0: - * raise ValueError("lam < 0") - * if lam > self.poisson_lam_max: # <<<<<<<<<<<<<< - * raise ValueError("lam value too large") - * return discd_array_sc(self.internal_state, rk_poisson, size, flam) - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__poisson_lam_max); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3669; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_lam, __pyx_t_2, Py_GT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3669; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3669; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3670 - * raise ValueError("lam < 0") - * if lam > self.poisson_lam_max: - * raise ValueError("lam value too large") # <<<<<<<<<<<<<< - * return discd_array_sc(self.internal_state, rk_poisson, size, flam) - * - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_155), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3670; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3670; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":3671 - * if lam > self.poisson_lam_max: - * raise ValueError("lam value too large") - * return discd_array_sc(self.internal_state, rk_poisson, size, flam) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __pyx_f_6mtrand_discd_array_sc(__pyx_v_self->internal_state, rk_poisson, __pyx_v_size, __pyx_v_flam); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3671; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":3673 - * return discd_array_sc(self.internal_state, rk_poisson, size, flam) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * olam = <ndarray>PyArray_FROM_OTF(lam, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":3675 - * PyErr_Clear() - * - * olam = <ndarray>PyArray_FROM_OTF(lam, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less(olam, 0)): - * raise ValueError("lam < 0") - */ - __pyx_t_3 = PyArray_FROM_OTF(__pyx_v_lam, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3675; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_olam = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":3676 - * - * olam = <ndarray>PyArray_FROM_OTF(lam, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less(olam, 0)): # <<<<<<<<<<<<<< - * raise ValueError("lam < 0") - * if np.any(np.greater(olam, self.poisson_lam_max)): - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3676; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3676; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3676; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3676; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3676; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)__pyx_v_olam)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_olam)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_olam)); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3676; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3676; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3676; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3676; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3677 - * olam = <ndarray>PyArray_FROM_OTF(lam, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less(olam, 0)): - * raise ValueError("lam < 0") # <<<<<<<<<<<<<< - * if np.any(np.greater(olam, self.poisson_lam_max)): - * raise ValueError("lam value too large.") - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_156), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3677; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3677; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":3678 - * if np.any(np.less(olam, 0)): - * raise ValueError("lam < 0") - * if np.any(np.greater(olam, self.poisson_lam_max)): # <<<<<<<<<<<<<< - * raise ValueError("lam value too large.") - * return discd_array(self.internal_state, rk_poisson, size, olam) - */ - __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3678; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3678; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3678; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__greater); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3678; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__poisson_lam_max); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3678; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3678; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(((PyObject *)__pyx_v_olam)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_olam)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_olam)); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3678; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3678; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3678; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3678; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3679 - * raise ValueError("lam < 0") - * if np.any(np.greater(olam, self.poisson_lam_max)): - * raise ValueError("lam value too large.") # <<<<<<<<<<<<<< - * return discd_array(self.internal_state, rk_poisson, size, olam) - * - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_158), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3679; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3679; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; - - /* "mtrand.pyx":3680 - * if np.any(np.greater(olam, self.poisson_lam_max)): - * raise ValueError("lam value too large.") - * return discd_array(self.internal_state, rk_poisson, size, olam) # <<<<<<<<<<<<<< - * - * def zipf(self, a, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_5 = __pyx_f_6mtrand_discd_array(__pyx_v_self->internal_state, rk_poisson, __pyx_v_size, __pyx_v_olam); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3680; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.poisson", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_olam); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_89zipf(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_88zipf[] = "\n zipf(a, size=None)\n\n Draw samples from a Zipf distribution.\n\n Samples are drawn from a Zipf distribution with specified parameter\n `a` > 1.\n\n The Zipf distribution (also known as the zeta distribution) is a\n continuous probability distribution that satisfies Zipf's law: the\n frequency of an item is inversely proportional to its rank in a\n frequency table.\n\n Parameters\n ----------\n a : float > 1\n Distribution parameter.\n size : int or tuple of int, optional\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn; a single integer is equivalent in\n its result to providing a mono-tuple, i.e., a 1-D array of length\n *size* is returned. The default is None, in which case a single\n scalar is returned.\n\n Returns\n -------\n samples : scalar or ndarray\n The returned samples are greater than or equal to one.\n\n See Also\n --------\n scipy.stats.distributions.zipf : probability density function,\n distribution, or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Zipf distribution is\n\n .. math:: p(x) = \\frac{x^{-a}}{\\zeta(a)},\n\n where :math:`\\zeta` is the Riemann Zeta function.\n\n It is named for the American linguist George Kingsley Zipf, who noted\n that the frequency of any word in a sample of a language is inversely\n proportional to its rank in the frequency table.\n\n References\n ----------\n Zipf, G. K., *Selected Studies of the Principle of Relative Frequency\n in Language*, Cambridge, MA: Harvard Univ. Press, 1932.\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> a = 2. # parameter\n >>> s = np.random.zipf""(a, 1000)\n\n Display the histogram of the samples, along with\n the probability density function:\n\n >>> import matplotlib.pyplot as plt\n >>> import scipy.special as sps\n Truncate s values at 50 so plot is interesting\n >>> count, bins, ignored = plt.hist(s[s<50], 50, normed=True)\n >>> x = np.arange(1., 50.)\n >>> y = x**(-a)/sps.zetac(a)\n >>> plt.plot(x, y/max(y), linewidth=2, color='r')\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_89zipf(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_a = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("zipf (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__a,&__pyx_n_s__size,0}; - PyObject* values[2] = {0,0}; - - /* "mtrand.pyx":3682 - * return discd_array(self.internal_state, rk_poisson, size, olam) - * - * def zipf(self, a, size=None): # <<<<<<<<<<<<<< - * """ - * zipf(a, size=None) - */ - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__a)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "zipf") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3682; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_a = values[0]; - __pyx_v_size = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("zipf", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3682; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.zipf", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_88zipf(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_a, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_88zipf(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_a, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_oa = 0; - double __pyx_v_fa; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("zipf", 0); - - /* "mtrand.pyx":3757 - * cdef double fa - * - * fa = PyFloat_AsDouble(a) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fa <= 1.0: - */ - __pyx_v_fa = PyFloat_AsDouble(__pyx_v_a); - - /* "mtrand.pyx":3758 - * - * fa = PyFloat_AsDouble(a) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fa <= 1.0: - * raise ValueError("a <= 1.0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":3759 - * fa = PyFloat_AsDouble(a) - * if not PyErr_Occurred(): - * if fa <= 1.0: # <<<<<<<<<<<<<< - * raise ValueError("a <= 1.0") - * return discd_array_sc(self.internal_state, rk_zipf, size, fa) - */ - __pyx_t_1 = (__pyx_v_fa <= 1.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3760 - * if not PyErr_Occurred(): - * if fa <= 1.0: - * raise ValueError("a <= 1.0") # <<<<<<<<<<<<<< - * return discd_array_sc(self.internal_state, rk_zipf, size, fa) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_160), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":3761 - * if fa <= 1.0: - * raise ValueError("a <= 1.0") - * return discd_array_sc(self.internal_state, rk_zipf, size, fa) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_discd_array_sc(__pyx_v_self->internal_state, rk_zipf, __pyx_v_size, __pyx_v_fa); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3761; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":3763 - * return discd_array_sc(self.internal_state, rk_zipf, size, fa) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":3765 - * PyErr_Clear() - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oa, 1.0)): - * raise ValueError("a <= 1.0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_a, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3765; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_oa = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":3766 - * - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 1.0)): # <<<<<<<<<<<<<< - * raise ValueError("a <= 1.0") - * return discd_array(self.internal_state, rk_zipf, size, oa) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3766; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3766; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3766; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3766; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3766; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3766; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_oa)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_oa)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_oa)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3766; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3766; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3766; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3766; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3767 - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 1.0)): - * raise ValueError("a <= 1.0") # <<<<<<<<<<<<<< - * return discd_array(self.internal_state, rk_zipf, size, oa) - * - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_161), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3767; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3767; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":3768 - * if np.any(np.less_equal(oa, 1.0)): - * raise ValueError("a <= 1.0") - * return discd_array(self.internal_state, rk_zipf, size, oa) # <<<<<<<<<<<<<< - * - * def geometric(self, p, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __pyx_f_6mtrand_discd_array(__pyx_v_self->internal_state, rk_zipf, __pyx_v_size, __pyx_v_oa); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.zipf", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_oa); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_91geometric(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_90geometric[] = "\n geometric(p, size=None)\n\n Draw samples from the geometric distribution.\n\n Bernoulli trials are experiments with one of two outcomes:\n success or failure (an example of such an experiment is flipping\n a coin). The geometric distribution models the number of trials\n that must be run in order to achieve success. It is therefore\n supported on the positive integers, ``k = 1, 2, ...``.\n\n The probability mass function of the geometric distribution is\n\n .. math:: f(k) = (1 - p)^{k - 1} p\n\n where `p` is the probability of success of an individual trial.\n\n Parameters\n ----------\n p : float\n The probability of success of an individual trial.\n size : tuple of ints\n Number of values to draw from the distribution. The output\n is shaped according to `size`.\n\n Returns\n -------\n out : ndarray\n Samples from the geometric distribution, shaped according to\n `size`.\n\n Examples\n --------\n Draw ten thousand values from the geometric distribution,\n with the probability of an individual success equal to 0.35:\n\n >>> z = np.random.geometric(p=0.35, size=10000)\n\n How many trials succeeded after a single run?\n\n >>> (z == 1).sum() / 10000.\n 0.34889999999999999 #random\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_91geometric(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_p = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("geometric (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__size,0}; - PyObject* values[2] = {0,0}; - - /* "mtrand.pyx":3770 - * return discd_array(self.internal_state, rk_zipf, size, oa) - * - * def geometric(self, p, size=None): # <<<<<<<<<<<<<< - * """ - * geometric(p, size=None) - */ - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "geometric") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3770; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_p = values[0]; - __pyx_v_size = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("geometric", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3770; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.geometric", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_90geometric(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_p, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_90geometric(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_p, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_op = 0; - double __pyx_v_fp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("geometric", 0); - - /* "mtrand.pyx":3818 - * cdef double fp - * - * fp = PyFloat_AsDouble(p) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fp < 0.0: - */ - __pyx_v_fp = PyFloat_AsDouble(__pyx_v_p); - - /* "mtrand.pyx":3819 - * - * fp = PyFloat_AsDouble(p) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fp < 0.0: - * raise ValueError("p < 0.0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":3820 - * fp = PyFloat_AsDouble(p) - * if not PyErr_Occurred(): - * if fp < 0.0: # <<<<<<<<<<<<<< - * raise ValueError("p < 0.0") - * if fp > 1.0: - */ - __pyx_t_1 = (__pyx_v_fp < 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3821 - * if not PyErr_Occurred(): - * if fp < 0.0: - * raise ValueError("p < 0.0") # <<<<<<<<<<<<<< - * if fp > 1.0: - * raise ValueError("p > 1.0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_163), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":3822 - * if fp < 0.0: - * raise ValueError("p < 0.0") - * if fp > 1.0: # <<<<<<<<<<<<<< - * raise ValueError("p > 1.0") - * return discd_array_sc(self.internal_state, rk_geometric, size, fp) - */ - __pyx_t_1 = (__pyx_v_fp > 1.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3823 - * raise ValueError("p < 0.0") - * if fp > 1.0: - * raise ValueError("p > 1.0") # <<<<<<<<<<<<<< - * return discd_array_sc(self.internal_state, rk_geometric, size, fp) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_165), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":3824 - * if fp > 1.0: - * raise ValueError("p > 1.0") - * return discd_array_sc(self.internal_state, rk_geometric, size, fp) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_discd_array_sc(__pyx_v_self->internal_state, rk_geometric, __pyx_v_size, __pyx_v_fp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":3826 - * return discd_array_sc(self.internal_state, rk_geometric, size, fp) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * - */ - PyErr_Clear(); - - /* "mtrand.pyx":3829 - * - * - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less(op, 0.0)): - * raise ValueError("p < 0.0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_p, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_op = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":3830 - * - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less(op, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("p < 0.0") - * if np.any(np.greater(op, 1.0)): - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_op)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_op)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_op)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3831 - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less(op, 0.0)): - * raise ValueError("p < 0.0") # <<<<<<<<<<<<<< - * if np.any(np.greater(op, 1.0)): - * raise ValueError("p > 1.0") - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_166), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":3832 - * if np.any(np.less(op, 0.0)): - * raise ValueError("p < 0.0") - * if np.any(np.greater(op, 1.0)): # <<<<<<<<<<<<<< - * raise ValueError("p > 1.0") - * return discd_array(self.internal_state, rk_geometric, size, op) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__greater); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(((PyObject *)__pyx_v_op)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_op)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_op)); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3833 - * raise ValueError("p < 0.0") - * if np.any(np.greater(op, 1.0)): - * raise ValueError("p > 1.0") # <<<<<<<<<<<<<< - * return discd_array(self.internal_state, rk_geometric, size, op) - * - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_167), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; - - /* "mtrand.pyx":3834 - * if np.any(np.greater(op, 1.0)): - * raise ValueError("p > 1.0") - * return discd_array(self.internal_state, rk_geometric, size, op) # <<<<<<<<<<<<<< - * - * def hypergeometric(self, ngood, nbad, nsample, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __pyx_f_6mtrand_discd_array(__pyx_v_self->internal_state, rk_geometric, __pyx_v_size, __pyx_v_op); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.geometric", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_op); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_93hypergeometric(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_92hypergeometric[] = "\n hypergeometric(ngood, nbad, nsample, size=None)\n\n Draw samples from a Hypergeometric distribution.\n\n Samples are drawn from a Hypergeometric distribution with specified\n parameters, ngood (ways to make a good selection), nbad (ways to make\n a bad selection), and nsample = number of items sampled, which is less\n than or equal to the sum ngood + nbad.\n\n Parameters\n ----------\n ngood : int or array_like\n Number of ways to make a good selection. Must be nonnegative.\n nbad : int or array_like\n Number of ways to make a bad selection. Must be nonnegative.\n nsample : int or array_like\n Number of items sampled. Must be at least 1 and at most\n ``ngood + nbad``.\n size : int or tuple of int\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : ndarray or scalar\n The values are all integers in [0, n].\n\n See Also\n --------\n scipy.stats.distributions.hypergeom : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Hypergeometric distribution is\n\n .. math:: P(x) = \\frac{\\binom{m}{n}\\binom{N-m}{n-x}}{\\binom{N}{n}},\n\n where :math:`0 \\le x \\le m` and :math:`n+m-N \\le x \\le n`\n\n for P(x) the probability of x successes, n = ngood, m = nbad, and\n N = number of samples.\n\n Consider an urn with black and white marbles in it, ngood of them\n black and nbad are white. If you draw nsample balls without\n replacement, then the Hypergeometric distribution describes the\n distribution of black balls in the drawn sample.\n\n Note that this distribution is very similar to the Binomial\n distrib""ution, except that in this case, samples are drawn without\n replacement, whereas in the Binomial case samples are drawn with\n replacement (or the sample space is infinite). As the sample space\n becomes large, this distribution approaches the Binomial.\n\n References\n ----------\n .. [1] Lentner, Marvin, \"Elementary Applied Statistics\", Bogden\n and Quigley, 1972.\n .. [2] Weisstein, Eric W. \"Hypergeometric Distribution.\" From\n MathWorld--A Wolfram Web Resource.\n http://mathworld.wolfram.com/HypergeometricDistribution.html\n .. [3] Wikipedia, \"Hypergeometric-distribution\",\n http://en.wikipedia.org/wiki/Hypergeometric-distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> ngood, nbad, nsamp = 100, 2, 10\n # number of good, number of bad, and number of samples\n >>> s = np.random.hypergeometric(ngood, nbad, nsamp, 1000)\n >>> hist(s)\n # note that it is very unlikely to grab both bad items\n\n Suppose you have an urn with 15 white and 15 black marbles.\n If you pull 15 marbles at random, how likely is it that\n 12 or more of them are one color?\n\n >>> s = np.random.hypergeometric(15, 15, 15, 100000)\n >>> sum(s>=12)/100000. + sum(s<=3)/100000.\n # answer = 0.003 ... pretty unlikely!\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_93hypergeometric(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_ngood = 0; - PyObject *__pyx_v_nbad = 0; - PyObject *__pyx_v_nsample = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("hypergeometric (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__ngood,&__pyx_n_s__nbad,&__pyx_n_s__nsample,&__pyx_n_s__size,0}; - PyObject* values[4] = {0,0,0,0}; - - /* "mtrand.pyx":3836 - * return discd_array(self.internal_state, rk_geometric, size, op) - * - * def hypergeometric(self, ngood, nbad, nsample, size=None): # <<<<<<<<<<<<<< - * """ - * hypergeometric(ngood, nbad, nsample, size=None) - */ - values[3] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__ngood)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nbad)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("hypergeometric", 0, 3, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3836; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__nsample)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("hypergeometric", 0, 3, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3836; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 3: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[3] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "hypergeometric") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3836; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_ngood = values[0]; - __pyx_v_nbad = values[1]; - __pyx_v_nsample = values[2]; - __pyx_v_size = values[3]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("hypergeometric", 0, 3, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3836; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.hypergeometric", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_92hypergeometric(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_ngood, __pyx_v_nbad, __pyx_v_nsample, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_92hypergeometric(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_ngood, PyObject *__pyx_v_nbad, PyObject *__pyx_v_nsample, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_ongood = 0; - PyArrayObject *__pyx_v_onbad = 0; - PyArrayObject *__pyx_v_onsample = 0; - long __pyx_v_lngood; - long __pyx_v_lnbad; - long __pyx_v_lnsample; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("hypergeometric", 0); - - /* "mtrand.pyx":3924 - * cdef long lngood, lnbad, lnsample - * - * lngood = PyInt_AsLong(ngood) # <<<<<<<<<<<<<< - * lnbad = PyInt_AsLong(nbad) - * lnsample = PyInt_AsLong(nsample) - */ - __pyx_v_lngood = PyInt_AsLong(__pyx_v_ngood); - - /* "mtrand.pyx":3925 - * - * lngood = PyInt_AsLong(ngood) - * lnbad = PyInt_AsLong(nbad) # <<<<<<<<<<<<<< - * lnsample = PyInt_AsLong(nsample) - * if not PyErr_Occurred(): - */ - __pyx_v_lnbad = PyInt_AsLong(__pyx_v_nbad); - - /* "mtrand.pyx":3926 - * lngood = PyInt_AsLong(ngood) - * lnbad = PyInt_AsLong(nbad) - * lnsample = PyInt_AsLong(nsample) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if lngood < 0: - */ - __pyx_v_lnsample = PyInt_AsLong(__pyx_v_nsample); - - /* "mtrand.pyx":3927 - * lnbad = PyInt_AsLong(nbad) - * lnsample = PyInt_AsLong(nsample) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if lngood < 0: - * raise ValueError("ngood < 0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":3928 - * lnsample = PyInt_AsLong(nsample) - * if not PyErr_Occurred(): - * if lngood < 0: # <<<<<<<<<<<<<< - * raise ValueError("ngood < 0") - * if lnbad < 0: - */ - __pyx_t_1 = (__pyx_v_lngood < 0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3929 - * if not PyErr_Occurred(): - * if lngood < 0: - * raise ValueError("ngood < 0") # <<<<<<<<<<<<<< - * if lnbad < 0: - * raise ValueError("nbad < 0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_169), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3929; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3929; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":3930 - * if lngood < 0: - * raise ValueError("ngood < 0") - * if lnbad < 0: # <<<<<<<<<<<<<< - * raise ValueError("nbad < 0") - * if lnsample < 1: - */ - __pyx_t_1 = (__pyx_v_lnbad < 0); - if (__pyx_t_1) { - - /* "mtrand.pyx":3931 - * raise ValueError("ngood < 0") - * if lnbad < 0: - * raise ValueError("nbad < 0") # <<<<<<<<<<<<<< - * if lnsample < 1: - * raise ValueError("nsample < 1") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_171), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3931; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3931; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":3932 - * if lnbad < 0: - * raise ValueError("nbad < 0") - * if lnsample < 1: # <<<<<<<<<<<<<< - * raise ValueError("nsample < 1") - * if lngood + lnbad < lnsample: - */ - __pyx_t_1 = (__pyx_v_lnsample < 1); - if (__pyx_t_1) { - - /* "mtrand.pyx":3933 - * raise ValueError("nbad < 0") - * if lnsample < 1: - * raise ValueError("nsample < 1") # <<<<<<<<<<<<<< - * if lngood + lnbad < lnsample: - * raise ValueError("ngood + nbad < nsample") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_173), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3933; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3933; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":3934 - * if lnsample < 1: - * raise ValueError("nsample < 1") - * if lngood + lnbad < lnsample: # <<<<<<<<<<<<<< - * raise ValueError("ngood + nbad < nsample") - * return discnmN_array_sc(self.internal_state, rk_hypergeometric, size, - */ - __pyx_t_1 = ((__pyx_v_lngood + __pyx_v_lnbad) < __pyx_v_lnsample); - if (__pyx_t_1) { - - /* "mtrand.pyx":3935 - * raise ValueError("nsample < 1") - * if lngood + lnbad < lnsample: - * raise ValueError("ngood + nbad < nsample") # <<<<<<<<<<<<<< - * return discnmN_array_sc(self.internal_state, rk_hypergeometric, size, - * lngood, lnbad, lnsample) - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_175), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3935; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3935; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; - - /* "mtrand.pyx":3936 - * if lngood + lnbad < lnsample: - * raise ValueError("ngood + nbad < nsample") - * return discnmN_array_sc(self.internal_state, rk_hypergeometric, size, # <<<<<<<<<<<<<< - * lngood, lnbad, lnsample) - * - */ - __Pyx_XDECREF(__pyx_r); - - /* "mtrand.pyx":3937 - * raise ValueError("ngood + nbad < nsample") - * return discnmN_array_sc(self.internal_state, rk_hypergeometric, size, - * lngood, lnbad, lnsample) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __pyx_t_2 = __pyx_f_6mtrand_discnmN_array_sc(__pyx_v_self->internal_state, rk_hypergeometric, __pyx_v_size, __pyx_v_lngood, __pyx_v_lnbad, __pyx_v_lnsample); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3936; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":3939 - * lngood, lnbad, lnsample) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * ongood = <ndarray>PyArray_FROM_OTF(ngood, NPY_LONG, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":3941 - * PyErr_Clear() - * - * ongood = <ndarray>PyArray_FROM_OTF(ngood, NPY_LONG, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * onbad = <ndarray>PyArray_FROM_OTF(nbad, NPY_LONG, NPY_ARRAY_ALIGNED) - * onsample = <ndarray>PyArray_FROM_OTF(nsample, NPY_LONG, NPY_ARRAY_ALIGNED) - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_ngood, NPY_LONG, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3941; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_ongood = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":3942 - * - * ongood = <ndarray>PyArray_FROM_OTF(ngood, NPY_LONG, NPY_ARRAY_ALIGNED) - * onbad = <ndarray>PyArray_FROM_OTF(nbad, NPY_LONG, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * onsample = <ndarray>PyArray_FROM_OTF(nsample, NPY_LONG, NPY_ARRAY_ALIGNED) - * if np.any(np.less(ongood, 0)): - */ - __pyx_t_3 = PyArray_FROM_OTF(__pyx_v_nbad, NPY_LONG, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3942; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __pyx_t_3; - __Pyx_INCREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_onbad = ((PyArrayObject *)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":3943 - * ongood = <ndarray>PyArray_FROM_OTF(ngood, NPY_LONG, NPY_ARRAY_ALIGNED) - * onbad = <ndarray>PyArray_FROM_OTF(nbad, NPY_LONG, NPY_ARRAY_ALIGNED) - * onsample = <ndarray>PyArray_FROM_OTF(nsample, NPY_LONG, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less(ongood, 0)): - * raise ValueError("ngood < 0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_nsample, NPY_LONG, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3943; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_onsample = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":3944 - * onbad = <ndarray>PyArray_FROM_OTF(nbad, NPY_LONG, NPY_ARRAY_ALIGNED) - * onsample = <ndarray>PyArray_FROM_OTF(nsample, NPY_LONG, NPY_ARRAY_ALIGNED) - * if np.any(np.less(ongood, 0)): # <<<<<<<<<<<<<< - * raise ValueError("ngood < 0") - * if np.any(np.less(onbad, 0)): - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(((PyObject *)__pyx_v_ongood)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_ongood)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_ongood)); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __pyx_t_5 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3945 - * onsample = <ndarray>PyArray_FROM_OTF(nsample, NPY_LONG, NPY_ARRAY_ALIGNED) - * if np.any(np.less(ongood, 0)): - * raise ValueError("ngood < 0") # <<<<<<<<<<<<<< - * if np.any(np.less(onbad, 0)): - * raise ValueError("nbad < 0") - */ - __pyx_t_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_176), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3945; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_Raise(__pyx_t_5, 0, 0, 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3945; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; - } - __pyx_L8:; - - /* "mtrand.pyx":3946 - * if np.any(np.less(ongood, 0)): - * raise ValueError("ngood < 0") - * if np.any(np.less(onbad, 0)): # <<<<<<<<<<<<<< - * raise ValueError("nbad < 0") - * if np.any(np.less(onsample, 1)): - */ - __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3946; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__any); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3946; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3946; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__less); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3946; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3946; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_onbad)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_onbad)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_onbad)); - __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_0); - __Pyx_GIVEREF(__pyx_int_0); - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3946; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3946; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3946; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3946; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3947 - * raise ValueError("ngood < 0") - * if np.any(np.less(onbad, 0)): - * raise ValueError("nbad < 0") # <<<<<<<<<<<<<< - * if np.any(np.less(onsample, 1)): - * raise ValueError("nsample < 1") - */ - __pyx_t_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_177), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3947; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3947; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L9; - } - __pyx_L9:; - - /* "mtrand.pyx":3948 - * if np.any(np.less(onbad, 0)): - * raise ValueError("nbad < 0") - * if np.any(np.less(onsample, 1)): # <<<<<<<<<<<<<< - * raise ValueError("nsample < 1") - * if np.any(np.less(np.add(ongood, onbad),onsample)): - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3948; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__any); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3948; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3948; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__less); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3948; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3948; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(((PyObject *)__pyx_v_onsample)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_onsample)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_onsample)); - __Pyx_INCREF(__pyx_int_1); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_int_1); - __Pyx_GIVEREF(__pyx_int_1); - __pyx_t_2 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3948; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3948; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3948; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3948; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3949 - * raise ValueError("nbad < 0") - * if np.any(np.less(onsample, 1)): - * raise ValueError("nsample < 1") # <<<<<<<<<<<<<< - * if np.any(np.less(np.add(ongood, onbad),onsample)): - * raise ValueError("ngood + nbad < nsample") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_178), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L10; - } - __pyx_L10:; - - /* "mtrand.pyx":3950 - * if np.any(np.less(onsample, 1)): - * raise ValueError("nsample < 1") - * if np.any(np.less(np.add(ongood, onbad),onsample)): # <<<<<<<<<<<<<< - * raise ValueError("ngood + nbad < nsample") - * return discnmN_array(self.internal_state, rk_hypergeometric, size, - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__any); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__less); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__add); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)__pyx_v_ongood)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_ongood)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_ongood)); - __Pyx_INCREF(((PyObject *)__pyx_v_onbad)); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_v_onbad)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_onbad)); - __pyx_t_6 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_6); - __Pyx_INCREF(((PyObject *)__pyx_v_onsample)); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)__pyx_v_onsample)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_onsample)); - __pyx_t_6 = 0; - __pyx_t_6 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_6); - __pyx_t_6 = 0; - __pyx_t_6 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":3951 - * raise ValueError("nsample < 1") - * if np.any(np.less(np.add(ongood, onbad),onsample)): - * raise ValueError("ngood + nbad < nsample") # <<<<<<<<<<<<<< - * return discnmN_array(self.internal_state, rk_hypergeometric, size, - * ongood, onbad, onsample) - */ - __pyx_t_6 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_179), NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3951; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __Pyx_Raise(__pyx_t_6, 0, 0, 0); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3951; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L11; - } - __pyx_L11:; - - /* "mtrand.pyx":3952 - * if np.any(np.less(np.add(ongood, onbad),onsample)): - * raise ValueError("ngood + nbad < nsample") - * return discnmN_array(self.internal_state, rk_hypergeometric, size, # <<<<<<<<<<<<<< - * ongood, onbad, onsample) - * - */ - __Pyx_XDECREF(__pyx_r); - - /* "mtrand.pyx":3953 - * raise ValueError("ngood + nbad < nsample") - * return discnmN_array(self.internal_state, rk_hypergeometric, size, - * ongood, onbad, onsample) # <<<<<<<<<<<<<< - * - * def logseries(self, p, size=None): - */ - __pyx_t_6 = __pyx_f_6mtrand_discnmN_array(__pyx_v_self->internal_state, rk_hypergeometric, __pyx_v_size, __pyx_v_ongood, __pyx_v_onbad, __pyx_v_onsample); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3952; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - __pyx_r = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("mtrand.RandomState.hypergeometric", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_ongood); - __Pyx_XDECREF((PyObject *)__pyx_v_onbad); - __Pyx_XDECREF((PyObject *)__pyx_v_onsample); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_95logseries(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_94logseries[] = "\n logseries(p, size=None)\n\n Draw samples from a Logarithmic Series distribution.\n\n Samples are drawn from a Log Series distribution with specified\n parameter, p (probability, 0 < p < 1).\n\n Parameters\n ----------\n loc : float\n\n scale : float > 0.\n\n size : {tuple, int}\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn.\n\n Returns\n -------\n samples : {ndarray, scalar}\n where the values are all integers in [0, n].\n\n See Also\n --------\n scipy.stats.distributions.logser : probability density function,\n distribution or cumulative density function, etc.\n\n Notes\n -----\n The probability density for the Log Series distribution is\n\n .. math:: P(k) = \\frac{-p^k}{k \\ln(1-p)},\n\n where p = probability.\n\n The Log Series distribution is frequently used to represent species\n richness and occurrence, first proposed by Fisher, Corbet, and\n Williams in 1943 [2]. It may also be used to model the numbers of\n occupants seen in cars [3].\n\n References\n ----------\n .. [1] Buzas, Martin A.; Culver, Stephen J., Understanding regional\n species diversity through the log series distribution of\n occurrences: BIODIVERSITY RESEARCH Diversity & Distributions,\n Volume 5, Number 5, September 1999 , pp. 187-195(9).\n .. [2] Fisher, R.A,, A.S. Corbet, and C.B. Williams. 1943. The\n relation between the number of species and the number of\n individuals in a random sample of an animal population.\n Journal of Animal Ecology, 12:42-58.\n .. [3] D. J. Hand, F. Daly, D. Lunn, E. Ostrowski, A Handbook of Small\n Data Sets, CRC Press, 1994.\n .. [4] Wikipedia, \"Log""arithmic-distribution\",\n http://en.wikipedia.org/wiki/Logarithmic-distribution\n\n Examples\n --------\n Draw samples from the distribution:\n\n >>> a = .6\n >>> s = np.random.logseries(a, 10000)\n >>> count, bins, ignored = plt.hist(s)\n\n # plot against distribution\n\n >>> def logseries(k, p):\n ... return -p**k/(k*log(1-p))\n >>> plt.plot(bins, logseries(bins, a)*count.max()/\n logseries(bins, a).max(), 'r')\n >>> plt.show()\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_95logseries(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_p = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("logseries (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__p,&__pyx_n_s__size,0}; - PyObject* values[2] = {0,0}; - - /* "mtrand.pyx":3955 - * ongood, onbad, onsample) - * - * def logseries(self, p, size=None): # <<<<<<<<<<<<<< - * """ - * logseries(p, size=None) - */ - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__p)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "logseries") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3955; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_p = values[0]; - __pyx_v_size = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("logseries", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3955; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.logseries", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_94logseries(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_p, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_94logseries(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_p, PyObject *__pyx_v_size) { - PyArrayObject *__pyx_v_op = 0; - double __pyx_v_fp; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("logseries", 0); - - /* "mtrand.pyx":4032 - * cdef double fp - * - * fp = PyFloat_AsDouble(p) # <<<<<<<<<<<<<< - * if not PyErr_Occurred(): - * if fp <= 0.0: - */ - __pyx_v_fp = PyFloat_AsDouble(__pyx_v_p); - - /* "mtrand.pyx":4033 - * - * fp = PyFloat_AsDouble(p) - * if not PyErr_Occurred(): # <<<<<<<<<<<<<< - * if fp <= 0.0: - * raise ValueError("p <= 0.0") - */ - __pyx_t_1 = (!PyErr_Occurred()); - if (__pyx_t_1) { - - /* "mtrand.pyx":4034 - * fp = PyFloat_AsDouble(p) - * if not PyErr_Occurred(): - * if fp <= 0.0: # <<<<<<<<<<<<<< - * raise ValueError("p <= 0.0") - * if fp >= 1.0: - */ - __pyx_t_1 = (__pyx_v_fp <= 0.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":4035 - * if not PyErr_Occurred(): - * if fp <= 0.0: - * raise ValueError("p <= 0.0") # <<<<<<<<<<<<<< - * if fp >= 1.0: - * raise ValueError("p >= 1.0") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_181), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4035; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4035; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":4036 - * if fp <= 0.0: - * raise ValueError("p <= 0.0") - * if fp >= 1.0: # <<<<<<<<<<<<<< - * raise ValueError("p >= 1.0") - * return discd_array_sc(self.internal_state, rk_logseries, size, fp) - */ - __pyx_t_1 = (__pyx_v_fp >= 1.0); - if (__pyx_t_1) { - - /* "mtrand.pyx":4037 - * raise ValueError("p <= 0.0") - * if fp >= 1.0: - * raise ValueError("p >= 1.0") # <<<<<<<<<<<<<< - * return discd_array_sc(self.internal_state, rk_logseries, size, fp) - * - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_183), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":4038 - * if fp >= 1.0: - * raise ValueError("p >= 1.0") - * return discd_array_sc(self.internal_state, rk_logseries, size, fp) # <<<<<<<<<<<<<< - * - * PyErr_Clear() - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_f_6mtrand_discd_array_sc(__pyx_v_self->internal_state, rk_logseries, __pyx_v_size, __pyx_v_fp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4038; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":4040 - * return discd_array_sc(self.internal_state, rk_logseries, size, fp) - * - * PyErr_Clear() # <<<<<<<<<<<<<< - * - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - */ - PyErr_Clear(); - - /* "mtrand.pyx":4042 - * PyErr_Clear() - * - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< - * if np.any(np.less_equal(op, 0.0)): - * raise ValueError("p <= 0.0") - */ - __pyx_t_2 = PyArray_FROM_OTF(__pyx_v_p, NPY_DOUBLE, NPY_ARRAY_ALIGNED); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4042; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_op = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":4043 - * - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(op, 0.0)): # <<<<<<<<<<<<<< - * raise ValueError("p <= 0.0") - * if np.any(np.greater_equal(op, 1.0)): - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__less_equal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(((PyObject *)__pyx_v_op)); - PyTuple_SET_ITEM(__pyx_t_5, 0, ((PyObject *)__pyx_v_op)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_op)); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":4044 - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(op, 0.0)): - * raise ValueError("p <= 0.0") # <<<<<<<<<<<<<< - * if np.any(np.greater_equal(op, 1.0)): - * raise ValueError("p >= 1.0") - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_184), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4044; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4044; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":4045 - * if np.any(np.less_equal(op, 0.0)): - * raise ValueError("p <= 0.0") - * if np.any(np.greater_equal(op, 1.0)): # <<<<<<<<<<<<<< - * raise ValueError("p >= 1.0") - * return discd_array(self.internal_state, rk_logseries, size, op) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__any); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__greater_equal); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(((PyObject *)__pyx_v_op)); - PyTuple_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_op)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_op)); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_5, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_1) { - - /* "mtrand.pyx":4046 - * raise ValueError("p <= 0.0") - * if np.any(np.greater_equal(op, 1.0)): - * raise ValueError("p >= 1.0") # <<<<<<<<<<<<<< - * return discd_array(self.internal_state, rk_logseries, size, op) - * - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_185), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4046; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4046; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L7; - } - __pyx_L7:; - - /* "mtrand.pyx":4047 - * if np.any(np.greater_equal(op, 1.0)): - * raise ValueError("p >= 1.0") - * return discd_array(self.internal_state, rk_logseries, size, op) # <<<<<<<<<<<<<< - * - * # Multivariate distributions: - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __pyx_f_6mtrand_discd_array(__pyx_v_self->internal_state, rk_logseries, __pyx_v_size, __pyx_v_op); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4047; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.logseries", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_op); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_97multivariate_normal(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_96multivariate_normal[] = "\n multivariate_normal(mean, cov[, size])\n\n Draw random samples from a multivariate normal distribution.\n\n The multivariate normal, multinormal or Gaussian distribution is a\n generalization of the one-dimensional normal distribution to higher\n dimensions. Such a distribution is specified by its mean and\n covariance matrix. These parameters are analogous to the mean\n (average or \"center\") and variance (standard deviation, or \"width,\"\n squared) of the one-dimensional normal distribution.\n\n Parameters\n ----------\n mean : 1-D array_like, of length N\n Mean of the N-dimensional distribution.\n cov : 2-D array_like, of shape (N, N)\n Covariance matrix of the distribution. Must be symmetric and\n positive semi-definite for \"physically meaningful\" results.\n size : int or tuple of ints, optional\n Given a shape of, for example, ``(m,n,k)``, ``m*n*k`` samples are\n generated, and packed in an `m`-by-`n`-by-`k` arrangement. Because\n each sample is `N`-dimensional, the output shape is ``(m,n,k,N)``.\n If no shape is specified, a single (`N`-D) sample is returned.\n\n Returns\n -------\n out : ndarray\n The drawn samples, of shape *size*, if that was provided. If not,\n the shape is ``(N,)``.\n\n In other words, each entry ``out[i,j,...,:]`` is an N-dimensional\n value drawn from the distribution.\n\n Notes\n -----\n The mean is a coordinate in N-dimensional space, which represents the\n location where samples are most likely to be generated. This is\n analogous to the peak of the bell curve for the one-dimensional or\n univariate normal distribution.\n\n Covariance indicates the level to which two variables vary together.\n From the multivariate normal distribution, w""e draw N-dimensional\n samples, :math:`X = [x_1, x_2, ... x_N]`. The covariance matrix\n element :math:`C_{ij}` is the covariance of :math:`x_i` and :math:`x_j`.\n The element :math:`C_{ii}` is the variance of :math:`x_i` (i.e. its\n \"spread\").\n\n Instead of specifying the full covariance matrix, popular\n approximations include:\n\n - Spherical covariance (*cov* is a multiple of the identity matrix)\n - Diagonal covariance (*cov* has non-negative elements, and only on\n the diagonal)\n\n This geometrical property can be seen in two dimensions by plotting\n generated data-points:\n\n >>> mean = [0,0]\n >>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis\n\n >>> import matplotlib.pyplot as plt\n >>> x,y = np.random.multivariate_normal(mean,cov,5000).T\n >>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()\n\n Note that the covariance matrix must be non-negative definite.\n\n References\n ----------\n Papoulis, A., *Probability, Random Variables, and Stochastic Processes*,\n 3rd ed., New York: McGraw-Hill, 1991.\n\n Duda, R. O., Hart, P. E., and Stork, D. G., *Pattern Classification*,\n 2nd ed., New York: Wiley, 2001.\n\n Examples\n --------\n >>> mean = (1,2)\n >>> cov = [[1,0],[1,0]]\n >>> x = np.random.multivariate_normal(mean,cov,(3,3))\n >>> x.shape\n (3, 3, 2)\n\n The following is probably true, given that 0.6 is roughly twice the\n standard deviation:\n\n >>> print list( (x[0,0,:] - mean) < 0.6 )\n [True, True]\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_97multivariate_normal(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_mean = 0; - PyObject *__pyx_v_cov = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("multivariate_normal (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__mean,&__pyx_n_s__cov,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - - /* "mtrand.pyx":4050 - * - * # Multivariate distributions: - * def multivariate_normal(self, mean, cov, size=None): # <<<<<<<<<<<<<< - * """ - * multivariate_normal(mean, cov[, size]) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__mean)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__cov)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("multivariate_normal", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4050; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "multivariate_normal") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4050; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_mean = values[0]; - __pyx_v_cov = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("multivariate_normal", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4050; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.multivariate_normal", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_96multivariate_normal(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_mean, __pyx_v_cov, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_96multivariate_normal(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_mean, PyObject *__pyx_v_cov, PyObject *__pyx_v_size) { - PyObject *__pyx_v_shape = NULL; - PyObject *__pyx_v_final_shape = NULL; - PyObject *__pyx_v_x = NULL; - PyObject *__pyx_v_svd = NULL; - CYTHON_UNUSED PyObject *__pyx_v_u = NULL; - PyObject *__pyx_v_s = NULL; - PyObject *__pyx_v_v = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - Py_ssize_t __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - PyObject *(*__pyx_t_11)(PyObject *); - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("multivariate_normal", 0); - __Pyx_INCREF(__pyx_v_mean); - __Pyx_INCREF(__pyx_v_cov); - - /* "mtrand.pyx":4142 - * """ - * # Check preconditions on arguments - * mean = np.array(mean) # <<<<<<<<<<<<<< - * cov = np.array(cov) - * if size is None: - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__array); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_mean); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_mean); - __Pyx_GIVEREF(__pyx_v_mean); - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_v_mean); - __pyx_v_mean = __pyx_t_3; - __pyx_t_3 = 0; - - /* "mtrand.pyx":4143 - * # Check preconditions on arguments - * mean = np.array(mean) - * cov = np.array(cov) # <<<<<<<<<<<<<< - * if size is None: - * shape = [] - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__array); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_cov); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_cov); - __Pyx_GIVEREF(__pyx_v_cov); - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4143; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_v_cov); - __pyx_v_cov = __pyx_t_2; - __pyx_t_2 = 0; - - /* "mtrand.pyx":4144 - * mean = np.array(mean) - * cov = np.array(cov) - * if size is None: # <<<<<<<<<<<<<< - * shape = [] - * else: - */ - __pyx_t_4 = (__pyx_v_size == Py_None); - if (__pyx_t_4) { - - /* "mtrand.pyx":4145 - * cov = np.array(cov) - * if size is None: - * shape = [] # <<<<<<<<<<<<<< - * else: - * shape = size - */ - __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_v_shape = ((PyObject *)__pyx_t_2); - __pyx_t_2 = 0; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":4147 - * shape = [] - * else: - * shape = size # <<<<<<<<<<<<<< - * if len(mean.shape) != 1: - * raise ValueError("mean must be 1 dimensional") - */ - __Pyx_INCREF(__pyx_v_size); - __pyx_v_shape = __pyx_v_size; - } - __pyx_L3:; - - /* "mtrand.pyx":4148 - * else: - * shape = size - * if len(mean.shape) != 1: # <<<<<<<<<<<<<< - * raise ValueError("mean must be 1 dimensional") - * if (len(cov.shape) != 2) or (cov.shape[0] != cov.shape[1]): - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_mean, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyObject_Length(__pyx_t_2); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4148; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_4 = (__pyx_t_5 != 1); - if (__pyx_t_4) { - - /* "mtrand.pyx":4149 - * shape = size - * if len(mean.shape) != 1: - * raise ValueError("mean must be 1 dimensional") # <<<<<<<<<<<<<< - * if (len(cov.shape) != 2) or (cov.shape[0] != cov.shape[1]): - * raise ValueError("cov must be 2 dimensional and square") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_187), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L4; - } - __pyx_L4:; - - /* "mtrand.pyx":4150 - * if len(mean.shape) != 1: - * raise ValueError("mean must be 1 dimensional") - * if (len(cov.shape) != 2) or (cov.shape[0] != cov.shape[1]): # <<<<<<<<<<<<<< - * raise ValueError("cov must be 2 dimensional and square") - * if mean.shape[0] != cov.shape[0]: - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_cov, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_5 = PyObject_Length(__pyx_t_2); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_4 = (__pyx_t_5 != 2); - if (!__pyx_t_4) { - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_cov, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_2, 0, sizeof(long), PyInt_FromLong, 0, 0, 1); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_cov, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 1, sizeof(long), PyInt_FromLong, 0, 0, 1); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_RichCompare(__pyx_t_3, __pyx_t_1, Py_NE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4150; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_7 = __pyx_t_6; - } else { - __pyx_t_7 = __pyx_t_4; - } - if (__pyx_t_7) { - - /* "mtrand.pyx":4151 - * raise ValueError("mean must be 1 dimensional") - * if (len(cov.shape) != 2) or (cov.shape[0] != cov.shape[1]): - * raise ValueError("cov must be 2 dimensional and square") # <<<<<<<<<<<<<< - * if mean.shape[0] != cov.shape[0]: - * raise ValueError("mean and cov must have same length") - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_189), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - - /* "mtrand.pyx":4152 - * if (len(cov.shape) != 2) or (cov.shape[0] != cov.shape[1]): - * raise ValueError("cov must be 2 dimensional and square") - * if mean.shape[0] != cov.shape[0]: # <<<<<<<<<<<<<< - * raise ValueError("mean and cov must have same length") - * # Compute shape of output - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_mean, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_t_2, 0, sizeof(long), PyInt_FromLong, 0, 0, 1); if (!__pyx_t_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_cov, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_2, 0, sizeof(long), PyInt_FromLong, 0, 0, 1); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyObject_RichCompare(__pyx_t_1, __pyx_t_3, Py_NE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_7 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4152; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (__pyx_t_7) { - - /* "mtrand.pyx":4153 - * raise ValueError("cov must be 2 dimensional and square") - * if mean.shape[0] != cov.shape[0]: - * raise ValueError("mean and cov must have same length") # <<<<<<<<<<<<<< - * # Compute shape of output - * if isinstance(shape, (int, long, np.integer)): - */ - __pyx_t_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_191), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_Raise(__pyx_t_2, 0, 0, 0); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; - - /* "mtrand.pyx":4155 - * raise ValueError("mean and cov must have same length") - * # Compute shape of output - * if isinstance(shape, (int, long, np.integer)): # <<<<<<<<<<<<<< - * shape = [shape] - * final_shape = list(shape[:]) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__integer); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyLong_Type)))); - PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)((PyObject*)(&PyLong_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyLong_Type)))); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_7 = PyObject_IsInstance(__pyx_v_shape, ((PyObject *)__pyx_t_2)); if (unlikely(__pyx_t_7 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - if (__pyx_t_7) { - - /* "mtrand.pyx":4156 - * # Compute shape of output - * if isinstance(shape, (int, long, np.integer)): - * shape = [shape] # <<<<<<<<<<<<<< - * final_shape = list(shape[:]) - * final_shape.append(mean.shape[0]) - */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_shape); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); - __Pyx_GIVEREF(__pyx_v_shape); - __Pyx_DECREF(__pyx_v_shape); - __pyx_v_shape = ((PyObject *)__pyx_t_2); - __pyx_t_2 = 0; - goto __pyx_L7; - } - __pyx_L7:; - - /* "mtrand.pyx":4157 - * if isinstance(shape, (int, long, np.integer)): - * shape = [shape] - * final_shape = list(shape[:]) # <<<<<<<<<<<<<< - * final_shape.append(mean.shape[0]) - * # Create a matrix of independent standard normally distributed random - */ - __pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_v_shape, 0, 0, NULL, NULL, &__pyx_k_slice_192, 0, 0, 1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_2 = PyObject_Call(((PyObject *)((PyObject*)(&PyList_Type))), ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_v_final_shape = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - - /* "mtrand.pyx":4158 - * shape = [shape] - * final_shape = list(shape[:]) - * final_shape.append(mean.shape[0]) # <<<<<<<<<<<<<< - * # Create a matrix of independent standard normally distributed random - * # numbers. The matrix has rows with the same length as mean and as - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_mean, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_GetItemInt(__pyx_t_2, 0, sizeof(long), PyInt_FromLong, 0, 0, 1); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_8 = __Pyx_PyList_Append(__pyx_v_final_shape, __pyx_t_3); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "mtrand.pyx":4162 - * # numbers. The matrix has rows with the same length as mean and as - * # many rows are necessary to form a matrix of shape final_shape. - * x = self.standard_normal(np.multiply.reduce(final_shape)) # <<<<<<<<<<<<<< - * x.shape = (np.multiply.reduce(final_shape[0:len(final_shape)-1]), - * mean.shape[0]) - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__standard_normal); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__multiply); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__reduce); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)__pyx_v_final_shape)); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)__pyx_v_final_shape)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_final_shape)); - __pyx_t_9 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_9); - __Pyx_GIVEREF(__pyx_t_9); - __pyx_t_9 = 0; - __pyx_t_9 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_v_x = __pyx_t_9; - __pyx_t_9 = 0; - - /* "mtrand.pyx":4163 - * # many rows are necessary to form a matrix of shape final_shape. - * x = self.standard_normal(np.multiply.reduce(final_shape)) - * x.shape = (np.multiply.reduce(final_shape[0:len(final_shape)-1]), # <<<<<<<<<<<<<< - * mean.shape[0]) - * # Transform matrix of standard normals into matrix where each row - */ - __pyx_t_9 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_9, __pyx_n_s__multiply); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__reduce); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = PyList_GET_SIZE(((PyObject *)__pyx_v_final_shape)); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = __Pyx_PyList_GetSlice(((PyObject *)__pyx_v_final_shape), 0, (__pyx_t_5 - 1)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_t_1)); - __Pyx_GIVEREF(((PyObject *)__pyx_t_1)); - __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_9, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - - /* "mtrand.pyx":4164 - * x = self.standard_normal(np.multiply.reduce(final_shape)) - * x.shape = (np.multiply.reduce(final_shape[0:len(final_shape)-1]), - * mean.shape[0]) # <<<<<<<<<<<<<< - * # Transform matrix of standard normals into matrix where each row - * # contains multivariate normals with the desired covariance. - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_mean, __pyx_n_s__shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_9 = __Pyx_GetItemInt(__pyx_t_3, 0, sizeof(long), PyInt_FromLong, 0, 0, 1); if (!__pyx_t_9) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_9); - __Pyx_GIVEREF(__pyx_t_9); - __pyx_t_1 = 0; - __pyx_t_9 = 0; - - /* "mtrand.pyx":4163 - * # many rows are necessary to form a matrix of shape final_shape. - * x = self.standard_normal(np.multiply.reduce(final_shape)) - * x.shape = (np.multiply.reduce(final_shape[0:len(final_shape)-1]), # <<<<<<<<<<<<<< - * mean.shape[0]) - * # Transform matrix of standard normals into matrix where each row - */ - if (__Pyx_PyObject_SetAttrStr(__pyx_v_x, __pyx_n_s__shape, ((PyObject *)__pyx_t_3)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - - /* "mtrand.pyx":4172 - * # decomposition of cov is such an A. - * - * from numpy.dual import svd # <<<<<<<<<<<<<< - * # XXX: we really should be doing this by Cholesky decomposition - * (u,s,v) = svd(cov) - */ - __pyx_t_3 = PyList_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(((PyObject *)__pyx_n_s__svd)); - PyList_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_n_s__svd)); - __Pyx_GIVEREF(((PyObject *)__pyx_n_s__svd)); - __pyx_t_9 = __Pyx_Import(((PyObject *)__pyx_n_s_193), ((PyObject *)__pyx_t_3), -1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_ImportFrom(__pyx_t_9, __pyx_n_s__svd); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_3); - __pyx_v_svd = __pyx_t_3; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "mtrand.pyx":4174 - * from numpy.dual import svd - * # XXX: we really should be doing this by Cholesky decomposition - * (u,s,v) = svd(cov) # <<<<<<<<<<<<<< - * x = np.dot(x*np.sqrt(s),v) - * # The rows of x now have the correct covariance but mean 0. Add - */ - __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_INCREF(__pyx_v_cov); - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_v_cov); - __Pyx_GIVEREF(__pyx_v_cov); - __pyx_t_3 = PyObject_Call(__pyx_v_svd, ((PyObject *)__pyx_t_9), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_3))) || (PyList_CheckExact(__pyx_t_3))) { - PyObject* sequence = __pyx_t_3; - #if CYTHON_COMPILING_IN_CPYTHON - Py_ssize_t size = Py_SIZE(sequence); - #else - Py_ssize_t size = PySequence_Size(sequence); - #endif - if (unlikely(size != 3)) { - if (size > 3) __Pyx_RaiseTooManyValuesError(3); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - #if CYTHON_COMPILING_IN_CPYTHON - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_9 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 2); - } else { - __pyx_t_9 = PyList_GET_ITEM(sequence, 0); - __pyx_t_1 = PyList_GET_ITEM(sequence, 1); - __pyx_t_2 = PyList_GET_ITEM(sequence, 2); - } - __Pyx_INCREF(__pyx_t_9); - __Pyx_INCREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_2); - #else - __pyx_t_9 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - #endif - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else - { - Py_ssize_t index = -1; - __pyx_t_10 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_11 = Py_TYPE(__pyx_t_10)->tp_iternext; - index = 0; __pyx_t_9 = __pyx_t_11(__pyx_t_10); if (unlikely(!__pyx_t_9)) goto __pyx_L8_unpacking_failed; - __Pyx_GOTREF(__pyx_t_9); - index = 1; __pyx_t_1 = __pyx_t_11(__pyx_t_10); if (unlikely(!__pyx_t_1)) goto __pyx_L8_unpacking_failed; - __Pyx_GOTREF(__pyx_t_1); - index = 2; __pyx_t_2 = __pyx_t_11(__pyx_t_10); if (unlikely(!__pyx_t_2)) goto __pyx_L8_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_11(__pyx_t_10), 3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_11 = NULL; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - goto __pyx_L9_unpacking_done; - __pyx_L8_unpacking_failed:; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_11 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_L9_unpacking_done:; - } - __pyx_v_u = __pyx_t_9; - __pyx_t_9 = 0; - __pyx_v_s = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_v_v = __pyx_t_2; - __pyx_t_2 = 0; - - /* "mtrand.pyx":4175 - * # XXX: we really should be doing this by Cholesky decomposition - * (u,s,v) = svd(cov) - * x = np.dot(x*np.sqrt(s),v) # <<<<<<<<<<<<<< - * # The rows of x now have the correct covariance but mean 0. Add - * # mean to each row. Then each row will have mean mean. - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__dot); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__sqrt); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_s); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_s); - __Pyx_GIVEREF(__pyx_v_s); - __pyx_t_9 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Multiply(__pyx_v_x, __pyx_t_9); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_v); - PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_v_v); - __Pyx_GIVEREF(__pyx_v_v); - __pyx_t_3 = 0; - __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_9), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_v_x); - __pyx_v_x = __pyx_t_3; - __pyx_t_3 = 0; - - /* "mtrand.pyx":4178 - * # The rows of x now have the correct covariance but mean 0. Add - * # mean to each row. Then each row will have mean mean. - * np.add(mean,x,x) # <<<<<<<<<<<<<< - * x.shape = tuple(final_shape) - * return x - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__add); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_mean); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_mean); - __Pyx_GIVEREF(__pyx_v_mean); - __Pyx_INCREF(__pyx_v_x); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_x); - __Pyx_GIVEREF(__pyx_v_x); - __Pyx_INCREF(__pyx_v_x); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_v_x); - __Pyx_GIVEREF(__pyx_v_x); - __pyx_t_2 = PyObject_Call(__pyx_t_9, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "mtrand.pyx":4179 - * # mean to each row. Then each row will have mean mean. - * np.add(mean,x,x) - * x.shape = tuple(final_shape) # <<<<<<<<<<<<<< - * return x - * - */ - __pyx_t_2 = ((PyObject *)PyList_AsTuple(__pyx_v_final_shape)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_2)); - if (__Pyx_PyObject_SetAttrStr(__pyx_v_x, __pyx_n_s__shape, ((PyObject *)__pyx_t_2)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - - /* "mtrand.pyx":4180 - * np.add(mean,x,x) - * x.shape = tuple(final_shape) - * return x # <<<<<<<<<<<<<< - * - * def multinomial(self, npy_intp n, object pvals, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_x); - __pyx_r = __pyx_v_x; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("mtrand.RandomState.multivariate_normal", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_shape); - __Pyx_XDECREF(__pyx_v_final_shape); - __Pyx_XDECREF(__pyx_v_x); - __Pyx_XDECREF(__pyx_v_svd); - __Pyx_XDECREF(__pyx_v_u); - __Pyx_XDECREF(__pyx_v_s); - __Pyx_XDECREF(__pyx_v_v); - __Pyx_XDECREF(__pyx_v_mean); - __Pyx_XDECREF(__pyx_v_cov); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_99multinomial(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_98multinomial[] = "\n multinomial(n, pvals, size=None)\n\n Draw samples from a multinomial distribution.\n\n The multinomial distribution is a multivariate generalisation of the\n binomial distribution. Take an experiment with one of ``p``\n possible outcomes. An example of such an experiment is throwing a dice,\n where the outcome can be 1 through 6. Each sample drawn from the\n distribution represents `n` such experiments. Its values,\n ``X_i = [X_0, X_1, ..., X_p]``, represent the number of times the outcome\n was ``i``.\n\n Parameters\n ----------\n n : int\n Number of experiments.\n pvals : sequence of floats, length p\n Probabilities of each of the ``p`` different outcomes. These\n should sum to 1 (however, the last element is always assumed to\n account for the remaining probability, as long as\n ``sum(pvals[:-1]) <= 1)``.\n size : tuple of ints\n Given a `size` of ``(M, N, K)``, then ``M*N*K`` samples are drawn,\n and the output shape becomes ``(M, N, K, p)``, since each sample\n has shape ``(p,)``.\n\n Examples\n --------\n Throw a dice 20 times:\n\n >>> np.random.multinomial(20, [1/6.]*6, size=1)\n array([[4, 1, 7, 5, 2, 1]])\n\n It landed 4 times on 1, once on 2, etc.\n\n Now, throw the dice 20 times, and 20 times again:\n\n >>> np.random.multinomial(20, [1/6.]*6, size=2)\n array([[3, 4, 3, 3, 4, 3],\n [2, 4, 3, 4, 0, 7]])\n\n For the first run, we threw 3 times 1, 4 times 2, etc. For the second,\n we threw 2 times 1, 4 times 2, etc.\n\n A loaded dice is more likely to land on number 6:\n\n >>> np.random.multinomial(100, [1/7.]*5)\n array([13, 16, 13, 16, 42])\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_99multinomial(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - npy_intp __pyx_v_n; - PyObject *__pyx_v_pvals = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("multinomial (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__n,&__pyx_n_s__pvals,&__pyx_n_s__size,0}; - PyObject* values[3] = {0,0,0}; - - /* "mtrand.pyx":4182 - * return x - * - * def multinomial(self, npy_intp n, object pvals, size=None): # <<<<<<<<<<<<<< - * """ - * multinomial(n, pvals, size=None) - */ - values[2] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__n)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__pvals)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("multinomial", 0, 2, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4182; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - case 2: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[2] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "multinomial") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4182; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_n = __Pyx_PyInt_from_py_npy_intp(values[0]); if (unlikely((__pyx_v_n == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4182; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_pvals = values[1]; - __pyx_v_size = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("multinomial", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4182; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.multinomial", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_98multinomial(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_n, __pyx_v_pvals, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_98multinomial(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, npy_intp __pyx_v_n, PyObject *__pyx_v_pvals, PyObject *__pyx_v_size) { - npy_intp __pyx_v_d; - PyArrayObject *arrayObject_parr = 0; - PyArrayObject *arrayObject_mnarr = 0; - double *__pyx_v_pix; - long *__pyx_v_mnix; - npy_intp __pyx_v_i; - npy_intp __pyx_v_j; - npy_intp __pyx_v_dn; - double __pyx_v_Sum; - PyObject *__pyx_v_shape = NULL; - PyObject *__pyx_v_multin = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - long __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("multinomial", 0); - - /* "mtrand.pyx":4241 - * cdef double Sum - * - * d = len(pvals) # <<<<<<<<<<<<<< - * parr = <ndarray>PyArray_ContiguousFromObject(pvals, NPY_DOUBLE, 1, 1) - * pix = <double*>PyArray_DATA(parr) - */ - __pyx_t_1 = PyObject_Length(__pyx_v_pvals); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_d = __pyx_t_1; - - /* "mtrand.pyx":4242 - * - * d = len(pvals) - * parr = <ndarray>PyArray_ContiguousFromObject(pvals, NPY_DOUBLE, 1, 1) # <<<<<<<<<<<<<< - * pix = <double*>PyArray_DATA(parr) - * - */ - __pyx_t_2 = PyArray_ContiguousFromObject(__pyx_v_pvals, NPY_DOUBLE, 1, 1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4242; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - arrayObject_parr = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":4243 - * d = len(pvals) - * parr = <ndarray>PyArray_ContiguousFromObject(pvals, NPY_DOUBLE, 1, 1) - * pix = <double*>PyArray_DATA(parr) # <<<<<<<<<<<<<< - * - * if kahan_sum(pix, d-1) > (1.0 + 1e-12): - */ - __pyx_v_pix = ((double *)PyArray_DATA(arrayObject_parr)); - - /* "mtrand.pyx":4245 - * pix = <double*>PyArray_DATA(parr) - * - * if kahan_sum(pix, d-1) > (1.0 + 1e-12): # <<<<<<<<<<<<<< - * raise ValueError("sum(pvals[:-1]) > 1.0") - * - */ - __pyx_t_4 = (__pyx_f_6mtrand_kahan_sum(__pyx_v_pix, (__pyx_v_d - 1)) > (1.0 + 1e-12)); - if (__pyx_t_4) { - - /* "mtrand.pyx":4246 - * - * if kahan_sum(pix, d-1) > (1.0 + 1e-12): - * raise ValueError("sum(pvals[:-1]) > 1.0") # <<<<<<<<<<<<<< - * - * if size is None: - */ - __pyx_t_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_k_tuple_195), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4246; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4246; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; - } - __pyx_L3:; - - /* "mtrand.pyx":4248 - * raise ValueError("sum(pvals[:-1]) > 1.0") - * - * if size is None: # <<<<<<<<<<<<<< - * shape = (d,) - * elif type(size) is int: - */ - __pyx_t_4 = (__pyx_v_size == Py_None); - if (__pyx_t_4) { - - /* "mtrand.pyx":4249 - * - * if size is None: - * shape = (d,) # <<<<<<<<<<<<<< - * elif type(size) is int: - * shape = (size, d) - */ - __pyx_t_3 = __Pyx_PyInt_to_py_npy_intp(__pyx_v_d); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_v_shape = ((PyObject *)__pyx_t_2); - __pyx_t_2 = 0; - goto __pyx_L4; - } - - /* "mtrand.pyx":4250 - * if size is None: - * shape = (d,) - * elif type(size) is int: # <<<<<<<<<<<<<< - * shape = (size, d) - * else: - */ - __pyx_t_4 = (((PyObject *)Py_TYPE(__pyx_v_size)) == ((PyObject *)((PyObject*)(&PyInt_Type)))); - if (__pyx_t_4) { - - /* "mtrand.pyx":4251 - * shape = (d,) - * elif type(size) is int: - * shape = (size, d) # <<<<<<<<<<<<<< - * else: - * shape = size + (d,) - */ - __pyx_t_2 = __Pyx_PyInt_to_py_npy_intp(__pyx_v_d); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_v_shape = ((PyObject *)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L4; - } - /*else*/ { - - /* "mtrand.pyx":4253 - * shape = (size, d) - * else: - * shape = size + (d,) # <<<<<<<<<<<<<< - * - * multin = np.zeros(shape, int) - */ - __pyx_t_3 = __Pyx_PyInt_to_py_npy_intp(__pyx_v_d); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Add(__pyx_v_size, ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4253; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_v_shape = __pyx_t_3; - __pyx_t_3 = 0; - } - __pyx_L4:; - - /* "mtrand.pyx":4255 - * shape = size + (d,) - * - * multin = np.zeros(shape, int) # <<<<<<<<<<<<<< - * mnarr = <ndarray>multin - * mnix = <long*>PyArray_DATA(mnarr) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_shape); - __Pyx_GIVEREF(__pyx_v_shape); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - PyTuple_SET_ITEM(__pyx_t_3, 1, ((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_v_multin = __pyx_t_5; - __pyx_t_5 = 0; - - /* "mtrand.pyx":4256 - * - * multin = np.zeros(shape, int) - * mnarr = <ndarray>multin # <<<<<<<<<<<<<< - * mnix = <long*>PyArray_DATA(mnarr) - * i = 0 - */ - __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_multin))); - arrayObject_mnarr = ((PyArrayObject *)__pyx_v_multin); - - /* "mtrand.pyx":4257 - * multin = np.zeros(shape, int) - * mnarr = <ndarray>multin - * mnix = <long*>PyArray_DATA(mnarr) # <<<<<<<<<<<<<< - * i = 0 - * while i < PyArray_SIZE(mnarr): - */ - __pyx_v_mnix = ((long *)PyArray_DATA(arrayObject_mnarr)); - - /* "mtrand.pyx":4258 - * mnarr = <ndarray>multin - * mnix = <long*>PyArray_DATA(mnarr) - * i = 0 # <<<<<<<<<<<<<< - * while i < PyArray_SIZE(mnarr): - * Sum = 1.0 - */ - __pyx_v_i = 0; - - /* "mtrand.pyx":4259 - * mnix = <long*>PyArray_DATA(mnarr) - * i = 0 - * while i < PyArray_SIZE(mnarr): # <<<<<<<<<<<<<< - * Sum = 1.0 - * dn = n - */ - while (1) { - __pyx_t_4 = (__pyx_v_i < PyArray_SIZE(arrayObject_mnarr)); - if (!__pyx_t_4) break; - - /* "mtrand.pyx":4260 - * i = 0 - * while i < PyArray_SIZE(mnarr): - * Sum = 1.0 # <<<<<<<<<<<<<< - * dn = n - * for j from 0 <= j < d-1: - */ - __pyx_v_Sum = 1.0; - - /* "mtrand.pyx":4261 - * while i < PyArray_SIZE(mnarr): - * Sum = 1.0 - * dn = n # <<<<<<<<<<<<<< - * for j from 0 <= j < d-1: - * mnix[i+j] = rk_binomial(self.internal_state, dn, pix[j]/Sum) - */ - __pyx_v_dn = __pyx_v_n; - - /* "mtrand.pyx":4262 - * Sum = 1.0 - * dn = n - * for j from 0 <= j < d-1: # <<<<<<<<<<<<<< - * mnix[i+j] = rk_binomial(self.internal_state, dn, pix[j]/Sum) - * dn = dn - mnix[i+j] - */ - __pyx_t_6 = (__pyx_v_d - 1); - for (__pyx_v_j = 0; __pyx_v_j < __pyx_t_6; __pyx_v_j++) { - - /* "mtrand.pyx":4263 - * dn = n - * for j from 0 <= j < d-1: - * mnix[i+j] = rk_binomial(self.internal_state, dn, pix[j]/Sum) # <<<<<<<<<<<<<< - * dn = dn - mnix[i+j] - * if dn <= 0: - */ - if (unlikely(__pyx_v_Sum == 0)) { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); - #endif - PyErr_Format(PyExc_ZeroDivisionError, "float division"); - #ifdef WITH_THREAD - PyGILState_Release(__pyx_gilstate_save); - #endif - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4263; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - (__pyx_v_mnix[(__pyx_v_i + __pyx_v_j)]) = rk_binomial(__pyx_v_self->internal_state, __pyx_v_dn, ((__pyx_v_pix[__pyx_v_j]) / __pyx_v_Sum)); - - /* "mtrand.pyx":4264 - * for j from 0 <= j < d-1: - * mnix[i+j] = rk_binomial(self.internal_state, dn, pix[j]/Sum) - * dn = dn - mnix[i+j] # <<<<<<<<<<<<<< - * if dn <= 0: - * break - */ - __pyx_v_dn = (__pyx_v_dn - (__pyx_v_mnix[(__pyx_v_i + __pyx_v_j)])); - - /* "mtrand.pyx":4265 - * mnix[i+j] = rk_binomial(self.internal_state, dn, pix[j]/Sum) - * dn = dn - mnix[i+j] - * if dn <= 0: # <<<<<<<<<<<<<< - * break - * Sum = Sum - pix[j] - */ - __pyx_t_4 = (__pyx_v_dn <= 0); - if (__pyx_t_4) { - - /* "mtrand.pyx":4266 - * dn = dn - mnix[i+j] - * if dn <= 0: - * break # <<<<<<<<<<<<<< - * Sum = Sum - pix[j] - * if dn > 0: - */ - goto __pyx_L8_break; - goto __pyx_L9; - } - __pyx_L9:; - - /* "mtrand.pyx":4267 - * if dn <= 0: - * break - * Sum = Sum - pix[j] # <<<<<<<<<<<<<< - * if dn > 0: - * mnix[i+d-1] = dn - */ - __pyx_v_Sum = (__pyx_v_Sum - (__pyx_v_pix[__pyx_v_j])); - } - __pyx_L8_break:; - - /* "mtrand.pyx":4268 - * break - * Sum = Sum - pix[j] - * if dn > 0: # <<<<<<<<<<<<<< - * mnix[i+d-1] = dn - * - */ - __pyx_t_4 = (__pyx_v_dn > 0); - if (__pyx_t_4) { - - /* "mtrand.pyx":4269 - * Sum = Sum - pix[j] - * if dn > 0: - * mnix[i+d-1] = dn # <<<<<<<<<<<<<< - * - * i = i + d - */ - (__pyx_v_mnix[((__pyx_v_i + __pyx_v_d) - 1)]) = __pyx_v_dn; - goto __pyx_L10; - } - __pyx_L10:; - - /* "mtrand.pyx":4271 - * mnix[i+d-1] = dn - * - * i = i + d # <<<<<<<<<<<<<< - * - * return multin - */ - __pyx_v_i = (__pyx_v_i + __pyx_v_d); - } - - /* "mtrand.pyx":4273 - * i = i + d - * - * return multin # <<<<<<<<<<<<<< - * - * def dirichlet(self, object alpha, size=None): - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_multin); - __pyx_r = __pyx_v_multin; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.multinomial", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)arrayObject_parr); - __Pyx_XDECREF((PyObject *)arrayObject_mnarr); - __Pyx_XDECREF(__pyx_v_shape); - __Pyx_XDECREF(__pyx_v_multin); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_101dirichlet(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_100dirichlet[] = "\n dirichlet(alpha, size=None)\n\n Draw samples from the Dirichlet distribution.\n\n Draw `size` samples of dimension k from a Dirichlet distribution. A\n Dirichlet-distributed random variable can be seen as a multivariate\n generalization of a Beta distribution. Dirichlet pdf is the conjugate\n prior of a multinomial in Bayesian inference.\n\n Parameters\n ----------\n alpha : array\n Parameter of the distribution (k dimension for sample of\n dimension k).\n size : array\n Number of samples to draw.\n\n Returns\n -------\n samples : ndarray,\n The drawn samples, of shape (alpha.ndim, size).\n\n Notes\n -----\n .. math:: X \\approx \\prod_{i=1}^{k}{x^{\\alpha_i-1}_i}\n\n Uses the following property for computation: for each dimension,\n draw a random sample y_i from a standard gamma generator of shape\n `alpha_i`, then\n :math:`X = \\frac{1}{\\sum_{i=1}^k{y_i}} (y_1, \\ldots, y_n)` is\n Dirichlet distributed.\n\n References\n ----------\n .. [1] David McKay, \"Information Theory, Inference and Learning\n Algorithms,\" chapter 23,\n http://www.inference.phy.cam.ac.uk/mackay/\n .. [2] Wikipedia, \"Dirichlet distribution\",\n http://en.wikipedia.org/wiki/Dirichlet_distribution\n\n Examples\n --------\n Taking an example cited in Wikipedia, this distribution can be used if\n one wanted to cut strings (each of initial length 1.0) into K pieces\n with different lengths, where each piece had, on average, a designated\n average length, but allowing some variation in the relative sizes of the\n pieces.\n\n >>> s = np.random.dirichlet((10, 5, 3), 20).transpose()\n\n >>> plt.barh(range(20), s[0])\n >>> plt.barh(range(20), s[1], left=s[0], color='g')""\n >>> plt.barh(range(20), s[2], left=s[0]+s[1], color='r')\n >>> plt.title(\"Lengths of Strings\")\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_101dirichlet(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_alpha = 0; - PyObject *__pyx_v_size = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("dirichlet (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__alpha,&__pyx_n_s__size,0}; - PyObject* values[2] = {0,0}; - - /* "mtrand.pyx":4275 - * return multin - * - * def dirichlet(self, object alpha, size=None): # <<<<<<<<<<<<<< - * """ - * dirichlet(alpha, size=None) - */ - values[1] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__alpha)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - case 1: - if (kw_args > 0) { - PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s__size); - if (value) { values[1] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "dirichlet") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4275; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_alpha = values[0]; - __pyx_v_size = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("dirichlet", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4275; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_L3_error:; - __Pyx_AddTraceback("mtrand.RandomState.dirichlet", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_6mtrand_11RandomState_100dirichlet(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), __pyx_v_alpha, __pyx_v_size); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_6mtrand_11RandomState_100dirichlet(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_alpha, PyObject *__pyx_v_size) { - npy_intp __pyx_v_k; - npy_intp __pyx_v_totsize; - PyArrayObject *__pyx_v_alpha_arr = 0; - PyArrayObject *__pyx_v_val_arr = 0; - double *__pyx_v_alpha_data; - double *__pyx_v_val_data; - npy_intp __pyx_v_i; - npy_intp __pyx_v_j; - double __pyx_v_acc; - double __pyx_v_invacc; - PyObject *__pyx_v_shape = NULL; - PyObject *__pyx_v_diric = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - npy_intp __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("dirichlet", 0); - - /* "mtrand.pyx":4361 - * cdef double acc, invacc - * - * k = len(alpha) # <<<<<<<<<<<<<< - * alpha_arr = <ndarray>PyArray_ContiguousFromObject(alpha, NPY_DOUBLE, 1, 1) - * alpha_data = <double*>PyArray_DATA(alpha_arr) - */ - __pyx_t_1 = PyObject_Length(__pyx_v_alpha); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4361; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_k = __pyx_t_1; - - /* "mtrand.pyx":4362 - * - * k = len(alpha) - * alpha_arr = <ndarray>PyArray_ContiguousFromObject(alpha, NPY_DOUBLE, 1, 1) # <<<<<<<<<<<<<< - * alpha_data = <double*>PyArray_DATA(alpha_arr) - * - */ - __pyx_t_2 = PyArray_ContiguousFromObject(__pyx_v_alpha, NPY_DOUBLE, 1, 1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4362; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_t_2; - __Pyx_INCREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_alpha_arr = ((PyArrayObject *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "mtrand.pyx":4363 - * k = len(alpha) - * alpha_arr = <ndarray>PyArray_ContiguousFromObject(alpha, NPY_DOUBLE, 1, 1) - * alpha_data = <double*>PyArray_DATA(alpha_arr) # <<<<<<<<<<<<<< - * - * if size is None: - */ - __pyx_v_alpha_data = ((double *)PyArray_DATA(__pyx_v_alpha_arr)); - - /* "mtrand.pyx":4365 - * alpha_data = <double*>PyArray_DATA(alpha_arr) - * - * if size is None: # <<<<<<<<<<<<<< - * shape = (k,) - * elif type(size) is int: - */ - __pyx_t_4 = (__pyx_v_size == Py_None); - if (__pyx_t_4) { - - /* "mtrand.pyx":4366 - * - * if size is None: - * shape = (k,) # <<<<<<<<<<<<<< - * elif type(size) is int: - * shape = (size, k) - */ - __pyx_t_3 = __Pyx_PyInt_to_py_npy_intp(__pyx_v_k); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_v_shape = ((PyObject *)__pyx_t_2); - __pyx_t_2 = 0; - goto __pyx_L3; - } - - /* "mtrand.pyx":4367 - * if size is None: - * shape = (k,) - * elif type(size) is int: # <<<<<<<<<<<<<< - * shape = (size, k) - * else: - */ - __pyx_t_4 = (((PyObject *)Py_TYPE(__pyx_v_size)) == ((PyObject *)((PyObject*)(&PyInt_Type)))); - if (__pyx_t_4) { - - /* "mtrand.pyx":4368 - * shape = (k,) - * elif type(size) is int: - * shape = (size, k) # <<<<<<<<<<<<<< - * else: - * shape = size + (k,) - */ - __pyx_t_2 = __Pyx_PyInt_to_py_npy_intp(__pyx_v_k); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_size); - __Pyx_GIVEREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_v_shape = ((PyObject *)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":4370 - * shape = (size, k) - * else: - * shape = size + (k,) # <<<<<<<<<<<<<< - * - * diric = np.zeros(shape, np.float64) - */ - __pyx_t_3 = __Pyx_PyInt_to_py_npy_intp(__pyx_v_k); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Add(__pyx_v_size, ((PyObject *)__pyx_t_2)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __pyx_v_shape = __pyx_t_3; - __pyx_t_3 = 0; - } - __pyx_L3:; - - /* "mtrand.pyx":4372 - * shape = size + (k,) - * - * diric = np.zeros(shape, np.float64) # <<<<<<<<<<<<<< - * val_arr = <ndarray>diric - * val_data= <double*>PyArray_DATA(val_arr) - */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__zeros); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__float64); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_shape); - __Pyx_GIVEREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_5 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_3), NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; - __pyx_v_diric = __pyx_t_5; - __pyx_t_5 = 0; - - /* "mtrand.pyx":4373 - * - * diric = np.zeros(shape, np.float64) - * val_arr = <ndarray>diric # <<<<<<<<<<<<<< - * val_data= <double*>PyArray_DATA(val_arr) - * - */ - __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_diric))); - __pyx_v_val_arr = ((PyArrayObject *)__pyx_v_diric); - - /* "mtrand.pyx":4374 - * diric = np.zeros(shape, np.float64) - * val_arr = <ndarray>diric - * val_data= <double*>PyArray_DATA(val_arr) # <<<<<<<<<<<<<< - * - * i = 0 - */ - __pyx_v_val_data = ((double *)PyArray_DATA(__pyx_v_val_arr)); - - /* "mtrand.pyx":4376 - * val_data= <double*>PyArray_DATA(val_arr) - * - * i = 0 # <<<<<<<<<<<<<< - * totsize = PyArray_SIZE(val_arr) - * while i < totsize: - */ - __pyx_v_i = 0; - - /* "mtrand.pyx":4377 - * - * i = 0 - * totsize = PyArray_SIZE(val_arr) # <<<<<<<<<<<<<< - * while i < totsize: - * acc = 0.0 - */ - __pyx_v_totsize = PyArray_SIZE(__pyx_v_val_arr); - - /* "mtrand.pyx":4378 - * i = 0 - * totsize = PyArray_SIZE(val_arr) - * while i < totsize: # <<<<<<<<<<<<<< - * acc = 0.0 - * for j from 0 <= j < k: - */ - while (1) { - __pyx_t_4 = (__pyx_v_i < __pyx_v_totsize); - if (!__pyx_t_4) break; - - /* "mtrand.pyx":4379 - * totsize = PyArray_SIZE(val_arr) - * while i < totsize: - * acc = 0.0 # <<<<<<<<<<<<<< - * for j from 0 <= j < k: - * val_data[i+j] = rk_standard_gamma(self.internal_state, alpha_data[j]) - */ - __pyx_v_acc = 0.0; - - /* "mtrand.pyx":4380 - * while i < totsize: - * acc = 0.0 - * for j from 0 <= j < k: # <<<<<<<<<<<<<< - * val_data[i+j] = rk_standard_gamma(self.internal_state, alpha_data[j]) - * acc = acc + val_data[i+j] - */ - __pyx_t_6 = __pyx_v_k; - for (__pyx_v_j = 0; __pyx_v_j < __pyx_t_6; __pyx_v_j++) { - - /* "mtrand.pyx":4381 - * acc = 0.0 - * for j from 0 <= j < k: - * val_data[i+j] = rk_standard_gamma(self.internal_state, alpha_data[j]) # <<<<<<<<<<<<<< - * acc = acc + val_data[i+j] - * invacc = 1/acc - */ - (__pyx_v_val_data[(__pyx_v_i + __pyx_v_j)]) = rk_standard_gamma(__pyx_v_self->internal_state, (__pyx_v_alpha_data[__pyx_v_j])); - - /* "mtrand.pyx":4382 - * for j from 0 <= j < k: - * val_data[i+j] = rk_standard_gamma(self.internal_state, alpha_data[j]) - * acc = acc + val_data[i+j] # <<<<<<<<<<<<<< - * invacc = 1/acc - * for j from 0 <= j < k: - */ - __pyx_v_acc = (__pyx_v_acc + (__pyx_v_val_data[(__pyx_v_i + __pyx_v_j)])); - } - - /* "mtrand.pyx":4383 - * val_data[i+j] = rk_standard_gamma(self.internal_state, alpha_data[j]) - * acc = acc + val_data[i+j] - * invacc = 1/acc # <<<<<<<<<<<<<< - * for j from 0 <= j < k: - * val_data[i+j] = val_data[i+j] * invacc - */ - if (unlikely(__pyx_v_acc == 0)) { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); - #endif - PyErr_Format(PyExc_ZeroDivisionError, "float division"); - #ifdef WITH_THREAD - PyGILState_Release(__pyx_gilstate_save); - #endif - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4383; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_v_invacc = (1.0 / __pyx_v_acc); - - /* "mtrand.pyx":4384 - * acc = acc + val_data[i+j] - * invacc = 1/acc - * for j from 0 <= j < k: # <<<<<<<<<<<<<< - * val_data[i+j] = val_data[i+j] * invacc - * i = i + k - */ - __pyx_t_6 = __pyx_v_k; - for (__pyx_v_j = 0; __pyx_v_j < __pyx_t_6; __pyx_v_j++) { - - /* "mtrand.pyx":4385 - * invacc = 1/acc - * for j from 0 <= j < k: - * val_data[i+j] = val_data[i+j] * invacc # <<<<<<<<<<<<<< - * i = i + k - * - */ - (__pyx_v_val_data[(__pyx_v_i + __pyx_v_j)]) = ((__pyx_v_val_data[(__pyx_v_i + __pyx_v_j)]) * __pyx_v_invacc); - } - - /* "mtrand.pyx":4386 - * for j from 0 <= j < k: - * val_data[i+j] = val_data[i+j] * invacc - * i = i + k # <<<<<<<<<<<<<< - * - * return diric - */ - __pyx_v_i = (__pyx_v_i + __pyx_v_k); - } - - /* "mtrand.pyx":4388 - * i = i + k - * - * return diric # <<<<<<<<<<<<<< - * - * # Shuffling and permutations: - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_diric); - __pyx_r = __pyx_v_diric; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("mtrand.RandomState.dirichlet", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_alpha_arr); - __Pyx_XDECREF((PyObject *)__pyx_v_val_arr); - __Pyx_XDECREF(__pyx_v_shape); - __Pyx_XDECREF(__pyx_v_diric); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_103shuffle(PyObject *__pyx_v_self, PyObject *__pyx_v_x); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_102shuffle[] = "\n shuffle(x)\n\n Modify a sequence in-place by shuffling its contents.\n\n Parameters\n ----------\n x : array_like\n The array or list to be shuffled.\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> arr = np.arange(10)\n >>> np.random.shuffle(arr)\n >>> arr\n [1 7 5 2 9 4 3 6 0 8]\n\n This function only shuffles the array along the first index of a\n multi-dimensional array:\n\n >>> arr = np.arange(9).reshape((3, 3))\n >>> np.random.shuffle(arr)\n >>> arr\n array([[3, 4, 5],\n [6, 7, 8],\n [0, 1, 2]])\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_103shuffle(PyObject *__pyx_v_self, PyObject *__pyx_v_x) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("shuffle (wrapper)", 0); - __pyx_r = __pyx_pf_6mtrand_11RandomState_102shuffle(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), ((PyObject *)__pyx_v_x)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":4391 - * - * # Shuffling and permutations: - * def shuffle(self, object x): # <<<<<<<<<<<<<< - * """ - * shuffle(x) - */ - -static PyObject *__pyx_pf_6mtrand_11RandomState_102shuffle(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_x) { - npy_intp __pyx_v_i; - npy_intp __pyx_v_j; - PyObject *__pyx_v_buf = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("shuffle", 0); - - /* "mtrand.pyx":4426 - * cdef npy_intp i, j - * - * i = len(x) - 1 # <<<<<<<<<<<<<< - * - * # Logic adapted from random.shuffle() - */ - __pyx_t_1 = PyObject_Length(__pyx_v_x); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4426; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_i = (__pyx_t_1 - 1); - - /* "mtrand.pyx":4429 - * - * # Logic adapted from random.shuffle() - * if isinstance(x, np.ndarray) and x.ndim > 1: # <<<<<<<<<<<<<< - * # For a multi-dimensional ndarray, indexing returns a view onto - * # each row. So we can't just use ordinary assignment to swap the - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__ndarray); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_4 = PyObject_IsInstance(__pyx_v_x, __pyx_t_3); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_4) { - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_x, __pyx_n_s__ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyObject_RichCompare(__pyx_t_3, __pyx_int_1, Py_GT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_5 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_5 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_6 = __pyx_t_5; - } else { - __pyx_t_6 = __pyx_t_4; - } - if (__pyx_t_6) { - - /* "mtrand.pyx":4433 - * # each row. So we can't just use ordinary assignment to swap the - * # rows; we need a bounce buffer. - * buf = np.empty(x.shape[1:], dtype=x.dtype) # <<<<<<<<<<<<<< - * while i > 0: - * j = rk_interval(i, self.internal_state) - */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__empty); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_x, __pyx_n_s__shape); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_7 = __Pyx_PyObject_GetSlice(__pyx_t_2, 1, 0, NULL, NULL, &__pyx_k_slice_196, 1, 0, 1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - __pyx_t_7 = 0; - __pyx_t_7 = PyDict_New(); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_7)); - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_x, __pyx_n_s__dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - if (PyDict_SetItem(__pyx_t_7, ((PyObject *)__pyx_n_s__dtype), __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_8 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_2), ((PyObject *)__pyx_t_7)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0; - __pyx_v_buf = __pyx_t_8; - __pyx_t_8 = 0; - - /* "mtrand.pyx":4434 - * # rows; we need a bounce buffer. - * buf = np.empty(x.shape[1:], dtype=x.dtype) - * while i > 0: # <<<<<<<<<<<<<< - * j = rk_interval(i, self.internal_state) - * buf[...] = x[j] - */ - while (1) { - __pyx_t_6 = (__pyx_v_i > 0); - if (!__pyx_t_6) break; - - /* "mtrand.pyx":4435 - * buf = np.empty(x.shape[1:], dtype=x.dtype) - * while i > 0: - * j = rk_interval(i, self.internal_state) # <<<<<<<<<<<<<< - * buf[...] = x[j] - * x[j] = x[i] - */ - __pyx_v_j = rk_interval(__pyx_v_i, __pyx_v_self->internal_state); - - /* "mtrand.pyx":4436 - * while i > 0: - * j = rk_interval(i, self.internal_state) - * buf[...] = x[j] # <<<<<<<<<<<<<< - * x[j] = x[i] - * x[i] = buf - */ - __pyx_t_8 = __Pyx_GetItemInt(__pyx_v_x, __pyx_v_j, sizeof(npy_intp), __Pyx_PyInt_to_py_npy_intp, 0, 1, 1); if (!__pyx_t_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - if (PyObject_SetItem(__pyx_v_buf, Py_Ellipsis, __pyx_t_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "mtrand.pyx":4437 - * j = rk_interval(i, self.internal_state) - * buf[...] = x[j] - * x[j] = x[i] # <<<<<<<<<<<<<< - * x[i] = buf - * i = i - 1 - */ - __pyx_t_8 = __Pyx_GetItemInt(__pyx_v_x, __pyx_v_i, sizeof(npy_intp), __Pyx_PyInt_to_py_npy_intp, 0, 1, 1); if (!__pyx_t_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - if (__Pyx_SetItemInt(__pyx_v_x, __pyx_v_j, __pyx_t_8, sizeof(npy_intp), __Pyx_PyInt_to_py_npy_intp, 0, 1, 1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "mtrand.pyx":4438 - * buf[...] = x[j] - * x[j] = x[i] - * x[i] = buf # <<<<<<<<<<<<<< - * i = i - 1 - * else: - */ - if (__Pyx_SetItemInt(__pyx_v_x, __pyx_v_i, __pyx_v_buf, sizeof(npy_intp), __Pyx_PyInt_to_py_npy_intp, 0, 1, 1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - - /* "mtrand.pyx":4439 - * x[j] = x[i] - * x[i] = buf - * i = i - 1 # <<<<<<<<<<<<<< - * else: - * # For single-dimensional arrays, lists, and any other Python - */ - __pyx_v_i = (__pyx_v_i - 1); - } - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":4444 - * # sequence types, indexing returns a real object that's - * # independent of the array contents, so we can just swap directly. - * while i > 0: # <<<<<<<<<<<<<< - * j = rk_interval(i, self.internal_state) - * x[i], x[j] = x[j], x[i] - */ - while (1) { - __pyx_t_6 = (__pyx_v_i > 0); - if (!__pyx_t_6) break; - - /* "mtrand.pyx":4445 - * # independent of the array contents, so we can just swap directly. - * while i > 0: - * j = rk_interval(i, self.internal_state) # <<<<<<<<<<<<<< - * x[i], x[j] = x[j], x[i] - * i = i - 1 - */ - __pyx_v_j = rk_interval(__pyx_v_i, __pyx_v_self->internal_state); - - /* "mtrand.pyx":4446 - * while i > 0: - * j = rk_interval(i, self.internal_state) - * x[i], x[j] = x[j], x[i] # <<<<<<<<<<<<<< - * i = i - 1 - * - */ - __pyx_t_8 = __Pyx_GetItemInt(__pyx_v_x, __pyx_v_j, sizeof(npy_intp), __Pyx_PyInt_to_py_npy_intp, 0, 1, 1); if (!__pyx_t_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_7 = __Pyx_GetItemInt(__pyx_v_x, __pyx_v_i, sizeof(npy_intp), __Pyx_PyInt_to_py_npy_intp, 0, 1, 1); if (!__pyx_t_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - if (__Pyx_SetItemInt(__pyx_v_x, __pyx_v_i, __pyx_t_8, sizeof(npy_intp), __Pyx_PyInt_to_py_npy_intp, 0, 1, 1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - if (__Pyx_SetItemInt(__pyx_v_x, __pyx_v_j, __pyx_t_7, sizeof(npy_intp), __Pyx_PyInt_to_py_npy_intp, 0, 1, 1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4446; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "mtrand.pyx":4447 - * j = rk_interval(i, self.internal_state) - * x[i], x[j] = x[j], x[i] - * i = i - 1 # <<<<<<<<<<<<<< - * - * def permutation(self, object x): - */ - __pyx_v_i = (__pyx_v_i - 1); - } - } - __pyx_L3:; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("mtrand.RandomState.shuffle", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_buf); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* Python wrapper */ -static PyObject *__pyx_pw_6mtrand_11RandomState_105permutation(PyObject *__pyx_v_self, PyObject *__pyx_v_x); /*proto*/ -static char __pyx_doc_6mtrand_11RandomState_104permutation[] = "\n permutation(x)\n\n Randomly permute a sequence, or return a permuted range.\n\n If `x` is a multi-dimensional array, it is only shuffled along its\n first index.\n\n Parameters\n ----------\n x : int or array_like\n If `x` is an integer, randomly permute ``np.arange(x)``.\n If `x` is an array, make a copy and shuffle the elements\n randomly.\n\n Returns\n -------\n out : ndarray\n Permuted sequence or array range.\n\n Examples\n --------\n >>> np.random.permutation(10)\n array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6])\n\n >>> np.random.permutation([1, 4, 9, 12, 15])\n array([15, 1, 9, 4, 12])\n\n >>> arr = np.arange(9).reshape((3, 3))\n >>> np.random.permutation(arr)\n array([[6, 7, 8],\n [0, 1, 2],\n [3, 4, 5]])\n\n "; -static PyObject *__pyx_pw_6mtrand_11RandomState_105permutation(PyObject *__pyx_v_self, PyObject *__pyx_v_x) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("permutation (wrapper)", 0); - __pyx_r = __pyx_pf_6mtrand_11RandomState_104permutation(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self), ((PyObject *)__pyx_v_x)); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "mtrand.pyx":4449 - * i = i - 1 - * - * def permutation(self, object x): # <<<<<<<<<<<<<< - * """ - * permutation(x) - */ - -static PyObject *__pyx_pf_6mtrand_11RandomState_104permutation(struct __pyx_obj_6mtrand_RandomState *__pyx_v_self, PyObject *__pyx_v_x) { - PyObject *__pyx_v_arr = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("permutation", 0); - - /* "mtrand.pyx":4485 - * - * """ - * if isinstance(x, (int, long, np.integer)): # <<<<<<<<<<<<<< - * arr = np.arange(x) - * else: - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__integer); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyInt_Type)))); - __Pyx_INCREF(((PyObject *)((PyObject*)(&PyLong_Type)))); - PyTuple_SET_ITEM(__pyx_t_1, 1, ((PyObject *)((PyObject*)(&PyLong_Type)))); - __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyLong_Type)))); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_3 = PyObject_IsInstance(__pyx_v_x, ((PyObject *)__pyx_t_1)); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4485; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - if (__pyx_t_3) { - - /* "mtrand.pyx":4486 - * """ - * if isinstance(x, (int, long, np.integer)): - * arr = np.arange(x) # <<<<<<<<<<<<<< - * else: - * arr = np.array(x) - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__arange); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_x); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_x); - __Pyx_GIVEREF(__pyx_v_x); - __pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4486; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_v_arr = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L3; - } - /*else*/ { - - /* "mtrand.pyx":4488 - * arr = np.arange(x) - * else: - * arr = np.array(x) # <<<<<<<<<<<<<< - * self.shuffle(arr) - * return arr - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__array); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_x); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_x); - __Pyx_GIVEREF(__pyx_v_x); - __pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4488; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __pyx_v_arr = __pyx_t_2; - __pyx_t_2 = 0; - } - __pyx_L3:; - - /* "mtrand.pyx":4489 - * else: - * arr = np.array(x) - * self.shuffle(arr) # <<<<<<<<<<<<<< - * return arr - * - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s__shuffle); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4489; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4489; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_arr); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_arr); - __Pyx_GIVEREF(__pyx_v_arr); - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_4), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4489; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_4)); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4490 - * arr = np.array(x) - * self.shuffle(arr) - * return arr # <<<<<<<<<<<<<< - * - * _rand = RandomState() - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_arr); - __pyx_r = __pyx_v_arr; - goto __pyx_L0; - - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("mtrand.RandomState.permutation", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_arr); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_tp_new_6mtrand_RandomState(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - return o; -} - -static void __pyx_tp_dealloc_6mtrand_RandomState(PyObject *o) { - { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - ++Py_REFCNT(o); - __pyx_pw_6mtrand_11RandomState_3__dealloc__(o); - if (PyErr_Occurred()) PyErr_WriteUnraisable(o); - --Py_REFCNT(o); - PyErr_Restore(etype, eval, etb); - } - (*Py_TYPE(o)->tp_free)(o); -} - -static PyMethodDef __pyx_methods_6mtrand_RandomState[] = { - {__Pyx_NAMESTR("seed"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_5seed, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_4seed)}, - {__Pyx_NAMESTR("get_state"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_7get_state, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_6get_state)}, - {__Pyx_NAMESTR("set_state"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_9set_state, METH_O, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_8set_state)}, - {__Pyx_NAMESTR("__getstate__"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_11__getstate__, METH_NOARGS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("__setstate__"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_13__setstate__, METH_O, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("__reduce__"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_15__reduce__, METH_NOARGS, __Pyx_DOCSTR(0)}, - {__Pyx_NAMESTR("random_sample"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_17random_sample, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_16random_sample)}, - {__Pyx_NAMESTR("tomaxint"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_19tomaxint, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_18tomaxint)}, - {__Pyx_NAMESTR("randint"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_21randint, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_20randint)}, - {__Pyx_NAMESTR("bytes"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_23bytes, METH_O, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_22bytes)}, - {__Pyx_NAMESTR("choice"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_25choice, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_24choice)}, - {__Pyx_NAMESTR("uniform"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_27uniform, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_26uniform)}, - {__Pyx_NAMESTR("rand"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_29rand, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_28rand)}, - {__Pyx_NAMESTR("randn"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_31randn, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_30randn)}, - {__Pyx_NAMESTR("random_integers"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_33random_integers, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_32random_integers)}, - {__Pyx_NAMESTR("standard_normal"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_35standard_normal, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_34standard_normal)}, - {__Pyx_NAMESTR("normal"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_37normal, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_36normal)}, - {__Pyx_NAMESTR("beta"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_39beta, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_38beta)}, - {__Pyx_NAMESTR("exponential"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_41exponential, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_40exponential)}, - {__Pyx_NAMESTR("standard_exponential"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_43standard_exponential, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_42standard_exponential)}, - {__Pyx_NAMESTR("standard_gamma"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_45standard_gamma, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_44standard_gamma)}, - {__Pyx_NAMESTR("gamma"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_47gamma, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_46gamma)}, - {__Pyx_NAMESTR("f"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_49f, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_48f)}, - {__Pyx_NAMESTR("noncentral_f"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_51noncentral_f, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_50noncentral_f)}, - {__Pyx_NAMESTR("chisquare"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_53chisquare, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_52chisquare)}, - {__Pyx_NAMESTR("noncentral_chisquare"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_55noncentral_chisquare, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_54noncentral_chisquare)}, - {__Pyx_NAMESTR("standard_cauchy"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_57standard_cauchy, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_56standard_cauchy)}, - {__Pyx_NAMESTR("standard_t"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_59standard_t, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_58standard_t)}, - {__Pyx_NAMESTR("vonmises"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_61vonmises, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_60vonmises)}, - {__Pyx_NAMESTR("pareto"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_63pareto, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_62pareto)}, - {__Pyx_NAMESTR("weibull"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_65weibull, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_64weibull)}, - {__Pyx_NAMESTR("power"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_67power, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_66power)}, - {__Pyx_NAMESTR("laplace"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_69laplace, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_68laplace)}, - {__Pyx_NAMESTR("gumbel"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_71gumbel, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_70gumbel)}, - {__Pyx_NAMESTR("logistic"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_73logistic, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_72logistic)}, - {__Pyx_NAMESTR("lognormal"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_75lognormal, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_74lognormal)}, - {__Pyx_NAMESTR("rayleigh"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_77rayleigh, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_76rayleigh)}, - {__Pyx_NAMESTR("wald"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_79wald, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_78wald)}, - {__Pyx_NAMESTR("triangular"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_81triangular, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_80triangular)}, - {__Pyx_NAMESTR("binomial"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_83binomial, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_82binomial)}, - {__Pyx_NAMESTR("negative_binomial"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_85negative_binomial, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_84negative_binomial)}, - {__Pyx_NAMESTR("poisson"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_87poisson, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_86poisson)}, - {__Pyx_NAMESTR("zipf"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_89zipf, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_88zipf)}, - {__Pyx_NAMESTR("geometric"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_91geometric, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_90geometric)}, - {__Pyx_NAMESTR("hypergeometric"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_93hypergeometric, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_92hypergeometric)}, - {__Pyx_NAMESTR("logseries"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_95logseries, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_94logseries)}, - {__Pyx_NAMESTR("multivariate_normal"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_97multivariate_normal, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_96multivariate_normal)}, - {__Pyx_NAMESTR("multinomial"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_99multinomial, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_98multinomial)}, - {__Pyx_NAMESTR("dirichlet"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_101dirichlet, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_100dirichlet)}, - {__Pyx_NAMESTR("shuffle"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_103shuffle, METH_O, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_102shuffle)}, - {__Pyx_NAMESTR("permutation"), (PyCFunction)__pyx_pw_6mtrand_11RandomState_105permutation, METH_O, __Pyx_DOCSTR(__pyx_doc_6mtrand_11RandomState_104permutation)}, - {0, 0, 0, 0} -}; - -static PyNumberMethods __pyx_tp_as_number_RandomState = { - 0, /*nb_add*/ - 0, /*nb_subtract*/ - 0, /*nb_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_divide*/ - #endif - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_coerce*/ - #endif - 0, /*nb_int*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_long*/ - #else - 0, /*reserved*/ - #endif - 0, /*nb_float*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_oct*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*nb_hex*/ - #endif - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - #if PY_MAJOR_VERSION < 3 - 0, /*nb_inplace_divide*/ - #endif - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - 0, /*nb_floor_divide*/ - 0, /*nb_true_divide*/ - 0, /*nb_inplace_floor_divide*/ - 0, /*nb_inplace_true_divide*/ - #if PY_VERSION_HEX >= 0x02050000 - 0, /*nb_index*/ - #endif -}; - -static PySequenceMethods __pyx_tp_as_sequence_RandomState = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - 0, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; - -static PyMappingMethods __pyx_tp_as_mapping_RandomState = { - 0, /*mp_length*/ - 0, /*mp_subscript*/ - 0, /*mp_ass_subscript*/ -}; - -static PyBufferProcs __pyx_tp_as_buffer_RandomState = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_getbuffer*/ - #endif - #if PY_VERSION_HEX >= 0x02060000 - 0, /*bf_releasebuffer*/ - #endif -}; - -static PyTypeObject __pyx_type_6mtrand_RandomState = { - PyVarObject_HEAD_INIT(0, 0) - __Pyx_NAMESTR("mtrand.RandomState"), /*tp_name*/ - sizeof(struct __pyx_obj_6mtrand_RandomState), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_6mtrand_RandomState, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #else - 0, /*reserved*/ - #endif - 0, /*tp_repr*/ - &__pyx_tp_as_number_RandomState, /*tp_as_number*/ - &__pyx_tp_as_sequence_RandomState, /*tp_as_sequence*/ - &__pyx_tp_as_mapping_RandomState, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - &__pyx_tp_as_buffer_RandomState, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - __Pyx_DOCSTR("\n RandomState(seed=None)\n\n Container for the Mersenne Twister pseudo-random number generator.\n\n `RandomState` exposes a number of methods for generating random numbers\n drawn from a variety of probability distributions. In addition to the\n distribution-specific arguments, each method takes a keyword argument\n `size` that defaults to ``None``. If `size` is ``None``, then a single\n value is generated and returned. If `size` is an integer, then a 1-D\n array filled with generated values is returned. If `size` is a tuple,\n then an array with that shape is filled and returned.\n\n Parameters\n ----------\n seed : int or array_like, optional\n Random seed initializing the pseudo-random number generator.\n Can be an integer, an array (or other sequence) of integers of\n any length, or ``None`` (the default).\n If `seed` is ``None``, then `RandomState` will try to read data from\n ``/dev/urandom`` (or the Windows analogue) if available or seed from\n the clock otherwise.\n\n Notes\n -----\n The Python stdlib module \"random\" also contains a Mersenne Twister\n pseudo-random number generator with a number of methods that are similar\n to the ones available in `RandomState`. `RandomState`, besides being\n NumPy-aware, has the advantage that it provides a much larger number\n of probability distributions to choose from.\n\n "), /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_6mtrand_RandomState, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_pw_6mtrand_11RandomState_1__init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_6mtrand_RandomState, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - #if PY_VERSION_HEX >= 0x02060000 - 0, /*tp_version_tag*/ - #endif -}; - -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 0} -}; - -#if PY_MAJOR_VERSION >= 3 -static struct PyModuleDef __pyx_moduledef = { - #if PY_VERSION_HEX < 0x03020000 - { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, - #else - PyModuleDef_HEAD_INIT, - #endif - __Pyx_NAMESTR("mtrand"), - 0, /* m_doc */ - -1, /* m_size */ - __pyx_methods /* m_methods */, - NULL, /* m_reload */ - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif - -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_s_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 1, 0}, - {&__pyx_kp_s_112, __pyx_k_112, sizeof(__pyx_k_112), 0, 0, 1, 0}, - {&__pyx_kp_s_114, __pyx_k_114, sizeof(__pyx_k_114), 0, 0, 1, 0}, - {&__pyx_kp_s_118, __pyx_k_118, sizeof(__pyx_k_118), 0, 0, 1, 0}, - {&__pyx_kp_s_120, __pyx_k_120, sizeof(__pyx_k_120), 0, 0, 1, 0}, - {&__pyx_kp_s_123, __pyx_k_123, sizeof(__pyx_k_123), 0, 0, 1, 0}, - {&__pyx_kp_s_126, __pyx_k_126, sizeof(__pyx_k_126), 0, 0, 1, 0}, - {&__pyx_kp_s_128, __pyx_k_128, sizeof(__pyx_k_128), 0, 0, 1, 0}, - {&__pyx_kp_s_13, __pyx_k_13, sizeof(__pyx_k_13), 0, 0, 1, 0}, - {&__pyx_kp_s_130, __pyx_k_130, sizeof(__pyx_k_130), 0, 0, 1, 0}, - {&__pyx_kp_s_135, __pyx_k_135, sizeof(__pyx_k_135), 0, 0, 1, 0}, - {&__pyx_kp_s_137, __pyx_k_137, sizeof(__pyx_k_137), 0, 0, 1, 0}, - {&__pyx_kp_s_139, __pyx_k_139, sizeof(__pyx_k_139), 0, 0, 1, 0}, - {&__pyx_kp_s_144, __pyx_k_144, sizeof(__pyx_k_144), 0, 0, 1, 0}, - {&__pyx_kp_s_15, __pyx_k_15, sizeof(__pyx_k_15), 0, 0, 1, 0}, - {&__pyx_kp_s_152, __pyx_k_152, sizeof(__pyx_k_152), 0, 0, 1, 0}, - {&__pyx_kp_s_154, __pyx_k_154, sizeof(__pyx_k_154), 0, 0, 1, 0}, - {&__pyx_kp_s_157, __pyx_k_157, sizeof(__pyx_k_157), 0, 0, 1, 0}, - {&__pyx_kp_s_159, __pyx_k_159, sizeof(__pyx_k_159), 0, 0, 1, 0}, - {&__pyx_kp_s_162, __pyx_k_162, sizeof(__pyx_k_162), 0, 0, 1, 0}, - {&__pyx_kp_s_164, __pyx_k_164, sizeof(__pyx_k_164), 0, 0, 1, 0}, - {&__pyx_kp_s_168, __pyx_k_168, sizeof(__pyx_k_168), 0, 0, 1, 0}, - {&__pyx_kp_s_170, __pyx_k_170, sizeof(__pyx_k_170), 0, 0, 1, 0}, - {&__pyx_kp_s_172, __pyx_k_172, sizeof(__pyx_k_172), 0, 0, 1, 0}, - {&__pyx_kp_s_174, __pyx_k_174, sizeof(__pyx_k_174), 0, 0, 1, 0}, - {&__pyx_kp_s_18, __pyx_k_18, sizeof(__pyx_k_18), 0, 0, 1, 0}, - {&__pyx_kp_s_180, __pyx_k_180, sizeof(__pyx_k_180), 0, 0, 1, 0}, - {&__pyx_kp_s_182, __pyx_k_182, sizeof(__pyx_k_182), 0, 0, 1, 0}, - {&__pyx_kp_s_186, __pyx_k_186, sizeof(__pyx_k_186), 0, 0, 1, 0}, - {&__pyx_kp_s_188, __pyx_k_188, sizeof(__pyx_k_188), 0, 0, 1, 0}, - {&__pyx_kp_s_190, __pyx_k_190, sizeof(__pyx_k_190), 0, 0, 1, 0}, - {&__pyx_n_s_193, __pyx_k_193, sizeof(__pyx_k_193), 0, 0, 1, 1}, - {&__pyx_kp_s_194, __pyx_k_194, sizeof(__pyx_k_194), 0, 0, 1, 0}, - {&__pyx_n_s_199, __pyx_k_199, sizeof(__pyx_k_199), 0, 0, 1, 1}, - {&__pyx_kp_s_20, __pyx_k_20, sizeof(__pyx_k_20), 0, 0, 1, 0}, - {&__pyx_n_s_200, __pyx_k_200, sizeof(__pyx_k_200), 0, 0, 1, 1}, - {&__pyx_kp_u_201, __pyx_k_201, sizeof(__pyx_k_201), 0, 1, 0, 0}, - {&__pyx_kp_u_202, __pyx_k_202, sizeof(__pyx_k_202), 0, 1, 0, 0}, - {&__pyx_kp_u_203, __pyx_k_203, sizeof(__pyx_k_203), 0, 1, 0, 0}, - {&__pyx_kp_u_204, __pyx_k_204, sizeof(__pyx_k_204), 0, 1, 0, 0}, - {&__pyx_kp_u_205, __pyx_k_205, sizeof(__pyx_k_205), 0, 1, 0, 0}, - {&__pyx_kp_u_206, __pyx_k_206, sizeof(__pyx_k_206), 0, 1, 0, 0}, - {&__pyx_kp_u_207, __pyx_k_207, sizeof(__pyx_k_207), 0, 1, 0, 0}, - {&__pyx_kp_u_208, __pyx_k_208, sizeof(__pyx_k_208), 0, 1, 0, 0}, - {&__pyx_kp_u_209, __pyx_k_209, sizeof(__pyx_k_209), 0, 1, 0, 0}, - {&__pyx_kp_u_210, __pyx_k_210, sizeof(__pyx_k_210), 0, 1, 0, 0}, - {&__pyx_kp_u_211, __pyx_k_211, sizeof(__pyx_k_211), 0, 1, 0, 0}, - {&__pyx_kp_u_212, __pyx_k_212, sizeof(__pyx_k_212), 0, 1, 0, 0}, - {&__pyx_kp_u_213, __pyx_k_213, sizeof(__pyx_k_213), 0, 1, 0, 0}, - {&__pyx_kp_u_214, __pyx_k_214, sizeof(__pyx_k_214), 0, 1, 0, 0}, - {&__pyx_kp_u_215, __pyx_k_215, sizeof(__pyx_k_215), 0, 1, 0, 0}, - {&__pyx_kp_u_216, __pyx_k_216, sizeof(__pyx_k_216), 0, 1, 0, 0}, - {&__pyx_kp_u_217, __pyx_k_217, sizeof(__pyx_k_217), 0, 1, 0, 0}, - {&__pyx_kp_u_218, __pyx_k_218, sizeof(__pyx_k_218), 0, 1, 0, 0}, - {&__pyx_kp_u_219, __pyx_k_219, sizeof(__pyx_k_219), 0, 1, 0, 0}, - {&__pyx_kp_s_22, __pyx_k_22, sizeof(__pyx_k_22), 0, 0, 1, 0}, - {&__pyx_kp_u_220, __pyx_k_220, sizeof(__pyx_k_220), 0, 1, 0, 0}, - {&__pyx_kp_u_221, __pyx_k_221, sizeof(__pyx_k_221), 0, 1, 0, 0}, - {&__pyx_kp_u_222, __pyx_k_222, sizeof(__pyx_k_222), 0, 1, 0, 0}, - {&__pyx_kp_u_223, __pyx_k_223, sizeof(__pyx_k_223), 0, 1, 0, 0}, - {&__pyx_kp_u_224, __pyx_k_224, sizeof(__pyx_k_224), 0, 1, 0, 0}, - {&__pyx_kp_u_225, __pyx_k_225, sizeof(__pyx_k_225), 0, 1, 0, 0}, - {&__pyx_kp_u_226, __pyx_k_226, sizeof(__pyx_k_226), 0, 1, 0, 0}, - {&__pyx_kp_u_227, __pyx_k_227, sizeof(__pyx_k_227), 0, 1, 0, 0}, - {&__pyx_kp_u_228, __pyx_k_228, sizeof(__pyx_k_228), 0, 1, 0, 0}, - {&__pyx_kp_u_229, __pyx_k_229, sizeof(__pyx_k_229), 0, 1, 0, 0}, - {&__pyx_kp_u_230, __pyx_k_230, sizeof(__pyx_k_230), 0, 1, 0, 0}, - {&__pyx_kp_u_231, __pyx_k_231, sizeof(__pyx_k_231), 0, 1, 0, 0}, - {&__pyx_kp_u_232, __pyx_k_232, sizeof(__pyx_k_232), 0, 1, 0, 0}, - {&__pyx_kp_u_233, __pyx_k_233, sizeof(__pyx_k_233), 0, 1, 0, 0}, - {&__pyx_kp_u_234, __pyx_k_234, sizeof(__pyx_k_234), 0, 1, 0, 0}, - {&__pyx_kp_u_235, __pyx_k_235, sizeof(__pyx_k_235), 0, 1, 0, 0}, - {&__pyx_kp_u_236, __pyx_k_236, sizeof(__pyx_k_236), 0, 1, 0, 0}, - {&__pyx_kp_u_237, __pyx_k_237, sizeof(__pyx_k_237), 0, 1, 0, 0}, - {&__pyx_kp_u_238, __pyx_k_238, sizeof(__pyx_k_238), 0, 1, 0, 0}, - {&__pyx_kp_u_239, __pyx_k_239, sizeof(__pyx_k_239), 0, 1, 0, 0}, - {&__pyx_kp_s_24, __pyx_k_24, sizeof(__pyx_k_24), 0, 0, 1, 0}, - {&__pyx_kp_u_240, __pyx_k_240, sizeof(__pyx_k_240), 0, 1, 0, 0}, - {&__pyx_kp_u_241, __pyx_k_241, sizeof(__pyx_k_241), 0, 1, 0, 0}, - {&__pyx_kp_u_242, __pyx_k_242, sizeof(__pyx_k_242), 0, 1, 0, 0}, - {&__pyx_kp_u_243, __pyx_k_243, sizeof(__pyx_k_243), 0, 1, 0, 0}, - {&__pyx_kp_u_244, __pyx_k_244, sizeof(__pyx_k_244), 0, 1, 0, 0}, - {&__pyx_kp_u_245, __pyx_k_245, sizeof(__pyx_k_245), 0, 1, 0, 0}, - {&__pyx_kp_u_246, __pyx_k_246, sizeof(__pyx_k_246), 0, 1, 0, 0}, - {&__pyx_kp_u_247, __pyx_k_247, sizeof(__pyx_k_247), 0, 1, 0, 0}, - {&__pyx_kp_u_248, __pyx_k_248, sizeof(__pyx_k_248), 0, 1, 0, 0}, - {&__pyx_kp_u_249, __pyx_k_249, sizeof(__pyx_k_249), 0, 1, 0, 0}, - {&__pyx_kp_u_250, __pyx_k_250, sizeof(__pyx_k_250), 0, 1, 0, 0}, - {&__pyx_kp_u_251, __pyx_k_251, sizeof(__pyx_k_251), 0, 1, 0, 0}, - {&__pyx_kp_u_252, __pyx_k_252, sizeof(__pyx_k_252), 0, 1, 0, 0}, - {&__pyx_kp_u_253, __pyx_k_253, sizeof(__pyx_k_253), 0, 1, 0, 0}, - {&__pyx_kp_u_254, __pyx_k_254, sizeof(__pyx_k_254), 0, 1, 0, 0}, - {&__pyx_kp_u_255, __pyx_k_255, sizeof(__pyx_k_255), 0, 1, 0, 0}, - {&__pyx_kp_u_256, __pyx_k_256, sizeof(__pyx_k_256), 0, 1, 0, 0}, - {&__pyx_kp_u_257, __pyx_k_257, sizeof(__pyx_k_257), 0, 1, 0, 0}, - {&__pyx_kp_u_258, __pyx_k_258, sizeof(__pyx_k_258), 0, 1, 0, 0}, - {&__pyx_kp_u_259, __pyx_k_259, sizeof(__pyx_k_259), 0, 1, 0, 0}, - {&__pyx_kp_s_26, __pyx_k_26, sizeof(__pyx_k_26), 0, 0, 1, 0}, - {&__pyx_kp_u_260, __pyx_k_260, sizeof(__pyx_k_260), 0, 1, 0, 0}, - {&__pyx_kp_u_261, __pyx_k_261, sizeof(__pyx_k_261), 0, 1, 0, 0}, - {&__pyx_kp_u_262, __pyx_k_262, sizeof(__pyx_k_262), 0, 1, 0, 0}, - {&__pyx_kp_u_263, __pyx_k_263, sizeof(__pyx_k_263), 0, 1, 0, 0}, - {&__pyx_kp_u_264, __pyx_k_264, sizeof(__pyx_k_264), 0, 1, 0, 0}, - {&__pyx_kp_u_265, __pyx_k_265, sizeof(__pyx_k_265), 0, 1, 0, 0}, - {&__pyx_kp_u_266, __pyx_k_266, sizeof(__pyx_k_266), 0, 1, 0, 0}, - {&__pyx_kp_u_267, __pyx_k_267, sizeof(__pyx_k_267), 0, 1, 0, 0}, - {&__pyx_kp_u_268, __pyx_k_268, sizeof(__pyx_k_268), 0, 1, 0, 0}, - {&__pyx_kp_u_269, __pyx_k_269, sizeof(__pyx_k_269), 0, 1, 0, 0}, - {&__pyx_kp_u_270, __pyx_k_270, sizeof(__pyx_k_270), 0, 1, 0, 0}, - {&__pyx_kp_u_271, __pyx_k_271, sizeof(__pyx_k_271), 0, 1, 0, 0}, - {&__pyx_kp_u_272, __pyx_k_272, sizeof(__pyx_k_272), 0, 1, 0, 0}, - {&__pyx_kp_u_273, __pyx_k_273, sizeof(__pyx_k_273), 0, 1, 0, 0}, - {&__pyx_kp_u_274, __pyx_k_274, sizeof(__pyx_k_274), 0, 1, 0, 0}, - {&__pyx_kp_u_275, __pyx_k_275, sizeof(__pyx_k_275), 0, 1, 0, 0}, - {&__pyx_kp_u_276, __pyx_k_276, sizeof(__pyx_k_276), 0, 1, 0, 0}, - {&__pyx_kp_u_277, __pyx_k_277, sizeof(__pyx_k_277), 0, 1, 0, 0}, - {&__pyx_kp_u_278, __pyx_k_278, sizeof(__pyx_k_278), 0, 1, 0, 0}, - {&__pyx_kp_u_279, __pyx_k_279, sizeof(__pyx_k_279), 0, 1, 0, 0}, - {&__pyx_kp_s_28, __pyx_k_28, sizeof(__pyx_k_28), 0, 0, 1, 0}, - {&__pyx_kp_u_280, __pyx_k_280, sizeof(__pyx_k_280), 0, 1, 0, 0}, - {&__pyx_kp_u_281, __pyx_k_281, sizeof(__pyx_k_281), 0, 1, 0, 0}, - {&__pyx_kp_u_282, __pyx_k_282, sizeof(__pyx_k_282), 0, 1, 0, 0}, - {&__pyx_kp_u_283, __pyx_k_283, sizeof(__pyx_k_283), 0, 1, 0, 0}, - {&__pyx_kp_u_284, __pyx_k_284, sizeof(__pyx_k_284), 0, 1, 0, 0}, - {&__pyx_kp_u_285, __pyx_k_285, sizeof(__pyx_k_285), 0, 1, 0, 0}, - {&__pyx_kp_u_286, __pyx_k_286, sizeof(__pyx_k_286), 0, 1, 0, 0}, - {&__pyx_kp_s_30, __pyx_k_30, sizeof(__pyx_k_30), 0, 0, 1, 0}, - {&__pyx_kp_s_32, __pyx_k_32, sizeof(__pyx_k_32), 0, 0, 1, 0}, - {&__pyx_kp_s_34, __pyx_k_34, sizeof(__pyx_k_34), 0, 0, 1, 0}, - {&__pyx_kp_s_36, __pyx_k_36, sizeof(__pyx_k_36), 0, 0, 1, 0}, - {&__pyx_kp_s_44, __pyx_k_44, sizeof(__pyx_k_44), 0, 0, 1, 0}, - {&__pyx_kp_s_47, __pyx_k_47, sizeof(__pyx_k_47), 0, 0, 1, 0}, - {&__pyx_kp_s_49, __pyx_k_49, sizeof(__pyx_k_49), 0, 0, 1, 0}, - {&__pyx_kp_s_56, __pyx_k_56, sizeof(__pyx_k_56), 0, 0, 1, 0}, - {&__pyx_kp_s_66, __pyx_k_66, sizeof(__pyx_k_66), 0, 0, 1, 0}, - {&__pyx_kp_s_68, __pyx_k_68, sizeof(__pyx_k_68), 0, 0, 1, 0}, - {&__pyx_kp_s_70, __pyx_k_70, sizeof(__pyx_k_70), 0, 0, 1, 0}, - {&__pyx_kp_s_73, __pyx_k_73, sizeof(__pyx_k_73), 0, 0, 1, 0}, - {&__pyx_kp_s_78, __pyx_k_78, sizeof(__pyx_k_78), 0, 0, 1, 0}, - {&__pyx_kp_s_82, __pyx_k_82, sizeof(__pyx_k_82), 0, 0, 1, 0}, - {&__pyx_kp_s_84, __pyx_k_84, sizeof(__pyx_k_84), 0, 0, 1, 0}, - {&__pyx_kp_s_89, __pyx_k_89, sizeof(__pyx_k_89), 0, 0, 1, 0}, - {&__pyx_kp_s_9, __pyx_k_9, sizeof(__pyx_k_9), 0, 0, 1, 0}, - {&__pyx_n_s__MT19937, __pyx_k__MT19937, sizeof(__pyx_k__MT19937), 0, 0, 1, 1}, - {&__pyx_n_s__TypeError, __pyx_k__TypeError, sizeof(__pyx_k__TypeError), 0, 0, 1, 1}, - {&__pyx_n_s__ValueError, __pyx_k__ValueError, sizeof(__pyx_k__ValueError), 0, 0, 1, 1}, - {&__pyx_n_s____RandomState_ctor, __pyx_k____RandomState_ctor, sizeof(__pyx_k____RandomState_ctor), 0, 0, 1, 1}, - {&__pyx_n_s____import__, __pyx_k____import__, sizeof(__pyx_k____import__), 0, 0, 1, 1}, - {&__pyx_n_s____main__, __pyx_k____main__, sizeof(__pyx_k____main__), 0, 0, 1, 1}, - {&__pyx_n_s____test__, __pyx_k____test__, sizeof(__pyx_k____test__), 0, 0, 1, 1}, - {&__pyx_n_s___rand, __pyx_k___rand, sizeof(__pyx_k___rand), 0, 0, 1, 1}, - {&__pyx_n_s__a, __pyx_k__a, sizeof(__pyx_k__a), 0, 0, 1, 1}, - {&__pyx_n_s__add, __pyx_k__add, sizeof(__pyx_k__add), 0, 0, 1, 1}, - {&__pyx_n_s__allclose, __pyx_k__allclose, sizeof(__pyx_k__allclose), 0, 0, 1, 1}, - {&__pyx_n_s__alpha, __pyx_k__alpha, sizeof(__pyx_k__alpha), 0, 0, 1, 1}, - {&__pyx_n_s__any, __pyx_k__any, sizeof(__pyx_k__any), 0, 0, 1, 1}, - {&__pyx_n_s__arange, __pyx_k__arange, sizeof(__pyx_k__arange), 0, 0, 1, 1}, - {&__pyx_n_s__array, __pyx_k__array, sizeof(__pyx_k__array), 0, 0, 1, 1}, - {&__pyx_n_s__asarray, __pyx_k__asarray, sizeof(__pyx_k__asarray), 0, 0, 1, 1}, - {&__pyx_n_s__b, __pyx_k__b, sizeof(__pyx_k__b), 0, 0, 1, 1}, - {&__pyx_n_s__beta, __pyx_k__beta, sizeof(__pyx_k__beta), 0, 0, 1, 1}, - {&__pyx_n_s__binomial, __pyx_k__binomial, sizeof(__pyx_k__binomial), 0, 0, 1, 1}, - {&__pyx_n_s__bytes, __pyx_k__bytes, sizeof(__pyx_k__bytes), 0, 0, 1, 1}, - {&__pyx_n_s__chisquare, __pyx_k__chisquare, sizeof(__pyx_k__chisquare), 0, 0, 1, 1}, - {&__pyx_n_s__choice, __pyx_k__choice, sizeof(__pyx_k__choice), 0, 0, 1, 1}, - {&__pyx_n_s__copy, __pyx_k__copy, sizeof(__pyx_k__copy), 0, 0, 1, 1}, - {&__pyx_n_s__cov, __pyx_k__cov, sizeof(__pyx_k__cov), 0, 0, 1, 1}, - {&__pyx_n_s__cumsum, __pyx_k__cumsum, sizeof(__pyx_k__cumsum), 0, 0, 1, 1}, - {&__pyx_n_s__df, __pyx_k__df, sizeof(__pyx_k__df), 0, 0, 1, 1}, - {&__pyx_n_s__dfden, __pyx_k__dfden, sizeof(__pyx_k__dfden), 0, 0, 1, 1}, - {&__pyx_n_s__dfnum, __pyx_k__dfnum, sizeof(__pyx_k__dfnum), 0, 0, 1, 1}, - {&__pyx_n_s__dirichlet, __pyx_k__dirichlet, sizeof(__pyx_k__dirichlet), 0, 0, 1, 1}, - {&__pyx_n_s__dot, __pyx_k__dot, sizeof(__pyx_k__dot), 0, 0, 1, 1}, - {&__pyx_n_s__double, __pyx_k__double, sizeof(__pyx_k__double), 0, 0, 1, 1}, - {&__pyx_n_s__dtype, __pyx_k__dtype, sizeof(__pyx_k__dtype), 0, 0, 1, 1}, - {&__pyx_n_s__empty, __pyx_k__empty, sizeof(__pyx_k__empty), 0, 0, 1, 1}, - {&__pyx_n_s__equal, __pyx_k__equal, sizeof(__pyx_k__equal), 0, 0, 1, 1}, - {&__pyx_n_s__exponential, __pyx_k__exponential, sizeof(__pyx_k__exponential), 0, 0, 1, 1}, - {&__pyx_n_s__f, __pyx_k__f, sizeof(__pyx_k__f), 0, 0, 1, 1}, - {&__pyx_n_s__float64, __pyx_k__float64, sizeof(__pyx_k__float64), 0, 0, 1, 1}, - {&__pyx_n_s__gamma, __pyx_k__gamma, sizeof(__pyx_k__gamma), 0, 0, 1, 1}, - {&__pyx_n_s__geometric, __pyx_k__geometric, sizeof(__pyx_k__geometric), 0, 0, 1, 1}, - {&__pyx_n_s__get_state, __pyx_k__get_state, sizeof(__pyx_k__get_state), 0, 0, 1, 1}, - {&__pyx_n_s__greater, __pyx_k__greater, sizeof(__pyx_k__greater), 0, 0, 1, 1}, - {&__pyx_n_s__greater_equal, __pyx_k__greater_equal, sizeof(__pyx_k__greater_equal), 0, 0, 1, 1}, - {&__pyx_n_s__gumbel, __pyx_k__gumbel, sizeof(__pyx_k__gumbel), 0, 0, 1, 1}, - {&__pyx_n_s__high, __pyx_k__high, sizeof(__pyx_k__high), 0, 0, 1, 1}, - {&__pyx_n_s__hypergeometric, __pyx_k__hypergeometric, sizeof(__pyx_k__hypergeometric), 0, 0, 1, 1}, - {&__pyx_n_s__iinfo, __pyx_k__iinfo, sizeof(__pyx_k__iinfo), 0, 0, 1, 1}, - {&__pyx_n_s__index, __pyx_k__index, sizeof(__pyx_k__index), 0, 0, 1, 1}, - {&__pyx_n_s__int, __pyx_k__int, sizeof(__pyx_k__int), 0, 0, 1, 1}, - {&__pyx_n_s__integer, __pyx_k__integer, sizeof(__pyx_k__integer), 0, 0, 1, 1}, - {&__pyx_n_s__intp, __pyx_k__intp, sizeof(__pyx_k__intp), 0, 0, 1, 1}, - {&__pyx_n_s__item, __pyx_k__item, sizeof(__pyx_k__item), 0, 0, 1, 1}, - {&__pyx_n_s__kappa, __pyx_k__kappa, sizeof(__pyx_k__kappa), 0, 0, 1, 1}, - {&__pyx_n_s__l, __pyx_k__l, sizeof(__pyx_k__l), 0, 0, 1, 1}, - {&__pyx_n_s__lam, __pyx_k__lam, sizeof(__pyx_k__lam), 0, 0, 1, 1}, - {&__pyx_n_s__laplace, __pyx_k__laplace, sizeof(__pyx_k__laplace), 0, 0, 1, 1}, - {&__pyx_n_s__left, __pyx_k__left, sizeof(__pyx_k__left), 0, 0, 1, 1}, - {&__pyx_n_s__less, __pyx_k__less, sizeof(__pyx_k__less), 0, 0, 1, 1}, - {&__pyx_n_s__less_equal, __pyx_k__less_equal, sizeof(__pyx_k__less_equal), 0, 0, 1, 1}, - {&__pyx_n_s__loc, __pyx_k__loc, sizeof(__pyx_k__loc), 0, 0, 1, 1}, - {&__pyx_n_s__logistic, __pyx_k__logistic, sizeof(__pyx_k__logistic), 0, 0, 1, 1}, - {&__pyx_n_s__lognormal, __pyx_k__lognormal, sizeof(__pyx_k__lognormal), 0, 0, 1, 1}, - {&__pyx_n_s__logseries, __pyx_k__logseries, sizeof(__pyx_k__logseries), 0, 0, 1, 1}, - {&__pyx_n_s__low, __pyx_k__low, sizeof(__pyx_k__low), 0, 0, 1, 1}, - {&__pyx_n_s__max, __pyx_k__max, sizeof(__pyx_k__max), 0, 0, 1, 1}, - {&__pyx_n_s__mean, __pyx_k__mean, sizeof(__pyx_k__mean), 0, 0, 1, 1}, - {&__pyx_n_s__mode, __pyx_k__mode, sizeof(__pyx_k__mode), 0, 0, 1, 1}, - {&__pyx_n_s__mu, __pyx_k__mu, sizeof(__pyx_k__mu), 0, 0, 1, 1}, - {&__pyx_n_s__multinomial, __pyx_k__multinomial, sizeof(__pyx_k__multinomial), 0, 0, 1, 1}, - {&__pyx_n_s__multiply, __pyx_k__multiply, sizeof(__pyx_k__multiply), 0, 0, 1, 1}, - {&__pyx_n_s__multivariate_normal, __pyx_k__multivariate_normal, sizeof(__pyx_k__multivariate_normal), 0, 0, 1, 1}, - {&__pyx_n_s__n, __pyx_k__n, sizeof(__pyx_k__n), 0, 0, 1, 1}, - {&__pyx_n_s__nbad, __pyx_k__nbad, sizeof(__pyx_k__nbad), 0, 0, 1, 1}, - {&__pyx_n_s__ndarray, __pyx_k__ndarray, sizeof(__pyx_k__ndarray), 0, 0, 1, 1}, - {&__pyx_n_s__ndim, __pyx_k__ndim, sizeof(__pyx_k__ndim), 0, 0, 1, 1}, - {&__pyx_n_s__ndmin, __pyx_k__ndmin, sizeof(__pyx_k__ndmin), 0, 0, 1, 1}, - {&__pyx_n_s__negative_binomial, __pyx_k__negative_binomial, sizeof(__pyx_k__negative_binomial), 0, 0, 1, 1}, - {&__pyx_n_s__ngood, __pyx_k__ngood, sizeof(__pyx_k__ngood), 0, 0, 1, 1}, - {&__pyx_n_s__nonc, __pyx_k__nonc, sizeof(__pyx_k__nonc), 0, 0, 1, 1}, - {&__pyx_n_s__noncentral_f, __pyx_k__noncentral_f, sizeof(__pyx_k__noncentral_f), 0, 0, 1, 1}, - {&__pyx_n_s__normal, __pyx_k__normal, sizeof(__pyx_k__normal), 0, 0, 1, 1}, - {&__pyx_n_s__np, __pyx_k__np, sizeof(__pyx_k__np), 0, 0, 1, 1}, - {&__pyx_n_s__nsample, __pyx_k__nsample, sizeof(__pyx_k__nsample), 0, 0, 1, 1}, - {&__pyx_n_s__numpy, __pyx_k__numpy, sizeof(__pyx_k__numpy), 0, 0, 1, 1}, - {&__pyx_n_s__operator, __pyx_k__operator, sizeof(__pyx_k__operator), 0, 0, 1, 1}, - {&__pyx_n_s__p, __pyx_k__p, sizeof(__pyx_k__p), 0, 0, 1, 1}, - {&__pyx_n_s__pareto, __pyx_k__pareto, sizeof(__pyx_k__pareto), 0, 0, 1, 1}, - {&__pyx_n_s__permutation, __pyx_k__permutation, sizeof(__pyx_k__permutation), 0, 0, 1, 1}, - {&__pyx_n_s__poisson, __pyx_k__poisson, sizeof(__pyx_k__poisson), 0, 0, 1, 1}, - {&__pyx_n_s__poisson_lam_max, __pyx_k__poisson_lam_max, sizeof(__pyx_k__poisson_lam_max), 0, 0, 1, 1}, - {&__pyx_n_s__power, __pyx_k__power, sizeof(__pyx_k__power), 0, 0, 1, 1}, - {&__pyx_n_s__prod, __pyx_k__prod, sizeof(__pyx_k__prod), 0, 0, 1, 1}, - {&__pyx_n_s__pvals, __pyx_k__pvals, sizeof(__pyx_k__pvals), 0, 0, 1, 1}, - {&__pyx_n_s__rand, __pyx_k__rand, sizeof(__pyx_k__rand), 0, 0, 1, 1}, - {&__pyx_n_s__randint, __pyx_k__randint, sizeof(__pyx_k__randint), 0, 0, 1, 1}, - {&__pyx_n_s__randn, __pyx_k__randn, sizeof(__pyx_k__randn), 0, 0, 1, 1}, - {&__pyx_n_s__random, __pyx_k__random, sizeof(__pyx_k__random), 0, 0, 1, 1}, - {&__pyx_n_s__random_integers, __pyx_k__random_integers, sizeof(__pyx_k__random_integers), 0, 0, 1, 1}, - {&__pyx_n_s__random_sample, __pyx_k__random_sample, sizeof(__pyx_k__random_sample), 0, 0, 1, 1}, - {&__pyx_n_s__ravel, __pyx_k__ravel, sizeof(__pyx_k__ravel), 0, 0, 1, 1}, - {&__pyx_n_s__rayleigh, __pyx_k__rayleigh, sizeof(__pyx_k__rayleigh), 0, 0, 1, 1}, - {&__pyx_n_s__reduce, __pyx_k__reduce, sizeof(__pyx_k__reduce), 0, 0, 1, 1}, - {&__pyx_n_s__replace, __pyx_k__replace, sizeof(__pyx_k__replace), 0, 0, 1, 1}, - {&__pyx_n_s__return_index, __pyx_k__return_index, sizeof(__pyx_k__return_index), 0, 0, 1, 1}, - {&__pyx_n_s__right, __pyx_k__right, sizeof(__pyx_k__right), 0, 0, 1, 1}, - {&__pyx_n_s__scale, __pyx_k__scale, sizeof(__pyx_k__scale), 0, 0, 1, 1}, - {&__pyx_n_s__searchsorted, __pyx_k__searchsorted, sizeof(__pyx_k__searchsorted), 0, 0, 1, 1}, - {&__pyx_n_s__seed, __pyx_k__seed, sizeof(__pyx_k__seed), 0, 0, 1, 1}, - {&__pyx_n_s__set_state, __pyx_k__set_state, sizeof(__pyx_k__set_state), 0, 0, 1, 1}, - {&__pyx_n_s__shape, __pyx_k__shape, sizeof(__pyx_k__shape), 0, 0, 1, 1}, - {&__pyx_n_s__shuffle, __pyx_k__shuffle, sizeof(__pyx_k__shuffle), 0, 0, 1, 1}, - {&__pyx_n_s__side, __pyx_k__side, sizeof(__pyx_k__side), 0, 0, 1, 1}, - {&__pyx_n_s__sigma, __pyx_k__sigma, sizeof(__pyx_k__sigma), 0, 0, 1, 1}, - {&__pyx_n_s__size, __pyx_k__size, sizeof(__pyx_k__size), 0, 0, 1, 1}, - {&__pyx_n_s__sort, __pyx_k__sort, sizeof(__pyx_k__sort), 0, 0, 1, 1}, - {&__pyx_n_s__sqrt, __pyx_k__sqrt, sizeof(__pyx_k__sqrt), 0, 0, 1, 1}, - {&__pyx_n_s__standard_cauchy, __pyx_k__standard_cauchy, sizeof(__pyx_k__standard_cauchy), 0, 0, 1, 1}, - {&__pyx_n_s__standard_gamma, __pyx_k__standard_gamma, sizeof(__pyx_k__standard_gamma), 0, 0, 1, 1}, - {&__pyx_n_s__standard_normal, __pyx_k__standard_normal, sizeof(__pyx_k__standard_normal), 0, 0, 1, 1}, - {&__pyx_n_s__standard_t, __pyx_k__standard_t, sizeof(__pyx_k__standard_t), 0, 0, 1, 1}, - {&__pyx_n_s__subtract, __pyx_k__subtract, sizeof(__pyx_k__subtract), 0, 0, 1, 1}, - {&__pyx_n_s__sum, __pyx_k__sum, sizeof(__pyx_k__sum), 0, 0, 1, 1}, - {&__pyx_n_s__svd, __pyx_k__svd, sizeof(__pyx_k__svd), 0, 0, 1, 1}, - {&__pyx_n_s__take, __pyx_k__take, sizeof(__pyx_k__take), 0, 0, 1, 1}, - {&__pyx_n_s__triangular, __pyx_k__triangular, sizeof(__pyx_k__triangular), 0, 0, 1, 1}, - {&__pyx_n_s__uint, __pyx_k__uint, sizeof(__pyx_k__uint), 0, 0, 1, 1}, - {&__pyx_n_s__uint32, __pyx_k__uint32, sizeof(__pyx_k__uint32), 0, 0, 1, 1}, - {&__pyx_n_s__uniform, __pyx_k__uniform, sizeof(__pyx_k__uniform), 0, 0, 1, 1}, - {&__pyx_n_s__unique, __pyx_k__unique, sizeof(__pyx_k__unique), 0, 0, 1, 1}, - {&__pyx_n_s__vonmises, __pyx_k__vonmises, sizeof(__pyx_k__vonmises), 0, 0, 1, 1}, - {&__pyx_n_s__wald, __pyx_k__wald, sizeof(__pyx_k__wald), 0, 0, 1, 1}, - {&__pyx_n_s__weibull, __pyx_k__weibull, sizeof(__pyx_k__weibull), 0, 0, 1, 1}, - {&__pyx_n_s__zeros, __pyx_k__zeros, sizeof(__pyx_k__zeros), 0, 0, 1, 1}, - {&__pyx_n_s__zipf, __pyx_k__zipf, sizeof(__pyx_k__zipf), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s__ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s__TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 701; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - return 0; - __pyx_L1_error:; - return -1; -} - -static int __Pyx_InitCachedConstants(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - - /* "mtrand.pyx":186 - * <void *>oa) - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_k_tuple_2 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_1)); if (unlikely(!__pyx_k_tuple_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_2); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_2)); - - /* "mtrand.pyx":235 - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>oa, <void *>ob) - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_k_tuple_3 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_1)); if (unlikely(!__pyx_k_tuple_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 235; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_3); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_3)); - - /* "mtrand.pyx":290 - * <void *>ob, <void *>oc) - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_k_tuple_4 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_1)); if (unlikely(!__pyx_k_tuple_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 290; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_4); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_4)); - - /* "mtrand.pyx":354 - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>on, <void *>op) - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * on_data = <long *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_k_tuple_5 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_1)); if (unlikely(!__pyx_k_tuple_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 354; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_5); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_5)); - - /* "mtrand.pyx":403 - * multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>on, <void *>op) - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * on_data = <double *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_k_tuple_6 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_1)); if (unlikely(!__pyx_k_tuple_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_6); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_6)); - - /* "mtrand.pyx":457 - * <void *>oN) - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * on_data = <long *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_k_tuple_7 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_1)); if (unlikely(!__pyx_k_tuple_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 457; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_7); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_7)); - - /* "mtrand.pyx":506 - * multi = <broadcast>PyArray_MultiIterNew(2, <void *>array, <void *>oa) - * if (multi.size != PyArray_SIZE(array)): - * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< - * for i from 0 <= i < multi.size: - * oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - */ - __pyx_k_tuple_8 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_1)); if (unlikely(!__pyx_k_tuple_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_8); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_8)); - - /* "mtrand.pyx":692 - * algorithm_name = state[0] - * if algorithm_name != 'MT19937': - * raise ValueError("algorithm must be 'MT19937'") # <<<<<<<<<<<<<< - * key, pos = state[1:3] - * if len(state) == 3: - */ - __pyx_k_tuple_10 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_9)); if (unlikely(!__pyx_k_tuple_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 692; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_10); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); - - /* "mtrand.pyx":693 - * if algorithm_name != 'MT19937': - * raise ValueError("algorithm must be 'MT19937'") - * key, pos = state[1:3] # <<<<<<<<<<<<<< - * if len(state) == 3: - * has_gauss = 0 - */ - __pyx_k_slice_11 = PySlice_New(__pyx_int_1, __pyx_int_3, Py_None); if (unlikely(!__pyx_k_slice_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 693; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_slice_11); - __Pyx_GIVEREF(__pyx_k_slice_11); - - /* "mtrand.pyx":698 - * cached_gaussian = 0.0 - * else: - * has_gauss, cached_gaussian = state[3:5] # <<<<<<<<<<<<<< - * try: - * obj = <ndarray>PyArray_ContiguousFromObject(key, NPY_ULONG, 1, 1) - */ - __pyx_k_slice_12 = PySlice_New(__pyx_int_3, __pyx_int_5, Py_None); if (unlikely(!__pyx_k_slice_12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 698; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_slice_12); - __Pyx_GIVEREF(__pyx_k_slice_12); - - /* "mtrand.pyx":705 - * obj = <ndarray>PyArray_ContiguousFromObject(key, NPY_LONG, 1, 1) - * if PyArray_DIM(obj, 0) != 624: - * raise ValueError("state must be 624 longs") # <<<<<<<<<<<<<< - * memcpy(<void*>(self.internal_state.key), <void*>PyArray_DATA(obj), 624*sizeof(long)) - * self.internal_state.pos = pos - */ - __pyx_k_tuple_14 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_13)); if (unlikely(!__pyx_k_tuple_14)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 705; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_14); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); - - /* "mtrand.pyx":877 - * - * if lo >= hi : - * raise ValueError("low >= high") # <<<<<<<<<<<<<< - * - * diff = <unsigned long>hi - <unsigned long>lo - 1UL - */ - __pyx_k_tuple_16 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_15)); if (unlikely(!__pyx_k_tuple_16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 877; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_16); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); - - /* "mtrand.pyx":1004 - * pop_size = operator.index(a.item()) - * except TypeError: - * raise ValueError("a must be 1-dimensional or an integer") # <<<<<<<<<<<<<< - * if pop_size <= 0: - * raise ValueError("a must be greater than 0") - */ - __pyx_k_tuple_19 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_18)); if (unlikely(!__pyx_k_tuple_19)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1004; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_19); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_19)); - - /* "mtrand.pyx":1006 - * raise ValueError("a must be 1-dimensional or an integer") - * if pop_size <= 0: - * raise ValueError("a must be greater than 0") # <<<<<<<<<<<<<< - * elif a.ndim != 1: - * raise ValueError("a must be 1-dimensional") - */ - __pyx_k_tuple_21 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_20)); if (unlikely(!__pyx_k_tuple_21)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1006; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_21); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_21)); - - /* "mtrand.pyx":1008 - * raise ValueError("a must be greater than 0") - * elif a.ndim != 1: - * raise ValueError("a must be 1-dimensional") # <<<<<<<<<<<<<< - * else: - * pop_size = a.shape[0] - */ - __pyx_k_tuple_23 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_22)); if (unlikely(!__pyx_k_tuple_23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1008; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_23); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_23)); - - /* "mtrand.pyx":1012 - * pop_size = a.shape[0] - * if pop_size is 0: - * raise ValueError("a must be non-empty") # <<<<<<<<<<<<<< - * - * if None != p: - */ - __pyx_k_tuple_25 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_24)); if (unlikely(!__pyx_k_tuple_25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1012; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_25); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_25)); - - /* "mtrand.pyx":1017 - * p = np.array(p, dtype=np.double, ndmin=1, copy=False) - * if p.ndim != 1: - * raise ValueError("p must be 1-dimensional") # <<<<<<<<<<<<<< - * if p.size != pop_size: - * raise ValueError("a and p must have same size") - */ - __pyx_k_tuple_27 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_26)); if (unlikely(!__pyx_k_tuple_27)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1017; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_27); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_27)); - - /* "mtrand.pyx":1019 - * raise ValueError("p must be 1-dimensional") - * if p.size != pop_size: - * raise ValueError("a and p must have same size") # <<<<<<<<<<<<<< - * if np.any(p < 0): - * raise ValueError("probabilities are not non-negative") - */ - __pyx_k_tuple_29 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_28)); if (unlikely(!__pyx_k_tuple_29)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1019; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_29); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_29)); - - /* "mtrand.pyx":1021 - * raise ValueError("a and p must have same size") - * if np.any(p < 0): - * raise ValueError("probabilities are not non-negative") # <<<<<<<<<<<<<< - * if not np.allclose(p.sum(), 1): - * raise ValueError("probabilities do not sum to 1") - */ - __pyx_k_tuple_31 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_30)); if (unlikely(!__pyx_k_tuple_31)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1021; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_31); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_31)); - - /* "mtrand.pyx":1023 - * raise ValueError("probabilities are not non-negative") - * if not np.allclose(p.sum(), 1): - * raise ValueError("probabilities do not sum to 1") # <<<<<<<<<<<<<< - * - * shape = size - */ - __pyx_k_tuple_33 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_32)); if (unlikely(!__pyx_k_tuple_33)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1023; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_33); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_33)); - - /* "mtrand.pyx":1043 - * else: - * if size > pop_size: - * raise ValueError("Cannot take a larger sample than " # <<<<<<<<<<<<<< - * "population when 'replace=False'") - * - */ - __pyx_k_tuple_35 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_34)); if (unlikely(!__pyx_k_tuple_35)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_35); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_35)); - - /* "mtrand.pyx":1048 - * if None != p: - * if np.sum(p > 0) < size: - * raise ValueError("Fewer non-zero entries in p than size") # <<<<<<<<<<<<<< - * n_uniq = 0 - * p = p.copy() - */ - __pyx_k_tuple_37 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_36)); if (unlikely(!__pyx_k_tuple_37)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1048; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_37); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_37)); - - /* "mtrand.pyx":1073 - * if shape is None and isinstance(idx, np.ndarray): - * # In most cases a scalar will have been made an array - * idx = idx.item(0) # <<<<<<<<<<<<<< - * - * #Use samples as indices for a if a is array-like - */ - __pyx_k_tuple_38 = PyTuple_Pack(1, __pyx_int_0); if (unlikely(!__pyx_k_tuple_38)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1073; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_38); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_38)); - - /* "mtrand.pyx":1085 - * # array, taking into account that np.array(item) may not work - * # for object arrays. - * res = np.empty((), dtype=a.dtype) # <<<<<<<<<<<<<< - * res[()] = a[idx] - * return res - */ - __pyx_k_tuple_39 = PyTuple_Pack(1, ((PyObject *)__pyx_empty_tuple)); if (unlikely(!__pyx_k_tuple_39)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1085; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_39); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_39)); - - /* "mtrand.pyx":1479 - * if not PyErr_Occurred(): - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_normal, size, floc, fscale) - * - */ - __pyx_k_tuple_45 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_45)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1479; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_45); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_45)); - - /* "mtrand.pyx":1487 - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0)): - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_normal, size, oloc, oscale) - * - */ - __pyx_k_tuple_46 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_46)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1487; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_46); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_46)); - - /* "mtrand.pyx":1534 - * if not PyErr_Occurred(): - * if fa <= 0: - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * if fb <= 0: - * raise ValueError("b <= 0") - */ - __pyx_k_tuple_48 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_47)); if (unlikely(!__pyx_k_tuple_48)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1534; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_48); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_48)); - - /* "mtrand.pyx":1536 - * raise ValueError("a <= 0") - * if fb <= 0: - * raise ValueError("b <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_beta, size, fa, fb) - * - */ - __pyx_k_tuple_50 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_49)); if (unlikely(!__pyx_k_tuple_50)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_50); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_50)); - - /* "mtrand.pyx":1544 - * ob = <ndarray>PyArray_FROM_OTF(b, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 0)): - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * if np.any(np.less_equal(ob, 0)): - * raise ValueError("b <= 0") - */ - __pyx_k_tuple_51 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_47)); if (unlikely(!__pyx_k_tuple_51)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1544; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_51); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_51)); - - /* "mtrand.pyx":1546 - * raise ValueError("a <= 0") - * if np.any(np.less_equal(ob, 0)): - * raise ValueError("b <= 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_beta, size, oa, ob) - * - */ - __pyx_k_tuple_52 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_49)); if (unlikely(!__pyx_k_tuple_52)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_52); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_52)); - - /* "mtrand.pyx":1593 - * if not PyErr_Occurred(): - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_exponential, size, fscale) - * - */ - __pyx_k_tuple_54 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_54)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_54); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_54)); - - /* "mtrand.pyx":1600 - * oscale = <ndarray> PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_exponential, size, oscale) - * - */ - __pyx_k_tuple_55 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_55)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1600; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_55); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_55)); - - /* "mtrand.pyx":1704 - * if not PyErr_Occurred(): - * if fshape <= 0: - * raise ValueError("shape <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_standard_gamma, size, fshape) - * - */ - __pyx_k_tuple_57 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_56)); if (unlikely(!__pyx_k_tuple_57)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1704; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_57); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_57)); - - /* "mtrand.pyx":1710 - * oshape = <ndarray> PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oshape, 0.0)): - * raise ValueError("shape <= 0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_standard_gamma, size, oshape) - * - */ - __pyx_k_tuple_58 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_56)); if (unlikely(!__pyx_k_tuple_58)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1710; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_58); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_58)); - - /* "mtrand.pyx":1790 - * if not PyErr_Occurred(): - * if fshape <= 0: - * raise ValueError("shape <= 0") # <<<<<<<<<<<<<< - * if fscale <= 0: - * raise ValueError("scale <= 0") - */ - __pyx_k_tuple_60 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_56)); if (unlikely(!__pyx_k_tuple_60)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1790; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_60); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_60)); - - /* "mtrand.pyx":1792 - * raise ValueError("shape <= 0") - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_gamma, size, fshape, fscale) - * - */ - __pyx_k_tuple_61 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_61)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1792; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_61); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_61)); - - /* "mtrand.pyx":1799 - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oshape, 0.0)): - * raise ValueError("shape <= 0") # <<<<<<<<<<<<<< - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") - */ - __pyx_k_tuple_62 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_56)); if (unlikely(!__pyx_k_tuple_62)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_62); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_62)); - - /* "mtrand.pyx":1801 - * raise ValueError("shape <= 0") - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_gamma, size, oshape, oscale) - * - */ - __pyx_k_tuple_63 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_63)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_63); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_63)); - - /* "mtrand.pyx":1891 - * if not PyErr_Occurred(): - * if fdfnum <= 0: - * raise ValueError("shape <= 0") # <<<<<<<<<<<<<< - * if fdfden <= 0: - * raise ValueError("scale <= 0") - */ - __pyx_k_tuple_64 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_56)); if (unlikely(!__pyx_k_tuple_64)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1891; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_64); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_64)); - - /* "mtrand.pyx":1893 - * raise ValueError("shape <= 0") - * if fdfden <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_f, size, fdfnum, fdfden) - * - */ - __pyx_k_tuple_65 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_65)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1893; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_65); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_65)); - - /* "mtrand.pyx":1901 - * odfden = <ndarray>PyArray_FROM_OTF(dfden, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(odfnum, 0.0)): - * raise ValueError("dfnum <= 0") # <<<<<<<<<<<<<< - * if np.any(np.less_equal(odfden, 0.0)): - * raise ValueError("dfden <= 0") - */ - __pyx_k_tuple_67 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_66)); if (unlikely(!__pyx_k_tuple_67)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1901; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_67); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_67)); - - /* "mtrand.pyx":1903 - * raise ValueError("dfnum <= 0") - * if np.any(np.less_equal(odfden, 0.0)): - * raise ValueError("dfden <= 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_f, size, odfnum, odfden) - * - */ - __pyx_k_tuple_69 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_68)); if (unlikely(!__pyx_k_tuple_69)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1903; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_69); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_69)); - - /* "mtrand.pyx":1978 - * if not PyErr_Occurred(): - * if fdfnum <= 1: - * raise ValueError("dfnum <= 1") # <<<<<<<<<<<<<< - * if fdfden <= 0: - * raise ValueError("dfden <= 0") - */ - __pyx_k_tuple_71 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_70)); if (unlikely(!__pyx_k_tuple_71)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1978; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_71); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_71)); - - /* "mtrand.pyx":1980 - * raise ValueError("dfnum <= 1") - * if fdfden <= 0: - * raise ValueError("dfden <= 0") # <<<<<<<<<<<<<< - * if fnonc < 0: - * raise ValueError("nonc < 0") - */ - __pyx_k_tuple_72 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_68)); if (unlikely(!__pyx_k_tuple_72)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1980; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_72); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_72)); - - /* "mtrand.pyx":1982 - * raise ValueError("dfden <= 0") - * if fnonc < 0: - * raise ValueError("nonc < 0") # <<<<<<<<<<<<<< - * return cont3_array_sc(self.internal_state, rk_noncentral_f, size, - * fdfnum, fdfden, fnonc) - */ - __pyx_k_tuple_74 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_73)); if (unlikely(!__pyx_k_tuple_74)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1982; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_74); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_74)); - - /* "mtrand.pyx":1993 - * - * if np.any(np.less_equal(odfnum, 1.0)): - * raise ValueError("dfnum <= 1") # <<<<<<<<<<<<<< - * if np.any(np.less_equal(odfden, 0.0)): - * raise ValueError("dfden <= 0") - */ - __pyx_k_tuple_75 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_70)); if (unlikely(!__pyx_k_tuple_75)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1993; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_75); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_75)); - - /* "mtrand.pyx":1995 - * raise ValueError("dfnum <= 1") - * if np.any(np.less_equal(odfden, 0.0)): - * raise ValueError("dfden <= 0") # <<<<<<<<<<<<<< - * if np.any(np.less(ononc, 0.0)): - * raise ValueError("nonc < 0") - */ - __pyx_k_tuple_76 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_68)); if (unlikely(!__pyx_k_tuple_76)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1995; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_76); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_76)); - - /* "mtrand.pyx":1997 - * raise ValueError("dfden <= 0") - * if np.any(np.less(ononc, 0.0)): - * raise ValueError("nonc < 0") # <<<<<<<<<<<<<< - * return cont3_array(self.internal_state, rk_noncentral_f, size, odfnum, - * odfden, ononc) - */ - __pyx_k_tuple_77 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_73)); if (unlikely(!__pyx_k_tuple_77)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1997; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_77); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_77)); - - /* "mtrand.pyx":2069 - * if not PyErr_Occurred(): - * if fdf <= 0: - * raise ValueError("df <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_chisquare, size, fdf) - * - */ - __pyx_k_tuple_79 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_78)); if (unlikely(!__pyx_k_tuple_79)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2069; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_79); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_79)); - - /* "mtrand.pyx":2076 - * odf = <ndarray>PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(odf, 0.0)): - * raise ValueError("df <= 0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_chisquare, size, odf) - * - */ - __pyx_k_tuple_80 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_78)); if (unlikely(!__pyx_k_tuple_80)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2076; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_80); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_80)); - - /* "mtrand.pyx":2154 - * if not PyErr_Occurred(): - * if fdf <= 1: - * raise ValueError("df <= 0") # <<<<<<<<<<<<<< - * if fnonc <= 0: - * raise ValueError("nonc <= 0") - */ - __pyx_k_tuple_81 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_78)); if (unlikely(!__pyx_k_tuple_81)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_81); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_81)); - - /* "mtrand.pyx":2156 - * raise ValueError("df <= 0") - * if fnonc <= 0: - * raise ValueError("nonc <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_noncentral_chisquare, - * size, fdf, fnonc) - */ - __pyx_k_tuple_83 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_82)); if (unlikely(!__pyx_k_tuple_83)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2156; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_83); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_83)); - - /* "mtrand.pyx":2165 - * ononc = <ndarray>PyArray_FROM_OTF(nonc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(odf, 0.0)): - * raise ValueError("df <= 1") # <<<<<<<<<<<<<< - * if np.any(np.less_equal(ononc, 0.0)): - * raise ValueError("nonc < 0") - */ - __pyx_k_tuple_85 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_84)); if (unlikely(!__pyx_k_tuple_85)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_85); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_85)); - - /* "mtrand.pyx":2167 - * raise ValueError("df <= 1") - * if np.any(np.less_equal(ononc, 0.0)): - * raise ValueError("nonc < 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_noncentral_chisquare, size, - * odf, ononc) - */ - __pyx_k_tuple_86 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_73)); if (unlikely(!__pyx_k_tuple_86)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_86); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_86)); - - /* "mtrand.pyx":2323 - * if not PyErr_Occurred(): - * if fdf <= 0: - * raise ValueError("df <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_standard_t, size, fdf) - * - */ - __pyx_k_tuple_87 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_78)); if (unlikely(!__pyx_k_tuple_87)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2323; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_87); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_87)); - - /* "mtrand.pyx":2330 - * odf = <ndarray> PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(odf, 0.0)): - * raise ValueError("df <= 0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_standard_t, size, odf) - * - */ - __pyx_k_tuple_88 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_78)); if (unlikely(!__pyx_k_tuple_88)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2330; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_88); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_88)); - - /* "mtrand.pyx":2416 - * if not PyErr_Occurred(): - * if fkappa < 0: - * raise ValueError("kappa < 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_vonmises, size, fmu, fkappa) - * - */ - __pyx_k_tuple_90 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_89)); if (unlikely(!__pyx_k_tuple_90)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2416; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_90); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_90)); - - /* "mtrand.pyx":2424 - * okappa = <ndarray> PyArray_FROM_OTF(kappa, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less(okappa, 0.0)): - * raise ValueError("kappa < 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_vonmises, size, omu, okappa) - * - */ - __pyx_k_tuple_91 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_89)); if (unlikely(!__pyx_k_tuple_91)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_91); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_91)); - - /* "mtrand.pyx":2513 - * if not PyErr_Occurred(): - * if fa <= 0: - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_pareto, size, fa) - * - */ - __pyx_k_tuple_92 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_47)); if (unlikely(!__pyx_k_tuple_92)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_92); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_92)); - - /* "mtrand.pyx":2520 - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 0.0)): - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_pareto, size, oa) - * - */ - __pyx_k_tuple_93 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_47)); if (unlikely(!__pyx_k_tuple_93)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2520; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_93); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_93)); - - /* "mtrand.pyx":2613 - * if not PyErr_Occurred(): - * if fa <= 0: - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_weibull, size, fa) - * - */ - __pyx_k_tuple_94 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_47)); if (unlikely(!__pyx_k_tuple_94)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2613; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_94); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_94)); - - /* "mtrand.pyx":2620 - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 0.0)): - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_weibull, size, oa) - * - */ - __pyx_k_tuple_95 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_47)); if (unlikely(!__pyx_k_tuple_95)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2620; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_95); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_95)); - - /* "mtrand.pyx":2722 - * if not PyErr_Occurred(): - * if fa <= 0: - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_power, size, fa) - * - */ - __pyx_k_tuple_96 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_47)); if (unlikely(!__pyx_k_tuple_96)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_96); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_96)); - - /* "mtrand.pyx":2729 - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 0.0)): - * raise ValueError("a <= 0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_power, size, oa) - * - */ - __pyx_k_tuple_97 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_47)); if (unlikely(!__pyx_k_tuple_97)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2729; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_97); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_97)); - - /* "mtrand.pyx":2812 - * if not PyErr_Occurred(): - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_laplace, size, floc, fscale) - * - */ - __pyx_k_tuple_100 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_100)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2812; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_100); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_100)); - - /* "mtrand.pyx":2819 - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_laplace, size, oloc, oscale) - * - */ - __pyx_k_tuple_101 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_101)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2819; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_101); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_101)); - - /* "mtrand.pyx":2943 - * if not PyErr_Occurred(): - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_gumbel, size, floc, fscale) - * - */ - __pyx_k_tuple_104 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_104)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2943; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_104); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_104)); - - /* "mtrand.pyx":2950 - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_gumbel, size, oloc, oscale) - * - */ - __pyx_k_tuple_105 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_105)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2950; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_105); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_105)); - - /* "mtrand.pyx":3031 - * if not PyErr_Occurred(): - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_logistic, size, floc, fscale) - * - */ - __pyx_k_tuple_108 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_108)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3031; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_108); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_108)); - - /* "mtrand.pyx":3038 - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_logistic, size, oloc, oscale) - * - */ - __pyx_k_tuple_109 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_109)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3038; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_109); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_109)); - - /* "mtrand.pyx":3151 - * if not PyErr_Occurred(): - * if fsigma <= 0: - * raise ValueError("sigma <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_lognormal, size, fmean, fsigma) - * - */ - __pyx_k_tuple_113 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_112)); if (unlikely(!__pyx_k_tuple_113)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_113); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_113)); - - /* "mtrand.pyx":3159 - * osigma = PyArray_FROM_OTF(sigma, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(osigma, 0.0)): - * raise ValueError("sigma <= 0.0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_lognormal, size, omean, osigma) - * - */ - __pyx_k_tuple_115 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_114)); if (unlikely(!__pyx_k_tuple_115)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_115); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_115)); - - /* "mtrand.pyx":3224 - * if not PyErr_Occurred(): - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont1_array_sc(self.internal_state, rk_rayleigh, size, fscale) - * - */ - __pyx_k_tuple_117 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_117)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_117); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_117)); - - /* "mtrand.pyx":3231 - * oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oscale, 0.0)): - * raise ValueError("scale <= 0.0") # <<<<<<<<<<<<<< - * return cont1_array(self.internal_state, rk_rayleigh, size, oscale) - * - */ - __pyx_k_tuple_119 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_118)); if (unlikely(!__pyx_k_tuple_119)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_119); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_119)); - - /* "mtrand.pyx":3304 - * if not PyErr_Occurred(): - * if fmean <= 0: - * raise ValueError("mean <= 0") # <<<<<<<<<<<<<< - * if fscale <= 0: - * raise ValueError("scale <= 0") - */ - __pyx_k_tuple_121 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_120)); if (unlikely(!__pyx_k_tuple_121)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3304; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_121); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_121)); - - /* "mtrand.pyx":3306 - * raise ValueError("mean <= 0") - * if fscale <= 0: - * raise ValueError("scale <= 0") # <<<<<<<<<<<<<< - * return cont2_array_sc(self.internal_state, rk_wald, size, fmean, fscale) - * - */ - __pyx_k_tuple_122 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_44)); if (unlikely(!__pyx_k_tuple_122)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3306; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_122); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_122)); - - /* "mtrand.pyx":3313 - * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(omean,0.0)): - * raise ValueError("mean <= 0.0") # <<<<<<<<<<<<<< - * elif np.any(np.less_equal(oscale,0.0)): - * raise ValueError("scale <= 0.0") - */ - __pyx_k_tuple_124 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_123)); if (unlikely(!__pyx_k_tuple_124)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3313; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_124); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_124)); - - /* "mtrand.pyx":3315 - * raise ValueError("mean <= 0.0") - * elif np.any(np.less_equal(oscale,0.0)): - * raise ValueError("scale <= 0.0") # <<<<<<<<<<<<<< - * return cont2_array(self.internal_state, rk_wald, size, omean, oscale) - * - */ - __pyx_k_tuple_125 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_118)); if (unlikely(!__pyx_k_tuple_125)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3315; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_125); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_125)); - - /* "mtrand.pyx":3385 - * if not PyErr_Occurred(): - * if fleft > fmode: - * raise ValueError("left > mode") # <<<<<<<<<<<<<< - * if fmode > fright: - * raise ValueError("mode > right") - */ - __pyx_k_tuple_127 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_126)); if (unlikely(!__pyx_k_tuple_127)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3385; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_127); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_127)); - - /* "mtrand.pyx":3387 - * raise ValueError("left > mode") - * if fmode > fright: - * raise ValueError("mode > right") # <<<<<<<<<<<<<< - * if fleft == fright: - * raise ValueError("left == right") - */ - __pyx_k_tuple_129 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_128)); if (unlikely(!__pyx_k_tuple_129)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3387; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_129); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_129)); - - /* "mtrand.pyx":3389 - * raise ValueError("mode > right") - * if fleft == fright: - * raise ValueError("left == right") # <<<<<<<<<<<<<< - * return cont3_array_sc(self.internal_state, rk_triangular, size, fleft, - * fmode, fright) - */ - __pyx_k_tuple_131 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_130)); if (unlikely(!__pyx_k_tuple_131)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3389; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_131); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_131)); - - /* "mtrand.pyx":3399 - * - * if np.any(np.greater(oleft, omode)): - * raise ValueError("left > mode") # <<<<<<<<<<<<<< - * if np.any(np.greater(omode, oright)): - * raise ValueError("mode > right") - */ - __pyx_k_tuple_132 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_126)); if (unlikely(!__pyx_k_tuple_132)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3399; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_132); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_132)); - - /* "mtrand.pyx":3401 - * raise ValueError("left > mode") - * if np.any(np.greater(omode, oright)): - * raise ValueError("mode > right") # <<<<<<<<<<<<<< - * if np.any(np.equal(oleft, oright)): - * raise ValueError("left == right") - */ - __pyx_k_tuple_133 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_128)); if (unlikely(!__pyx_k_tuple_133)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3401; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_133); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_133)); - - /* "mtrand.pyx":3403 - * raise ValueError("mode > right") - * if np.any(np.equal(oleft, oright)): - * raise ValueError("left == right") # <<<<<<<<<<<<<< - * return cont3_array(self.internal_state, rk_triangular, size, oleft, - * omode, oright) - */ - __pyx_k_tuple_134 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_130)); if (unlikely(!__pyx_k_tuple_134)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3403; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_134); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_134)); - - /* "mtrand.pyx":3497 - * if not PyErr_Occurred(): - * if ln < 0: - * raise ValueError("n < 0") # <<<<<<<<<<<<<< - * if fp < 0: - * raise ValueError("p < 0") - */ - __pyx_k_tuple_136 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_135)); if (unlikely(!__pyx_k_tuple_136)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_136); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_136)); - - /* "mtrand.pyx":3499 - * raise ValueError("n < 0") - * if fp < 0: - * raise ValueError("p < 0") # <<<<<<<<<<<<<< - * elif fp > 1: - * raise ValueError("p > 1") - */ - __pyx_k_tuple_138 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_137)); if (unlikely(!__pyx_k_tuple_138)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_138); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_138)); - - /* "mtrand.pyx":3501 - * raise ValueError("p < 0") - * elif fp > 1: - * raise ValueError("p > 1") # <<<<<<<<<<<<<< - * return discnp_array_sc(self.internal_state, rk_binomial, size, ln, fp) - * - */ - __pyx_k_tuple_140 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_139)); if (unlikely(!__pyx_k_tuple_140)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3501; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_140); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_140)); - - /* "mtrand.pyx":3509 - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less(n, 0)): - * raise ValueError("n < 0") # <<<<<<<<<<<<<< - * if np.any(np.less(p, 0)): - * raise ValueError("p < 0") - */ - __pyx_k_tuple_141 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_135)); if (unlikely(!__pyx_k_tuple_141)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_141); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_141)); - - /* "mtrand.pyx":3511 - * raise ValueError("n < 0") - * if np.any(np.less(p, 0)): - * raise ValueError("p < 0") # <<<<<<<<<<<<<< - * if np.any(np.greater(p, 1)): - * raise ValueError("p > 1") - */ - __pyx_k_tuple_142 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_137)); if (unlikely(!__pyx_k_tuple_142)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_142); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_142)); - - /* "mtrand.pyx":3513 - * raise ValueError("p < 0") - * if np.any(np.greater(p, 1)): - * raise ValueError("p > 1") # <<<<<<<<<<<<<< - * return discnp_array(self.internal_state, rk_binomial, size, on, op) - * - */ - __pyx_k_tuple_143 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_139)); if (unlikely(!__pyx_k_tuple_143)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_143); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_143)); - - /* "mtrand.pyx":3590 - * if not PyErr_Occurred(): - * if fn <= 0: - * raise ValueError("n <= 0") # <<<<<<<<<<<<<< - * if fp < 0: - * raise ValueError("p < 0") - */ - __pyx_k_tuple_145 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_144)); if (unlikely(!__pyx_k_tuple_145)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3590; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_145); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_145)); - - /* "mtrand.pyx":3592 - * raise ValueError("n <= 0") - * if fp < 0: - * raise ValueError("p < 0") # <<<<<<<<<<<<<< - * elif fp > 1: - * raise ValueError("p > 1") - */ - __pyx_k_tuple_146 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_137)); if (unlikely(!__pyx_k_tuple_146)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_146); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_146)); - - /* "mtrand.pyx":3594 - * raise ValueError("p < 0") - * elif fp > 1: - * raise ValueError("p > 1") # <<<<<<<<<<<<<< - * return discdd_array_sc(self.internal_state, rk_negative_binomial, - * size, fn, fp) - */ - __pyx_k_tuple_147 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_139)); if (unlikely(!__pyx_k_tuple_147)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3594; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_147); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_147)); - - /* "mtrand.pyx":3603 - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(n, 0)): - * raise ValueError("n <= 0") # <<<<<<<<<<<<<< - * if np.any(np.less(p, 0)): - * raise ValueError("p < 0") - */ - __pyx_k_tuple_148 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_144)); if (unlikely(!__pyx_k_tuple_148)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3603; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_148); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_148)); - - /* "mtrand.pyx":3605 - * raise ValueError("n <= 0") - * if np.any(np.less(p, 0)): - * raise ValueError("p < 0") # <<<<<<<<<<<<<< - * if np.any(np.greater(p, 1)): - * raise ValueError("p > 1") - */ - __pyx_k_tuple_149 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_137)); if (unlikely(!__pyx_k_tuple_149)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3605; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_149); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_149)); - - /* "mtrand.pyx":3607 - * raise ValueError("p < 0") - * if np.any(np.greater(p, 1)): - * raise ValueError("p > 1") # <<<<<<<<<<<<<< - * return discdd_array(self.internal_state, rk_negative_binomial, size, - * on, op) - */ - __pyx_k_tuple_150 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_139)); if (unlikely(!__pyx_k_tuple_150)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3607; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_150); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_150)); - - /* "mtrand.pyx":3668 - * if not PyErr_Occurred(): - * if lam < 0: - * raise ValueError("lam < 0") # <<<<<<<<<<<<<< - * if lam > self.poisson_lam_max: - * raise ValueError("lam value too large") - */ - __pyx_k_tuple_153 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_152)); if (unlikely(!__pyx_k_tuple_153)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3668; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_153); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_153)); - - /* "mtrand.pyx":3670 - * raise ValueError("lam < 0") - * if lam > self.poisson_lam_max: - * raise ValueError("lam value too large") # <<<<<<<<<<<<<< - * return discd_array_sc(self.internal_state, rk_poisson, size, flam) - * - */ - __pyx_k_tuple_155 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_154)); if (unlikely(!__pyx_k_tuple_155)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3670; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_155); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_155)); - - /* "mtrand.pyx":3677 - * olam = <ndarray>PyArray_FROM_OTF(lam, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less(olam, 0)): - * raise ValueError("lam < 0") # <<<<<<<<<<<<<< - * if np.any(np.greater(olam, self.poisson_lam_max)): - * raise ValueError("lam value too large.") - */ - __pyx_k_tuple_156 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_152)); if (unlikely(!__pyx_k_tuple_156)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3677; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_156); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_156)); - - /* "mtrand.pyx":3679 - * raise ValueError("lam < 0") - * if np.any(np.greater(olam, self.poisson_lam_max)): - * raise ValueError("lam value too large.") # <<<<<<<<<<<<<< - * return discd_array(self.internal_state, rk_poisson, size, olam) - * - */ - __pyx_k_tuple_158 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_157)); if (unlikely(!__pyx_k_tuple_158)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3679; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_158); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_158)); - - /* "mtrand.pyx":3760 - * if not PyErr_Occurred(): - * if fa <= 1.0: - * raise ValueError("a <= 1.0") # <<<<<<<<<<<<<< - * return discd_array_sc(self.internal_state, rk_zipf, size, fa) - * - */ - __pyx_k_tuple_160 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_159)); if (unlikely(!__pyx_k_tuple_160)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3760; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_160); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_160)); - - /* "mtrand.pyx":3767 - * oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(oa, 1.0)): - * raise ValueError("a <= 1.0") # <<<<<<<<<<<<<< - * return discd_array(self.internal_state, rk_zipf, size, oa) - * - */ - __pyx_k_tuple_161 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_159)); if (unlikely(!__pyx_k_tuple_161)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3767; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_161); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_161)); - - /* "mtrand.pyx":3821 - * if not PyErr_Occurred(): - * if fp < 0.0: - * raise ValueError("p < 0.0") # <<<<<<<<<<<<<< - * if fp > 1.0: - * raise ValueError("p > 1.0") - */ - __pyx_k_tuple_163 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_162)); if (unlikely(!__pyx_k_tuple_163)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3821; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_163); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_163)); - - /* "mtrand.pyx":3823 - * raise ValueError("p < 0.0") - * if fp > 1.0: - * raise ValueError("p > 1.0") # <<<<<<<<<<<<<< - * return discd_array_sc(self.internal_state, rk_geometric, size, fp) - * - */ - __pyx_k_tuple_165 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_164)); if (unlikely(!__pyx_k_tuple_165)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3823; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_165); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_165)); - - /* "mtrand.pyx":3831 - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less(op, 0.0)): - * raise ValueError("p < 0.0") # <<<<<<<<<<<<<< - * if np.any(np.greater(op, 1.0)): - * raise ValueError("p > 1.0") - */ - __pyx_k_tuple_166 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_162)); if (unlikely(!__pyx_k_tuple_166)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_166); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_166)); - - /* "mtrand.pyx":3833 - * raise ValueError("p < 0.0") - * if np.any(np.greater(op, 1.0)): - * raise ValueError("p > 1.0") # <<<<<<<<<<<<<< - * return discd_array(self.internal_state, rk_geometric, size, op) - * - */ - __pyx_k_tuple_167 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_164)); if (unlikely(!__pyx_k_tuple_167)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_167); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_167)); - - /* "mtrand.pyx":3929 - * if not PyErr_Occurred(): - * if lngood < 0: - * raise ValueError("ngood < 0") # <<<<<<<<<<<<<< - * if lnbad < 0: - * raise ValueError("nbad < 0") - */ - __pyx_k_tuple_169 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_168)); if (unlikely(!__pyx_k_tuple_169)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3929; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_169); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_169)); - - /* "mtrand.pyx":3931 - * raise ValueError("ngood < 0") - * if lnbad < 0: - * raise ValueError("nbad < 0") # <<<<<<<<<<<<<< - * if lnsample < 1: - * raise ValueError("nsample < 1") - */ - __pyx_k_tuple_171 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_170)); if (unlikely(!__pyx_k_tuple_171)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3931; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_171); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_171)); - - /* "mtrand.pyx":3933 - * raise ValueError("nbad < 0") - * if lnsample < 1: - * raise ValueError("nsample < 1") # <<<<<<<<<<<<<< - * if lngood + lnbad < lnsample: - * raise ValueError("ngood + nbad < nsample") - */ - __pyx_k_tuple_173 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_172)); if (unlikely(!__pyx_k_tuple_173)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3933; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_173); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_173)); - - /* "mtrand.pyx":3935 - * raise ValueError("nsample < 1") - * if lngood + lnbad < lnsample: - * raise ValueError("ngood + nbad < nsample") # <<<<<<<<<<<<<< - * return discnmN_array_sc(self.internal_state, rk_hypergeometric, size, - * lngood, lnbad, lnsample) - */ - __pyx_k_tuple_175 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_174)); if (unlikely(!__pyx_k_tuple_175)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3935; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_175); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_175)); - - /* "mtrand.pyx":3945 - * onsample = <ndarray>PyArray_FROM_OTF(nsample, NPY_LONG, NPY_ARRAY_ALIGNED) - * if np.any(np.less(ongood, 0)): - * raise ValueError("ngood < 0") # <<<<<<<<<<<<<< - * if np.any(np.less(onbad, 0)): - * raise ValueError("nbad < 0") - */ - __pyx_k_tuple_176 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_168)); if (unlikely(!__pyx_k_tuple_176)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3945; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_176); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_176)); - - /* "mtrand.pyx":3947 - * raise ValueError("ngood < 0") - * if np.any(np.less(onbad, 0)): - * raise ValueError("nbad < 0") # <<<<<<<<<<<<<< - * if np.any(np.less(onsample, 1)): - * raise ValueError("nsample < 1") - */ - __pyx_k_tuple_177 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_170)); if (unlikely(!__pyx_k_tuple_177)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3947; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_177); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_177)); - - /* "mtrand.pyx":3949 - * raise ValueError("nbad < 0") - * if np.any(np.less(onsample, 1)): - * raise ValueError("nsample < 1") # <<<<<<<<<<<<<< - * if np.any(np.less(np.add(ongood, onbad),onsample)): - * raise ValueError("ngood + nbad < nsample") - */ - __pyx_k_tuple_178 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_172)); if (unlikely(!__pyx_k_tuple_178)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3949; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_178); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_178)); - - /* "mtrand.pyx":3951 - * raise ValueError("nsample < 1") - * if np.any(np.less(np.add(ongood, onbad),onsample)): - * raise ValueError("ngood + nbad < nsample") # <<<<<<<<<<<<<< - * return discnmN_array(self.internal_state, rk_hypergeometric, size, - * ongood, onbad, onsample) - */ - __pyx_k_tuple_179 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_174)); if (unlikely(!__pyx_k_tuple_179)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3951; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_179); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_179)); - - /* "mtrand.pyx":4035 - * if not PyErr_Occurred(): - * if fp <= 0.0: - * raise ValueError("p <= 0.0") # <<<<<<<<<<<<<< - * if fp >= 1.0: - * raise ValueError("p >= 1.0") - */ - __pyx_k_tuple_181 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_180)); if (unlikely(!__pyx_k_tuple_181)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4035; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_181); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_181)); - - /* "mtrand.pyx":4037 - * raise ValueError("p <= 0.0") - * if fp >= 1.0: - * raise ValueError("p >= 1.0") # <<<<<<<<<<<<<< - * return discd_array_sc(self.internal_state, rk_logseries, size, fp) - * - */ - __pyx_k_tuple_183 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_182)); if (unlikely(!__pyx_k_tuple_183)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_183); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_183)); - - /* "mtrand.pyx":4044 - * op = <ndarray>PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) - * if np.any(np.less_equal(op, 0.0)): - * raise ValueError("p <= 0.0") # <<<<<<<<<<<<<< - * if np.any(np.greater_equal(op, 1.0)): - * raise ValueError("p >= 1.0") - */ - __pyx_k_tuple_184 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_180)); if (unlikely(!__pyx_k_tuple_184)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4044; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_184); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_184)); - - /* "mtrand.pyx":4046 - * raise ValueError("p <= 0.0") - * if np.any(np.greater_equal(op, 1.0)): - * raise ValueError("p >= 1.0") # <<<<<<<<<<<<<< - * return discd_array(self.internal_state, rk_logseries, size, op) - * - */ - __pyx_k_tuple_185 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_182)); if (unlikely(!__pyx_k_tuple_185)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4046; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_185); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_185)); - - /* "mtrand.pyx":4149 - * shape = size - * if len(mean.shape) != 1: - * raise ValueError("mean must be 1 dimensional") # <<<<<<<<<<<<<< - * if (len(cov.shape) != 2) or (cov.shape[0] != cov.shape[1]): - * raise ValueError("cov must be 2 dimensional and square") - */ - __pyx_k_tuple_187 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_186)); if (unlikely(!__pyx_k_tuple_187)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4149; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_187); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_187)); - - /* "mtrand.pyx":4151 - * raise ValueError("mean must be 1 dimensional") - * if (len(cov.shape) != 2) or (cov.shape[0] != cov.shape[1]): - * raise ValueError("cov must be 2 dimensional and square") # <<<<<<<<<<<<<< - * if mean.shape[0] != cov.shape[0]: - * raise ValueError("mean and cov must have same length") - */ - __pyx_k_tuple_189 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_188)); if (unlikely(!__pyx_k_tuple_189)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_189); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_189)); - - /* "mtrand.pyx":4153 - * raise ValueError("cov must be 2 dimensional and square") - * if mean.shape[0] != cov.shape[0]: - * raise ValueError("mean and cov must have same length") # <<<<<<<<<<<<<< - * # Compute shape of output - * if isinstance(shape, (int, long, np.integer)): - */ - __pyx_k_tuple_191 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_190)); if (unlikely(!__pyx_k_tuple_191)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4153; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_191); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_191)); - - /* "mtrand.pyx":4157 - * if isinstance(shape, (int, long, np.integer)): - * shape = [shape] - * final_shape = list(shape[:]) # <<<<<<<<<<<<<< - * final_shape.append(mean.shape[0]) - * # Create a matrix of independent standard normally distributed random - */ - __pyx_k_slice_192 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_k_slice_192)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_slice_192); - __Pyx_GIVEREF(__pyx_k_slice_192); - - /* "mtrand.pyx":4246 - * - * if kahan_sum(pix, d-1) > (1.0 + 1e-12): - * raise ValueError("sum(pvals[:-1]) > 1.0") # <<<<<<<<<<<<<< - * - * if size is None: - */ - __pyx_k_tuple_195 = PyTuple_Pack(1, ((PyObject *)__pyx_kp_s_194)); if (unlikely(!__pyx_k_tuple_195)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4246; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_195); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_195)); - - /* "mtrand.pyx":4433 - * # each row. So we can't just use ordinary assignment to swap the - * # rows; we need a bounce buffer. - * buf = np.empty(x.shape[1:], dtype=x.dtype) # <<<<<<<<<<<<<< - * while i > 0: - * j = rk_interval(i, self.internal_state) - */ - __pyx_k_slice_196 = PySlice_New(__pyx_int_1, Py_None, Py_None); if (unlikely(!__pyx_k_slice_196)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_slice_196); - __Pyx_GIVEREF(__pyx_k_slice_196); - - /* "mtrand.pyx":559 - * """ - * cdef rk_state *internal_state - * poisson_lam_max = np.iinfo('l').max - np.sqrt(np.iinfo('l').max)*10 # <<<<<<<<<<<<<< - * - * def __init__(self, seed=None): - */ - __pyx_k_tuple_197 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__l)); if (unlikely(!__pyx_k_tuple_197)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_197); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_197)); - __pyx_k_tuple_198 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__l)); if (unlikely(!__pyx_k_tuple_198)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_k_tuple_198); - __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_198)); - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_3 = PyInt_FromLong(3); if (unlikely(!__pyx_int_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_5 = PyInt_FromLong(5); if (unlikely(!__pyx_int_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_10 = PyInt_FromLong(10); if (unlikely(!__pyx_int_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_624 = PyInt_FromLong(624); if (unlikely(!__pyx_int_624)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - return 0; - __pyx_L1_error:; - return -1; -} - -#if PY_MAJOR_VERSION < 3 -PyMODINIT_FUNC initmtrand(void); /*proto*/ -PyMODINIT_FUNC initmtrand(void) -#else -PyMODINIT_FUNC PyInit_mtrand(void); /*proto*/ -PyMODINIT_FUNC PyInit_mtrand(void) -#endif -{ - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - #if CYTHON_REFNANNY - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); - if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); - } - #endif - __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_mtrand(void)", 0); - if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #ifdef __Pyx_CyFunction_USED - if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - #ifdef WITH_THREAD /* Python build with threading support? */ - PyEval_InitThreads(); - #endif - #endif - /*--- Module creation code ---*/ - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4(__Pyx_NAMESTR("mtrand"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_INCREF(__pyx_d); - #if PY_MAJOR_VERSION >= 3 - { - PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (!PyDict_GetItemString(modules, "mtrand")) { - if (unlikely(PyDict_SetItemString(modules, "mtrand", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - } - #endif - __pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #if CYTHON_COMPILING_IN_PYPY - Py_INCREF(__pyx_b); - #endif - if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - /*--- Initialize various global constants etc. ---*/ - if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) - if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - if (__pyx_module_is_main_mtrand) { - if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s____main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - } - /*--- Builtin init code ---*/ - if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Constants init code ---*/ - if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Global init code ---*/ - /*--- Variable export code ---*/ - /*--- Function export code ---*/ - /*--- Type init code ---*/ - __pyx_ptype_6mtrand_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_6mtrand_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_6mtrand_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_6mtrand_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 78; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_6mtrand_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_6mtrand_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_6mtrand_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_6mtrand_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 86; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyType_Ready(&__pyx_type_6mtrand_RandomState) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (__Pyx_SetAttrString(__pyx_m, "RandomState", (PyObject *)&__pyx_type_6mtrand_RandomState) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_ptype_6mtrand_RandomState = &__pyx_type_6mtrand_RandomState; - /*--- Type import code ---*/ - /*--- Variable import code ---*/ - /*--- Function import code ---*/ - /*--- Execution code ---*/ - - /* "mtrand.pyx":124 - * - * # Initialize numpy - * import_array() # <<<<<<<<<<<<<< - * - * import numpy as np - */ - import_array(); - - /* "mtrand.pyx":126 - * import_array() - * - * import numpy as np # <<<<<<<<<<<<<< - * import operator - * - */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__numpy), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s__np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":127 - * - * import numpy as np - * import operator # <<<<<<<<<<<<<< - * - * cdef object cont0_array(rk_state *state, rk_cont0 func, object size): - */ - __pyx_t_1 = __Pyx_Import(((PyObject *)__pyx_n_s__operator), 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s__operator, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":559 - * """ - * cdef rk_state *internal_state - * poisson_lam_max = np.iinfo('l').max - np.sqrt(np.iinfo('l').max)*10 # <<<<<<<<<<<<<< - * - * def __init__(self, seed=None): - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__iinfo); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_k_tuple_197), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__max); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__sqrt); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__iinfo); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyObject_Call(__pyx_t_4, ((PyObject *)__pyx_k_tuple_198), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__max); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyObject_Call(__pyx_t_3, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - __pyx_t_1 = PyNumber_Multiply(__pyx_t_4, __pyx_int_10); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyNumber_Subtract(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem((PyObject *)__pyx_ptype_6mtrand_RandomState->tp_dict, __pyx_n_s__poisson_lam_max, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - PyType_Modified(__pyx_ptype_6mtrand_RandomState); - - /* "mtrand.pyx":920 - * - * - * def choice(self, a, size=None, replace=True, p=None): # <<<<<<<<<<<<<< - * """ - * choice(a, size=None, replace=True, p=None) - */ - __pyx_t_4 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 920; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_17 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - - /* "mtrand.pyx":1092 - * - * - * def uniform(self, low=0.0, high=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * uniform(low=0.0, high=1.0, size=1) - */ - __pyx_t_4 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1092; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_40 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1092; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_41 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - - /* "mtrand.pyx":1390 - * return cont0_array(self.internal_state, rk_gauss, size) - * - * def normal(self, loc=0.0, scale=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * normal(loc=0.0, scale=1.0, size=None) - */ - __pyx_t_4 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_42 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1390; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_43 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - - /* "mtrand.pyx":1549 - * return cont2_array(self.internal_state, rk_beta, size, oa, ob) - * - * def exponential(self, scale=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * exponential(scale=1.0, size=None) - */ - __pyx_t_4 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1549; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_53 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - - /* "mtrand.pyx":1713 - * return cont1_array(self.internal_state, rk_standard_gamma, size, oshape) - * - * def gamma(self, shape, scale=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * gamma(shape, scale=1.0, size=None) - */ - __pyx_t_4 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1713; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_59 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - - /* "mtrand.pyx":2732 - * return cont1_array(self.internal_state, rk_power, size, oa) - * - * def laplace(self, loc=0.0, scale=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * laplace(loc=0.0, scale=1.0, size=None) - */ - __pyx_t_4 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2732; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_98 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2732; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_99 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - - /* "mtrand.pyx":2822 - * return cont2_array(self.internal_state, rk_laplace, size, oloc, oscale) - * - * def gumbel(self, loc=0.0, scale=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * gumbel(loc=0.0, scale=1.0, size=None) - */ - __pyx_t_4 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_102 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2822; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_103 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - - /* "mtrand.pyx":2953 - * return cont2_array(self.internal_state, rk_gumbel, size, oloc, oscale) - * - * def logistic(self, loc=0.0, scale=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * logistic(loc=0.0, scale=1.0, size=None) - */ - __pyx_t_4 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2953; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_106 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2953; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_107 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - - /* "mtrand.pyx":3041 - * return cont2_array(self.internal_state, rk_logistic, size, oloc, oscale) - * - * def lognormal(self, mean=0.0, sigma=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * lognormal(mean=0.0, sigma=1.0, size=None) - */ - __pyx_t_4 = PyFloat_FromDouble(0.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3041; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_110 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_4 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3041; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_111 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - - /* "mtrand.pyx":3162 - * return cont2_array(self.internal_state, rk_lognormal, size, omean, osigma) - * - * def rayleigh(self, scale=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * rayleigh(scale=1.0, size=None) - */ - __pyx_t_4 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_116 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - - /* "mtrand.pyx":3611 - * on, op) - * - * def poisson(self, lam=1.0, size=None): # <<<<<<<<<<<<<< - * """ - * poisson(lam=1.0, size=None) - */ - __pyx_t_4 = PyFloat_FromDouble(1.0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3611; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_k_151 = __pyx_t_4; - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - - /* "mtrand.pyx":4492 - * return arr - * - * _rand = RandomState() # <<<<<<<<<<<<<< - * seed = _rand.seed - * get_state = _rand.get_state - */ - __pyx_t_4 = PyObject_Call(((PyObject *)((PyObject*)__pyx_ptype_6mtrand_RandomState)), ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_d, __pyx_n_s___rand, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4493 - * - * _rand = RandomState() - * seed = _rand.seed # <<<<<<<<<<<<<< - * get_state = _rand.get_state - * set_state = _rand.set_state - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__seed); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__seed, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4494 - * _rand = RandomState() - * seed = _rand.seed - * get_state = _rand.get_state # <<<<<<<<<<<<<< - * set_state = _rand.set_state - * random_sample = _rand.random_sample - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__get_state); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__get_state, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4495 - * seed = _rand.seed - * get_state = _rand.get_state - * set_state = _rand.set_state # <<<<<<<<<<<<<< - * random_sample = _rand.random_sample - * choice = _rand.choice - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__set_state); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__set_state, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4496 - * get_state = _rand.get_state - * set_state = _rand.set_state - * random_sample = _rand.random_sample # <<<<<<<<<<<<<< - * choice = _rand.choice - * randint = _rand.randint - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__random_sample); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__random_sample, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4497 - * set_state = _rand.set_state - * random_sample = _rand.random_sample - * choice = _rand.choice # <<<<<<<<<<<<<< - * randint = _rand.randint - * bytes = _rand.bytes - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__choice); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__choice, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4498 - * random_sample = _rand.random_sample - * choice = _rand.choice - * randint = _rand.randint # <<<<<<<<<<<<<< - * bytes = _rand.bytes - * uniform = _rand.uniform - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4498; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__randint); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4498; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__randint, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4498; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4499 - * choice = _rand.choice - * randint = _rand.randint - * bytes = _rand.bytes # <<<<<<<<<<<<<< - * uniform = _rand.uniform - * rand = _rand.rand - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__bytes); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__bytes, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4500 - * randint = _rand.randint - * bytes = _rand.bytes - * uniform = _rand.uniform # <<<<<<<<<<<<<< - * rand = _rand.rand - * randn = _rand.randn - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4500; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__uniform); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4500; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__uniform, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4500; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4501 - * bytes = _rand.bytes - * uniform = _rand.uniform - * rand = _rand.rand # <<<<<<<<<<<<<< - * randn = _rand.randn - * random_integers = _rand.random_integers - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4501; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4501; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__rand, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4501; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4502 - * uniform = _rand.uniform - * rand = _rand.rand - * randn = _rand.randn # <<<<<<<<<<<<<< - * random_integers = _rand.random_integers - * standard_normal = _rand.standard_normal - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__randn); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__randn, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4503 - * rand = _rand.rand - * randn = _rand.randn - * random_integers = _rand.random_integers # <<<<<<<<<<<<<< - * standard_normal = _rand.standard_normal - * normal = _rand.normal - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__random_integers); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__random_integers, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4504 - * randn = _rand.randn - * random_integers = _rand.random_integers - * standard_normal = _rand.standard_normal # <<<<<<<<<<<<<< - * normal = _rand.normal - * beta = _rand.beta - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4504; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__standard_normal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4504; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__standard_normal, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4504; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4505 - * random_integers = _rand.random_integers - * standard_normal = _rand.standard_normal - * normal = _rand.normal # <<<<<<<<<<<<<< - * beta = _rand.beta - * exponential = _rand.exponential - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4505; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__normal); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4505; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__normal, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4505; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4506 - * standard_normal = _rand.standard_normal - * normal = _rand.normal - * beta = _rand.beta # <<<<<<<<<<<<<< - * exponential = _rand.exponential - * standard_exponential = _rand.standard_exponential - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__beta); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__beta, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4507 - * normal = _rand.normal - * beta = _rand.beta - * exponential = _rand.exponential # <<<<<<<<<<<<<< - * standard_exponential = _rand.standard_exponential - * standard_gamma = _rand.standard_gamma - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4507; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__exponential); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4507; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__exponential, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4507; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4508 - * beta = _rand.beta - * exponential = _rand.exponential - * standard_exponential = _rand.standard_exponential # <<<<<<<<<<<<<< - * standard_gamma = _rand.standard_gamma - * gamma = _rand.gamma - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_199); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s_199, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4509 - * exponential = _rand.exponential - * standard_exponential = _rand.standard_exponential - * standard_gamma = _rand.standard_gamma # <<<<<<<<<<<<<< - * gamma = _rand.gamma - * f = _rand.f - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__standard_gamma); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__standard_gamma, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4510 - * standard_exponential = _rand.standard_exponential - * standard_gamma = _rand.standard_gamma - * gamma = _rand.gamma # <<<<<<<<<<<<<< - * f = _rand.f - * noncentral_f = _rand.noncentral_f - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__gamma); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__gamma, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4511 - * standard_gamma = _rand.standard_gamma - * gamma = _rand.gamma - * f = _rand.f # <<<<<<<<<<<<<< - * noncentral_f = _rand.noncentral_f - * chisquare = _rand.chisquare - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__f); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__f, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4512 - * gamma = _rand.gamma - * f = _rand.f - * noncentral_f = _rand.noncentral_f # <<<<<<<<<<<<<< - * chisquare = _rand.chisquare - * noncentral_chisquare = _rand.noncentral_chisquare - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__noncentral_f); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__noncentral_f, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4513 - * f = _rand.f - * noncentral_f = _rand.noncentral_f - * chisquare = _rand.chisquare # <<<<<<<<<<<<<< - * noncentral_chisquare = _rand.noncentral_chisquare - * standard_cauchy = _rand.standard_cauchy - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__chisquare); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__chisquare, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4514 - * noncentral_f = _rand.noncentral_f - * chisquare = _rand.chisquare - * noncentral_chisquare = _rand.noncentral_chisquare # <<<<<<<<<<<<<< - * standard_cauchy = _rand.standard_cauchy - * standard_t = _rand.standard_t - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_200); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s_200, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4515 - * chisquare = _rand.chisquare - * noncentral_chisquare = _rand.noncentral_chisquare - * standard_cauchy = _rand.standard_cauchy # <<<<<<<<<<<<<< - * standard_t = _rand.standard_t - * vonmises = _rand.vonmises - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4515; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__standard_cauchy); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4515; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__standard_cauchy, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4515; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4516 - * noncentral_chisquare = _rand.noncentral_chisquare - * standard_cauchy = _rand.standard_cauchy - * standard_t = _rand.standard_t # <<<<<<<<<<<<<< - * vonmises = _rand.vonmises - * pareto = _rand.pareto - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4516; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__standard_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4516; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__standard_t, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4516; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4517 - * standard_cauchy = _rand.standard_cauchy - * standard_t = _rand.standard_t - * vonmises = _rand.vonmises # <<<<<<<<<<<<<< - * pareto = _rand.pareto - * weibull = _rand.weibull - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4517; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__vonmises); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4517; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__vonmises, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4517; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4518 - * standard_t = _rand.standard_t - * vonmises = _rand.vonmises - * pareto = _rand.pareto # <<<<<<<<<<<<<< - * weibull = _rand.weibull - * power = _rand.power - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4518; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__pareto); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4518; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__pareto, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4518; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4519 - * vonmises = _rand.vonmises - * pareto = _rand.pareto - * weibull = _rand.weibull # <<<<<<<<<<<<<< - * power = _rand.power - * laplace = _rand.laplace - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__weibull); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__weibull, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4520 - * pareto = _rand.pareto - * weibull = _rand.weibull - * power = _rand.power # <<<<<<<<<<<<<< - * laplace = _rand.laplace - * gumbel = _rand.gumbel - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4520; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__power); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4520; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__power, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4520; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4521 - * weibull = _rand.weibull - * power = _rand.power - * laplace = _rand.laplace # <<<<<<<<<<<<<< - * gumbel = _rand.gumbel - * logistic = _rand.logistic - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__laplace); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__laplace, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4522 - * power = _rand.power - * laplace = _rand.laplace - * gumbel = _rand.gumbel # <<<<<<<<<<<<<< - * logistic = _rand.logistic - * lognormal = _rand.lognormal - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4522; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__gumbel); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4522; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__gumbel, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4522; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4523 - * laplace = _rand.laplace - * gumbel = _rand.gumbel - * logistic = _rand.logistic # <<<<<<<<<<<<<< - * lognormal = _rand.lognormal - * rayleigh = _rand.rayleigh - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__logistic); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__logistic, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4524 - * gumbel = _rand.gumbel - * logistic = _rand.logistic - * lognormal = _rand.lognormal # <<<<<<<<<<<<<< - * rayleigh = _rand.rayleigh - * wald = _rand.wald - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__lognormal); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__lognormal, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4525 - * logistic = _rand.logistic - * lognormal = _rand.lognormal - * rayleigh = _rand.rayleigh # <<<<<<<<<<<<<< - * wald = _rand.wald - * triangular = _rand.triangular - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__rayleigh); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__rayleigh, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4526 - * lognormal = _rand.lognormal - * rayleigh = _rand.rayleigh - * wald = _rand.wald # <<<<<<<<<<<<<< - * triangular = _rand.triangular - * - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__wald); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__wald, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4527 - * rayleigh = _rand.rayleigh - * wald = _rand.wald - * triangular = _rand.triangular # <<<<<<<<<<<<<< - * - * binomial = _rand.binomial - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__triangular); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__triangular, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4529 - * triangular = _rand.triangular - * - * binomial = _rand.binomial # <<<<<<<<<<<<<< - * negative_binomial = _rand.negative_binomial - * poisson = _rand.poisson - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__binomial); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__binomial, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4530 - * - * binomial = _rand.binomial - * negative_binomial = _rand.negative_binomial # <<<<<<<<<<<<<< - * poisson = _rand.poisson - * zipf = _rand.zipf - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__negative_binomial); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__negative_binomial, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4531 - * binomial = _rand.binomial - * negative_binomial = _rand.negative_binomial - * poisson = _rand.poisson # <<<<<<<<<<<<<< - * zipf = _rand.zipf - * geometric = _rand.geometric - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__poisson); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__poisson, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4532 - * negative_binomial = _rand.negative_binomial - * poisson = _rand.poisson - * zipf = _rand.zipf # <<<<<<<<<<<<<< - * geometric = _rand.geometric - * hypergeometric = _rand.hypergeometric - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4532; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__zipf); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4532; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__zipf, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4532; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4533 - * poisson = _rand.poisson - * zipf = _rand.zipf - * geometric = _rand.geometric # <<<<<<<<<<<<<< - * hypergeometric = _rand.hypergeometric - * logseries = _rand.logseries - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4533; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__geometric); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4533; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__geometric, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4533; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4534 - * zipf = _rand.zipf - * geometric = _rand.geometric - * hypergeometric = _rand.hypergeometric # <<<<<<<<<<<<<< - * logseries = _rand.logseries - * - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4534; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__hypergeometric); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4534; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__hypergeometric, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4534; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4535 - * geometric = _rand.geometric - * hypergeometric = _rand.hypergeometric - * logseries = _rand.logseries # <<<<<<<<<<<<<< - * - * multivariate_normal = _rand.multivariate_normal - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__logseries); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__logseries, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4535; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4537 - * logseries = _rand.logseries - * - * multivariate_normal = _rand.multivariate_normal # <<<<<<<<<<<<<< - * multinomial = _rand.multinomial - * dirichlet = _rand.dirichlet - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__multivariate_normal); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__multivariate_normal, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4538 - * - * multivariate_normal = _rand.multivariate_normal - * multinomial = _rand.multinomial # <<<<<<<<<<<<<< - * dirichlet = _rand.dirichlet - * - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__multinomial); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__multinomial, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4539 - * multivariate_normal = _rand.multivariate_normal - * multinomial = _rand.multinomial - * dirichlet = _rand.dirichlet # <<<<<<<<<<<<<< - * - * shuffle = _rand.shuffle - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4539; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__dirichlet); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4539; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__dirichlet, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4539; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":4541 - * dirichlet = _rand.dirichlet - * - * shuffle = _rand.shuffle # <<<<<<<<<<<<<< - * permutation = _rand.permutation - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4541; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s__shuffle); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4541; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__shuffle, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4541; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "mtrand.pyx":4542 - * - * shuffle = _rand.shuffle - * permutation = _rand.permutation # <<<<<<<<<<<<<< - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s___rand); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s__permutation); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (PyDict_SetItem(__pyx_d, __pyx_n_s__permutation, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "mtrand.pyx":1 - * # mtrand.pyx -- A Pyrex wrapper of Jean-Sebastien Roy's RandomKit # <<<<<<<<<<<<<< - * # - * # Copyright 2005 Robert Kern (robert.kern@gmail.com) - */ - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_201), ((PyObject *)__pyx_kp_u_202)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_203), ((PyObject *)__pyx_kp_u_204)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_205), ((PyObject *)__pyx_kp_u_206)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_207), ((PyObject *)__pyx_kp_u_208)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_209), ((PyObject *)__pyx_kp_u_210)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_211), ((PyObject *)__pyx_kp_u_212)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_213), ((PyObject *)__pyx_kp_u_214)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_215), ((PyObject *)__pyx_kp_u_216)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_217), ((PyObject *)__pyx_kp_u_218)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_219), ((PyObject *)__pyx_kp_u_220)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_221), ((PyObject *)__pyx_kp_u_222)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_223), ((PyObject *)__pyx_kp_u_224)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_225), ((PyObject *)__pyx_kp_u_226)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_227), ((PyObject *)__pyx_kp_u_228)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_229), ((PyObject *)__pyx_kp_u_230)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_231), ((PyObject *)__pyx_kp_u_232)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_233), ((PyObject *)__pyx_kp_u_234)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_235), ((PyObject *)__pyx_kp_u_236)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_237), ((PyObject *)__pyx_kp_u_238)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_239), ((PyObject *)__pyx_kp_u_240)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_241), ((PyObject *)__pyx_kp_u_242)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_243), ((PyObject *)__pyx_kp_u_244)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_245), ((PyObject *)__pyx_kp_u_246)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_247), ((PyObject *)__pyx_kp_u_248)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_249), ((PyObject *)__pyx_kp_u_250)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_251), ((PyObject *)__pyx_kp_u_252)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_253), ((PyObject *)__pyx_kp_u_254)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_255), ((PyObject *)__pyx_kp_u_256)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_257), ((PyObject *)__pyx_kp_u_258)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_259), ((PyObject *)__pyx_kp_u_260)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_261), ((PyObject *)__pyx_kp_u_262)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_263), ((PyObject *)__pyx_kp_u_264)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_265), ((PyObject *)__pyx_kp_u_266)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_267), ((PyObject *)__pyx_kp_u_268)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_269), ((PyObject *)__pyx_kp_u_270)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_271), ((PyObject *)__pyx_kp_u_272)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_273), ((PyObject *)__pyx_kp_u_274)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_275), ((PyObject *)__pyx_kp_u_276)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_277), ((PyObject *)__pyx_kp_u_278)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_279), ((PyObject *)__pyx_kp_u_280)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_281), ((PyObject *)__pyx_kp_u_282)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_283), ((PyObject *)__pyx_kp_u_284)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_t_1, ((PyObject *)__pyx_kp_u_285), ((PyObject *)__pyx_kp_u_286)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_d, __pyx_n_s____test__, ((PyObject *)__pyx_t_1)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - if (__pyx_m) { - __Pyx_AddTraceback("init mtrand", __pyx_clineno, __pyx_lineno, __pyx_filename); - Py_DECREF(__pyx_m); __pyx_m = 0; - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init mtrand"); - } - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - #if PY_MAJOR_VERSION < 3 - return; - #else - return __pyx_m; - #endif -} - -/* Runtime support code */ -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule((char *)modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif /* CYTHON_REFNANNY */ - -static PyObject *__Pyx_GetBuiltinName(PyObject *name) { - PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); - if (unlikely(!result)) { - PyErr_Format(PyExc_NameError, -#if PY_MAJOR_VERSION >= 3 - "name '%U' is not defined", name); -#else - "name '%s' is not defined", PyString_AS_STRING(name)); -#endif - } - return result; -} - -static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { - PyObject *result; -#if CYTHON_COMPILING_IN_CPYTHON - result = PyDict_GetItem(__pyx_d, name); - if (result) { - Py_INCREF(result); - } else { -#else - result = PyObject_GetItem(__pyx_d, name); - if (!result) { - PyErr_Clear(); -#endif - result = __Pyx_GetBuiltinName(name); - } - return result; -} - -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { -#if CYTHON_COMPILING_IN_CPYTHON - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_Restore(type, value, tb); -#endif -} -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { -#if CYTHON_COMPILING_IN_CPYTHON - PyThreadState *tstate = PyThreadState_GET(); - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -#else - PyErr_Fetch(type, value, tb); -#endif -} - -#if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, - CYTHON_UNUSED PyObject *cause) { - Py_XINCREF(type); - if (!value || value == Py_None) - value = NULL; - else - Py_INCREF(value); - if (!tb || tb == Py_None) - tb = NULL; - else { - Py_INCREF(tb); - if (!PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - } - #if PY_VERSION_HEX < 0x02050000 - if (PyClass_Check(type)) { - #else - if (PyType_Check(type)) { - #endif -#if CYTHON_COMPILING_IN_PYPY - if (!value) { - Py_INCREF(Py_None); - value = Py_None; - } -#endif - PyErr_NormalizeException(&type, &value, &tb); - } else { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; - } - value = type; - #if PY_VERSION_HEX < 0x02050000 - if (PyInstance_Check(type)) { - type = (PyObject*) ((PyInstanceObject*)type)->in_class; - Py_INCREF(type); - } else { - type = 0; - PyErr_SetString(PyExc_TypeError, - "raise: exception must be an old-style class or instance"); - goto raise_error; - } - #else - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } - #endif - } - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; -} -#else /* Python 3+ */ -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - PyObject* owned_instance = NULL; - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto bad; - } - if (value == Py_None) - value = 0; - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto bad; - } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (PyExceptionClass_Check(type)) { - PyObject *args; - if (!value) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } else - args = PyTuple_Pack(1, value); - if (!args) - goto bad; - owned_instance = PyEval_CallObject(type, args); - Py_DECREF(args); - if (!owned_instance) - goto bad; - value = owned_instance; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, - "calling %R should have returned an instance of " - "BaseException, not %R", - type, Py_TYPE(value)); - goto bad; - } - } else { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; - } -#if PY_VERSION_HEX >= 0x03030000 - if (cause) { -#else - if (cause && cause != Py_None) { -#endif - PyObject *fixed_cause; - if (cause == Py_None) { - fixed_cause = NULL; - } else if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; - } else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); - } else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; - } - PyException_SetCause(value, fixed_cause); - } - PyErr_SetObject(type, value); - if (tb) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } - } -bad: - Py_XDECREF(owned_instance); - return; -} -#endif - -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AsString(kw_name)); - #endif -} - -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - continue; - } - name = first_kw_arg; - #if PY_MAJOR_VERSION < 3 - if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { - while (*name) { - if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) - && _PyString_Eq(**name, key)) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - if ((**argname == key) || ( - (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) - && _PyString_Eq(**argname, key))) { - goto arg_passed_twice; - } - argname++; - } - } - } else - #endif - if (likely(PyUnicode_Check(key))) { - while (*name) { - int cmp = (**name == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : - #endif - PyUnicode_Compare(**name, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - int cmp = (**argname == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : - #endif - PyUnicode_Compare(**argname, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) goto arg_passed_twice; - argname++; - } - } - } else - goto invalid_keyword_type; - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, key); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%s() takes %s %" CYTHON_FORMAT_SSIZE_T "d positional argument%s (%" CYTHON_FORMAT_SSIZE_T "d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck) { -#if CYTHON_COMPILING_IN_CPYTHON - if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); - if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck) { -#if CYTHON_COMPILING_IN_CPYTHON - if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); - if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, - int is_list, int wraparound, int boundscheck) { -#if CYTHON_COMPILING_IN_CPYTHON - if (is_list || PyList_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { - PyObject *r = PyList_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } - else if (PyTuple_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); - if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } else { - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_Clear(); - else - return NULL; - } - } - return m->sq_item(o, i); - } - } -#else - if (is_list || PySequence_Check(o)) { - return PySequence_GetItem(o, i); - } -#endif - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} - -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( - PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, - PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, - int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { -#if CYTHON_COMPILING_IN_CPYTHON - PyMappingMethods* mp; -#if PY_MAJOR_VERSION < 3 - PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; - if (likely(ms && ms->sq_slice)) { - if (!has_cstart) { - if (_py_start && (*_py_start != Py_None)) { - cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); - if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; - } else - cstart = 0; - } - if (!has_cstop) { - if (_py_stop && (*_py_stop != Py_None)) { - cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); - if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; - } else - cstop = PY_SSIZE_T_MAX; - } - if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { - Py_ssize_t l = ms->sq_length(obj); - if (likely(l >= 0)) { - if (cstop < 0) { - cstop += l; - if (cstop < 0) cstop = 0; - } - if (cstart < 0) { - cstart += l; - if (cstart < 0) cstart = 0; - } - } else { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_Clear(); - else - goto bad; - } - } - return ms->sq_slice(obj, cstart, cstop); - } -#endif - mp = Py_TYPE(obj)->tp_as_mapping; - if (likely(mp && mp->mp_subscript)) -#endif - { - PyObject* result; - PyObject *py_slice, *py_start, *py_stop; - if (_py_slice) { - py_slice = *_py_slice; - } else { - PyObject* owned_start = NULL; - PyObject* owned_stop = NULL; - if (_py_start) { - py_start = *_py_start; - } else { - if (has_cstart) { - owned_start = py_start = PyInt_FromSsize_t(cstart); - if (unlikely(!py_start)) goto bad; - } else - py_start = Py_None; - } - if (_py_stop) { - py_stop = *_py_stop; - } else { - if (has_cstop) { - owned_stop = py_stop = PyInt_FromSsize_t(cstop); - if (unlikely(!py_stop)) { - Py_XDECREF(owned_start); - goto bad; - } - } else - py_stop = Py_None; - } - py_slice = PySlice_New(py_start, py_stop, Py_None); - Py_XDECREF(owned_start); - Py_XDECREF(owned_stop); - if (unlikely(!py_slice)) goto bad; - } -#if CYTHON_COMPILING_IN_CPYTHON - result = mp->mp_subscript(obj, py_slice); -#else - result = PyObject_GetItem(obj, py_slice); -#endif - if (!_py_slice) { - Py_DECREF(py_slice); - } - return result; - } - PyErr_Format(PyExc_TypeError, - "'%.200s' object is unsliceable", Py_TYPE(obj)->tp_name); -bad: - return NULL; -} - -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); -} - -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %" CYTHON_FORMAT_SSIZE_T "d value%s to unpack", - index, (index == 1) ? "" : "s"); -} - -static CYTHON_INLINE int __Pyx_IterFinish(void) { -#if CYTHON_COMPILING_IN_CPYTHON - PyThreadState *tstate = PyThreadState_GET(); - PyObject* exc_type = tstate->curexc_type; - if (unlikely(exc_type)) { - if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { - PyObject *exc_value, *exc_tb; - exc_value = tstate->curexc_value; - exc_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; - Py_DECREF(exc_type); - Py_XDECREF(exc_value); - Py_XDECREF(exc_tb); - return 0; - } else { - return -1; - } - } - return 0; -#else - if (unlikely(PyErr_Occurred())) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { - PyErr_Clear(); - return 0; - } else { - return -1; - } - } - return 0; -#endif -} - -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { - if (unlikely(retval)) { - Py_DECREF(retval); - __Pyx_RaiseTooManyValuesError(expected); - return -1; - } else { - return __Pyx_IterFinish(); - } - return 0; -} - -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { - PyObject *local_type, *local_value, *local_tb; -#if CYTHON_COMPILING_IN_CPYTHON - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyThreadState *tstate = PyThreadState_GET(); - local_type = tstate->curexc_type; - local_value = tstate->curexc_value; - local_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -#else - PyErr_Fetch(&local_type, &local_value, &local_tb); -#endif - PyErr_NormalizeException(&local_type, &local_value, &local_tb); -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(tstate->curexc_type)) -#else - if (unlikely(PyErr_Occurred())) -#endif - goto bad; - #if PY_MAJOR_VERSION >= 3 - if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) - goto bad; - #endif - Py_INCREF(local_type); - Py_INCREF(local_value); - Py_INCREF(local_tb); - *type = local_type; - *value = local_value; - *tb = local_tb; -#if CYTHON_COMPILING_IN_CPYTHON - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = local_type; - tstate->exc_value = local_value; - tstate->exc_traceback = local_tb; - /* Make sure tstate is in a consistent state when we XDECREF - these objects (DECREF may run arbitrary code). */ - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_SetExcInfo(local_type, local_value, local_tb); -#endif - return 0; -bad: - *type = 0; - *value = 0; - *tb = 0; - Py_XDECREF(local_type); - Py_XDECREF(local_value); - Py_XDECREF(local_tb); - return -1; -} - -static CYTHON_INLINE int __Pyx_PyObject_SetSlice( - PyObject* obj, PyObject* value, Py_ssize_t cstart, Py_ssize_t cstop, - PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, - int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { -#if CYTHON_COMPILING_IN_CPYTHON - PyMappingMethods* mp; -#if PY_MAJOR_VERSION < 3 - PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; - if (likely(ms && ms->sq_ass_slice)) { - if (!has_cstart) { - if (_py_start && (*_py_start != Py_None)) { - cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); - if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; - } else - cstart = 0; - } - if (!has_cstop) { - if (_py_stop && (*_py_stop != Py_None)) { - cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); - if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; - } else - cstop = PY_SSIZE_T_MAX; - } - if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { - Py_ssize_t l = ms->sq_length(obj); - if (likely(l >= 0)) { - if (cstop < 0) { - cstop += l; - if (cstop < 0) cstop = 0; - } - if (cstart < 0) { - cstart += l; - if (cstart < 0) cstart = 0; - } - } else { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_Clear(); - else - goto bad; - } - } - return ms->sq_ass_slice(obj, cstart, cstop, value); - } -#endif - mp = Py_TYPE(obj)->tp_as_mapping; - if (likely(mp && mp->mp_ass_subscript)) -#endif - { - int result; - PyObject *py_slice, *py_start, *py_stop; - if (_py_slice) { - py_slice = *_py_slice; - } else { - PyObject* owned_start = NULL; - PyObject* owned_stop = NULL; - if (_py_start) { - py_start = *_py_start; - } else { - if (has_cstart) { - owned_start = py_start = PyInt_FromSsize_t(cstart); - if (unlikely(!py_start)) goto bad; - } else - py_start = Py_None; - } - if (_py_stop) { - py_stop = *_py_stop; - } else { - if (has_cstop) { - owned_stop = py_stop = PyInt_FromSsize_t(cstop); - if (unlikely(!py_stop)) { - Py_XDECREF(owned_start); - goto bad; - } - } else - py_stop = Py_None; - } - py_slice = PySlice_New(py_start, py_stop, Py_None); - Py_XDECREF(owned_start); - Py_XDECREF(owned_stop); - if (unlikely(!py_slice)) goto bad; - } -#if CYTHON_COMPILING_IN_CPYTHON - result = mp->mp_ass_subscript(obj, py_slice, value); -#else - result = value ? PyObject_SetItem(obj, py_slice, value) : PyObject_DelItem(obj, py_slice); -#endif - if (!_py_slice) { - Py_DECREF(py_slice); - } - return result; - } - PyErr_Format(PyExc_TypeError, - "'%.200s' object does not support slice %s", - Py_TYPE(obj)->tp_name, value ? "assignment" : "deletion"); -bad: - return -1; -} - -static CYTHON_INLINE int __Pyx_CheckKeywordStrings( - PyObject *kwdict, - const char* function_name, - int kw_allowed) -{ - PyObject* key = 0; - Py_ssize_t pos = 0; -#if CPYTHON_COMPILING_IN_PYPY - if (!kw_allowed && PyDict_Next(kwdict, &pos, &key, 0)) - goto invalid_keyword; - return 1; -#else - while (PyDict_Next(kwdict, &pos, &key, 0)) { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) - #endif - if (unlikely(!PyUnicode_Check(key))) - goto invalid_keyword_type; - } - if ((!kw_allowed) && unlikely(key)) - goto invalid_keyword; - return 1; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%s() keywords must be strings", function_name); - return 0; -#endif -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%s() got an unexpected keyword argument '%s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif - return 0; -} - -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_Format(PyExc_SystemError, "Missing type object"); - return 0; - } - if (likely(PyObject_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; -} - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE void __Pyx_crop_slice(Py_ssize_t* _start, Py_ssize_t* _stop, Py_ssize_t* _length) { - Py_ssize_t start = *_start, stop = *_stop, length = *_length; - if (start < 0) { - start += length; - if (start < 0) - start = 0; - } - if (stop < 0) - stop += length; - else if (stop > length) - stop = length; - *_length = stop - start; - *_start = start; - *_stop = stop; -} -#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L -static CYTHON_INLINE void __Pyx_copy_object_array(PyObject** restrict src, PyObject** restrict dest, Py_ssize_t length) { -#else -static CYTHON_INLINE void __Pyx_copy_object_array(PyObject** src, PyObject** dest, Py_ssize_t length) { -#endif - PyObject *v; - Py_ssize_t i; - for (i = 0; i < length; i++) { - v = dest[i] = src[i]; - Py_INCREF(v); - } -} -static CYTHON_INLINE PyObject* __Pyx_PyList_GetSlice( - PyObject* src, Py_ssize_t start, Py_ssize_t stop) { - PyObject* dest; - Py_ssize_t length = PyList_GET_SIZE(src); - __Pyx_crop_slice(&start, &stop, &length); - if (unlikely(length <= 0)) - return PyList_New(0); - dest = PyList_New(length); - if (unlikely(!dest)) - return NULL; - __Pyx_copy_object_array( - ((PyListObject*)src)->ob_item + start, - ((PyListObject*)dest)->ob_item, - length); - return dest; -} -static CYTHON_INLINE PyObject* __Pyx_PyTuple_GetSlice( - PyObject* src, Py_ssize_t start, Py_ssize_t stop) { - PyObject* dest; - Py_ssize_t length = PyTuple_GET_SIZE(src); - __Pyx_crop_slice(&start, &stop, &length); - if (unlikely(length <= 0)) - return PyTuple_New(0); - dest = PyTuple_New(length); - if (unlikely(!dest)) - return NULL; - __Pyx_copy_object_array( - ((PyTupleObject*)src)->ob_item + start, - ((PyTupleObject*)dest)->ob_item, - length); - return dest; -} -#endif - -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { - PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); - if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_ImportError, - #if PY_MAJOR_VERSION < 3 - "cannot import name %.230s", PyString_AS_STRING(name)); - #else - "cannot import name %S", name); - #endif - } - return value; -} - -static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { - int r; - if (!j) return -1; - r = PyObject_SetItem(o, j, v); - Py_DECREF(j); - return r; -} -static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, - int is_list, int wraparound, int boundscheck) { -#if CYTHON_COMPILING_IN_CPYTHON - if (is_list || PyList_CheckExact(o)) { - Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); - if ((!boundscheck) || likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { - PyObject* old = PyList_GET_ITEM(o, n); - Py_INCREF(v); - PyList_SET_ITEM(o, n, v); - Py_DECREF(old); - return 1; - } - } else { - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_ass_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_Clear(); - else - return -1; - } - } - return m->sq_ass_item(o, i, v); - } - } -#else -#if CYTHON_COMPILING_IN_PYPY - if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) { -#else - if (is_list || PySequence_Check(o)) { -#endif - return PySequence_SetItem(o, i, v); - } -#endif - return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); -} - -static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { -#if CYTHON_COMPILING_IN_CPYTHON - PyThreadState *tstate = PyThreadState_GET(); - *type = tstate->exc_type; - *value = tstate->exc_value; - *tb = tstate->exc_traceback; - Py_XINCREF(*type); - Py_XINCREF(*value); - Py_XINCREF(*tb); -#else - PyErr_GetExcInfo(type, value, tb); -#endif -} -static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { -#if CYTHON_COMPILING_IN_CPYTHON - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = type; - tstate->exc_value = value; - tstate->exc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_SetExcInfo(type, value, tb); -#endif -} - -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - #if PY_VERSION_HEX < 0x03030000 - PyObject *py_import; - py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s____import__); - if (!py_import) - goto bad; - #endif - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; - } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - #if PY_VERSION_HEX >= 0x02050000 - { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { - if (strchr(__Pyx_MODULE_NAME, '.')) { - #if PY_VERSION_HEX < 0x03030000 - PyObject *py_level = PyInt_FromLong(1); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, 1); - #endif - if (!module) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - goto bad; - PyErr_Clear(); - } - } - level = 0; /* try absolute import on failure */ - } - #endif - if (!module) { - #if PY_VERSION_HEX < 0x03030000 - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, level); - #endif - } - } - #else - if (level>0) { - PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4."); - goto bad; - } - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, NULL); - #endif -bad: - #if PY_VERSION_HEX < 0x03030000 - Py_XDECREF(py_import); - #endif - Py_XDECREF(empty_list); - Py_XDECREF(empty_dict); - return module; -} - -static CYTHON_INLINE npy_intp __Pyx_PyInt_from_py_npy_intp(PyObject* x) { - const npy_intp neg_one = (npy_intp)-1, const_zero = (npy_intp)0; - const int is_unsigned = const_zero < neg_one; - if (sizeof(npy_intp) == sizeof(char)) { - if (is_unsigned) - return (npy_intp)__Pyx_PyInt_AsUnsignedChar(x); - else - return (npy_intp)__Pyx_PyInt_AsSignedChar(x); - } else if (sizeof(npy_intp) == sizeof(short)) { - if (is_unsigned) - return (npy_intp)__Pyx_PyInt_AsUnsignedShort(x); - else - return (npy_intp)__Pyx_PyInt_AsSignedShort(x); - } else if (sizeof(npy_intp) == sizeof(int)) { - if (is_unsigned) - return (npy_intp)__Pyx_PyInt_AsUnsignedInt(x); - else - return (npy_intp)__Pyx_PyInt_AsSignedInt(x); - } else if (sizeof(npy_intp) == sizeof(long)) { - if (is_unsigned) - return (npy_intp)__Pyx_PyInt_AsUnsignedLong(x); - else - return (npy_intp)__Pyx_PyInt_AsSignedLong(x); - } else if (sizeof(npy_intp) == sizeof(PY_LONG_LONG)) { - if (is_unsigned) - return (npy_intp)__Pyx_PyInt_AsUnsignedLongLong(x); - else - return (npy_intp)__Pyx_PyInt_AsSignedLongLong(x); - } else { - #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); - #else - npy_intp val; - PyObject *v = __Pyx_PyNumber_Int(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } - #endif - return (npy_intp)-1; - } -} - -static CYTHON_INLINE PyObject *__Pyx_PyInt_to_py_npy_intp(npy_intp val) { - const npy_intp neg_one = (npy_intp)-1, const_zero = (npy_intp)0; - const int is_unsigned = const_zero < neg_one; - if ((sizeof(npy_intp) == sizeof(char)) || - (sizeof(npy_intp) == sizeof(short))) { - return PyInt_FromLong((long)val); - } else if ((sizeof(npy_intp) == sizeof(int)) || - (sizeof(npy_intp) == sizeof(long))) { - if (is_unsigned) - return PyLong_FromUnsignedLong((unsigned long)val); - else - return PyInt_FromLong((long)val); - } else if (sizeof(npy_intp) == sizeof(PY_LONG_LONG)) { - if (is_unsigned) - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)val); - else - return PyLong_FromLongLong((PY_LONG_LONG)val); - } else { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - return _PyLong_FromByteArray(bytes, sizeof(npy_intp), - little, !is_unsigned); - } -} - -static CYTHON_INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) { - const unsigned char neg_one = (unsigned char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned char" : - "value too large to convert to unsigned char"); - } - return (unsigned char)-1; - } - return (unsigned char)val; - } - return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) { - const unsigned short neg_one = (unsigned short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned short" : - "value too large to convert to unsigned short"); - } - return (unsigned short)-1; - } - return (unsigned short)val; - } - return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) { - const unsigned int neg_one = (unsigned int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(unsigned int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(unsigned int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to unsigned int" : - "value too large to convert to unsigned int"); - } - return (unsigned int)-1; - } - return (unsigned int)val; - } - return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x); -} - -static CYTHON_INLINE char __Pyx_PyInt_AsChar(PyObject* x) { - const char neg_one = (char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to char" : - "value too large to convert to char"); - } - return (char)-1; - } - return (char)val; - } - return (char)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE short __Pyx_PyInt_AsShort(PyObject* x) { - const short neg_one = (short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to short" : - "value too large to convert to short"); - } - return (short)-1; - } - return (short)val; - } - return (short)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsInt(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -static CYTHON_INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) { - const signed char neg_one = (signed char)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed char) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed char)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed char" : - "value too large to convert to signed char"); - } - return (signed char)-1; - } - return (signed char)val; - } - return (signed char)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) { - const signed short neg_one = (signed short)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed short) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed short)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed short" : - "value too large to convert to signed short"); - } - return (signed short)-1; - } - return (signed short)val; - } - return (signed short)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) { - const signed int neg_one = (signed int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(signed int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(signed int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to signed int" : - "value too large to convert to signed int"); - } - return (signed int)-1; - } - return (signed int)val; - } - return (signed int)__Pyx_PyInt_AsSignedLong(x); -} - -static CYTHON_INLINE int __Pyx_PyInt_AsLongDouble(PyObject* x) { - const int neg_one = (int)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (sizeof(int) < sizeof(long)) { - long val = __Pyx_PyInt_AsLong(x); - if (unlikely(val != (long)(int)val)) { - if (!unlikely(val == -1 && PyErr_Occurred())) { - PyErr_SetString(PyExc_OverflowError, - (is_unsigned && unlikely(val < 0)) ? - "can't convert negative value to int" : - "value too large to convert to int"); - } - return (int)-1; - } - return (int)val; - } - return (int)__Pyx_PyInt_AsLong(x); -} - -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS -#include "longintrepr.h" -#endif -#endif -static CYTHON_INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) { - const unsigned long neg_one = (unsigned long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS - if (sizeof(digit) <= sizeof(unsigned long)) { - switch (Py_SIZE(x)) { - case 0: return 0; - case 1: return (unsigned long) ((PyLongObject*)x)->ob_digit[0]; - } - } -#endif -#endif - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long)-1; - } - return (unsigned long)PyLong_AsUnsignedLong(x); - } else { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS - if (sizeof(digit) <= sizeof(unsigned long)) { - switch (Py_SIZE(x)) { - case 0: return 0; - case 1: return +(unsigned long) ((PyLongObject*)x)->ob_digit[0]; - case -1: return -(unsigned long) ((PyLongObject*)x)->ob_digit[0]; - } - } -#endif -#endif - return (unsigned long)PyLong_AsLong(x); - } - } else { - unsigned long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned long)-1; - val = __Pyx_PyInt_AsUnsignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS -#include "longintrepr.h" -#endif -#endif -static CYTHON_INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) { - const unsigned PY_LONG_LONG neg_one = (unsigned PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS - if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { - switch (Py_SIZE(x)) { - case 0: return 0; - case 1: return (unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; - } - } -#endif -#endif - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned PY_LONG_LONG"); - return (unsigned PY_LONG_LONG)-1; - } - return (unsigned PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS - if (sizeof(digit) <= sizeof(unsigned PY_LONG_LONG)) { - switch (Py_SIZE(x)) { - case 0: return 0; - case 1: return +(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; - case -1: return -(unsigned PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; - } - } -#endif -#endif - return (unsigned PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - unsigned PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (unsigned PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsUnsignedLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS -#include "longintrepr.h" -#endif -#endif -static CYTHON_INLINE long __Pyx_PyInt_AsLong(PyObject* x) { - const long neg_one = (long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; - } - return (long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS - if (sizeof(digit) <= sizeof(long)) { - switch (Py_SIZE(x)) { - case 0: return 0; - case 1: return (long) ((PyLongObject*)x)->ob_digit[0]; - } - } -#endif -#endif - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long)-1; - } - return (long)PyLong_AsUnsignedLong(x); - } else { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS - if (sizeof(digit) <= sizeof(long)) { - switch (Py_SIZE(x)) { - case 0: return 0; - case 1: return +(long) ((PyLongObject*)x)->ob_digit[0]; - case -1: return -(long) ((PyLongObject*)x)->ob_digit[0]; - } - } -#endif -#endif - return (long)PyLong_AsLong(x); - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (long)-1; - val = __Pyx_PyInt_AsLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS -#include "longintrepr.h" -#endif -#endif -static CYTHON_INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) { - const PY_LONG_LONG neg_one = (PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; - } - return (PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS - if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { - switch (Py_SIZE(x)) { - case 0: return 0; - case 1: return (PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; - } - } -#endif -#endif - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to PY_LONG_LONG"); - return (PY_LONG_LONG)-1; - } - return (PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS - if (sizeof(digit) <= sizeof(PY_LONG_LONG)) { - switch (Py_SIZE(x)) { - case 0: return 0; - case 1: return +(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; - case -1: return -(PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; - } - } -#endif -#endif - return (PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS -#include "longintrepr.h" -#endif -#endif -static CYTHON_INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) { - const signed long neg_one = (signed long)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; - } - return (signed long)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS - if (sizeof(digit) <= sizeof(signed long)) { - switch (Py_SIZE(x)) { - case 0: return 0; - case 1: return (signed long) ((PyLongObject*)x)->ob_digit[0]; - } - } -#endif -#endif - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed long"); - return (signed long)-1; - } - return (signed long)PyLong_AsUnsignedLong(x); - } else { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS - if (sizeof(digit) <= sizeof(signed long)) { - switch (Py_SIZE(x)) { - case 0: return 0; - case 1: return +(signed long) ((PyLongObject*)x)->ob_digit[0]; - case -1: return -(signed long) ((PyLongObject*)x)->ob_digit[0]; - } - } -#endif -#endif - return (signed long)PyLong_AsLong(x); - } - } else { - signed long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed long)-1; - val = __Pyx_PyInt_AsSignedLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS -#include "longintrepr.h" -#endif -#endif -static CYTHON_INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) { - const signed PY_LONG_LONG neg_one = (signed PY_LONG_LONG)-1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; - } - return (signed PY_LONG_LONG)val; - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS - if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { - switch (Py_SIZE(x)) { - case 0: return 0; - case 1: return (signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; - } - } -#endif -#endif - if (unlikely(Py_SIZE(x) < 0)) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to signed PY_LONG_LONG"); - return (signed PY_LONG_LONG)-1; - } - return (signed PY_LONG_LONG)PyLong_AsUnsignedLongLong(x); - } else { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 -#if CYTHON_USE_PYLONG_INTERNALS - if (sizeof(digit) <= sizeof(signed PY_LONG_LONG)) { - switch (Py_SIZE(x)) { - case 0: return 0; - case 1: return +(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; - case -1: return -(signed PY_LONG_LONG) ((PyLongObject*)x)->ob_digit[0]; - } - } -#endif -#endif - return (signed PY_LONG_LONG)PyLong_AsLongLong(x); - } - } else { - signed PY_LONG_LONG val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (signed PY_LONG_LONG)-1; - val = __Pyx_PyInt_AsSignedLongLong(tmp); - Py_DECREF(tmp); - return val; - } -} - -static int __Pyx_check_binary_version(void) { - char ctversion[4], rtversion[4]; - PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); - PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); - if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { - char message[200]; - PyOS_snprintf(message, sizeof(message), - "compiletime version %s of module '%.100s' " - "does not match runtime version %s", - ctversion, __Pyx_MODULE_NAME, rtversion); - #if PY_VERSION_HEX < 0x02050000 - return PyErr_Warn(NULL, message); - #else - return PyErr_WarnEx(NULL, message, 1); - #endif - } - return 0; -} - -#ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - py_name = __Pyx_PyIdentifier_FromString(name); - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; -} -#endif - -#ifndef __PYX_HAVE_RT_ImportType -#define __PYX_HAVE_RT_ImportType -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, - size_t size, int strict) -{ - PyObject *py_module = 0; - PyObject *result = 0; - PyObject *py_name = 0; - char warning[200]; - Py_ssize_t basicsize; -#ifdef Py_LIMITED_API - PyObject *py_basicsize; -#endif - py_module = __Pyx_ImportModule(module_name); - if (!py_module) - goto bad; - py_name = __Pyx_PyIdentifier_FromString(class_name); - if (!py_name) - goto bad; - result = PyObject_GetAttr(py_module, py_name); - Py_DECREF(py_name); - py_name = 0; - Py_DECREF(py_module); - py_module = 0; - if (!result) - goto bad; - if (!PyType_Check(result)) { - PyErr_Format(PyExc_TypeError, - "%s.%s is not a type object", - module_name, class_name); - goto bad; - } -#ifndef Py_LIMITED_API - basicsize = ((PyTypeObject *)result)->tp_basicsize; -#else - py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); - if (!py_basicsize) - goto bad; - basicsize = PyLong_AsSsize_t(py_basicsize); - Py_DECREF(py_basicsize); - py_basicsize = 0; - if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) - goto bad; -#endif - if (!strict && (size_t)basicsize > size) { - PyOS_snprintf(warning, sizeof(warning), - "%s.%s size changed, may indicate binary incompatibility", - module_name, class_name); - #if PY_VERSION_HEX < 0x02050000 - if (PyErr_Warn(NULL, warning) < 0) goto bad; - #else - if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; - #endif - } - else if ((size_t)basicsize != size) { - PyErr_Format(PyExc_ValueError, - "%s.%s has the wrong size, try recompiling", - module_name, class_name); - goto bad; - } - return (PyTypeObject *)result; -bad: - Py_XDECREF(py_module); - Py_XDECREF(result); - return NULL; -} -#endif - -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; - } - while (start < end) { - mid = (start + end) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } - } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; - } -} -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { - return NULL; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { - return NULL; - } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; -} -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); - } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( - __pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; - } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(filename); - #else - py_srcfile = PyUnicode_FromString(filename); - #endif - if (!py_srcfile) goto bad; - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_code = __Pyx_PyCode_New( - 0, /*int argcount,*/ - 0, /*int kwonlyargcount,*/ - 0, /*int nlocals,*/ - 0, /*int stacksize,*/ - 0, /*int flags,*/ - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, /*int firstlineno,*/ - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); - Py_DECREF(py_funcname); - return py_code; -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - return NULL; -} -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_globals = 0; - PyFrameObject *py_frame = 0; - py_code = __pyx_find_code_object(c_line ? c_line : py_line); - if (!py_code) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; - __pyx_insert_code_object(c_line ? c_line : py_line, py_code); - } - py_globals = PyModule_GetDict(__pyx_m); - if (!py_globals) goto bad; - py_frame = PyFrame_New( - PyThreadState_GET(), /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - py_globals, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - py_frame->f_lineno = py_line; - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { - while (t->p) { - #if PY_MAJOR_VERSION < 3 - if (t->is_unicode) { - *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); - } else if (t->intern) { - *t->p = PyString_InternFromString(t->s); - } else { - *t->p = PyString_FromStringAndSize(t->s, t->n - 1); - } - #else /* Python 3+ has unicode identifiers */ - if (t->is_unicode | t->is_str) { - if (t->intern) { - *t->p = PyUnicode_InternFromString(t->s); - } else if (t->encoding) { - *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); - } else { - *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); - } - } else { - *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); - } - #endif - if (!*t->p) - return -1; - ++t; - } - return 0; -} - -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) { - return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str)); -} -static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { - Py_ssize_t ignore; - return __Pyx_PyObject_AsStringAndSize(o, &ignore); -} -static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT - if ( -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - __Pyx_sys_getdefaultencoding_not_ascii && -#endif - PyUnicode_Check(o)) { -#if PY_VERSION_HEX < 0x03030000 - char* defenc_c; - PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); - if (!defenc) return NULL; - defenc_c = PyBytes_AS_STRING(defenc); -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - { - char* end = defenc_c + PyBytes_GET_SIZE(defenc); - char* c; - for (c = defenc_c; c < end; c++) { - if ((unsigned char) (*c) >= 128) { - PyUnicode_AsASCIIString(o); - return NULL; - } - } - } -#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/ - *length = PyBytes_GET_SIZE(defenc); - return defenc_c; -#else /* PY_VERSION_HEX < 0x03030000 */ - if (PyUnicode_READY(o) == -1) return NULL; -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - if (PyUnicode_IS_ASCII(o)) { - *length = PyUnicode_GET_DATA_SIZE(o); - return PyUnicode_AsUTF8(o); - } else { - PyUnicode_AsASCIIString(o); - return NULL; - } -#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ - return PyUnicode_AsUTF8AndSize(o, length); -#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */ -#endif /* PY_VERSION_HEX < 0x03030000 */ - } else -#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */ - { - char* result; - int r = PyBytes_AsStringAndSize(o, &result, length); - if (r < 0) { - return NULL; - } else { - return result; - } - } -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { - int is_true = x == Py_True; - if (is_true | (x == Py_False) | (x == Py_None)) return is_true; - else return PyObject_IsTrue(x); -} -static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { - PyNumberMethods *m; - const char *name = NULL; - PyObject *res = NULL; -#if PY_MAJOR_VERSION < 3 - if (PyInt_Check(x) || PyLong_Check(x)) -#else - if (PyLong_Check(x)) -#endif - return Py_INCREF(x), x; - m = Py_TYPE(x)->tp_as_number; -#if PY_MAJOR_VERSION < 3 - if (m && m->nb_int) { - name = "int"; - res = PyNumber_Int(x); - } - else if (m && m->nb_long) { - name = "long"; - res = PyNumber_Long(x); - } -#else - if (m && m->nb_int) { - name = "int"; - res = PyNumber_Long(x); - } -#endif - if (res) { -#if PY_MAJOR_VERSION < 3 - if (!PyInt_Check(res) && !PyLong_Check(res)) { -#else - if (!PyLong_Check(res)) { -#endif - PyErr_Format(PyExc_TypeError, - "__%s__ returned non-%s (type %.200s)", - name, name, Py_TYPE(res)->tp_name); - Py_DECREF(res); - return NULL; - } - } - else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - } - return res; -} -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { - Py_ssize_t ival; - PyObject* x = PyNumber_Index(b); - if (!x) return -1; - ival = PyInt_AsSsize_t(x); - Py_DECREF(x); - return ival; -} -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { -#if PY_VERSION_HEX < 0x02050000 - if (ival <= LONG_MAX) - return PyInt_FromLong((long)ival); - else { - unsigned char *bytes = (unsigned char *) &ival; - int one = 1; int little = (int)*(unsigned char*)&one; - return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0); - } -#else - return PyInt_FromSize_t(ival); -#endif -} -static CYTHON_INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) { - unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x); - if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) { - if ((val != (unsigned PY_LONG_LONG)-1) || !PyErr_Occurred()) - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); - return (size_t)-1; - } - return (size_t)val; -} - - -#endif /* Py_PYTHON_H */ diff --git a/numpy/random/mtrand/mtrand.pyx b/numpy/random/mtrand/mtrand.pyx index 84b52079d..55138cba7 100644 --- a/numpy/random/mtrand/mtrand.pyx +++ b/numpy/random/mtrand/mtrand.pyx @@ -55,65 +55,66 @@ cdef extern from "randomkit.h": void rk_seed(unsigned long seed, rk_state *state) rk_error rk_randomseed(rk_state *state) unsigned long rk_random(rk_state *state) - long rk_long(rk_state *state) - unsigned long rk_ulong(rk_state *state) - unsigned long rk_interval(unsigned long max, rk_state *state) - double rk_double(rk_state *state) - void rk_fill(void *buffer, size_t size, rk_state *state) + long rk_long(rk_state *state) nogil + unsigned long rk_ulong(rk_state *state) nogil + unsigned long rk_interval(unsigned long max, rk_state *state) nogil + double rk_double(rk_state *state) nogil + void rk_fill(void *buffer, size_t size, rk_state *state) nogil rk_error rk_devfill(void *buffer, size_t size, int strong) rk_error rk_altfill(void *buffer, size_t size, int strong, - rk_state *state) - double rk_gauss(rk_state *state) + rk_state *state) nogil + double rk_gauss(rk_state *state) nogil cdef extern from "distributions.h": - - double rk_normal(rk_state *state, double loc, double scale) - double rk_standard_exponential(rk_state *state) - double rk_exponential(rk_state *state, double scale) - double rk_uniform(rk_state *state, double loc, double scale) - double rk_standard_gamma(rk_state *state, double shape) - double rk_gamma(rk_state *state, double shape, double scale) - double rk_beta(rk_state *state, double a, double b) - double rk_chisquare(rk_state *state, double df) - double rk_noncentral_chisquare(rk_state *state, double df, double nonc) - double rk_f(rk_state *state, double dfnum, double dfden) - double rk_noncentral_f(rk_state *state, double dfnum, double dfden, double nonc) - double rk_standard_cauchy(rk_state *state) - double rk_standard_t(rk_state *state, double df) - double rk_vonmises(rk_state *state, double mu, double kappa) - double rk_pareto(rk_state *state, double a) - double rk_weibull(rk_state *state, double a) - double rk_power(rk_state *state, double a) - double rk_laplace(rk_state *state, double loc, double scale) - double rk_gumbel(rk_state *state, double loc, double scale) - double rk_logistic(rk_state *state, double loc, double scale) - double rk_lognormal(rk_state *state, double mode, double sigma) - double rk_rayleigh(rk_state *state, double mode) - double rk_wald(rk_state *state, double mean, double scale) - double rk_triangular(rk_state *state, double left, double mode, double right) - - long rk_binomial(rk_state *state, long n, double p) - long rk_binomial_btpe(rk_state *state, long n, double p) - long rk_binomial_inversion(rk_state *state, long n, double p) - long rk_negative_binomial(rk_state *state, double n, double p) - long rk_poisson(rk_state *state, double lam) - long rk_poisson_mult(rk_state *state, double lam) - long rk_poisson_ptrs(rk_state *state, double lam) - long rk_zipf(rk_state *state, double a) - long rk_geometric(rk_state *state, double p) - long rk_hypergeometric(rk_state *state, long good, long bad, long sample) - long rk_logseries(rk_state *state, double p) - -ctypedef double (* rk_cont0)(rk_state *state) -ctypedef double (* rk_cont1)(rk_state *state, double a) -ctypedef double (* rk_cont2)(rk_state *state, double a, double b) -ctypedef double (* rk_cont3)(rk_state *state, double a, double b, double c) - -ctypedef long (* rk_disc0)(rk_state *state) -ctypedef long (* rk_discnp)(rk_state *state, long n, double p) -ctypedef long (* rk_discdd)(rk_state *state, double n, double p) -ctypedef long (* rk_discnmN)(rk_state *state, long n, long m, long N) -ctypedef long (* rk_discd)(rk_state *state, double a) + # do not need the GIL, but they do need a lock on the state !! */ + + double rk_normal(rk_state *state, double loc, double scale) nogil + double rk_standard_exponential(rk_state *state) nogil + double rk_exponential(rk_state *state, double scale) nogil + double rk_uniform(rk_state *state, double loc, double scale) nogil + double rk_standard_gamma(rk_state *state, double shape) nogil + double rk_gamma(rk_state *state, double shape, double scale) nogil + double rk_beta(rk_state *state, double a, double b) nogil + double rk_chisquare(rk_state *state, double df) nogil + double rk_noncentral_chisquare(rk_state *state, double df, double nonc) nogil + double rk_f(rk_state *state, double dfnum, double dfden) nogil + double rk_noncentral_f(rk_state *state, double dfnum, double dfden, double nonc) nogil + double rk_standard_cauchy(rk_state *state) nogil + double rk_standard_t(rk_state *state, double df) nogil + double rk_vonmises(rk_state *state, double mu, double kappa) nogil + double rk_pareto(rk_state *state, double a) nogil + double rk_weibull(rk_state *state, double a) nogil + double rk_power(rk_state *state, double a) nogil + double rk_laplace(rk_state *state, double loc, double scale) nogil + double rk_gumbel(rk_state *state, double loc, double scale) nogil + double rk_logistic(rk_state *state, double loc, double scale) nogil + double rk_lognormal(rk_state *state, double mode, double sigma) nogil + double rk_rayleigh(rk_state *state, double mode) nogil + double rk_wald(rk_state *state, double mean, double scale) nogil + double rk_triangular(rk_state *state, double left, double mode, double right) nogil + + long rk_binomial(rk_state *state, long n, double p) nogil + long rk_binomial_btpe(rk_state *state, long n, double p) nogil + long rk_binomial_inversion(rk_state *state, long n, double p) nogil + long rk_negative_binomial(rk_state *state, double n, double p) nogil + long rk_poisson(rk_state *state, double lam) nogil + long rk_poisson_mult(rk_state *state, double lam) nogil + long rk_poisson_ptrs(rk_state *state, double lam) nogil + long rk_zipf(rk_state *state, double a) nogil + long rk_geometric(rk_state *state, double p) nogil + long rk_hypergeometric(rk_state *state, long good, long bad, long sample) nogil + long rk_logseries(rk_state *state, double p) nogil + +ctypedef double (* rk_cont0)(rk_state *state) nogil +ctypedef double (* rk_cont1)(rk_state *state, double a) nogil +ctypedef double (* rk_cont2)(rk_state *state, double a, double b) nogil +ctypedef double (* rk_cont3)(rk_state *state, double a, double b, double c) nogil + +ctypedef long (* rk_disc0)(rk_state *state) nogil +ctypedef long (* rk_discnp)(rk_state *state, long n, double p) nogil +ctypedef long (* rk_discdd)(rk_state *state, double n, double p) nogil +ctypedef long (* rk_discnmN)(rk_state *state, long n, long m, long N) nogil +ctypedef long (* rk_discd)(rk_state *state, double a) nogil cdef extern from "initarray.h": @@ -125,8 +126,11 @@ import_array() import numpy as np import operator +import warnings +from threading import Lock -cdef object cont0_array(rk_state *state, rk_cont0 func, object size): +cdef object cont0_array(rk_state *state, rk_cont0 func, object size, + object lock): cdef double *array_data cdef ndarray array "arrayObject" cdef npy_intp length @@ -138,12 +142,14 @@ cdef object cont0_array(rk_state *state, rk_cont0 func, object size): array = <ndarray>np.empty(size, np.float64) length = PyArray_SIZE(array) array_data = <double *>PyArray_DATA(array) - for i from 0 <= i < length: - array_data[i] = func(state) + with lock, nogil: + for i from 0 <= i < length: + array_data[i] = func(state) return array -cdef object cont1_array_sc(rk_state *state, rk_cont1 func, object size, double a): +cdef object cont1_array_sc(rk_state *state, rk_cont1 func, object size, double a, + object lock): cdef double *array_data cdef ndarray array "arrayObject" cdef npy_intp length @@ -155,11 +161,13 @@ cdef object cont1_array_sc(rk_state *state, rk_cont1 func, object size, double a array = <ndarray>np.empty(size, np.float64) length = PyArray_SIZE(array) array_data = <double *>PyArray_DATA(array) - for i from 0 <= i < length: - array_data[i] = func(state, a) + with lock, nogil: + for i from 0 <= i < length: + array_data[i] = func(state, a) return array -cdef object cont1_array(rk_state *state, rk_cont1 func, object size, ndarray oa): +cdef object cont1_array(rk_state *state, rk_cont1 func, object size, + ndarray oa, object lock): cdef double *array_data cdef double *oa_data cdef ndarray array "arrayObject" @@ -174,9 +182,10 @@ cdef object cont1_array(rk_state *state, rk_cont1 func, object size, ndarray oa) length = PyArray_SIZE(array) array_data = <double *>PyArray_DATA(array) itera = <flatiter>PyArray_IterNew(<object>oa) - for i from 0 <= i < length: - array_data[i] = func(state, (<double *>(itera.dataptr))[0]) - PyArray_ITER_NEXT(itera) + with lock, nogil: + for i from 0 <= i < length: + array_data[i] = func(state, (<double *>(itera.dataptr))[0]) + PyArray_ITER_NEXT(itera) else: array = <ndarray>np.empty(size, np.float64) array_data = <double *>PyArray_DATA(array) @@ -184,14 +193,15 @@ cdef object cont1_array(rk_state *state, rk_cont1 func, object size, ndarray oa) <void *>oa) if (multi.size != PyArray_SIZE(array)): raise ValueError("size is not compatible with inputs") - for i from 0 <= i < multi.size: - oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - array_data[i] = func(state, oa_data[0]) - PyArray_MultiIter_NEXTi(multi, 1) + with lock, nogil: + for i from 0 <= i < multi.size: + oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) + array_data[i] = func(state, oa_data[0]) + PyArray_MultiIter_NEXTi(multi, 1) return array cdef object cont2_array_sc(rk_state *state, rk_cont2 func, object size, double a, - double b): + double b, object lock): cdef double *array_data cdef ndarray array "arrayObject" cdef npy_intp length @@ -203,13 +213,14 @@ cdef object cont2_array_sc(rk_state *state, rk_cont2 func, object size, double a array = <ndarray>np.empty(size, np.float64) length = PyArray_SIZE(array) array_data = <double *>PyArray_DATA(array) - for i from 0 <= i < length: - array_data[i] = func(state, a, b) + with lock, nogil: + for i from 0 <= i < length: + array_data[i] = func(state, a, b) return array cdef object cont2_array(rk_state *state, rk_cont2 func, object size, - ndarray oa, ndarray ob): + ndarray oa, ndarray ob, object lock): cdef double *array_data cdef double *oa_data cdef double *ob_data @@ -222,27 +233,29 @@ cdef object cont2_array(rk_state *state, rk_cont2 func, object size, multi = <broadcast> PyArray_MultiIterNew(2, <void *>oa, <void *>ob) array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) array_data = <double *>PyArray_DATA(array) - for i from 0 <= i < multi.size: - oa_data = <double *>PyArray_MultiIter_DATA(multi, 0) - ob_data = <double *>PyArray_MultiIter_DATA(multi, 1) - array_data[i] = func(state, oa_data[0], ob_data[0]) - PyArray_MultiIter_NEXT(multi) + with lock, nogil: + for i from 0 <= i < multi.size: + oa_data = <double *>PyArray_MultiIter_DATA(multi, 0) + ob_data = <double *>PyArray_MultiIter_DATA(multi, 1) + array_data[i] = func(state, oa_data[0], ob_data[0]) + PyArray_MultiIter_NEXT(multi) else: array = <ndarray>np.empty(size, np.float64) array_data = <double *>PyArray_DATA(array) multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>oa, <void *>ob) if (multi.size != PyArray_SIZE(array)): raise ValueError("size is not compatible with inputs") - for i from 0 <= i < multi.size: - oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - ob_data = <double *>PyArray_MultiIter_DATA(multi, 2) - array_data[i] = func(state, oa_data[0], ob_data[0]) - PyArray_MultiIter_NEXTi(multi, 1) - PyArray_MultiIter_NEXTi(multi, 2) + with lock, nogil: + for i from 0 <= i < multi.size: + oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) + ob_data = <double *>PyArray_MultiIter_DATA(multi, 2) + array_data[i] = func(state, oa_data[0], ob_data[0]) + PyArray_MultiIter_NEXTi(multi, 1) + PyArray_MultiIter_NEXTi(multi, 2) return array cdef object cont3_array_sc(rk_state *state, rk_cont3 func, object size, double a, - double b, double c): + double b, double c, object lock): cdef double *array_data cdef ndarray array "arrayObject" @@ -255,12 +268,13 @@ cdef object cont3_array_sc(rk_state *state, rk_cont3 func, object size, double a array = <ndarray>np.empty(size, np.float64) length = PyArray_SIZE(array) array_data = <double *>PyArray_DATA(array) - for i from 0 <= i < length: - array_data[i] = func(state, a, b, c) + with lock, nogil: + for i from 0 <= i < length: + array_data[i] = func(state, a, b, c) return array -cdef object cont3_array(rk_state *state, rk_cont3 func, object size, ndarray oa, - ndarray ob, ndarray oc): +cdef object cont3_array(rk_state *state, rk_cont3 func, object size, + ndarray oa, ndarray ob, ndarray oc, object lock): cdef double *array_data cdef double *oa_data @@ -275,12 +289,13 @@ cdef object cont3_array(rk_state *state, rk_cont3 func, object size, ndarray oa, multi = <broadcast> PyArray_MultiIterNew(3, <void *>oa, <void *>ob, <void *>oc) array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) array_data = <double *>PyArray_DATA(array) - for i from 0 <= i < multi.size: - oa_data = <double *>PyArray_MultiIter_DATA(multi, 0) - ob_data = <double *>PyArray_MultiIter_DATA(multi, 1) - oc_data = <double *>PyArray_MultiIter_DATA(multi, 2) - array_data[i] = func(state, oa_data[0], ob_data[0], oc_data[0]) - PyArray_MultiIter_NEXT(multi) + with lock, nogil: + for i from 0 <= i < multi.size: + oa_data = <double *>PyArray_MultiIter_DATA(multi, 0) + ob_data = <double *>PyArray_MultiIter_DATA(multi, 1) + oc_data = <double *>PyArray_MultiIter_DATA(multi, 2) + array_data[i] = func(state, oa_data[0], ob_data[0], oc_data[0]) + PyArray_MultiIter_NEXT(multi) else: array = <ndarray>np.empty(size, np.float64) array_data = <double *>PyArray_DATA(array) @@ -288,15 +303,16 @@ cdef object cont3_array(rk_state *state, rk_cont3 func, object size, ndarray oa, <void *>ob, <void *>oc) if (multi.size != PyArray_SIZE(array)): raise ValueError("size is not compatible with inputs") - for i from 0 <= i < multi.size: - oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - ob_data = <double *>PyArray_MultiIter_DATA(multi, 2) - oc_data = <double *>PyArray_MultiIter_DATA(multi, 3) - array_data[i] = func(state, oa_data[0], ob_data[0], oc_data[0]) - PyArray_MultiIter_NEXT(multi) + with lock, nogil: + for i from 0 <= i < multi.size: + oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) + ob_data = <double *>PyArray_MultiIter_DATA(multi, 2) + oc_data = <double *>PyArray_MultiIter_DATA(multi, 3) + array_data[i] = func(state, oa_data[0], ob_data[0], oc_data[0]) + PyArray_MultiIter_NEXT(multi) return array -cdef object disc0_array(rk_state *state, rk_disc0 func, object size): +cdef object disc0_array(rk_state *state, rk_disc0 func, object size, object lock): cdef long *array_data cdef ndarray array "arrayObject" cdef npy_intp length @@ -308,11 +324,13 @@ cdef object disc0_array(rk_state *state, rk_disc0 func, object size): array = <ndarray>np.empty(size, int) length = PyArray_SIZE(array) array_data = <long *>PyArray_DATA(array) - for i from 0 <= i < length: - array_data[i] = func(state) + with lock, nogil: + for i from 0 <= i < length: + array_data[i] = func(state) return array -cdef object discnp_array_sc(rk_state *state, rk_discnp func, object size, long n, double p): +cdef object discnp_array_sc(rk_state *state, rk_discnp func, object size, + long n, double p, object lock): cdef long *array_data cdef ndarray array "arrayObject" cdef npy_intp length @@ -324,11 +342,13 @@ cdef object discnp_array_sc(rk_state *state, rk_discnp func, object size, long n array = <ndarray>np.empty(size, int) length = PyArray_SIZE(array) array_data = <long *>PyArray_DATA(array) - for i from 0 <= i < length: - array_data[i] = func(state, n, p) + with lock, nogil: + for i from 0 <= i < length: + array_data[i] = func(state, n, p) return array -cdef object discnp_array(rk_state *state, rk_discnp func, object size, ndarray on, ndarray op): +cdef object discnp_array(rk_state *state, rk_discnp func, object size, + ndarray on, ndarray op, object lock): cdef long *array_data cdef ndarray array "arrayObject" cdef npy_intp length @@ -341,27 +361,30 @@ cdef object discnp_array(rk_state *state, rk_discnp func, object size, ndarray o multi = <broadcast> PyArray_MultiIterNew(2, <void *>on, <void *>op) array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) array_data = <long *>PyArray_DATA(array) - for i from 0 <= i < multi.size: - on_data = <long *>PyArray_MultiIter_DATA(multi, 0) - op_data = <double *>PyArray_MultiIter_DATA(multi, 1) - array_data[i] = func(state, on_data[0], op_data[0]) - PyArray_MultiIter_NEXT(multi) + with lock, nogil: + for i from 0 <= i < multi.size: + on_data = <long *>PyArray_MultiIter_DATA(multi, 0) + op_data = <double *>PyArray_MultiIter_DATA(multi, 1) + array_data[i] = func(state, on_data[0], op_data[0]) + PyArray_MultiIter_NEXT(multi) else: array = <ndarray>np.empty(size, int) array_data = <long *>PyArray_DATA(array) multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>on, <void *>op) if (multi.size != PyArray_SIZE(array)): raise ValueError("size is not compatible with inputs") - for i from 0 <= i < multi.size: - on_data = <long *>PyArray_MultiIter_DATA(multi, 1) - op_data = <double *>PyArray_MultiIter_DATA(multi, 2) - array_data[i] = func(state, on_data[0], op_data[0]) - PyArray_MultiIter_NEXTi(multi, 1) - PyArray_MultiIter_NEXTi(multi, 2) + with lock, nogil: + for i from 0 <= i < multi.size: + on_data = <long *>PyArray_MultiIter_DATA(multi, 1) + op_data = <double *>PyArray_MultiIter_DATA(multi, 2) + array_data[i] = func(state, on_data[0], op_data[0]) + PyArray_MultiIter_NEXTi(multi, 1) + PyArray_MultiIter_NEXTi(multi, 2) return array -cdef object discdd_array_sc(rk_state *state, rk_discdd func, object size, double n, double p): +cdef object discdd_array_sc(rk_state *state, rk_discdd func, object size, + double n, double p, object lock): cdef long *array_data cdef ndarray array "arrayObject" cdef npy_intp length @@ -373,11 +396,13 @@ cdef object discdd_array_sc(rk_state *state, rk_discdd func, object size, double array = <ndarray>np.empty(size, int) length = PyArray_SIZE(array) array_data = <long *>PyArray_DATA(array) - for i from 0 <= i < length: - array_data[i] = func(state, n, p) + with lock, nogil: + for i from 0 <= i < length: + array_data[i] = func(state, n, p) return array -cdef object discdd_array(rk_state *state, rk_discdd func, object size, ndarray on, ndarray op): +cdef object discdd_array(rk_state *state, rk_discdd func, object size, + ndarray on, ndarray op, object lock): cdef long *array_data cdef ndarray array "arrayObject" cdef npy_intp length @@ -390,28 +415,30 @@ cdef object discdd_array(rk_state *state, rk_discdd func, object size, ndarray o multi = <broadcast> PyArray_MultiIterNew(2, <void *>on, <void *>op) array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) array_data = <long *>PyArray_DATA(array) - for i from 0 <= i < multi.size: - on_data = <double *>PyArray_MultiIter_DATA(multi, 0) - op_data = <double *>PyArray_MultiIter_DATA(multi, 1) - array_data[i] = func(state, on_data[0], op_data[0]) - PyArray_MultiIter_NEXT(multi) + with lock, nogil: + for i from 0 <= i < multi.size: + on_data = <double *>PyArray_MultiIter_DATA(multi, 0) + op_data = <double *>PyArray_MultiIter_DATA(multi, 1) + array_data[i] = func(state, on_data[0], op_data[0]) + PyArray_MultiIter_NEXT(multi) else: array = <ndarray>np.empty(size, int) array_data = <long *>PyArray_DATA(array) multi = <broadcast>PyArray_MultiIterNew(3, <void*>array, <void *>on, <void *>op) if (multi.size != PyArray_SIZE(array)): raise ValueError("size is not compatible with inputs") - for i from 0 <= i < multi.size: - on_data = <double *>PyArray_MultiIter_DATA(multi, 1) - op_data = <double *>PyArray_MultiIter_DATA(multi, 2) - array_data[i] = func(state, on_data[0], op_data[0]) - PyArray_MultiIter_NEXTi(multi, 1) - PyArray_MultiIter_NEXTi(multi, 2) + with lock, nogil: + for i from 0 <= i < multi.size: + on_data = <double *>PyArray_MultiIter_DATA(multi, 1) + op_data = <double *>PyArray_MultiIter_DATA(multi, 2) + array_data[i] = func(state, on_data[0], op_data[0]) + PyArray_MultiIter_NEXTi(multi, 1) + PyArray_MultiIter_NEXTi(multi, 2) return array cdef object discnmN_array_sc(rk_state *state, rk_discnmN func, object size, - long n, long m, long N): + long n, long m, long N, object lock): cdef long *array_data cdef ndarray array "arrayObject" cdef npy_intp length @@ -423,12 +450,13 @@ cdef object discnmN_array_sc(rk_state *state, rk_discnmN func, object size, array = <ndarray>np.empty(size, int) length = PyArray_SIZE(array) array_data = <long *>PyArray_DATA(array) - for i from 0 <= i < length: - array_data[i] = func(state, n, m, N) + with lock, nogil: + for i from 0 <= i < length: + array_data[i] = func(state, n, m, N) return array cdef object discnmN_array(rk_state *state, rk_discnmN func, object size, - ndarray on, ndarray om, ndarray oN): + ndarray on, ndarray om, ndarray oN, object lock): cdef long *array_data cdef long *on_data cdef long *om_data @@ -442,12 +470,13 @@ cdef object discnmN_array(rk_state *state, rk_discnmN func, object size, multi = <broadcast> PyArray_MultiIterNew(3, <void *>on, <void *>om, <void *>oN) array = <ndarray> PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) array_data = <long *>PyArray_DATA(array) - for i from 0 <= i < multi.size: - on_data = <long *>PyArray_MultiIter_DATA(multi, 0) - om_data = <long *>PyArray_MultiIter_DATA(multi, 1) - oN_data = <long *>PyArray_MultiIter_DATA(multi, 2) - array_data[i] = func(state, on_data[0], om_data[0], oN_data[0]) - PyArray_MultiIter_NEXT(multi) + with lock, nogil: + for i from 0 <= i < multi.size: + on_data = <long *>PyArray_MultiIter_DATA(multi, 0) + om_data = <long *>PyArray_MultiIter_DATA(multi, 1) + oN_data = <long *>PyArray_MultiIter_DATA(multi, 2) + array_data[i] = func(state, on_data[0], om_data[0], oN_data[0]) + PyArray_MultiIter_NEXT(multi) else: array = <ndarray>np.empty(size, int) array_data = <long *>PyArray_DATA(array) @@ -455,16 +484,18 @@ cdef object discnmN_array(rk_state *state, rk_discnmN func, object size, <void *>oN) if (multi.size != PyArray_SIZE(array)): raise ValueError("size is not compatible with inputs") - for i from 0 <= i < multi.size: - on_data = <long *>PyArray_MultiIter_DATA(multi, 1) - om_data = <long *>PyArray_MultiIter_DATA(multi, 2) - oN_data = <long *>PyArray_MultiIter_DATA(multi, 3) - array_data[i] = func(state, on_data[0], om_data[0], oN_data[0]) - PyArray_MultiIter_NEXT(multi) + with lock, nogil: + for i from 0 <= i < multi.size: + on_data = <long *>PyArray_MultiIter_DATA(multi, 1) + om_data = <long *>PyArray_MultiIter_DATA(multi, 2) + oN_data = <long *>PyArray_MultiIter_DATA(multi, 3) + array_data[i] = func(state, on_data[0], om_data[0], oN_data[0]) + PyArray_MultiIter_NEXT(multi) return array -cdef object discd_array_sc(rk_state *state, rk_discd func, object size, double a): +cdef object discd_array_sc(rk_state *state, rk_discd func, object size, + double a, object lock): cdef long *array_data cdef ndarray array "arrayObject" cdef npy_intp length @@ -476,11 +507,13 @@ cdef object discd_array_sc(rk_state *state, rk_discd func, object size, double a array = <ndarray>np.empty(size, int) length = PyArray_SIZE(array) array_data = <long *>PyArray_DATA(array) - for i from 0 <= i < length: - array_data[i] = func(state, a) + with lock, nogil: + for i from 0 <= i < length: + array_data[i] = func(state, a) return array -cdef object discd_array(rk_state *state, rk_discd func, object size, ndarray oa): +cdef object discd_array(rk_state *state, rk_discd func, object size, ndarray oa, + object lock): cdef long *array_data cdef double *oa_data cdef ndarray array "arrayObject" @@ -495,19 +528,21 @@ cdef object discd_array(rk_state *state, rk_discd func, object size, ndarray oa) length = PyArray_SIZE(array) array_data = <long *>PyArray_DATA(array) itera = <flatiter>PyArray_IterNew(<object>oa) - for i from 0 <= i < length: - array_data[i] = func(state, (<double *>(itera.dataptr))[0]) - PyArray_ITER_NEXT(itera) + with lock, nogil: + for i from 0 <= i < length: + array_data[i] = func(state, (<double *>(itera.dataptr))[0]) + PyArray_ITER_NEXT(itera) else: array = <ndarray>np.empty(size, int) array_data = <long *>PyArray_DATA(array) multi = <broadcast>PyArray_MultiIterNew(2, <void *>array, <void *>oa) if (multi.size != PyArray_SIZE(array)): raise ValueError("size is not compatible with inputs") - for i from 0 <= i < multi.size: - oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) - array_data[i] = func(state, oa_data[0]) - PyArray_MultiIter_NEXTi(multi, 1) + with lock, nogil: + for i from 0 <= i < multi.size: + oa_data = <double *>PyArray_MultiIter_DATA(multi, 1) + array_data[i] = func(state, oa_data[0]) + PyArray_MultiIter_NEXTi(multi, 1) return array cdef double kahan_sum(double *darr, npy_intp n): @@ -522,6 +557,16 @@ cdef double kahan_sum(double *darr, npy_intp n): sum = t return sum +def _shape_from_size(size, d): + if size is None: + shape = (d,) + else: + try: + shape = (operator.index(size), d) + except TypeError: + shape = tuple(size) + (d,) + return shape + cdef class RandomState: """ RandomState(seed=None) @@ -556,12 +601,14 @@ cdef class RandomState: """ cdef rk_state *internal_state + cdef object lock poisson_lam_max = np.iinfo('l').max - np.sqrt(np.iinfo('l').max)*10 def __init__(self, seed=None): self.internal_state = <rk_state*>PyMem_Malloc(sizeof(rk_state)) self.seed(seed) + self.lock = Lock() def __dealloc__(self): if self.internal_state != NULL: @@ -581,6 +628,7 @@ cdef class RandomState: ---------- seed : int or array_like, optional Seed for `RandomState`. + Must be convertable to 32 bit unsigned integers. See Also -------- @@ -589,15 +637,19 @@ cdef class RandomState: """ cdef rk_error errcode cdef ndarray obj "arrayObject_obj" - if seed is None: - errcode = rk_randomseed(self.internal_state) - elif type(seed) is int: - rk_seed(seed, self.internal_state) - elif isinstance(seed, np.integer): - iseed = int(seed) - rk_seed(iseed, self.internal_state) - else: - obj = <ndarray>PyArray_ContiguousFromObject(seed, NPY_LONG, 1, 1) + try: + if seed is None: + errcode = rk_randomseed(self.internal_state) + else: + idx = operator.index(seed) + if idx > int(2**32 - 1) or idx < 0: + raise ValueError("Seed must be between 0 and 4294967295") + rk_seed(idx, self.internal_state) + except TypeError: + obj = np.asarray(seed).astype(np.int64, casting='safe') + if ((obj > int(2**32 - 1)) | (obj < 0)).any(): + raise ValueError("Seed must be between 0 and 4294967295") + obj = obj.astype('L', casting='unsafe') init_by_array(self.internal_state, <unsigned long *>PyArray_DATA(obj), PyArray_DIM(obj, 0)) @@ -734,8 +786,9 @@ cdef class RandomState: Parameters ---------- size : int or tuple of ints, optional - Defines the shape of the returned array of random floats. If None - (the default), returns a single float. + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -760,7 +813,7 @@ cdef class RandomState: [-1.23204345, -1.75224494]]) """ - return cont0_array(self.internal_state, rk_double, size) + return cont0_array(self.internal_state, rk_double, size, self.lock) def tomaxint(self, size=None): """ @@ -773,10 +826,10 @@ cdef class RandomState: Parameters ---------- - size : tuple of ints, int, optional - Shape of output. If this is, for example, (m,n,k), m*n*k samples - are generated. If no shape is specified, a single sample is - returned. + size : int or tuple of ints, optional + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -807,7 +860,7 @@ cdef class RandomState: [ True, True]]], dtype=bool) """ - return disc0_array(self.internal_state, rk_long, size) + return disc0_array(self.internal_state, rk_long, size, self.lock) def randint(self, low, high=None, size=None): """ @@ -829,8 +882,9 @@ cdef class RandomState: If provided, one above the largest (signed) integer to be drawn from the distribution (see above for behavior if ``high=None``). size : int or tuple of ints, optional - Output shape. Default is None, in which case a single int is - returned. + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -884,9 +938,10 @@ cdef class RandomState: array = <ndarray>np.empty(size, int) length = PyArray_SIZE(array) array_data = <long *>PyArray_DATA(array) - for i from 0 <= i < length: - rv = lo + <long>rk_interval(diff, self. internal_state) - array_data[i] = rv + with self.lock, nogil: + for i from 0 <= i < length: + rv = lo + <long>rk_interval(diff, self. internal_state) + array_data[i] = rv return array def bytes(self, npy_intp length): @@ -913,7 +968,8 @@ cdef class RandomState: """ cdef void *bytes bytestring = empty_py_bytes(length, &bytes) - rk_fill(bytes, length, self.internal_state) + with self.lock, nogil: + rk_fill(bytes, length, self.internal_state) return bytestring @@ -931,13 +987,14 @@ cdef class RandomState: If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a was np.arange(n) size : int or tuple of ints, optional - Output shape. Default is None, in which case a single value is - returned. + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. replace : boolean, optional Whether the sample is with or without replacement p : 1-D array-like, optional The probabilities associated with each entry in a. - If not given the sample assumes a uniform distribtion over all + If not given the sample assumes a uniform distribution over all entries in a. Returns @@ -976,7 +1033,7 @@ cdef class RandomState: >>> np.random.choice(5, 3, replace=False) array([3,1,0]) - >>> #This is equivalent to np.random.shuffle(np.arange(5))[:3] + >>> #This is equivalent to np.random.permutation(np.arange(5))[:3] Generate a non-uniform random sample from np.arange(5) of size 3 without replacement: @@ -1012,14 +1069,17 @@ cdef class RandomState: raise ValueError("a must be non-empty") if None != p: - p = np.array(p, dtype=np.double, ndmin=1, copy=False) + d = len(p) + p = <ndarray>PyArray_ContiguousFromObject(p, NPY_DOUBLE, 1, 1) + pix = <double*>PyArray_DATA(p) + if p.ndim != 1: raise ValueError("p must be 1-dimensional") if p.size != pop_size: raise ValueError("a and p must have same size") - if np.any(p < 0): + if np.logical_or.reduce(p < 0): raise ValueError("probabilities are not non-negative") - if not np.allclose(p.sum(), 1): + if abs(kahan_sum(pix, d) - 1.) > 1e-8: raise ValueError("probabilities do not sum to 1") shape = size @@ -1044,7 +1104,7 @@ cdef class RandomState: "population when 'replace=False'") if None != p: - if np.sum(p > 0) < size: + if np.count_nonzero(p > 0) < size: raise ValueError("Fewer non-zero entries in p than size") n_uniq = 0 p = p.copy() @@ -1091,7 +1151,7 @@ cdef class RandomState: def uniform(self, low=0.0, high=1.0, size=None): """ - uniform(low=0.0, high=1.0, size=1) + uniform(low=0.0, high=1.0, size=None) Draw samples from a uniform distribution. @@ -1109,9 +1169,9 @@ cdef class RandomState: Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0. size : int or tuple of ints, optional - Shape of output. If the given size is, for example, (m,n,k), - m*n*k samples are generated. If no shape is specified, a single sample - is returned. + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -1166,7 +1226,9 @@ cdef class RandomState: flow = PyFloat_AsDouble(low) fhigh = PyFloat_AsDouble(high) if not PyErr_Occurred(): - return cont2_array_sc(self.internal_state, rk_uniform, size, flow, fhigh-flow) + return cont2_array_sc(self.internal_state, rk_uniform, size, flow, + fhigh-flow, self.lock) + PyErr_Clear() olow = <ndarray>PyArray_FROM_OTF(low, NPY_DOUBLE, NPY_ARRAY_ALIGNED) ohigh = <ndarray>PyArray_FROM_OTF(high, NPY_DOUBLE, NPY_ARRAY_ALIGNED) @@ -1174,7 +1236,8 @@ cdef class RandomState: Py_INCREF(temp) # needed to get around Pyrex's automatic reference-counting # rules because EnsureArray steals a reference odiff = <ndarray>PyArray_EnsureArray(temp) - return cont2_array(self.internal_state, rk_uniform, size, olow, odiff) + return cont2_array(self.internal_state, rk_uniform, size, olow, odiff, + self.lock) def rand(self, *args): """ @@ -1297,7 +1360,9 @@ cdef class RandomState: If provided, the largest (signed) integer to be drawn from the distribution (see above for behavior if ``high=None``). size : int or tuple of ints, optional - Output shape. Default is None, in which case a single int is returned. + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -1364,8 +1429,9 @@ cdef class RandomState: Parameters ---------- size : int or tuple of ints, optional - Output shape. Default is None, in which case a single value is - returned. + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -1385,7 +1451,7 @@ cdef class RandomState: (3, 4, 2) """ - return cont0_array(self.internal_state, rk_gauss, size) + return cont0_array(self.internal_state, rk_gauss, size, self.lock) def normal(self, loc=0.0, scale=1.0, size=None): """ @@ -1409,9 +1475,10 @@ cdef class RandomState: Mean ("centre") of the distribution. scale : float Standard deviation (spread or "width") of the distribution. - size : tuple of ints + size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. See Also -------- @@ -1477,7 +1544,8 @@ cdef class RandomState: if not PyErr_Occurred(): if fscale <= 0: raise ValueError("scale <= 0") - return cont2_array_sc(self.internal_state, rk_normal, size, floc, fscale) + return cont2_array_sc(self.internal_state, rk_normal, size, floc, + fscale, self.lock) PyErr_Clear() @@ -1485,7 +1553,8 @@ cdef class RandomState: oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less_equal(oscale, 0)): raise ValueError("scale <= 0") - return cont2_array(self.internal_state, rk_normal, size, oloc, oscale) + return cont2_array(self.internal_state, rk_normal, size, oloc, oscale, + self.lock) def beta(self, a, b, size=None): """ @@ -1513,9 +1582,10 @@ cdef class RandomState: Alpha, non-negative. b : float Beta, non-negative. - size : tuple of ints, optional - The number of samples to draw. The output is packed according to - the size given. + size : int or tuple of ints, optional + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -1534,7 +1604,8 @@ cdef class RandomState: raise ValueError("a <= 0") if fb <= 0: raise ValueError("b <= 0") - return cont2_array_sc(self.internal_state, rk_beta, size, fa, fb) + return cont2_array_sc(self.internal_state, rk_beta, size, fa, fb, + self.lock) PyErr_Clear() @@ -1544,7 +1615,8 @@ cdef class RandomState: raise ValueError("a <= 0") if np.any(np.less_equal(ob, 0)): raise ValueError("b <= 0") - return cont2_array(self.internal_state, rk_beta, size, oa, ob) + return cont2_array(self.internal_state, rk_beta, size, oa, ob, + self.lock) def exponential(self, scale=1.0, size=None): """ @@ -1570,9 +1642,10 @@ cdef class RandomState: ---------- scale : float The scale parameter, :math:`\\beta = 1/\\lambda`. - size : tuple of ints - Number of samples to draw. The output is shaped - according to `size`. + size : int or tuple of ints, optional + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. References ---------- @@ -1591,14 +1664,16 @@ cdef class RandomState: if not PyErr_Occurred(): if fscale <= 0: raise ValueError("scale <= 0") - return cont1_array_sc(self.internal_state, rk_exponential, size, fscale) + return cont1_array_sc(self.internal_state, rk_exponential, size, + fscale, self.lock) PyErr_Clear() oscale = <ndarray> PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less_equal(oscale, 0.0)): raise ValueError("scale <= 0") - return cont1_array(self.internal_state, rk_exponential, size, oscale) + return cont1_array(self.internal_state, rk_exponential, size, oscale, + self.lock) def standard_exponential(self, size=None): """ @@ -1611,8 +1686,10 @@ cdef class RandomState: Parameters ---------- - size : int or tuple of ints - Shape of the output. + size : int or tuple of ints, optional + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -1626,7 +1703,8 @@ cdef class RandomState: >>> n = np.random.standard_exponential((3, 8000)) """ - return cont0_array(self.internal_state, rk_standard_exponential, size) + return cont0_array(self.internal_state, rk_standard_exponential, size, + self.lock) def standard_gamma(self, shape, size=None): """ @@ -1641,9 +1719,10 @@ cdef class RandomState: ---------- shape : float Parameter, should be > 0. - size : int or tuple of ints + size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -1702,13 +1781,14 @@ cdef class RandomState: if not PyErr_Occurred(): if fshape <= 0: raise ValueError("shape <= 0") - return cont1_array_sc(self.internal_state, rk_standard_gamma, size, fshape) + return cont1_array_sc(self.internal_state, rk_standard_gamma, size, fshape, self.lock) PyErr_Clear() oshape = <ndarray> PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less_equal(oshape, 0.0)): raise ValueError("shape <= 0") - return cont1_array(self.internal_state, rk_standard_gamma, size, oshape) + return cont1_array(self.internal_state, rk_standard_gamma, size, + oshape, self.lock) def gamma(self, shape, scale=1.0, size=None): """ @@ -1726,9 +1806,10 @@ cdef class RandomState: The shape of the gamma distribution. scale : scalar > 0, optional The scale of the gamma distribution. Default is equal to 1. - size : shape_tuple, optional + size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -1790,7 +1871,8 @@ cdef class RandomState: raise ValueError("shape <= 0") if fscale <= 0: raise ValueError("scale <= 0") - return cont2_array_sc(self.internal_state, rk_gamma, size, fshape, fscale) + return cont2_array_sc(self.internal_state, rk_gamma, size, fshape, + fscale, self.lock) PyErr_Clear() oshape = <ndarray>PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) @@ -1799,7 +1881,8 @@ cdef class RandomState: raise ValueError("shape <= 0") if np.any(np.less_equal(oscale, 0.0)): raise ValueError("scale <= 0") - return cont2_array(self.internal_state, rk_gamma, size, oshape, oscale) + return cont2_array(self.internal_state, rk_gamma, size, oshape, oscale, + self.lock) def f(self, dfnum, dfden, size=None): """ @@ -1822,10 +1905,10 @@ cdef class RandomState: Degrees of freedom in numerator. Should be greater than zero. dfden : float Degrees of freedom in denominator. Should be greater than zero. - size : {tuple, int}, optional - Output shape. If the given shape is, e.g., ``(m, n, k)``, - then ``m * n * k`` samples are drawn. By default only one sample - is returned. + size : int or tuple of ints, optional + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -1891,7 +1974,8 @@ cdef class RandomState: raise ValueError("shape <= 0") if fdfden <= 0: raise ValueError("scale <= 0") - return cont2_array_sc(self.internal_state, rk_f, size, fdfnum, fdfden) + return cont2_array_sc(self.internal_state, rk_f, size, fdfnum, + fdfden, self.lock) PyErr_Clear() @@ -1901,7 +1985,8 @@ cdef class RandomState: raise ValueError("dfnum <= 0") if np.any(np.less_equal(odfden, 0.0)): raise ValueError("dfden <= 0") - return cont2_array(self.internal_state, rk_f, size, odfnum, odfden) + return cont2_array(self.internal_state, rk_f, size, odfnum, odfden, + self.lock) def noncentral_f(self, dfnum, dfden, nonc, size=None): """ @@ -1922,9 +2007,10 @@ cdef class RandomState: Parameter, should be > 1. nonc : float Parameter, should be >= 0. - size : int or tuple of ints - Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + size : int or tuple of ints, optional + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -1981,7 +2067,7 @@ cdef class RandomState: if fnonc < 0: raise ValueError("nonc < 0") return cont3_array_sc(self.internal_state, rk_noncentral_f, size, - fdfnum, fdfden, fnonc) + fdfnum, fdfden, fnonc, self.lock) PyErr_Clear() @@ -1996,7 +2082,7 @@ cdef class RandomState: if np.any(np.less(ononc, 0.0)): raise ValueError("nonc < 0") return cont3_array(self.internal_state, rk_noncentral_f, size, odfnum, - odfden, ononc) + odfden, ononc, self.lock) def chisquare(self, df, size=None): """ @@ -2013,9 +2099,10 @@ cdef class RandomState: ---------- df : int Number of degrees of freedom. - size : tuple of ints, int, optional - Size of the returned array. By default, a scalar is - returned. + size : int or tuple of ints, optional + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -2067,14 +2154,16 @@ cdef class RandomState: if not PyErr_Occurred(): if fdf <= 0: raise ValueError("df <= 0") - return cont1_array_sc(self.internal_state, rk_chisquare, size, fdf) + return cont1_array_sc(self.internal_state, rk_chisquare, size, fdf, + self.lock) PyErr_Clear() odf = <ndarray>PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less_equal(odf, 0.0)): raise ValueError("df <= 0") - return cont1_array(self.internal_state, rk_chisquare, size, odf) + return cont1_array(self.internal_state, rk_chisquare, size, odf, + self.lock) def noncentral_chisquare(self, df, nonc, size=None): """ @@ -2091,8 +2180,10 @@ cdef class RandomState: Degrees of freedom, should be >= 1. nonc : float Non-centrality, should be > 0. - size : int or tuple of ints - Shape of the output. + size : int or tuple of ints, optional + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Notes ----- @@ -2155,7 +2246,7 @@ cdef class RandomState: if fnonc <= 0: raise ValueError("nonc <= 0") return cont2_array_sc(self.internal_state, rk_noncentral_chisquare, - size, fdf, fnonc) + size, fdf, fnonc, self.lock) PyErr_Clear() @@ -2166,7 +2257,7 @@ cdef class RandomState: if np.any(np.less_equal(ononc, 0.0)): raise ValueError("nonc < 0") return cont2_array(self.internal_state, rk_noncentral_chisquare, size, - odf, ononc) + odf, ononc, self.lock) def standard_cauchy(self, size=None): """ @@ -2178,8 +2269,10 @@ cdef class RandomState: Parameters ---------- - size : int or tuple of ints - Shape of the output. + size : int or tuple of ints, optional + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -2227,7 +2320,8 @@ cdef class RandomState: >>> plt.show() """ - return cont0_array(self.internal_state, rk_standard_cauchy, size) + return cont0_array(self.internal_state, rk_standard_cauchy, size, + self.lock) def standard_t(self, df, size=None): """ @@ -2244,8 +2338,9 @@ cdef class RandomState: df : int Degrees of freedom, should be > 0. size : int or tuple of ints, optional - Output shape. Default is None, in which case a single value is - returned. + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -2321,14 +2416,16 @@ cdef class RandomState: if not PyErr_Occurred(): if fdf <= 0: raise ValueError("df <= 0") - return cont1_array_sc(self.internal_state, rk_standard_t, size, fdf) + return cont1_array_sc(self.internal_state, rk_standard_t, size, + fdf, self.lock) PyErr_Clear() odf = <ndarray> PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less_equal(odf, 0.0)): raise ValueError("df <= 0") - return cont1_array(self.internal_state, rk_standard_t, size, odf) + return cont1_array(self.internal_state, rk_standard_t, size, odf, + self.lock) def vonmises(self, mu, kappa, size=None): """ @@ -2350,9 +2447,10 @@ cdef class RandomState: Mode ("center") of the distribution. kappa : float Dispersion of the distribution, has to be >=0. - size : int or tuple of int + size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -2414,7 +2512,8 @@ cdef class RandomState: if not PyErr_Occurred(): if fkappa < 0: raise ValueError("kappa < 0") - return cont2_array_sc(self.internal_state, rk_vonmises, size, fmu, fkappa) + return cont2_array_sc(self.internal_state, rk_vonmises, size, fmu, + fkappa, self.lock) PyErr_Clear() @@ -2422,7 +2521,8 @@ cdef class RandomState: okappa = <ndarray> PyArray_FROM_OTF(kappa, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less(okappa, 0.0)): raise ValueError("kappa < 0") - return cont2_array(self.internal_state, rk_vonmises, size, omu, okappa) + return cont2_array(self.internal_state, rk_vonmises, size, omu, okappa, + self.lock) def pareto(self, a, size=None): """ @@ -2448,9 +2548,10 @@ cdef class RandomState: ---------- shape : float, > 0. Shape of the distribution. - size : tuple of ints + size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. See Also -------- @@ -2511,14 +2612,15 @@ cdef class RandomState: if not PyErr_Occurred(): if fa <= 0: raise ValueError("a <= 0") - return cont1_array_sc(self.internal_state, rk_pareto, size, fa) + return cont1_array_sc(self.internal_state, rk_pareto, size, fa, + self.lock) PyErr_Clear() oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less_equal(oa, 0.0)): raise ValueError("a <= 0") - return cont1_array(self.internal_state, rk_pareto, size, oa) + return cont1_array(self.internal_state, rk_pareto, size, oa, self.lock) def weibull(self, a, size=None): """ @@ -2540,9 +2642,10 @@ cdef class RandomState: ---------- a : float Shape of the distribution. - size : tuple of ints + size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. See Also -------- @@ -2611,14 +2714,16 @@ cdef class RandomState: if not PyErr_Occurred(): if fa <= 0: raise ValueError("a <= 0") - return cont1_array_sc(self.internal_state, rk_weibull, size, fa) + return cont1_array_sc(self.internal_state, rk_weibull, size, fa, + self.lock) PyErr_Clear() oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less_equal(oa, 0.0)): raise ValueError("a <= 0") - return cont1_array(self.internal_state, rk_weibull, size, oa) + return cont1_array(self.internal_state, rk_weibull, size, oa, + self.lock) def power(self, a, size=None): """ @@ -2633,9 +2738,10 @@ cdef class RandomState: ---------- a : float parameter, > 0 - size : tuple of ints + size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -2720,14 +2826,15 @@ cdef class RandomState: if not PyErr_Occurred(): if fa <= 0: raise ValueError("a <= 0") - return cont1_array_sc(self.internal_state, rk_power, size, fa) + return cont1_array_sc(self.internal_state, rk_power, size, fa, + self.lock) PyErr_Clear() oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less_equal(oa, 0.0)): raise ValueError("a <= 0") - return cont1_array(self.internal_state, rk_power, size, oa) + return cont1_array(self.internal_state, rk_power, size, oa, self.lock) def laplace(self, loc=0.0, scale=1.0, size=None): """ @@ -2747,6 +2854,10 @@ cdef class RandomState: The position, :math:`\\mu`, of the distribution peak. scale : float :math:`\\lambda`, the exponential decay. + size : int or tuple of ints, optional + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Notes ----- @@ -2810,14 +2921,16 @@ cdef class RandomState: if not PyErr_Occurred(): if fscale <= 0: raise ValueError("scale <= 0") - return cont2_array_sc(self.internal_state, rk_laplace, size, floc, fscale) + return cont2_array_sc(self.internal_state, rk_laplace, size, floc, + fscale, self.lock) PyErr_Clear() oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less_equal(oscale, 0.0)): raise ValueError("scale <= 0") - return cont2_array(self.internal_state, rk_laplace, size, oloc, oscale) + return cont2_array(self.internal_state, rk_laplace, size, oloc, oscale, + self.lock) def gumbel(self, loc=0.0, scale=1.0, size=None): """ @@ -2835,9 +2948,10 @@ cdef class RandomState: The location of the mode of the distribution. scale : float The scale parameter of the distribution. - size : tuple of ints + size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -2941,14 +3055,16 @@ cdef class RandomState: if not PyErr_Occurred(): if fscale <= 0: raise ValueError("scale <= 0") - return cont2_array_sc(self.internal_state, rk_gumbel, size, floc, fscale) + return cont2_array_sc(self.internal_state, rk_gumbel, size, floc, + fscale, self.lock) PyErr_Clear() oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less_equal(oscale, 0.0)): raise ValueError("scale <= 0") - return cont2_array(self.internal_state, rk_gumbel, size, oloc, oscale) + return cont2_array(self.internal_state, rk_gumbel, size, oloc, oscale, + self.lock) def logistic(self, loc=0.0, scale=1.0, size=None): """ @@ -2965,9 +3081,10 @@ cdef class RandomState: scale : float > 0. - size : {tuple, int} + size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -3029,14 +3146,16 @@ cdef class RandomState: if not PyErr_Occurred(): if fscale <= 0: raise ValueError("scale <= 0") - return cont2_array_sc(self.internal_state, rk_logistic, size, floc, fscale) + return cont2_array_sc(self.internal_state, rk_logistic, size, floc, + fscale, self.lock) PyErr_Clear() oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less_equal(oscale, 0.0)): raise ValueError("scale <= 0") - return cont2_array(self.internal_state, rk_logistic, size, oloc, oscale) + return cont2_array(self.internal_state, rk_logistic, size, oloc, + oscale, self.lock) def lognormal(self, mean=0.0, sigma=1.0, size=None): """ @@ -3055,9 +3174,10 @@ cdef class RandomState: Mean value of the underlying normal distribution sigma : float, > 0. Standard deviation of the underlying normal distribution - size : tuple of ints + size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -3149,7 +3269,8 @@ cdef class RandomState: if not PyErr_Occurred(): if fsigma <= 0: raise ValueError("sigma <= 0") - return cont2_array_sc(self.internal_state, rk_lognormal, size, fmean, fsigma) + return cont2_array_sc(self.internal_state, rk_lognormal, size, + fmean, fsigma, self.lock) PyErr_Clear() @@ -3157,7 +3278,8 @@ cdef class RandomState: osigma = PyArray_FROM_OTF(sigma, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less_equal(osigma, 0.0)): raise ValueError("sigma <= 0.0") - return cont2_array(self.internal_state, rk_lognormal, size, omean, osigma) + return cont2_array(self.internal_state, rk_lognormal, size, omean, + osigma, self.lock) def rayleigh(self, scale=1.0, size=None): """ @@ -3173,8 +3295,9 @@ cdef class RandomState: scale : scalar Scale, also equals the mode. Should be >= 0. size : int or tuple of ints, optional - Shape of the output. Default is None, in which case a single - value is returned. + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Notes ----- @@ -3222,14 +3345,16 @@ cdef class RandomState: if not PyErr_Occurred(): if fscale <= 0: raise ValueError("scale <= 0") - return cont1_array_sc(self.internal_state, rk_rayleigh, size, fscale) + return cont1_array_sc(self.internal_state, rk_rayleigh, size, + fscale, self.lock) PyErr_Clear() oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less_equal(oscale, 0.0)): raise ValueError("scale <= 0.0") - return cont1_array(self.internal_state, rk_rayleigh, size, oscale) + return cont1_array(self.internal_state, rk_rayleigh, size, oscale, + self.lock) def wald(self, mean, scale, size=None): """ @@ -3255,8 +3380,9 @@ cdef class RandomState: scale : scalar Scale parameter, should be >= 0. size : int or tuple of ints, optional - Output shape. Default is None, in which case a single value is - returned. + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -3304,7 +3430,8 @@ cdef class RandomState: raise ValueError("mean <= 0") if fscale <= 0: raise ValueError("scale <= 0") - return cont2_array_sc(self.internal_state, rk_wald, size, fmean, fscale) + return cont2_array_sc(self.internal_state, rk_wald, size, fmean, + fscale, self.lock) PyErr_Clear() omean = PyArray_FROM_OTF(mean, NPY_DOUBLE, NPY_ARRAY_ALIGNED) @@ -3313,9 +3440,8 @@ cdef class RandomState: raise ValueError("mean <= 0.0") elif np.any(np.less_equal(oscale,0.0)): raise ValueError("scale <= 0.0") - return cont2_array(self.internal_state, rk_wald, size, omean, oscale) - - + return cont2_array(self.internal_state, rk_wald, size, omean, oscale, + self.lock) def triangular(self, left, mode, right, size=None): """ @@ -3337,8 +3463,9 @@ cdef class RandomState: right : scalar Upper limit, should be larger than `left`. size : int or tuple of ints, optional - Output shape. Default is None, in which case a single value is - returned. + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -3388,7 +3515,7 @@ cdef class RandomState: if fleft == fright: raise ValueError("left == right") return cont3_array_sc(self.internal_state, rk_triangular, size, fleft, - fmode, fright) + fmode, fright, self.lock) PyErr_Clear() oleft = <ndarray>PyArray_FROM_OTF(left, NPY_DOUBLE, NPY_ARRAY_ALIGNED) @@ -3402,7 +3529,7 @@ cdef class RandomState: if np.any(np.equal(oleft, oright)): raise ValueError("left == right") return cont3_array(self.internal_state, rk_triangular, size, oleft, - omode, oright) + omode, oright, self.lock) # Complicated, discrete distributions: def binomial(self, n, p, size=None): @@ -3422,9 +3549,10 @@ cdef class RandomState: parameter, >= 0. p : float parameter, >= 0 and <=1. - size : {tuple, int} + size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -3499,7 +3627,10 @@ cdef class RandomState: raise ValueError("p < 0") elif fp > 1: raise ValueError("p > 1") - return discnp_array_sc(self.internal_state, rk_binomial, size, ln, fp) + elif np.isnan(fp): + raise ValueError("p is nan") + return discnp_array_sc(self.internal_state, rk_binomial, size, ln, + fp, self.lock) PyErr_Clear() @@ -3511,7 +3642,8 @@ cdef class RandomState: raise ValueError("p < 0") if np.any(np.greater(p, 1)): raise ValueError("p > 1") - return discnp_array(self.internal_state, rk_binomial, size, on, op) + return discnp_array(self.internal_state, rk_binomial, size, on, op, + self.lock) def negative_binomial(self, n, p, size=None): """ @@ -3529,9 +3661,10 @@ cdef class RandomState: Parameter, > 0. p : float Parameter, >= 0 and <=1. - size : int or tuple of ints - Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + size : int or tuple of ints, optional + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -3593,7 +3726,7 @@ cdef class RandomState: elif fp > 1: raise ValueError("p > 1") return discdd_array_sc(self.internal_state, rk_negative_binomial, - size, fn, fp) + size, fn, fp, self.lock) PyErr_Clear() @@ -3606,7 +3739,7 @@ cdef class RandomState: if np.any(np.greater(p, 1)): raise ValueError("p > 1") return discdd_array(self.internal_state, rk_negative_binomial, size, - on, op) + on, op, self.lock) def poisson(self, lam=1.0, size=None): """ @@ -3619,11 +3752,13 @@ cdef class RandomState: Parameters ---------- - lam : float - Expectation of interval, should be >= 0. + lam : float or sequence of float + Expectation of interval, should be >= 0. A sequence of expectation + intervals must be broadcastable over the requested size. size : int or tuple of ints, optional - Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Notes ----- @@ -3659,6 +3794,10 @@ cdef class RandomState: >>> count, bins, ignored = plt.hist(s, 14, normed=True) >>> plt.show() + Draw each 100 values for lambda 100 and 500: + + >>> s = np.random.poisson(lam=(100., 500.), size=(100, 2)) + """ cdef ndarray olam cdef double flam @@ -3668,7 +3807,8 @@ cdef class RandomState: raise ValueError("lam < 0") if lam > self.poisson_lam_max: raise ValueError("lam value too large") - return discd_array_sc(self.internal_state, rk_poisson, size, flam) + return discd_array_sc(self.internal_state, rk_poisson, size, flam, + self.lock) PyErr_Clear() @@ -3677,7 +3817,7 @@ cdef class RandomState: raise ValueError("lam < 0") if np.any(np.greater(olam, self.poisson_lam_max)): raise ValueError("lam value too large.") - return discd_array(self.internal_state, rk_poisson, size, olam) + return discd_array(self.internal_state, rk_poisson, size, olam, self.lock) def zipf(self, a, size=None): """ @@ -3697,12 +3837,10 @@ cdef class RandomState: ---------- a : float > 1 Distribution parameter. - size : int or tuple of int, optional + size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn; a single integer is equivalent in - its result to providing a mono-tuple, i.e., a 1-D array of length - *size* is returned. The default is None, in which case a single - scalar is returned. + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -3758,14 +3896,15 @@ cdef class RandomState: if not PyErr_Occurred(): if fa <= 1.0: raise ValueError("a <= 1.0") - return discd_array_sc(self.internal_state, rk_zipf, size, fa) + return discd_array_sc(self.internal_state, rk_zipf, size, fa, + self.lock) PyErr_Clear() oa = <ndarray>PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) if np.any(np.less_equal(oa, 1.0)): raise ValueError("a <= 1.0") - return discd_array(self.internal_state, rk_zipf, size, oa) + return discd_array(self.internal_state, rk_zipf, size, oa, self.lock) def geometric(self, p, size=None): """ @@ -3789,9 +3928,10 @@ cdef class RandomState: ---------- p : float The probability of success of an individual trial. - size : tuple of ints - Number of values to draw from the distribution. The output - is shaped according to `size`. + size : int or tuple of ints, optional + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -3821,7 +3961,8 @@ cdef class RandomState: raise ValueError("p < 0.0") if fp > 1.0: raise ValueError("p > 1.0") - return discd_array_sc(self.internal_state, rk_geometric, size, fp) + return discd_array_sc(self.internal_state, rk_geometric, size, fp, + self.lock) PyErr_Clear() @@ -3831,7 +3972,7 @@ cdef class RandomState: raise ValueError("p < 0.0") if np.any(np.greater(op, 1.0)): raise ValueError("p > 1.0") - return discd_array(self.internal_state, rk_geometric, size, op) + return discd_array(self.internal_state, rk_geometric, size, op, self.lock) def hypergeometric(self, ngood, nbad, nsample, size=None): """ @@ -3853,9 +3994,10 @@ cdef class RandomState: nsample : int or array_like Number of items sampled. Must be at least 1 and at most ``ngood + nbad``. - size : int or tuple of int + size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -3933,8 +4075,8 @@ cdef class RandomState: raise ValueError("nsample < 1") if lngood + lnbad < lnsample: raise ValueError("ngood + nbad < nsample") - return discnmN_array_sc(self.internal_state, rk_hypergeometric, size, - lngood, lnbad, lnsample) + return discnmN_array_sc(self.internal_state, rk_hypergeometric, + size, lngood, lnbad, lnsample, self.lock) PyErr_Clear() @@ -3950,7 +4092,7 @@ cdef class RandomState: if np.any(np.less(np.add(ongood, onbad),onsample)): raise ValueError("ngood + nbad < nsample") return discnmN_array(self.internal_state, rk_hypergeometric, size, - ongood, onbad, onsample) + ongood, onbad, onsample, self.lock) def logseries(self, p, size=None): """ @@ -3967,9 +4109,10 @@ cdef class RandomState: scale : float > 0. - size : {tuple, int} + size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then - ``m * n * k`` samples are drawn. + ``m * n * k`` samples are drawn. Default is None, in which case a + single value is returned. Returns ------- @@ -4035,7 +4178,8 @@ cdef class RandomState: raise ValueError("p <= 0.0") if fp >= 1.0: raise ValueError("p >= 1.0") - return discd_array_sc(self.internal_state, rk_logseries, size, fp) + return discd_array_sc(self.internal_state, rk_logseries, size, fp, + self.lock) PyErr_Clear() @@ -4044,7 +4188,7 @@ cdef class RandomState: raise ValueError("p <= 0.0") if np.any(np.greater_equal(op, 1.0)): raise ValueError("p >= 1.0") - return discd_array(self.internal_state, rk_logseries, size, op) + return discd_array(self.internal_state, rk_logseries, size, op, self.lock) # Multivariate distributions: def multivariate_normal(self, mean, cov, size=None): @@ -4066,7 +4210,7 @@ cdef class RandomState: Mean of the N-dimensional distribution. cov : 2-D array_like, of shape (N, N) Covariance matrix of the distribution. Must be symmetric and - positive semi-definite for "physically meaningful" results. + positive-semidefinite for "physically meaningful" results. size : int or tuple of ints, optional Given a shape of, for example, ``(m,n,k)``, ``m*n*k`` samples are generated, and packed in an `m`-by-`n`-by-`k` arrangement. Because @@ -4138,44 +4282,55 @@ cdef class RandomState: [True, True] """ + from numpy.dual import svd + # Check preconditions on arguments mean = np.array(mean) cov = np.array(cov) if size is None: shape = [] + elif isinstance(size, (int, long, np.integer)): + shape = [size] else: shape = size + if len(mean.shape) != 1: raise ValueError("mean must be 1 dimensional") if (len(cov.shape) != 2) or (cov.shape[0] != cov.shape[1]): raise ValueError("cov must be 2 dimensional and square") if mean.shape[0] != cov.shape[0]: raise ValueError("mean and cov must have same length") - # Compute shape of output - if isinstance(shape, (int, long, np.integer)): - shape = [shape] + + # Compute shape of output and create a matrix of independent + # standard normally distributed random numbers. The matrix has rows + # with the same length as mean and as many rows are necessary to + # form a matrix of shape final_shape. final_shape = list(shape[:]) final_shape.append(mean.shape[0]) - # Create a matrix of independent standard normally distributed random - # numbers. The matrix has rows with the same length as mean and as - # many rows are necessary to form a matrix of shape final_shape. - x = self.standard_normal(np.multiply.reduce(final_shape)) - x.shape = (np.multiply.reduce(final_shape[0:len(final_shape)-1]), - mean.shape[0]) + x = self.standard_normal(final_shape).reshape(-1, mean.shape[0]) + # Transform matrix of standard normals into matrix where each row # contains multivariate normals with the desired covariance. # Compute A such that dot(transpose(A),A) == cov. # Then the matrix products of the rows of x and A has the desired # covariance. Note that sqrt(s)*v where (u,s,v) is the singular value # decomposition of cov is such an A. - - from numpy.dual import svd - # XXX: we really should be doing this by Cholesky decomposition - (u,s,v) = svd(cov) - x = np.dot(x*np.sqrt(s),v) - # The rows of x now have the correct covariance but mean 0. Add - # mean to each row. Then each row will have mean mean. - np.add(mean,x,x) + # + # Also check that cov is positive-semidefinite. If so, the u.T and v + # matrices should be equal up to roundoff error if cov is + # symmetrical and the singular value of the corresponding row is + # not zero. We continue to use the SVD rather than Cholesky in + # order to preserve current outputs. Note that symmetry has not + # been checked. + (u, s, v) = svd(cov) + neg = (np.sum(u.T * v, axis=1) < 0) & (s > 0) + if np.any(neg): + s[neg] = 0. + warnings.warn("covariance is not positive-semidefinite.", + RuntimeWarning) + + x = np.dot(x, np.sqrt(s)[:, None] * v) + x += mean x.shape = tuple(final_shape) return x @@ -4235,7 +4390,7 @@ cdef class RandomState: cdef ndarray parr "arrayObject_parr", mnarr "arrayObject_mnarr" cdef double *pix cdef long *mnix - cdef npy_intp i, j, dn + cdef npy_intp i, j, dn, sz cdef double Sum d = len(pvals) @@ -4245,30 +4400,27 @@ cdef class RandomState: if kahan_sum(pix, d-1) > (1.0 + 1e-12): raise ValueError("sum(pvals[:-1]) > 1.0") - if size is None: - shape = (d,) - elif type(size) is int: - shape = (size, d) - else: - shape = size + (d,) + shape = _shape_from_size(size, d) multin = np.zeros(shape, int) mnarr = <ndarray>multin mnix = <long*>PyArray_DATA(mnarr) - i = 0 - while i < PyArray_SIZE(mnarr): - Sum = 1.0 - dn = n - for j from 0 <= j < d-1: - mnix[i+j] = rk_binomial(self.internal_state, dn, pix[j]/Sum) - dn = dn - mnix[i+j] - if dn <= 0: - break - Sum = Sum - pix[j] - if dn > 0: - mnix[i+d-1] = dn - - i = i + d + sz = PyArray_SIZE(mnarr) + with self.lock, nogil: + i = 0 + while i < sz: + Sum = 1.0 + dn = n + for j from 0 <= j < d-1: + mnix[i+j] = rk_binomial(self.internal_state, dn, pix[j]/Sum) + dn = dn - mnix[i+j] + if dn <= 0: + break + Sum = Sum - pix[j] + if dn > 0: + mnix[i+d-1] = dn + + i = i + d return multin @@ -4354,7 +4506,8 @@ cdef class RandomState: cdef npy_intp k cdef npy_intp totsize cdef ndarray alpha_arr, val_arr - cdef double *alpha_data, *val_data + cdef double *alpha_data + cdef double *val_data cdef npy_intp i, j cdef double acc, invacc @@ -4362,12 +4515,7 @@ cdef class RandomState: alpha_arr = <ndarray>PyArray_ContiguousFromObject(alpha, NPY_DOUBLE, 1, 1) alpha_data = <double*>PyArray_DATA(alpha_arr) - if size is None: - shape = (k,) - elif type(size) is int: - shape = (size, k) - else: - shape = size + (k,) + shape = _shape_from_size(size, k) diric = np.zeros(shape, np.float64) val_arr = <ndarray>diric @@ -4375,15 +4523,17 @@ cdef class RandomState: i = 0 totsize = PyArray_SIZE(val_arr) - while i < totsize: - acc = 0.0 - for j from 0 <= j < k: - val_data[i+j] = rk_standard_gamma(self.internal_state, alpha_data[j]) - acc = acc + val_data[i+j] - invacc = 1/acc - for j from 0 <= j < k: - val_data[i+j] = val_data[i+j] * invacc - i = i + k + with self.lock, nogil: + while i < totsize: + acc = 0.0 + for j from 0 <= j < k: + val_data[i+j] = rk_standard_gamma(self.internal_state, + alpha_data[j]) + acc = acc + val_data[i+j] + invacc = 1/acc + for j from 0 <= j < k: + val_data[i+j] = val_data[i+j] * invacc + i = i + k return diric @@ -4426,11 +4576,12 @@ cdef class RandomState: i = len(x) - 1 # Logic adapted from random.shuffle() - if isinstance(x, np.ndarray) and x.ndim > 1: + if isinstance(x, np.ndarray) and \ + (x.ndim > 1 or x.dtype.fields is not None): # For a multi-dimensional ndarray, indexing returns a view onto # each row. So we can't just use ordinary assignment to swap the # rows; we need a bounce buffer. - buf = np.empty(x.shape[1:], dtype=x.dtype) + buf = np.empty_like(x[0]) while i > 0: j = rk_interval(i, self.internal_state) buf[...] = x[j] diff --git a/numpy/random/mtrand/numpy.pxd b/numpy/random/mtrand/numpy.pxd index 572b51fdd..c54f79c0a 100644 --- a/numpy/random/mtrand/numpy.pxd +++ b/numpy/random/mtrand/numpy.pxd @@ -114,12 +114,14 @@ cdef extern from "numpy/arrayobject.h": object PyArray_MultiIterNew(int n, ...) - char *PyArray_MultiIter_DATA(broadcast multi, int i) - void PyArray_MultiIter_NEXTi(broadcast multi, int i) - void PyArray_MultiIter_NEXT(broadcast multi) + char *PyArray_MultiIter_DATA(broadcast multi, int i) nogil + void PyArray_MultiIter_NEXTi(broadcast multi, int i) nogil + void PyArray_MultiIter_NEXT(broadcast multi) nogil object PyArray_IterNew(object arr) - void PyArray_ITER_NEXT(flatiter it) + void PyArray_ITER_NEXT(flatiter it) nogil + + dtype PyArray_DescrFromType(int) void import_array() diff --git a/numpy/random/tests/test_random.py b/numpy/random/tests/test_random.py index 4ae7cfeb1..b64c9d6cd 100644 --- a/numpy/random/tests/test_random.py +++ b/numpy/random/tests/test_random.py @@ -1,11 +1,41 @@ from __future__ import division, absolute_import, print_function -from numpy.testing import TestCase, run_module_suite, assert_,\ - assert_raises +import numpy as np +from numpy.testing import ( + TestCase, run_module_suite, assert_, assert_raises, assert_equal, + assert_warns) from numpy import random from numpy.compat import asbytes -import numpy as np +class TestSeed(TestCase): + def test_scalar(self): + s = np.random.RandomState(0) + assert_equal(s.randint(1000), 684) + s = np.random.RandomState(4294967295) + assert_equal(s.randint(1000), 419) + + def test_array(self): + s = np.random.RandomState(range(10)) + assert_equal(s.randint(1000), 468) + s = np.random.RandomState(np.arange(10)) + assert_equal(s.randint(1000), 468) + s = np.random.RandomState([0]) + assert_equal(s.randint(1000), 973) + s = np.random.RandomState([4294967295]) + assert_equal(s.randint(1000), 265) + + def test_invalid_scalar(self): + # seed must be a unsigned 32 bit integers + assert_raises(TypeError, np.random.RandomState, -0.5) + assert_raises(ValueError, np.random.RandomState, -1) + + def test_invalid_array(self): + # seed must be a unsigned 32 bit integers + assert_raises(TypeError, np.random.RandomState, [-0.5]) + assert_raises(ValueError, np.random.RandomState, [-1]) + assert_raises(ValueError, np.random.RandomState, [4294967296]) + assert_raises(ValueError, np.random.RandomState, [1, 2, 4294967296]) + assert_raises(ValueError, np.random.RandomState, [1, -2, 4294967296]) class TestBinomial(TestCase): def test_n_zero(self): @@ -17,6 +47,10 @@ class TestBinomial(TestCase): assert_(random.binomial(0, p) == 0) np.testing.assert_array_equal(random.binomial(zeros, p), zeros) + def test_p_is_nan(self): + # Issue #4571. + assert_raises(ValueError, random.binomial, 1, np.nan) + class TestMultinomial(TestCase): def test_basic(self): @@ -31,6 +65,20 @@ class TestMultinomial(TestCase): assert_(np.all(-5 <= x)) assert_(np.all(x < -1)) + def test_size(self): + # gh-3173 + p = [0.5, 0.5] + assert_equal(np.random.multinomial(1 ,p, np.uint32(1)).shape, (1, 2)) + assert_equal(np.random.multinomial(1 ,p, np.uint32(1)).shape, (1, 2)) + assert_equal(np.random.multinomial(1 ,p, np.uint32(1)).shape, (1, 2)) + assert_equal(np.random.multinomial(1 ,p, [2, 2]).shape, (2, 2, 2)) + assert_equal(np.random.multinomial(1 ,p, (2, 2)).shape, (2, 2, 2)) + assert_equal(np.random.multinomial(1 ,p, np.array((2, 2))).shape, + (2, 2, 2)) + + assert_raises(TypeError, np.random.multinomial, 1 , p, + np.float(1)) + class TestSetState(TestCase): def setUp(self): @@ -230,6 +278,29 @@ class TestRandomDist(TestCase): desired = conv([0, 1, 9, 6, 2, 4, 5, 8, 7, 3]) np.testing.assert_array_equal(actual, desired) + def test_shuffle_flexible(self): + # gh-4270 + arr = [(0, 1), (2, 3)] + dt = np.dtype([('a', np.int32, 1), ('b', np.int32, 1)]) + nparr = np.array(arr, dtype=dt) + a, b = nparr[0].copy(), nparr[1].copy() + for i in range(50): + np.random.shuffle(nparr) + assert_(a in nparr) + assert_(b in nparr) + + def test_shuffle_masked(self): + # gh-3263 + a = np.ma.masked_values(np.reshape(range(20), (5,4)) % 3 - 1, -1) + b = np.ma.masked_values(np.arange(20) % 3 - 1, -1) + ma = np.ma.count_masked(a) + mb = np.ma.count_masked(b) + for i in range(50): + np.random.shuffle(a) + self.assertEqual(ma, np.ma.count_masked(a)) + np.random.shuffle(b) + self.assertEqual(mb, np.ma.count_masked(b)) + def test_beta(self): np.random.seed(self.seed) actual = np.random.beta(.1, .9, size=(3, 2)) @@ -266,6 +337,18 @@ class TestRandomDist(TestCase): [ 0.56974431743975207, 0.43025568256024799]]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) + def test_dirichlet_size(self): + # gh-3173 + p = np.array([51.72840233779265162, 39.74494232180943953]) + assert_equal(np.random.dirichlet(p, np.uint32(1)).shape, (1, 2)) + assert_equal(np.random.dirichlet(p, np.uint32(1)).shape, (1, 2)) + assert_equal(np.random.dirichlet(p, np.uint32(1)).shape, (1, 2)) + assert_equal(np.random.dirichlet(p, [2, 2]).shape, (2, 2, 2)) + assert_equal(np.random.dirichlet(p, (2, 2)).shape, (2, 2, 2)) + assert_equal(np.random.dirichlet(p, np.array((2, 2))).shape, (2, 2, 2)) + + assert_raises(TypeError, np.random.dirichlet, p, np.float(1)) + def test_exponential(self): np.random.seed(self.seed) actual = np.random.exponential(1.1234, size=(3, 2)) @@ -378,20 +461,32 @@ class TestRandomDist(TestCase): def test_multivariate_normal(self): np.random.seed(self.seed) mean= (.123456789, 10) + # Hmm... not even symmetric. cov = [[1, 0], [1, 0]] size = (3, 2) actual = np.random.multivariate_normal(mean, cov, size) - desired = np.array([[[ -1.47027513018564449, 10. ], - [ -1.65915081534845532, 10. ]], - [[ -2.29186329304599745, 10. ], - [ -1.77505606019580053, 10. ]], - [[ -0.54970369430044119, 10. ], - [ 0.29768848031692957, 10. ]]]) + desired = np.array([[[-1.47027513018564449, 10.], + [-1.65915081534845532, 10.]], + [[-2.29186329304599745, 10.], + [-1.77505606019580053, 10.]], + [[-0.54970369430044119, 10.], + [ 0.29768848031692957, 10.]]]) + np.testing.assert_array_almost_equal(actual, desired, decimal=15) + + # Check for default size, was raising deprecation warning + actual = np.random.multivariate_normal(mean, cov) + desired = np.array([-0.79441224511977482, 10.]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) + # Check that non positive-semidefinite covariance raises warning + mean= [0, 0] + cov = [[1, 1 + 1e-10], [1 + 1e-10, 1]] + rng = np.random.multivariate_normal + assert_warns(RuntimeWarning, np.random.multivariate_normal, mean, cov) + def test_negative_binomial(self): np.random.seed(self.seed) - actual = np.random.negative_binomial(n = 100, p = .12345, size = (3, 2)) + actual = np.random.negative_binomial(n=100, p=.12345, size=(3, 2)) desired = np.array([[848, 841], [892, 611], [779, 647]]) @@ -534,6 +629,12 @@ class TestRandomDist(TestCase): [ 1.19153771588353052, 1.83509849681825354]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) + def test_vonmises_small(self): + # check infinite loop, gh-4720 + np.random.seed(self.seed) + r = np.random.vonmises(mu=0., kappa=1.1e-8, size=10**6) + np.testing.assert_(np.isfinite(r).all()) + def test_wald(self): np.random.seed(self.seed) actual = np.random.wald(mean = 1.23, scale = 1.54, size = (3, 2)) @@ -558,5 +659,45 @@ class TestRandomDist(TestCase): [ 3, 13]]) np.testing.assert_array_equal(actual, desired) + +class TestThread: + """ make sure each state produces the same sequence even in threads """ + def setUp(self): + self.seeds = range(4) + + def check_function(self, function, sz): + from threading import Thread + + out1 = np.empty((len(self.seeds),) + sz) + out2 = np.empty((len(self.seeds),) + sz) + + # threaded generation + t = [Thread(target=function, args=(np.random.RandomState(s), o)) + for s, o in zip(self.seeds, out1)] + [x.start() for x in t] + [x.join() for x in t] + + # the same serial + for s, o in zip(self.seeds, out2): + function(np.random.RandomState(s), o) + + np.testing.assert_array_equal(out1, out2) + + def test_normal(self): + def gen_random(state, out): + out[...] = state.normal(size=10000) + self.check_function(gen_random, sz=(10000,)) + + def test_exp(self): + def gen_random(state, out): + out[...] = state.exponential(scale=np.ones((100, 1000))) + self.check_function(gen_random, sz=(100, 1000)) + + def test_multinomial(self): + def gen_random(state, out): + out[...] = state.multinomial(10, [1/6.]*6, size=10000) + self.check_function(gen_random, sz=(10000,6)) + + if __name__ == "__main__": run_module_suite() diff --git a/numpy/testing/__init__.py b/numpy/testing/__init__.py index aad448c96..258cbe928 100644 --- a/numpy/testing/__init__.py +++ b/numpy/testing/__init__.py @@ -11,7 +11,6 @@ from unittest import TestCase from . import decorators as dec from .utils import * -from .numpytest import importall # remove for numpy 1.9.0 from .nosetester import NoseTester as Tester from .nosetester import run_module_suite test = Tester().test diff --git a/numpy/testing/nosetester.py b/numpy/testing/nosetester.py index 77ac61074..a06d559e7 100644 --- a/numpy/testing/nosetester.py +++ b/numpy/testing/nosetester.py @@ -75,14 +75,55 @@ def import_nose(): return nose -def run_module_suite(file_to_run = None): +def run_module_suite(file_to_run=None, argv=None): + """ + Run a test module. + + Equivalent to calling ``$ nosetests <argv> <file_to_run>`` from + the command line + + Parameters + ---------- + file_to_run: str, optional + Path to test module, or None. + By default, run the module from which this function is called. + argv: list of strings + Arguments to be passed to the nose test runner. ``argv[0]`` is + ignored. All command line arguments accepted by ``nosetests`` + will work. + + .. versionadded:: 1.9.0 + + Examples + -------- + Adding the following:: + + if __name__ == "__main__" : + run_module_suite(argv=sys.argv) + + at the end of a test module will run the tests when that module is + called in the python interpreter. + + Alternatively, calling:: + + >>> run_module_suite(file_to_run="numpy/tests/test_matlib.py") + + from an interpreter will run all the test routine in 'test_matlib.py'. + """ if file_to_run is None: f = sys._getframe(1) file_to_run = f.f_locals.get('__file__', None) if file_to_run is None: raise AssertionError - import_nose().run(argv=['', file_to_run]) + if argv is None: + argv = ['', file_to_run] + else: + argv = argv + [file_to_run] + + nose = import_nose() + from .noseclasses import KnownFailure + nose.run(argv=argv, addplugins=[KnownFailure()]) class NoseTester(object): @@ -378,6 +419,10 @@ class NoseTester(object): warnings.filterwarnings("ignore", message="numpy.ufunc size changed") warnings.filterwarnings("ignore", category=ModuleDeprecationWarning) warnings.filterwarnings("ignore", category=FutureWarning) + # Filter out boolean '-' deprecation messages. This allows + # older versions of scipy to test without a flood of messages. + warnings.filterwarnings("ignore", message=".*boolean negative.*") + warnings.filterwarnings("ignore", message=".*boolean subtract.*") from .noseclasses import NumpyTestProgram diff --git a/numpy/testing/numpytest.py b/numpy/testing/numpytest.py deleted file mode 100644 index d83a21d83..000000000 --- a/numpy/testing/numpytest.py +++ /dev/null @@ -1,36 +0,0 @@ -from __future__ import division, absolute_import, print_function - -import os -import warnings - -__all__ = ['importall'] - - -def importall(package): - """ - `importall` is DEPRECATED and will be removed in numpy 1.9.0 - - Try recursively to import all subpackages under package. - """ - warnings.warn("`importall is deprecated, and will be remobed in numpy 1.9.0", - DeprecationWarning) - - if isinstance(package, str): - package = __import__(package) - - package_name = package.__name__ - package_dir = os.path.dirname(package.__file__) - for subpackage_name in os.listdir(package_dir): - subdir = os.path.join(package_dir, subpackage_name) - if not os.path.isdir(subdir): - continue - if not os.path.isfile(os.path.join(subdir, '__init__.py')): - continue - name = package_name+'.'+subpackage_name - try: - exec('import %s as m' % (name)) - except Exception as msg: - print('Failed importing %s: %s' %(name, msg)) - continue - importall(m) - return diff --git a/numpy/testing/tests/test_utils.py b/numpy/testing/tests/test_utils.py index 94fc4d655..aa0a2669f 100644 --- a/numpy/testing/tests/test_utils.py +++ b/numpy/testing/tests/test_utils.py @@ -53,6 +53,9 @@ class _GenericTest(object): a = np.array([1, 1], dtype=np.object) self._test_equal(a, 1) + def test_array_likes(self): + self._test_equal([1, 2, 3], (1, 2, 3)) + class TestArrayEqual(_GenericTest, unittest.TestCase): def setUp(self): self._assert_func = assert_array_equal @@ -131,6 +134,49 @@ class TestArrayEqual(_GenericTest, unittest.TestCase): self._test_not_equal(c, b) +class TestBuildErrorMessage(unittest.TestCase): + def test_build_err_msg_defaults(self): + x = np.array([1.00001, 2.00002, 3.00003]) + y = np.array([1.00002, 2.00003, 3.00004]) + err_msg = 'There is a mismatch' + + a = build_err_msg([x, y], err_msg) + b = ('\nItems are not equal: There is a mismatch\n ACTUAL: array([ ' + '1.00001, 2.00002, 3.00003])\n DESIRED: array([ 1.00002, ' + '2.00003, 3.00004])') + self.assertEqual(a, b) + + def test_build_err_msg_no_verbose(self): + x = np.array([1.00001, 2.00002, 3.00003]) + y = np.array([1.00002, 2.00003, 3.00004]) + err_msg = 'There is a mismatch' + + a = build_err_msg([x, y], err_msg, verbose=False) + b = '\nItems are not equal: There is a mismatch' + self.assertEqual(a, b) + + def test_build_err_msg_custom_names(self): + x = np.array([1.00001, 2.00002, 3.00003]) + y = np.array([1.00002, 2.00003, 3.00004]) + err_msg = 'There is a mismatch' + + a = build_err_msg([x, y], err_msg, names=('FOO', 'BAR')) + b = ('\nItems are not equal: There is a mismatch\n FOO: array([ ' + '1.00001, 2.00002, 3.00003])\n BAR: array([ 1.00002, 2.00003, ' + '3.00004])') + self.assertEqual(a, b) + + def test_build_err_msg_custom_precision(self): + x = np.array([1.000000001, 2.00002, 3.00003]) + y = np.array([1.000000002, 2.00003, 3.00004]) + err_msg = 'There is a mismatch' + + a = build_err_msg([x, y], err_msg, precision=10) + b = ('\nItems are not equal: There is a mismatch\n ACTUAL: array([ ' + '1.000000001, 2.00002 , 3.00003 ])\n DESIRED: array([ ' + '1.000000002, 2.00003 , 3.00004 ])') + self.assertEqual(a, b) + class TestEqual(TestArrayEqual): def setUp(self): self._assert_func = assert_equal @@ -236,6 +282,31 @@ class TestAlmostEqual(_GenericTest, unittest.TestCase): self._test_not_equal(x, y) self._test_not_equal(x, z) + def test_error_message(self): + """Check the message is formatted correctly for the decimal value""" + x = np.array([1.00000000001, 2.00000000002, 3.00003]) + y = np.array([1.00000000002, 2.00000000003, 3.00004]) + + # test with a different amount of decimal digits + # note that we only check for the formatting of the arrays themselves + b = ('x: array([ 1.00000000001, 2.00000000002, 3.00003 ' + ' ])\n y: array([ 1.00000000002, 2.00000000003, 3.00004 ])') + try: + self._assert_func(x, y, decimal=12) + except AssertionError as e: + # remove anything that's not the array string + self.assertEqual(str(e).split('%)\n ')[1], b) + + # with the default value of decimal digits, only the 3rd element differs + # note that we only check for the formatting of the arrays themselves + b = ('x: array([ 1. , 2. , 3.00003])\n y: array([ 1. , ' + '2. , 3.00004])') + try: + self._assert_func(x, y) + except AssertionError as e: + # remove anything that's not the array string + self.assertEqual(str(e).split('%)\n ')[1], b) + class TestApproxEqual(unittest.TestCase): def setUp(self): self._assert_func = assert_approx_equal @@ -373,6 +444,11 @@ class TestAssertAllclose(unittest.TestCase): assert_allclose(6, 10, rtol=0.5) self.assertRaises(AssertionError, assert_allclose, 10, 6, rtol=0.5) + def test_min_int(self): + a = np.array([np.iinfo(np.int_).min], dtype=np.int_) + # Should not raise: + assert_allclose(a, a) + class TestArrayAlmostEqualNulp(unittest.TestCase): @dec.knownfailureif(True, "Github issue #347") diff --git a/numpy/testing/utils.py b/numpy/testing/utils.py index 2a99fe5cb..13c3e4610 100644 --- a/numpy/testing/utils.py +++ b/numpy/testing/utils.py @@ -9,8 +9,12 @@ import sys import re import operator import warnings +from functools import partial +import shutil +import contextlib +from tempfile import mkdtemp from .nosetester import import_nose -from numpy.core import float32, empty, arange +from numpy.core import float32, empty, arange, array_repr, ndarray if sys.version_info[0] >= 3: from io import StringIO @@ -22,7 +26,7 @@ __all__ = ['assert_equal', 'assert_almost_equal', 'assert_approx_equal', 'assert_array_almost_equal', 'assert_raises', 'build_err_msg', 'decorate_methods', 'jiffies', 'memusage', 'print_assert_equal', 'raises', 'rand', 'rundocs', 'runstring', 'verbose', 'measure', - 'assert_', 'assert_array_almost_equal_nulp', + 'assert_', 'assert_array_almost_equal_nulp', 'assert_raises_regex', 'assert_array_max_ulp', 'assert_warns', 'assert_no_warnings', 'assert_allclose', 'IgnoreException'] @@ -190,8 +194,7 @@ if os.name=='nt' and sys.version[:3] > '2.3': win32pdh.PDH_FMT_LONG, None) def build_err_msg(arrays, err_msg, header='Items are not equal:', - verbose=True, - names=('ACTUAL', 'DESIRED')): + verbose=True, names=('ACTUAL', 'DESIRED'), precision=8): msg = ['\n' + header] if err_msg: if err_msg.find('\n') == -1 and len(err_msg) < 79-len(header): @@ -200,8 +203,15 @@ def build_err_msg(arrays, err_msg, header='Items are not equal:', msg.append(err_msg) if verbose: for i, a in enumerate(arrays): + + if isinstance(a, ndarray): + # precision argument is only needed if the objects are ndarrays + r_func = partial(array_repr, precision=precision) + else: + r_func = repr + try: - r = repr(a) + r = r_func(a) except: r = '[repr failed]' if r.count('\n') > 3: @@ -318,7 +328,9 @@ def assert_equal(actual,desired,err_msg='',verbose=True): # as before except (TypeError, ValueError, NotImplementedError): pass - if desired != actual : + + # Explicitly use __eq__ for comparison, ticket #2552 + if not (desired == actual): raise AssertionError(msg) def print_assert_equal(test_string, actual, desired): @@ -573,7 +585,7 @@ def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True): raise AssertionError(msg) def assert_array_compare(comparison, x, y, err_msg='', verbose=True, - header=''): + header='', precision=6): from numpy.core import array, isnan, isinf, any, all, inf x = array(x, copy=False, subok=True) y = array(y, copy=False, subok=True) @@ -590,7 +602,7 @@ def assert_array_compare(comparison, x, y, err_msg='', verbose=True, msg = build_err_msg([x, y], err_msg + '\nx and y %s location mismatch:' \ % (hasval), verbose=verbose, header=header, - names=('x', 'y')) + names=('x', 'y'), precision=precision) raise AssertionError(msg) try: @@ -601,7 +613,7 @@ def assert_array_compare(comparison, x, y, err_msg='', verbose=True, + '\n(shapes %s, %s mismatch)' % (x.shape, y.shape), verbose=verbose, header=header, - names=('x', 'y')) + names=('x', 'y'), precision=precision) if not cond : raise AssertionError(msg) @@ -646,7 +658,7 @@ def assert_array_compare(comparison, x, y, err_msg='', verbose=True, err_msg + '\n(mismatch %s%%)' % (match,), verbose=verbose, header=header, - names=('x', 'y')) + names=('x', 'y'), precision=precision) if not cond : raise AssertionError(msg) except ValueError as e: @@ -655,7 +667,7 @@ def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header = 'error during assertion:\n\n%s\n\n%s' % (efmt, header) msg = build_err_msg([x, y], err_msg, verbose=verbose, header=header, - names=('x', 'y')) + names=('x', 'y'), precision=precision) raise ValueError(msg) def assert_array_equal(x, y, err_msg='', verbose=True): @@ -793,7 +805,7 @@ def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True): y: array([ 1. , 2.33333, 5. ]) """ - from numpy.core import around, number, float_ + from numpy.core import around, number, float_, result_type, array from numpy.core.numerictypes import issubdtype from numpy.core.fromnumeric import any as npany def compare(x, y): @@ -810,12 +822,22 @@ def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True): y = y[~yinfid] except (TypeError, NotImplementedError): pass + + # make sure y is an inexact type to avoid abs(MIN_INT); will cause + # casting of x later. + dtype = result_type(y, 1.) + y = array(y, dtype=dtype, copy=False) z = abs(x-y) + if not issubdtype(z.dtype, number): z = z.astype(float_) # handle object arrays + return around(z, decimal) <= 10.0**(-decimal) + assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose, - header=('Arrays are not almost equal to %d decimals' % decimal)) + header=('Arrays are not almost equal to %d decimals' % decimal), + precision=decimal) + def assert_array_less(x, y, err_msg='', verbose=True): """ @@ -1011,6 +1033,7 @@ def raises(*args,**kwargs): nose = import_nose() return nose.tools.raises(*args,**kwargs) + def assert_raises(*args,**kwargs): """ assert_raises(exception_class, callable, *args, **kwargs) @@ -1026,6 +1049,85 @@ def assert_raises(*args,**kwargs): nose = import_nose() return nose.tools.assert_raises(*args,**kwargs) + +assert_raises_regex_impl = None + + +def assert_raises_regex(exception_class, expected_regexp, + callable_obj=None, *args, **kwargs): + """ + Fail unless an exception of class exception_class and with message that + matches expected_regexp is thrown by callable when invoked with arguments + args and keyword arguments kwargs. + + Name of this function adheres to Python 3.2+ reference, but should work in + all versions down to 2.6. + + """ + nose = import_nose() + + global assert_raises_regex_impl + if assert_raises_regex_impl is None: + try: + # Python 3.2+ + assert_raises_regex_impl = nose.tools.assert_raises_regex + except AttributeError: + try: + # 2.7+ + assert_raises_regex_impl = nose.tools.assert_raises_regexp + except AttributeError: + # 2.6 + + # This class is copied from Python2.7 stdlib almost verbatim + class _AssertRaisesContext(object): + """A context manager used to implement TestCase.assertRaises* methods.""" + + def __init__(self, expected, expected_regexp=None): + self.expected = expected + self.expected_regexp = expected_regexp + + def failureException(self, msg): + return AssertionError(msg) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, tb): + if exc_type is None: + try: + exc_name = self.expected.__name__ + except AttributeError: + exc_name = str(self.expected) + raise self.failureException( + "{0} not raised".format(exc_name)) + if not issubclass(exc_type, self.expected): + # let unexpected exceptions pass through + return False + self.exception = exc_value # store for later retrieval + if self.expected_regexp is None: + return True + + expected_regexp = self.expected_regexp + if isinstance(expected_regexp, basestring): + expected_regexp = re.compile(expected_regexp) + if not expected_regexp.search(str(exc_value)): + raise self.failureException( + '"%s" does not match "%s"' % + (expected_regexp.pattern, str(exc_value))) + return True + + def impl(cls, regex, callable_obj, *a, **kw): + mgr = _AssertRaisesContext(cls, regex) + if callable_obj is None: + return mgr + with mgr: + callable_obj(*a, **kw) + assert_raises_regex_impl = impl + + return assert_raises_regex_impl(exception_class, expected_regexp, + callable_obj, *args, **kwargs) + + def decorate_methods(cls, decorator, testmatch=None): """ Apply a decorator to all methods in a class matching a regular expression. @@ -1147,6 +1249,8 @@ def assert_allclose(actual, desired, rtol=1e-7, atol=0, It compares the difference between `actual` and `desired` to ``atol + rtol * abs(desired)``. + .. versionadded:: 1.5.0 + Parameters ---------- actual : array_like @@ -1231,7 +1335,6 @@ def assert_array_almost_equal_nulp(x, y, nulp=1): >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x) >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x) - ------------------------------------------------------------ Traceback (most recent call last): ... AssertionError: X and Y are not equal to 1 ULP (max is 2) @@ -1456,6 +1559,7 @@ class WarningManager(object): self._module.filters = self._filters self._module.showwarning = self._showwarning + def assert_warns(warning_class, func, *args, **kw): """ Fail unless the given callable throws the specified warning. @@ -1465,6 +1569,8 @@ def assert_warns(warning_class, func, *args, **kw): If a different type of warning is thrown, it will not be caught, and the test case will be deemed to have suffered an error. + .. versionadded:: 1.4.0 + Parameters ---------- warning_class : class @@ -1496,6 +1602,8 @@ def assert_no_warnings(func, *args, **kw): """ Fail if the given callable produces any warnings. + .. versionadded:: 1.7.0 + Parameters ---------- func : callable @@ -1587,3 +1695,16 @@ def _gen_alignment_data(dtype=float32, type='binary', max_size=24): class IgnoreException(Exception): "Ignoring this exception due to disabled feature" + + +@contextlib.contextmanager +def tempdir(*args, **kwargs): + """Context manager to provide a temporary test folder. + + All arguments are passed as this to the underlying tempfile.mkdtemp + function. + + """ + tmpdir = mkdtemp(*args, **kwargs) + yield tmpdir + shutil.rmtree(tmpdir) |